-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathV3ServerAPICalls.cs
More file actions
1723 lines (1516 loc) · 81.3 KB
/
V3ServerAPICalls.cs
File metadata and controls
1723 lines (1516 loc) · 81.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Collections;
using System.Management.Automation;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
internal class V3ServerAPICalls : ServerApiCall
{
#region Members
public override PSRepositoryInfo Repository { get; set; }
internal override bool WriteWarnings { get; set; }
private readonly PSCmdlet _cmdletPassedIn;
private HttpClient _sessionClient { get; set; }
private bool _isNuGetRepo { get; set; }
private bool _isJFrogRepo { get; set; }
private bool _isGHPkgsRepo { get; set; }
private bool _isMyGetRepo { get; set; }
public FindResponseType v3FindResponseType = FindResponseType.ResponseString;
private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{};
private static readonly string nugetRepoUri = "https://api.nuget.org/v3/index.json";
private static readonly string resourcesName = "resources";
private static readonly string itemsName = "items";
private static readonly string versionName = "version";
private static readonly string dataName = "data";
private static readonly string idName = "id";
private static readonly string idLinkName = "@id";
private static readonly string tagsName = "tags";
private static readonly string catalogEntryProperty = "catalogEntry";
private static readonly string packageContentProperty = "packageContent";
// MyGet.org repository responses from SearchQueryService have a peculiarity where the totalHits property int returned is 10,000 + actual number of hits.
// This is intentional on their end and "is to preserve the uninterrupted pagination of NuGet within Visual Studio 2015".
private readonly int myGetTotalHitsBuffer = 10000;
#endregion
#region Constructor
public V3ServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base(repository, networkCredential)
{
this.Repository = repository;
_cmdletPassedIn = cmdletPassedIn;
HttpClientHandler handler = new HttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
bool token = false;
if(networkCredential != null)
{
token = String.Equals("token", networkCredential.UserName) ? true : false;
};
if (token)
{
string credString = string.Format(":{0}", networkCredential.Password);
byte[] byteArray = Encoding.ASCII.GetBytes(credString);
_sessionClient = new HttpClient(handler);
_sessionClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
} else {
handler.Credentials = networkCredential;
_sessionClient = new HttpClient(handler);
};
_sessionClient.Timeout = TimeSpan.FromMinutes(10);
_sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString);
_isNuGetRepo = String.Equals(Repository.Uri.AbsoluteUri, nugetRepoUri, StringComparison.InvariantCultureIgnoreCase);
_isJFrogRepo = Repository.Uri.AbsoluteUri.ToLower().Contains("jfrog.io");
_isGHPkgsRepo = Repository.Uri.AbsoluteUri.ToLower().Contains("pkg.github.com");
_isMyGetRepo = Repository.Uri.AbsoluteUri.ToLower().Contains("myget.org");
}
#endregion
#region Overridden Methods
/// <summary>
/// Find method which allows for searching for all packages from a repository and returns latest version for each.
/// Not supported for V3 repository.
/// </summary>
public override FindResults FindAll(bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindAll()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find all is not supported for the V3 server protocol repository '{Repository.Name}'"),
"FindAllFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Find method which allows for searching for packages with tag(s) from a repository and returns latest version for each.
/// This is supported only for the NuGet repository special case, not other V3 repositories.
/// </summary>
public override FindResults FindTags(string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindTags()");
if (_isNuGetRepo || _isJFrogRepo)
{
return FindTagsFromNuGetRepo(tags, includePrerelease, out errRecord);
}
else
{
errRecord = new ErrorRecord(
new InvalidOperationException($"Find by Tags is not supported for the V3 server protocol repository '{Repository.Name}'"),
"FindTagsFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
/// <summary>
/// Find method which allows for searching for packages with specified Command or DSCResource name.
/// Not supported for V3 repository.
/// </summary>
public override FindResults FindCommandOrDscResource(string[] tags, bool includePrerelease, bool isSearchingForCommands, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindCommandOrDscResource()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find by CommandName or DSCResource is not supported for the V3 server protocol repository '{Repository.Name}'"),
"FindCommandOrDscResourceFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name and returns latest version.
/// Name: no wildcard support
/// Examples: Search "Newtonsoft.Json"
/// We use the latest RegistrationBaseUrl version resource we can find and check if contains an entry with the package name.
/// </summary>
public override FindResults FindName(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindName()");
return FindNameHelper(packageName, tags: Utils.EmptyStrArray, includePrerelease, type, out errRecord);
}
/// <summary>
/// Find method which allows for searching for single name and specified tag(s) and returns latest version.
/// Name: no wildcard support
/// Examples: Search "Newtonsoft.Json" -Tag "json"
/// We use the latest RegistrationBaseUrl version resource we can find and check if contains an entry with the package name.
/// </summary>
public override FindResults FindNameWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindNameWithTag()");
return FindNameHelper(packageName, tags, includePrerelease, type, out errRecord);
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and returns latest version.
/// This is supported only for the NuGet repository special case, not other V3 repositories.
/// </summary>
public override FindResults FindNameGlobbing(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindNameGlobbing()");
if (_isNuGetRepo || _isJFrogRepo || _isGHPkgsRepo || _isMyGetRepo)
{
return FindNameGlobbingFromNuGetRepo(packageName, tags: Utils.EmptyStrArray, includePrerelease, out errRecord);
}
else
{
errRecord = new ErrorRecord(
new InvalidOperationException($"Find with Name containing wildcards is not supported for the V3 server protocol repository '{Repository.Name}'"),
"FindNameGlobbingFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and tag and returns latest version.
/// This is supported only for the NuGet repository special case, not other V3 repositories.
/// </summary>
public override FindResults FindNameGlobbingWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindNameGlobbingWithTag()");
if (_isNuGetRepo || _isJFrogRepo || _isGHPkgsRepo || _isMyGetRepo)
{
return FindNameGlobbingFromNuGetRepo(packageName, tags, includePrerelease, out errRecord);
}
else
{
errRecord = new ErrorRecord(
new InvalidOperationException($"Find with Name containing wildcards is not supported for the V3 server protocol repository '{Repository.Name}'"),
"FindNameGlobbingWithTagFailure",
ErrorCategory.InvalidOperation,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
/// <summary>
/// Find method which allows for searching for single name with version range.
/// Name: no wildcard support
/// Version: supports wildcards
/// Examples: Search "NuGet.Server.Core" "[1.0.0.0, 5.0.0.0]"
/// Search "NuGet.Server.Core" "3.*"
/// We use the latest RegistrationBaseUrl version resource we can find and check if contains an entry with the package name, then get all versions and match to satisfying versions.
/// </summary>
public override FindResults FindVersionGlobbing(string packageName, VersionRange versionRange, bool includePrerelease, ResourceType type, bool getOnlyLatest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindVersionGlobbing()");
string[] versionedResponses = GetVersionedPackageEntriesFromRegistrationsResource(packageName, catalogEntryProperty, isSearch: true, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
List<string> satisfyingVersions = new List<string>();
foreach (string response in versionedResponses)
{
try
{
using (JsonDocument pkgVersionEntry = JsonDocument.Parse(response))
{
JsonElement rootDom = pkgVersionEntry.RootElement;
if (!rootDom.TryGetProperty(versionName, out JsonElement pkgVersionElement))
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain '{versionName}' element."),
"FindVersionGlobbingFailure",
ErrorCategory.InvalidData,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (NuGetVersion.TryParse(pkgVersionElement.ToString(), out NuGetVersion pkgVersion) && versionRange.Satisfies(pkgVersion))
{
_cmdletPassedIn.WriteDebug($"Package version parsed as '{pkgVersion}' satisfies the version range");
if (!pkgVersion.IsPrerelease || includePrerelease)
{
satisfyingVersions.Add(response);
}
}
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"FindVersionGlobbingFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
return new FindResults(stringResponse: satisfyingVersions.ToArray(), hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "NuGet.Server.Core" "3.0.0-beta"
/// We use the latest RegistrationBaseUrl version resource we can find and check if contains an entry with the package name, then match to the specified version.
/// </summary>
public override FindResults FindVersion(string packageName, string version, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindVersion()");
return FindVersionHelper(packageName, version, tags: Utils.EmptyStrArray, type, out errRecord);
}
/// <summary>
/// Find method which allows for searching for single name with specific version and tag(s).
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "NuGet.Server.Core" "3.0.0-beta" -Tag "core"
/// We use the latest RegistrationBaseUrl version resource we can find and check if contains an entry with the package name, then match to the specified version.
/// </summary>
public override FindResults FindVersionWithTag(string packageName, string version, string[] tags, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindVersionWithTag()");
return FindVersionHelper(packageName, version, tags: tags, type, out errRecord);
}
/** INSTALL APIS **/
/// <summary>
/// Installs a specific package.
/// User may request to install package with or without providing version (as seen in examples below), but prior to calling this method the package is located and package version determined.
/// Therefore, package version should not be null in this method.
/// Name: no wildcard support.
/// Examples: Install "PowerShellGet"
/// Install "PowerShellGet" -Version "3.0.0"
/// </summary>
public override Stream InstallPackage(string packageName, string packageVersion, bool includePrerelease, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::InstallPackage()");
Stream results = new MemoryStream();
if (string.IsNullOrEmpty(packageVersion))
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException($"Package version could not be found for {packageName}"),
"PackageVersionNullOrEmptyError",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);
return results;
}
results = InstallVersion(packageName, packageVersion, out errRecord);
return results;
}
#endregion
#region Private Methods
/// <summary>
/// Helper method called by FindNameGlobbing() and FindNameGlobbingWithTag() for special case where repository is NuGet.org repository.
/// </summary>
private FindResults FindNameGlobbingFromNuGetRepo(string packageName, string[] tags, bool includePrerelease, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindNameGlobbingFromNuGetRepo()");
var names = packageName.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
string querySearchTerm;
if (names.Length == 0)
{
errRecord = new ErrorRecord(
new ArgumentException("-Name '*' for V3 server protocol repositories is not supported"),
"FindNameGlobbingFromNuGetRepoFailure",
ErrorCategory.InvalidArgument,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (names.Length == 1)
{
// packageName: *get* -> q: get
// packageName: PowerShell* -> q: PowerShell
// packageName: *ShellGet -> q: ShellGet
querySearchTerm = names[0];
}
else
{
// *pow*get*
// pow*get -> only support this (V2)
// pow*get*
// *pow*get
errRecord = new ErrorRecord(
new ArgumentException("-Name with wildcards is only supported for scenarios similar to the following examples: PowerShell*, *ShellGet, *Shell*."),
"FindNameGlobbingFromNuGetRepoFailure",
ErrorCategory.InvalidArgument,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
var matchingPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(querySearchTerm, includePrerelease, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
List<string> matchingResponses = new List<string>();
foreach (var pkgEntry in matchingPkgEntries)
{
string id = string.Empty;
string latestVersion = string.Empty;
string[] pkgTags = Utils.EmptyStrArray;
try
{
if (!pkgEntry.TryGetProperty(idName, out JsonElement idItem))
{
errRecord = new ErrorRecord(
new JsonParsingException("FindNameGlobbing(): Name element could not be found in response."),
"GetEntriesFromSearchQueryResourceFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (!pkgEntry.TryGetProperty(tagsName, out JsonElement tagsItem))
{
errRecord = new ErrorRecord(
new JsonParsingException("FindNameGlobbing(): Tags element could not be found in response."),
"GetEntriesFromSearchQueryResourceFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
id = idItem.ToString();
_cmdletPassedIn.WriteDebug($"Id for package that could be candidate for FindNameGlobbing found '{id}'");
// determine if id matches our wildcard criteria
if ((packageName.StartsWith("*") && packageName.EndsWith("*") && id.ToLower().Contains(querySearchTerm.ToLower())) ||
(packageName.EndsWith("*") && id.StartsWith(querySearchTerm, StringComparison.OrdinalIgnoreCase)) ||
(packageName.StartsWith("*") && id.EndsWith(querySearchTerm, StringComparison.OrdinalIgnoreCase)))
{
_cmdletPassedIn.WriteDebug($"Id '{id}' matches wildcard search criteria");
bool isTagMatch = IsRequiredTagSatisfied(tagsItem, tags, out errRecord);
if (!isTagMatch)
{
continue;
}
matchingResponses.Add(pkgEntry.ToString());
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"GetEntriesFromSearchQueryResourceFailure",
ErrorCategory.InvalidResult,
this);
break;
}
}
return new FindResults(stringResponse: matchingResponses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Helper method called by FindTags() for special case where repository is NuGet.org repository.
/// </summary>
private FindResults FindTagsFromNuGetRepo(string[] tags, bool includePrerelease, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindTagsFromNuGetRepo()");
string tagsQueryTerm = $"tags:{String.Join(" ", tags)}";
// Get responses for all packages that contain the required tags
// example query:
var tagPkgEntries = GetVersionedPackageEntriesFromSearchQueryResource(tagsQueryTerm, includePrerelease, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (tagPkgEntries.Count == 0)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with Tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."),
"PackageWithSpecifiedTagsNotFound",
ErrorCategory.ObjectNotFound,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
List<string> matchingPkgResponses = new List<string>();
foreach (var pkgEntry in tagPkgEntries)
{
matchingPkgResponses.Add(pkgEntry.ToString());
}
return new FindResults(stringResponse: matchingPkgResponses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Helper method called by FindName() and FindNameWithTag()
/// <summary>
private FindResults FindNameHelper(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindNameHelper()");
string[] versionedResponses = GetVersionedPackageEntriesFromRegistrationsResource(packageName, catalogEntryProperty, isSearch: true, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
string latestVersionResponse = String.Empty;
bool isTagMatch = true;
foreach (string response in versionedResponses)
{
try
{
using (JsonDocument pkgVersionEntry = JsonDocument.Parse(response))
{
JsonElement rootDom = pkgVersionEntry.RootElement;
if (!rootDom.TryGetProperty(versionName, out JsonElement pkgVersionElement))
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain '{versionName}' element for search with Name '{packageName}' in '{Repository.Name}'."),
"FindNameFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (!rootDom.TryGetProperty(tagsName, out JsonElement tagsItem) && tags.Length != 0)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain '{tagsName}' element for search with Name '{packageName}' in '{Repository.Name}'."),
"FindNameFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (NuGetVersion.TryParse(pkgVersionElement.ToString(), out NuGetVersion pkgVersion))
{
_cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{pkgVersion}'");
if (!pkgVersion.IsPrerelease || includePrerelease)
{
// Versions are always in descending order i.e 5.0.0, 3.0.0, 1.0.0 so grabbing the first match suffices
latestVersionResponse = response;
isTagMatch = IsRequiredTagSatisfied(tagsItem, tags, out errRecord);
break;
}
}
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"FindNameFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
if (String.IsNullOrEmpty(latestVersionResponse))
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
// Check and write error for tags matching requirement. If no tags were required the isTagMatch variable will be true.
if (!isTagMatch)
{
if (errRecord == null)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
}
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
return new FindResults(stringResponse: new string[] { latestVersionResponse }, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Helper method called by FindVersion() and FindVersionWithTag()
/// </summary>
private FindResults FindVersionHelper(string packageName, string version, string[] tags, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindVersionHelper()");
if (!NuGetVersion.TryParse(version, out NuGetVersion requiredVersion))
{
errRecord = new ErrorRecord(
new ArgumentException($"Version {version} to be found is not a valid NuGet version."),
"FindNameFailure",
ErrorCategory.InvalidArgument,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
_cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{requiredVersion}'");
string[] versionedResponses = GetVersionedPackageEntriesFromRegistrationsResource(packageName, catalogEntryProperty, isSearch: true, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
string latestVersionResponse = String.Empty;
bool isTagMatch = true;
foreach (string response in versionedResponses)
{
// Versions are always in descending order i.e 5.0.0, 3.0.0, 1.0.0
try
{
using (JsonDocument pkgVersionEntry = JsonDocument.Parse(response))
{
JsonElement rootDom = pkgVersionEntry.RootElement;
if (!rootDom.TryGetProperty(versionName, out JsonElement pkgVersionElement))
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain '{versionName}' element for search with name '{packageName}' and version '{version}' in repository '{Repository.Name}'."),
"FindVersionFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (!rootDom.TryGetProperty(tagsName, out JsonElement tagsItem) && tags.Length != 0)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain '{tagsName}' element for search with name '{packageName}' and version '{version}' in repository '{Repository.Name}'."),
"FindVersionFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (NuGetVersion.TryParse(pkgVersionElement.ToString(), out NuGetVersion pkgVersion))
{
if (pkgVersion == requiredVersion)
{
latestVersionResponse = response;
isTagMatch = IsRequiredTagSatisfied(tagsItem, tags, out errRecord);
break;
}
}
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"FindVersionFailure",
ErrorCategory.InvalidResult,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
}
if (String.IsNullOrEmpty(latestVersionResponse))
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}', version '{version}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
if (!isTagMatch)
{
if (errRecord == null)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"FindVersion(): Package with name '{packageName}', version '{version}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
}
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
return new FindResults(stringResponse: new string[] { latestVersionResponse }, hashtableResponse: emptyHashResponses, responseType: v3FindResponseType);
}
/// <summary>
/// Installs specific package.
/// Name: no wildcard support.
/// Examples: Install "Newtonsoft.json"
/// </summary>
private Stream InstallName(string packageName, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::InstallName()");
return InstallHelper(packageName, version: null, out errRecord);
}
/// <summary>
/// Installs package with specific name and version.
/// Name: no wildcard support.
/// Version: no wildcard support.
/// Examples: Install "Newtonsoft.json" -Version "1.0.0.0"
/// Install "Newtonsoft.json" -Version "2.5.0-beta"
/// </summary>
private Stream InstallVersion(string packageName, string version, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::InstallVersion()");
if (!NuGetVersion.TryParse(version, out NuGetVersion requiredVersion))
{
errRecord = new ErrorRecord(
new ArgumentException($"Version {version} to be installed is not a valid NuGet version."),
"InstallVersionFailure",
ErrorCategory.InvalidArgument,
this);
return null;
}
return InstallHelper(packageName, requiredVersion, out errRecord);
}
/// <summary>
/// Helper method that is called by InstallName() and InstallVersion()
/// For InstallName() we want latest version installed (so version parameter passed in will be null), for InstallVersion() we want specified, non-null version installed.
/// </summary>
private Stream InstallHelper(string packageName, NuGetVersion version, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::InstallHelper()");
Stream pkgStream = null;
bool getLatestVersion = true;
if (version != null)
{
getLatestVersion = false;
}
string[] versionedResponses = GetVersionedPackageEntriesFromRegistrationsResource(packageName, packageContentProperty, isSearch: false, out errRecord);
if (errRecord != null)
{
return pkgStream;
}
if (versionedResponses.Length == 0)
{
errRecord = new ErrorRecord(
new Exception($"Package with name '{packageName}' and version '{version}' could not be found in repository '{Repository.Name}'"),
"InstallFailure",
ErrorCategory.InvalidResult,
this);
return null;
}
string pkgContentUrl = String.Empty;
if (getLatestVersion)
{
pkgContentUrl = versionedResponses[0];
}
else
{
// loop through responses to find one containing required version
foreach (string response in versionedResponses)
{
// Response will be "packageContent" element value that looks like: "{packageBaseAddress}/{packageName}/{normalizedVersion}/{packageName}.{normalizedVersion}.nupkg"
// Ex: https://api.nuget.org/v3-flatcontainer/test_module/1.0.0/test_module.1.0.0.nupkg
if (response.Contains(version.ToNormalizedString()))
{
pkgContentUrl = response;
break;
}
}
}
if (String.IsNullOrEmpty(pkgContentUrl))
{
errRecord = new ErrorRecord(
new Exception($"Package with name '{packageName}' and version '{version}' could not be found in repository '{Repository.Name}'"),
"InstallFailure",
ErrorCategory.InvalidResult,
this);
return null;
}
var content = HttpRequestCallForContent(pkgContentUrl, out errRecord);
if (errRecord != null)
{
return null;
}
if (content is null)
{
errRecord = new ErrorRecord(
new Exception($"No content was returned by repository '{Repository.Name}'"),
"InstallFailureContentNullv3",
ErrorCategory.InvalidResult,
this);
return null;
}
return content.ReadAsStreamAsync().Result;
}
/// <summary>
/// Gets the versioned package entries from the RegistrationsBaseUrl resource
/// i.e when the package Name being searched for does not contain wildcard
/// This is called by FindNameHelper(), FindVersionHelper(), FindVersionGlobbing(), InstallHelper()
/// </summary>
private string[] GetVersionedPackageEntriesFromRegistrationsResource(string packageName, string propertyName, bool isSearch, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::GetVersionedPackageEntriesFromRegistrationsResource()");
string[] responses = Utils.EmptyStrArray;
Dictionary<string, string> resources = GetResourcesFromServiceIndex(out errRecord);
if (errRecord != null)
{
return responses;
}
string registrationsBaseUrl = FindRegistrationsBaseUrl(resources, out errRecord);
if (errRecord != null)
{
return responses;
}
responses = GetVersionedResponsesFromRegistrationsResource(registrationsBaseUrl, packageName, propertyName, isSearch, out errRecord);
if (errRecord != null)
{
return Utils.EmptyStrArray;
}
return responses;
}
/// <summary>
/// Gets the versioned package entries from SearchQueryService resource
/// i.e when the package Name being searched for contains wildcards or a Tag query search is performed
/// This is called by FindNameGlobbingFromNuGetRepo() and FindTagsFromNuGetRepo()
/// </summary>
private List<JsonElement> GetVersionedPackageEntriesFromSearchQueryResource(string queryTerm, bool includePrerelease, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::GetVersionedPackageEntriesFromSearchQueryResource()");
List<JsonElement> pkgEntries = new();
Dictionary<string, string> resources = GetResourcesFromServiceIndex(out errRecord);
if (errRecord != null)
{
return pkgEntries;
}
string searchQueryServiceUrl = FindSearchQueryService(resources, out errRecord);
if (errRecord != null)
{
return pkgEntries;
}
// Get initial response
int skip = 0;
string query = $"{searchQueryServiceUrl}?q={queryTerm}&prerelease={includePrerelease}&semVerLevel=2.0.0&skip={skip}&take=100";
// Get responses for all packages that contain the required tags
pkgEntries.AddRange(GetJsonElementArr(query, dataName, out int initialCount, out errRecord).ToList());
// check count (ie "totalHits") 425 ==> count/100 ~~> 4 calls ~~> + 1 = 5 calls
int count = initialCount / 100 + 1;
// if more than 100 count, loop and add response to list
while (count > 0)
{
skip += 100;
query = $"{searchQueryServiceUrl}?q={queryTerm}&prerelease={includePrerelease}&semVerLevel=2.0.0&skip={skip}&take=100";
pkgEntries.AddRange(GetJsonElementArr(query, dataName, out int unneededCount, out errRecord).ToList());
count--;
}
return pkgEntries;
}
/// <summary>
/// Finds all resources present in the repository's service index.
/// For example: https://api.nuget.org/v3/index.json
/// </summary>
private Dictionary<string, string> GetResourcesFromServiceIndex(out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::GetResourcesFromServiceIndex()");
Dictionary<string, string> resources = new Dictionary<string, string>();
JsonElement[] resourcesArray = GetJsonElementArr($"{Repository.Uri}", resourcesName, out int totalHits, out errRecord);
if (errRecord != null)
{
return resources;
}
foreach (JsonElement resource in resourcesArray)
{
try
{
if (!resource.TryGetProperty("@type", out JsonElement typeElement))
{
errRecord = new ErrorRecord(
new JsonParsingException($"@type element not found for resource in service index for repository '{Repository.Name}'"), "GetResourcesFromServiceIndexFailure",
ErrorCategory.InvalidResult,
this);
return new Dictionary<string, string>();
}
if (!resource.TryGetProperty("@id", out JsonElement idElement))
{
errRecord = new ErrorRecord(
new JsonParsingException($"@id element not found for resource in service index for repository '{Repository.Name}'"),
"GetResourcesFromServiceIndexFailure",
ErrorCategory.InvalidResult,
this);
return new Dictionary<string, string>();
}
if (!resources.ContainsKey(typeElement.ToString()))
{
// Some resources have a primary and secondary entry. The @id value is the same, so we only choose the primary entry.
resources.Add(typeElement.ToString(), idElement.ToString());
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
new Exception($"Exception parsing service index JSON for repository '{Repository.Name}' with error: {e.Message}"),
"GetResourcesFromServiceIndexFailure",
ErrorCategory.InvalidResult,
this);
return new Dictionary<string, string>();
}
}
return resources;
}
/// <summary>
/// Gets the resource of type "RegistrationBaseUrl" from the repository's resources.
/// A repository can have multiple resources of type "RegistrationsBaseUrl" so it finds the best match according to the guideline comment in the method.
/// </summary>
private string FindRegistrationsBaseUrl(Dictionary<string, string> resources, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindRegistrationsBaseUrl()");
errRecord = null;
string registrationsBaseUrl = String.Empty;
/**
If RegistrationsBaseUrl/3.6.0 exists, use RegistrationsBaseUrl/3.6.0
Otherwise, if RegistrationsBaseUrl/3.4.0 exists, use RegistrationsBaseUrl/3.4.0
Otherwise, if RegistrationsBaseUrl/3.0.0-rc exists, use RegistrationsBaseUrl/3.0.0-rc
Otherwise, if RegistrationsBaseUrl/3.0.0-beta exists, use RegistrationsBaseUrl/3.0.0-beta
Otherwise, if RegistrationsBaseUrl exists, use RegistrationsBaseUrl
Otherwise, report an error
*/
if (resources.ContainsKey("RegistrationsBaseUrl/3.6.0"))
{
registrationsBaseUrl = resources["RegistrationsBaseUrl/3.6.0"];
}
else if (resources.ContainsKey("RegistrationsBaseUrl/3.4.0"))
{
registrationsBaseUrl = resources["RegistrationsBaseUrl/3.4.0"];
}
else if (resources.ContainsKey("RegistrationsBaseUrl/3.0.0-rc"))
{
registrationsBaseUrl = resources["RegistrationsBaseUrl/3.0.0-rc"];
}
else if (resources.ContainsKey("RegistrationsBaseUrl/3.0.0-beta"))
{
registrationsBaseUrl = resources["RegistrationsBaseUrl/3.0.0-beta"];
}
else if (resources.ContainsKey("RegistrationsBaseUrl"))
{
registrationsBaseUrl = resources["RegistrationsBaseUrl"];
}
else
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"RegistrationBaseUrl resource could not be found for repository '{Repository.Name}'"),
"FindRegistrationsBaseUrlFailure",
ErrorCategory.InvalidResult,
this);
}
return registrationsBaseUrl;
}
/// <summary>
/// Gets the resource of type "SearchQueryService" from the repository's resources.
/// A repository can have multiple resources of type "SearchQueryService" so it finds the best match according to the guideline comment in the method.
/// </summary>
private string FindSearchQueryService(Dictionary<string, string> resources, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V3ServerAPICalls::FindSearchQueryService()");
errRecord = null;
string searchQueryServiceUrl = String.Empty;
if (resources.ContainsKey("SearchQueryService/3.5.0"))
{
searchQueryServiceUrl = resources["SearchQueryService/3.5.0"];
}