-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathV2ServerAPICalls.cs
More file actions
1587 lines (1375 loc) · 75.6 KB
/
V2ServerAPICalls.cs
File metadata and controls
1587 lines (1375 loc) · 75.6 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 System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using NuGet.Versioning;
using System.Threading.Tasks;
using System.Xml;
using System.Net;
using System.Text;
using System.Runtime.ExceptionServices;
using System.Management.Automation;
using System.Reflection;
using System.Data.Common;
using System.Linq;
namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
{
internal class V2ServerAPICalls : ServerApiCall
{
/* ******NOTE*******:
/* Quotations in the urls can change the response.
/* for example: http://www.powershellgallery.com/api/v2/Search()?$filter=IsLatestVersion&searchTerm='az* tag:PSScript'&includePrerelease=true
/* will return something different than
/* http://www.powershellgallery.com/api/v2/Search()?$filter=IsLatestVersion&searchTerm=az* tag:PSScript&includePrerelease=true
/* We believe the first example returns an "and" of the search term and the tag and the second returns "or",
/* this needs more investigation.
/* Some of the urls below may need to be modified.
*/
// Any interface method that is not implemented here should be processed in the parent method and then call one of the implemented
// methods below.
#region Members
public override PSRepositoryInfo Repository { get; set; }
internal override bool WriteWarnings { get; set; }
private readonly PSCmdlet _cmdletPassedIn;
private HttpClient _sessionClient { get; set; }
private static readonly Hashtable[] emptyHashResponses = new Hashtable[]{};
public FindResponseType v2FindResponseType = FindResponseType.ResponseString;
private bool _isADORepo;
private bool _isJFrogRepo;
private bool _isPSGalleryRepo;
#endregion
#region Constructor
public V2ServerAPICalls (PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base (repository, networkCredential)
{
this.Repository = repository;
_cmdletPassedIn = cmdletPassedIn;
HttpClientHandler handler = new HttpClientHandler();
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);
var repoURL = repository.Uri.ToString().ToLower();
_isADORepo = repoURL.Contains("pkgs.dev.azure.com") || repoURL.Contains("pkgs.visualstudio.com");
_isJFrogRepo = repoURL.Contains("jfrog") || repoURL.Contains("artifactory");
_isPSGalleryRepo = repoURL.Contains("powershellgallery.com/api/v2");
}
#endregion
#region Overridden Methods
/// <summary>
/// Find method which allows for searching for all packages from a repository and returns latest version for each.
/// Examples: Search -Repository PSGallery
/// API call:
/// - No prerelease: http://www.powershellgallery.com/api/v2/Search()?$filter=IsLatestVersion
/// </summary>
public override FindResults FindAll(bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindAll()");
errRecord = null;
List<string> responses = new List<string>();
if (type == ResourceType.Script || type == ResourceType.None)
{
int scriptSkip = 0;
string initialScriptResponse = FindAllFromTypeEndPoint(includePrerelease, isSearchingModule: false, scriptSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialScriptCount = GetCountFromResponse(initialScriptResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialScriptCount != 0)
{
responses.Add(initialScriptResponse);
int count = initialScriptCount / 6000;
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
scriptSkip += 6000;
var tmpResponse = FindAllFromTypeEndPoint(includePrerelease, isSearchingModule: false, scriptSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
}
if (type != ResourceType.Script)
{
int moduleSkip = 0;
string initialModuleResponse = FindAllFromTypeEndPoint(includePrerelease, isSearchingModule: true, moduleSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialModuleCount = GetCountFromResponse(initialModuleResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialModuleCount != 0)
{
responses.Add(initialModuleResponse);
int count = initialModuleCount / 6000;
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
moduleSkip += 6000;
var tmpResponse = FindAllFromTypeEndPoint(includePrerelease, isSearchingModule: true, moduleSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for packages with tag from a repository and returns latest version for each.
/// Examples: Search -Tag "JSON" -Repository PSGallery
/// API call:
/// - Include prerelease: https://www.powershellgallery.com/api/v2/Search()?includePrerelease=true&$filter=IsAbsoluteLatestVersion and substringof('PSModule', Tags) eq true and substringof('CrescendoBuilt', Tags) eq true&$orderby=Id desc&$inlinecount=allpages&$skip=0&$top=6000
/// </summary>
public override FindResults FindTags(string[] tags, bool includePrerelease, ResourceType _type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindTags()");
errRecord = null;
List<string> responses = new List<string>();
if (_type == ResourceType.Script || _type == ResourceType.None)
{
int scriptSkip = 0;
string initialScriptResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialScriptCount = GetCountFromResponse(initialScriptResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialScriptCount != 0)
{
responses.Add(initialScriptResponse);
int count = initialScriptCount / 100;
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
// skip 100
scriptSkip += 100;
var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: false, scriptSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
}
if (_type != ResourceType.Script)
{
int moduleSkip = 0;
string initialModuleResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: true, moduleSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialModuleCount = GetCountFromResponse(initialModuleResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialModuleCount != 0)
{
responses.Add(initialModuleResponse);
int count = initialModuleCount / 100;
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
moduleSkip += 100;
var tmpResponse = FindTagFromEndpoint(tags, includePrerelease, isSearchingModule: true, moduleSkip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
}
if (responses.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: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for all packages that have specified Command or DSCResource name.
/// </summary>
public override FindResults FindCommandOrDscResource(string[] tags, bool includePrerelease, bool isSearchingForCommands, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindCommandOrDscResource()");
List<string> responses = new List<string>();
int skip = 0;
string initialResponse = FindCommandOrDscResource(tags, includePrerelease, isSearchingForCommands, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialCount = GetCountFromResponse(initialResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialCount != 0)
{
responses.Add(initialResponse);
int count = (int)Math.Ceiling((double)(initialCount / 100));
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
skip += 100;
var tmpResponse = FindCommandOrDscResource(tags, includePrerelease, isSearchingForCommands, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
if (responses.Count == 0)
{
string parameterForErrorMsg = isSearchingForCommands ? "Command" : "DSC Resource";
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with {parameterForErrorMsg} '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."),
"PackageWithSpecifiedCmdOrDSCNotFound",
ErrorCategory.InvalidResult,
this);
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet"
/// API call:
/// - No prerelease: http://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'
/// - Include prerelease: http://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'
/// Implementation Note: Need to filter further for latest version (prerelease or non-prerelease depending on user preference)
/// </summary>
public override FindResults FindName(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindName()");
// Make sure to include quotations around the package name
// This should return the latest stable version or the latest prerelease version (respectively)
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'&$filter=IsLatestVersion and substringof('PSModule', Tags) eq true
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id',
// however filtering on 'and Title eq '<packageName>' returns "Response status code does not indicate success: 500".
if (!_isJFrogRepo) {
filterBuilder.AddCriterion($"Id eq '{packageName}'");
}
filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion eq true" : "IsLatestVersion eq true");
if (type != ResourceType.None) {
filterBuilder.AddCriterion(GetTypeFilterForRequest(type));
}
var requestUrlV2 = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrlV2, out errRecord);
if (errRecord != null)
{
// usually this is for errors in calling the V2 server, but for ADO V2 this error will include package not found errors which we want to deliver in a standard message
if (_isADORepo && errRecord.Exception is ResourceNotFoundException)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}' could not be found in repository '{Repository.Name}'. For ADO feed, if the package is in an upstream feed make sure you are authenticated to the upstream feed.", errRecord.Exception),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
response = string.Empty;
}
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = GetCountFromResponse(response, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (count == 0)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
response = string.Empty;
}
return new FindResults(stringResponse: new string[]{ response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name and tag and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet" -Tag "Provider"
/// Implementation Note: Need to filter further for latest version (prerelease or non-prerelease depending on user preference)
/// </summary>
public override FindResults FindNameWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindNameWithTag()");
// Make sure to include quotations around the package name
// This should return the latest stable version or the latest prerelease version (respectively)
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'&$filter=IsLatestVersion and substringof('PSModule', Tags) eq true
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id',
// however filtering on 'and Title eq '<packageName>' returns "Response status code does not indicate success: 500".
if (!_isJFrogRepo) {
filterBuilder.AddCriterion($"Id eq '{packageName}'");
}
filterBuilder.AddCriterion(includePrerelease ? "IsAbsoluteLatestVersion eq true" : "IsLatestVersion eq true");
if (type != ResourceType.None) {
filterBuilder.AddCriterion(GetTypeFilterForRequest(type));
}
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrlV2 = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrlV2, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = GetCountFromResponse(response, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (count == 0)
{
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);
response = string.Empty;
}
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*"
/// API call:
/// - No prerelease: http://www.powershellgallery.com/api/v2/Search()?$filter=IsLatestVersion&searchTerm='az*'
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbing(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindNameGlobbing()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindNameGlobbing(packageName, type, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(initialResponse);
// check count (regex) 425 ==> count/100 ~~> 4 calls
int initialCount = GetCountFromResponse(initialResponse, out errRecord); // count = 4
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
// If count is 0, early out as this means no packages matching search criteria were found. We want to set the responses array to empty and not set ErrorRecord (as is a globbing scenario).
if (initialCount == 0)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = (int)Math.Ceiling((double)(initialCount / 100));
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
// skip 100
skip += 100;
var tmpResponse = FindNameGlobbing(packageName, type, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and tag and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*" -Tag "Provider"
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbingWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindNameGlobbingWithTag()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindNameGlobbingWithTag(packageName, tags, type, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(initialResponse);
// check count (regex) 425 ==> count/100 ~~> 4 calls
int initialCount = GetCountFromResponse(initialResponse, out errRecord); // count = 4
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialCount == 0)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = (int)Math.Ceiling((double)(initialCount / 100));
// if more than 100 count, loop and add response to list
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
// skip 100
skip += 100;
var tmpResponse = FindNameGlobbingWithTag(packageName, tags, type, includePrerelease, skip, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with version range.
/// Name: no wildcard support
/// Version: supports wildcards
/// Examples: Search "PowerShellGet" "[3.0.0.0, 5.0.0.0]"
/// Search "PowerShellGet" "3.*"
/// API Call: http://www.powershellgallery.com/api/v2/FindPackagesById()?id='PowerShellGet'
/// Implementation note: Returns all versions, including prerelease ones. Later (in the API client side) we'll do filtering on the versions to satisfy what user provided.
/// </summary>
public override FindResults FindVersionGlobbing(string packageName, VersionRange versionRange, bool includePrerelease, ResourceType type, bool getOnlyLatest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindVersionGlobbing()");
List<string> responses = new List<string>();
int skip = 0;
var initialResponse = FindVersionGlobbing(packageName, versionRange, includePrerelease, type, skip, getOnlyLatest, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int initialCount = GetCountFromResponse(initialResponse, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (initialCount == 0)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(initialResponse);
if (!getOnlyLatest)
{
int count = (int)Math.Ceiling((double)(initialCount / 100));
while (count > 0)
{
_cmdletPassedIn.WriteDebug($"Count is '{count}'");
// skip 100
skip += 100;
var tmpResponse = FindVersionGlobbing(packageName, versionRange, includePrerelease, type, skip, getOnlyLatest, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
responses.Add(tmpResponse);
count--;
}
}
return new FindResults(stringResponse: responses.ToArray(), hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5"
/// API call: http://www.powershellgallery.com/api/v2/Packages(Id='PowerShellGet', Version='2.2.5')
/// </summary>
public override FindResults FindVersion(string packageName, string version, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindVersion()");
// https://www.powershellgallery.com/api/v2/FindPackagesById()?id='blah'&includePrerelease=false&$filter= NormalizedVersion eq '1.1.0' and substringof('PSModule', Tags) eq true
// Quotations around package name and version do not matter, same metadata gets returned.
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id',
// however filtering on 'and Title eq '<packageName>' returns "Response status code does not indicate success: 500".
if (!_isJFrogRepo) {
filterBuilder.AddCriterion($"Id eq '{packageName}'");
}
filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'");
if (type != ResourceType.None) {
filterBuilder.AddCriterion(GetTypeFilterForRequest(type));
}
var requestUrlV2 = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrlV2, out errRecord);
if (errRecord != null)
{
// usually this is for errors in calling the V2 server, but for ADO V2 this error will include package not found errors which we want to deliver with a standard message
if (_isADORepo && errRecord.Exception is ResourceNotFoundException)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}' and version '{version}' could not be found in repository '{Repository.Name}'. For ADO feed, if the package is in an upstream feed make sure you are authenticated to the upstream feed.", errRecord.Exception),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
response = string.Empty;
}
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = GetCountFromResponse(response, out errRecord);
_cmdletPassedIn.WriteDebug($"Count from response is '{count}'");
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (count == 0)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}', version '{version}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
response = string.Empty;
}
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version and tag.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5" -Tag "Provider"
/// </summary>
public override FindResults FindVersionWithTag(string packageName, string version, string[] tags, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindVersionWithTag()");
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "id", $"'{packageName}'" },
});
var filterBuilder = queryBuilder.FilterBuilder;
// We need to explicitly add 'Id eq <packageName>' whenever $filter is used, otherwise arbitrary results are returned.
// If it's a JFrog repository do not include the Id filter portion since JFrog uses 'Title' instead of 'Id',
// however filtering on 'and Title eq '<packageName>' returns "Response status code does not indicate success: 500".
if (!_isJFrogRepo) {
filterBuilder.AddCriterion($"Id eq '{packageName}'");
}
filterBuilder.AddCriterion($"NormalizedVersion eq '{version}'");
if (type != ResourceType.None) {
filterBuilder.AddCriterion(GetTypeFilterForRequest(type));
}
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrlV2 = $"{Repository.Uri}/FindPackagesById()?{queryBuilder.BuildQueryString()}";
string response = HttpRequestCall(requestUrlV2, out errRecord);
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
int count = GetCountFromResponse(response, out errRecord);
_cmdletPassedIn.WriteDebug($"Count from response is '{count}'");
if (errRecord != null)
{
return new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
if (count == 0)
{
errRecord = new ErrorRecord(
new ResourceNotFoundException($"Package with name '{packageName}', version '{version}' and tags '{String.Join(", ", tags)}' could not be found in repository '{Repository.Name}'."),
"PackageNotFound",
ErrorCategory.ObjectNotFound,
this);
response = string.Empty;
}
return new FindResults(stringResponse: new string[] { response }, hashtableResponse: emptyHashResponses, responseType: v2FindResponseType);
}
/** 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)
{
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;
}
/// <summary>
/// Helper method that makes the HTTP request for the V2 server protocol url passed in for find APIs.
/// </summary>
private string HttpRequestCall(string requestUrlV2, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::HttpRequestCall()");
errRecord = null;
string response = string.Empty;
try
{
_cmdletPassedIn.WriteDebug($"Request url is '{requestUrlV2}'");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrlV2);
response = SendV2RequestAsync(request, _sessionClient).GetAwaiter().GetResult();
}
catch (ResourceNotFoundException e)
{
errRecord = new ErrorRecord(
exception: e,
"ResourceNotFound",
ErrorCategory.InvalidResult,
this);
}
catch (UnauthorizedException e)
{
errRecord = new ErrorRecord(
exception: e,
"UnauthorizedRequest",
ErrorCategory.InvalidResult,
this);
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.ConnectionError,
this);
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.ConnectionError,
this);
}
if (string.IsNullOrEmpty(response))
{
_cmdletPassedIn.WriteDebug("Response is empty");
}
return response;
}
/// <summary>
/// Helper method that makes the HTTP request for the V2 server protocol url passed in for install APIs.
/// </summary>
private HttpContent HttpRequestCallForContent(string requestUrlV2, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::HttpRequestCallForContent()");
errRecord = null;
HttpContent content = null;
try
{
_cmdletPassedIn.WriteDebug($"Request url is '{requestUrlV2}'");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrlV2);
content = SendV2RequestForContentAsync(request, _sessionClient).GetAwaiter().GetResult();
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.ConnectionError,
this);
}
catch (ArgumentNullException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.InvalidData,
this);
}
catch (InvalidOperationException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestFailure",
ErrorCategory.InvalidOperation,
this);
}
if (content == null || string.IsNullOrEmpty(content.ToString()))
{
_cmdletPassedIn.WriteDebug("Response is empty");
}
return content;
}
#endregion
#region Private Methods
/// <summary>
/// Helper method for string[] FindAll(string, PSRepositoryInfo, bool, bool, ResourceType, out string)
/// </summary>
private string FindAllFromTypeEndPoint(bool includePrerelease, bool isSearchingModule, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindAllFromTypeEndPoint()");
string typeEndpoint = _isPSGalleryRepo && !isSearchingModule ? "/items/psscript" : String.Empty;
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString()},
{ "$top", "6000"}
});
var filterBuilder = queryBuilder.FilterBuilder;
if (_isPSGalleryRepo) {
queryBuilder.AdditionalParameters["$orderby"] = "Id desc";
}
// JFrog/Artifactory requires an empty search term to enumerate all packages in the feed
if (_isJFrogRepo) {
queryBuilder.SearchTerm = "''";
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
// note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly
filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true");
} else {
// note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsLatestVersion correctly
filterBuilder.AddCriterion("IsLatestVersion eq true");
}
}
else {
// For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
} else {
filterBuilder.AddCriterion("IsLatestVersion");
}
}
var requestUrlV2 = $"{Repository.Uri}{typeEndpoint}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrlV2, out errRecord);
}
/// <summary>
/// Helper method for string[] FindTag(string, PSRepositoryInfo, bool, bool, ResourceType, out string)
/// </summary>
private string FindTagFromEndpoint(string[] tags, bool includePrerelease, bool isSearchingModule, int skip, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In V2ServerAPICalls::FindTagFromEndpoint()");
// scenarios with type + tags:
// type: None -> search both endpoints
// type: M -> just search Module endpoint
// type: S -> just search Scripts end point
// type: DSCResource -> just search Modules
// type: Command -> just search Modules
string typeEndpoint = _isPSGalleryRepo && !isSearchingModule ? "/items/psscript" : String.Empty;
var queryBuilder = new NuGetV2QueryBuilder(new Dictionary<string, string>{
{ "$inlinecount", "allpages" },
{ "$skip", skip.ToString()},
{ "$top", "6000"}
});
var filterBuilder = queryBuilder.FilterBuilder;
if (_isPSGalleryRepo) {
queryBuilder.AdditionalParameters["$orderby"] = "Id desc";
}
if (includePrerelease) {
queryBuilder.AdditionalParameters["includePrerelease"] = "true";
if (_isJFrogRepo) {
// note: we add 'eq true' because some PMPs (currently we know of JFrog, but others may do this too) will proxy the query unedited to the upstream remote and if that's PSGallery, it doesn't handle IsAbsoluteLatestVersion correctly
filterBuilder.AddCriterion("IsAbsoluteLatestVersion eq true");
}
else {
// For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only
filterBuilder.AddCriterion("IsAbsoluteLatestVersion");
}
} else {
if (_isJFrogRepo) {
filterBuilder.AddCriterion("IsLatestVersion eq true");
}
else {
// For ADO, 'IsLatestVersion eq true' and 'IsAbsoluteLatestVersion eq true' in the filter create a bad request error, so we use 'IsLatestVersion' or 'IsAbsoluteLatestVersion' only
filterBuilder.AddCriterion("IsLatestVersion");
}
}
filterBuilder.AddCriterion($"substringof('PS{(isSearchingModule ? "Module" : "Script")}', Tags) eq true");
foreach (string tag in tags)
{
filterBuilder.AddCriterion($"substringof('{tag}', Tags) eq true");
}
var requestUrlV2 = $"{Repository.Uri}{typeEndpoint}/Search()?{queryBuilder.BuildQueryString()}";
return HttpRequestCall(requestUrlV2: requestUrlV2, out errRecord);
}
/// <summary>