forked from OneGet/NuGetProvider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NugetLightRequest.cs
2115 lines (1869 loc) · 88.6 KB
/
NugetLightRequest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Security.AccessControl;
using Microsoft.PackageManagement.Internal.Utility.Platform;
namespace Microsoft.PackageManagement.NuGetProvider
{
using System;
using System.Text;
using System.Net.Http;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Resources;
using System.Security.Cryptography;
using System.Security;
using System.Runtime.InteropServices;
using System.Net;
using SemanticVersion = Microsoft.PackageManagement.Provider.Utility.SemanticVersion;
using Microsoft.PackageManagement.Provider.Utility;
using Microsoft.PackageManagement.Internal.Utility.Platform;
using System.Diagnostics;
/// <summary>
/// This class drives the Request class that is an interface exposed from the PackageManagement Platform to the provider to use.
/// </summary>
public abstract class NuGetRequest : Request
{
private static readonly Regex _regexFastPath = new Regex(@"\$(?<source>[\w,\+,\/,=]*)\\(?<id>[\w,\+,\/,=]*)\\(?<version>[\w,\+,\/,=]*)\\(?<sources>[\w,\+,\/,=]*)(\\(?<powershellget>[\w,\+,\/,=]*))?");
private static readonly byte[] _nugetBytes = Encoding.UTF8.GetBytes("NuGet");
private string _configurationFileLocation;
private XDocument _config;
internal readonly Lazy<bool> AllowPrereleaseVersions;
internal readonly Lazy<bool> AllVersions;
internal readonly Lazy<string> Contains;
internal readonly Lazy<bool> ExcludeVersion;
internal readonly Lazy<string[]> FilterOnTag;
internal readonly Lazy<string[]> Headers;
internal readonly Lazy<string> Scope;
internal readonly Lazy<PackageBase[]> InstalledPackages;
private static IDictionary<string, PackageSource> _registeredPackageSources;
private static IDictionary<string, PackageSource> _checkedUnregisteredPackageSources = new ConcurrentDictionary<string, PackageSource>();
private string _destinationPath = null;
internal Lazy<bool> SkipValidate; //??? Seems to be a design choice. Why let a user to decide?
// we cannot enable skipdepedencies because this will break downlevel psget which sets skipdependencies to true
internal Lazy<bool> SkipDependencies;
//internal ImplictLazy<bool> ContinueOnFailure;
//internal ImplictLazy<bool> FindByCanonicalId;
private HttpClient _httpClient;
private HttpClient _httpClientWithoutAcceptHeader;
private bool? _isCalledFromPowerShellGet;
private string _CredentialUsername;
private SecureString _CredentialPassword;
public HttpClient SetHttpClient (HttpClient client)
{
return _httpClient = client;
}
public override string CredentialUsername
{
get { return _CredentialUsername; }
set { _CredentialUsername = value; }
}
public override SecureString CredentialPassword
{
get { return _CredentialPassword; }
set { _CredentialPassword = value; }
}
internal const string DefaultConfig = @"<?xml version=""1.0""?>
<configuration>
<packageSources>
</packageSources>
</configuration>";
/// <summary>
/// Ctor required by the PackageManagement Platform
/// </summary>
protected NuGetRequest()
{
FilterOnTag = new Lazy<string[]>(() => (GetOptionValues("FilterOnTag") ?? new string[0]).ToArray());
Contains = new Lazy<string>(() => GetOptionValue("Contains"));
ExcludeVersion = new Lazy<bool>(() => GetOptionValue("ExcludeVersion").IsTrue());
AllowPrereleaseVersions = new Lazy<bool>(() => GetOptionValue("AllowPrereleaseVersions").IsTrue());
AllVersions = new Lazy<bool>(() => GetOptionValue("AllVersions").IsTrue());
SkipValidate = new Lazy<bool>(() => GetOptionValue("SkipValidate").IsTrue());
Scope = new Lazy<string>(() => GetOptionValue("Scope"));
SkipDependencies = new Lazy<bool>(() => GetOptionValue("SkipDependencies").IsTrue());
//ContinueOnFailure = new ImplictLazy<bool>(() => GetOptionValue("ContinueOnFailure").IsTrue());
//FindByCanonicalId = new ImplictLazy<bool>(() => GetOptionValue("FindByCanonicalId").IsTrue());
Headers = new Lazy<string[]>(() => (GetOptionValues("Headers") ?? new string[0]).ToArray());
InstalledPackages = new Lazy<PackageBase[]>(() => (GetInstalledPackagesOptionValue()).ToArray());
}
// parse the list of installed packages
private IEnumerable<PackageBase> GetInstalledPackagesOptionValue()
{
// get possible installed packages
var installedPackages = GetOptionValues("InstalledPackages") ?? new string[0];
// parse the installed package options passed in
foreach (var installedPackage in installedPackages)
{
// we assume that the name passed in is something like jquery#1.2.5
string[] nameAndVersion = installedPackage.Split(new[] { "!#!" }, StringSplitOptions.None);
var package = new PackageBase();
// only name passed in, no version
if (nameAndVersion.Count() == 1)
{
package.Id = nameAndVersion[0];
yield return package;
}
else if (nameAndVersion.Count() == 2)
{
// this means there is version
SemanticVersion semVers = null;
try
{
// convert version to semvers
semVers = new SemanticVersion(nameAndVersion[1]);
}
catch
{
// not a valid version, ignores this entry
continue;
}
// set name and version of this installed packages
package.Id = nameAndVersion[0];
package.Version = semVers.Version.ToStringSafe();
yield return package;
}
}
}
/// <summary>
/// Package sources
/// </summary>
internal string[] OriginalSources { get; set; }
/// <summary>
/// Package installation location used by get-installedpackages.
/// </summary>
internal IEnumerable<string> InstalledPath
{
get
{
var path = GetOptionValue("Destination");
if (!string.IsNullOrWhiteSpace(path))
{
yield return Path.GetFullPath(path);
}
else
{
// If a user does not specify -destination, we will look into the default locations.
yield return AllUserDefaultInstallLocation;
yield return CurrentUserDefaultInstallLocation;
}
}
}
/// <summary>
/// Package destination path
/// </summary>
internal string Destination
{
get
{
if (_destinationPath != null)
{
return _destinationPath;
}
var path = GetOptionValue("Destination");
if (!string.IsNullOrWhiteSpace(path))
{
_destinationPath = Path.GetFullPath(path);
return _destinationPath;
}
// If a user does not give -destination for the install, we put the package under $env:USERPROFILE\PackageManagement\nuget\packages folder
// or $env:programfiles\PackageManagement\NuGet\Packages\ if you are an admin.
try
{
string basePath;
var scope = (Scope == null) ? null : Scope.Value;
scope = string.IsNullOrWhiteSpace(scope) ? Constants.AllUsers : scope;
if (scope.EqualsIgnoreCase(Constants.CurrentUser))
{
// Does not matter whether elevated or not
basePath = CurrentUserDefaultInstallLocation;
}
else if (ProviderServices.IsElevated)
{
//Scope=AllUser or No Scope but elevated
basePath = AllUserDefaultInstallLocation;
}
else
{
//Scope=AllUser but not elevated
WriteError(ErrorCategory.InvalidOperation, ErrorCategory.InvalidOperation.ToString(),
Constants.Messages.InstallRequiresCurrentUserScopeParameterForNonAdminUser,
AllUserDefaultInstallLocation, CurrentUserDefaultInstallLocation);
return string.Empty;
}
if (!Directory.Exists(basePath))
{
CreateDirectoryInternal(basePath);
}
_destinationPath = basePath;
return basePath;
}
catch (Exception e)
{
e.Dump(this);
WriteError(ErrorCategory.InvalidArgument, "Destination", Constants.Messages.MissingRequiredParameter,
"Destination");
return string.Empty;
}
}
}
internal void CreateDirectoryInternal(string dirPath)
{
try
{
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
}
catch (System.UnauthorizedAccessException ex)
{
if (OSInformation.IsWindows)
{
//a user specifies 'AllUsers' that requires Admin privilege. However his console gets launched by non-elevated.
WriteError(ErrorCategory.InvalidOperation, ErrorCategory.InvalidOperation.ToString(),
Resources.Messages.InstallRequiresCurrentUserScopeParameterForNonAdminUser,
dirPath, CurrentUserDefaultInstallLocation);
}
else
{
WriteError(ErrorCategory.InvalidOperation, ErrorCategory.InvalidOperation.ToString(),
Resources.Messages.InstallRequiresCurrentUserScopeParameterForNonSudoUser,
dirPath, CurrentUserDefaultInstallLocation);
}
Verbose(ex.Message);
throw;
}
}
internal string CurrentUserDefaultInstallLocation
{
get
{
var path = Path.Combine(OSInformation.LocalAppDataDirectory, "PackageManagement", "NuGet", "Packages");
Debug("CurrentUserDefaultInstallLocation: {0}", path);
return path;
}
}
internal string AllUserDefaultInstallLocation
{
get
{
var path = Path.Combine(OSInformation.ProgramFilesDirectory, "PackageManagement", "NuGet", "Packages");
Debug("AllUserDefaultInstallLocation: {0}", path);
return path;
}
}
/// <summary>
/// Get the PackageItem object from the fast path
/// </summary>
/// <param name="fastPath"></param>
/// <returns></returns>
internal PackageItem GetPackageByFastpath(string fastPath)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "GetPackageByFastpath", fastPath);
string sourceLocation;
string id;
string version;
string[] sources;
if (TryParseFastPath(fastPath, out sourceLocation, out id, out version, out sources))
{
var source = ResolvePackageSource(sourceLocation);
if (source.IsSourceAFile)
{
return GetPackageByFilePath(sourceLocation);
}
// repository should not be null if source is not a file
if (source.Repository == null)
{
return null;
}
// Have to find package again to get possible dependencies
var pkg = source.Repository.FindPackage(new NuGetSearchContext()
{
PackageInfo = new PackageEntryInfo(id),
RequiredVersion = new SemanticVersion(version)
}, this);
// only finds the pkg if it is a file. so we don't return it here
// otherwise we make another download request
return new PackageItem
{
FastPath = fastPath,
Package = pkg,
PackageSource = source,
Sources = sources
};
}
return null;
}
/// <summary>
/// Get a package object from the package manifest file
/// </summary>
/// <param name="filePath">package manifest file path</param>
/// <param name="packageName">package Id or Name</param>
/// <returns></returns>
internal PackageItem GetPackageByFilePath(string filePath, string packageName)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "GetPackageByFilePath", filePath, packageName);
PackageBase package = null;
try
{
if (NuGetPathUtility.IsManifest(filePath))
{
//.nuspec
package = PackageUtility.ProcessNuspec(filePath);
}
else if (NuGetPathUtility.IsPackageFile(filePath))
{
//.nupkg or .zip
//The file name may contains version. ex: jQuery.2.1.1.nupkg
package = PackageUtility.DecompressFile(filePath, packageName);
}
else
{
Warning(Resources.Messages.InvalidFileExtension, filePath);
}
}
catch (Exception ex)
{
ex.Dump(this);
}
if (package == null)
{
return null;
}
var source = ResolvePackageSource(filePath);
return new PackageItem
{
FastPath = MakeFastPath(source, package.Id, package.Version),
PackageSource = source,
Package = package,
IsPackageFile = true,
FullPath = filePath,
};
}
/// <summary>
/// Get a package object from the package manifest file
/// </summary>
/// <param name="filePath">package manifest file path</param>
/// <returns></returns>
internal PackageItem GetPackageByFilePath(string filePath)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "GetPackageByFilePath", filePath);
var packageName = Path.GetFileNameWithoutExtension(filePath);
var pkgItem = GetPackageByFilePath(filePath, packageName);
return pkgItem;
}
/// <summary>
/// Unregister the package source
/// </summary>
/// <param name="id">package source id or name</param>
internal void RemovePackageSource(string id)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "RemovePackageSource", id);
var config = Config;
if (config == null)
{
return;
}
try
{
XElement configuration = config.ElementsNoNamespace("configuration").FirstOrDefault();
if (configuration == null)
{
return;
}
XElement packageSources = configuration.ElementsNoNamespace("packageSources").FirstOrDefault();
if (packageSources == null)
{
return;
}
var nodes = packageSources.Elements("add");
if (nodes == null)
{
return;
}
foreach (XElement node in nodes)
{
if (node.Attribute("key") != null && String.Equals(node.Attribute("key").Value, id, StringComparison.OrdinalIgnoreCase))
{
// remove itself
node.Remove();
Config = config;
Verbose(Resources.Messages.RemovedPackageSource, id);
break;
}
}
if (_registeredPackageSources.ContainsKey(id))
{
_registeredPackageSources.Remove(id);
}
if (_checkedUnregisteredPackageSources.ContainsKey(id))
{
_checkedUnregisteredPackageSources.Remove(id);
}
//var source = config.SelectNodes("/configuration/packageSources/add").Cast<XmlNode>().FirstOrDefault(node => String.Equals(node.Attributes["key"].Value, id, StringComparison.CurrentCultureIgnoreCase));
//if (source != null)
//{
// source.ParentNode.RemoveChild(source);
// Config = config;
// Verbose(Resources.Messages.RemovedPackageSource, id);
//}
}
catch (Exception ex)
{
ex.Dump(this);
}
}
/// <summary>
/// Register the package source
/// </summary>
/// <param name="name">package source name</param>
/// <param name="location">package source location</param>
/// <param name="isTrusted">is the source trusted</param>
/// <param name="isValidated">need validate before storing the information to config file</param>
internal void AddPackageSource(string name, string location, bool isTrusted, bool isValidated)
{
Debug(Resources.Messages.DebugInfoCallMethod, "NuGetRequest", string.Format(CultureInfo.InvariantCulture, "AddPackageSource - name= {0}, location={1}", name, location));
try
{
// here the source is already validated by the caller
var config = Config;
if (config == null)
{
return;
}
XElement source = null;
XElement packageSources = null;
// Check whether there is an existing node with the same name
var configuration = config.ElementsNoNamespace("configuration").FirstOrDefault();
if (configuration != null)
{
packageSources = configuration.ElementsNoNamespace("packageSources").FirstOrDefault();
if (packageSources != null)
{
source = packageSources.Elements("add").FirstOrDefault(node =>
node.Attribute("key") != null && String.Equals(node.Attribute("key").Value, name, StringComparison.OrdinalIgnoreCase));
}
}
else
{
// create configuration node if it does not exist
configuration = new XElement("configuration");
// add that to the config
config.Add(configuration);
}
// There is no existing node with the same name. So we have to create one.
if (source == null)
{
// if packagesources is null we have to create that too
if (packageSources == null)
{
// create packagesources node
packageSources = new XElement("packageSources");
// add that to the config
configuration.Add(packageSources);
}
// Create new source
source = new XElement("add");
// Add that to packagesource
packageSources.Add(source);
}
// Now set the source node properties
source.SetAttributeValue("key", name);
source.SetAttributeValue("value", location);
if (isValidated)
{
source.SetAttributeValue("validated", true.ToString());
}
if (isTrusted)
{
source.SetAttributeValue("trusted", true.ToString());
}
// Write back to the config file
Config = config;
// Add or set the source node from the dictionary depends on whether it was there
if (_registeredPackageSources.ContainsKey(name))
{
var packageSource = _registeredPackageSources[name];
packageSource.Name = name;
packageSource.Location = location;
packageSource.Trusted = isTrusted;
packageSource.IsRegistered = true;
packageSource.IsValidated = isValidated;
}
else
{
_registeredPackageSources.Add(name, new PackageSource
{
Request = this,
Name = name,
Location = location,
Trusted = isTrusted,
IsRegistered = true,
IsValidated = isValidated,
});
}
}
catch (Exception ex)
{
ex.Dump(this);
}
}
/// <summary>
/// Check if the package source location is valid
/// </summary>
/// <param name="location"></param>
/// <returns></returns>
internal bool ValidateSourceLocation(string location)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "ValidateSourceLocation", location);
//Handling http: or file: cases
if (Uri.IsWellFormedUriString(location, UriKind.Absolute))
{
return NuGetPathUtility.ValidateSourceUri(SupportedSchemes, new Uri(location), this);
}
try
{
//UNC or local file
if (Directory.Exists(location) || File.Exists(location))
{
return true;
}
}
catch
{
}
return false;
}
/// <summary>
/// Supported package source schemes by this provider
/// </summary>
internal static IEnumerable<string> SupportedSchemes
{
get
{
return NuGetProvider.Features[Constants.Features.SupportedSchemes];
}
}
/// <summary>
/// Return the package source object
/// </summary>
/// <param name="name">The package source name to search for</param>
/// <returns>package source object</returns>
internal PackageSource FindRegisteredSource(string name)
{
Debug(Resources.Messages.DebugInfoCallMethod3, "NuGetRequest", "FindRegisteredSource", name);
var srcs = RegisteredPackageSources;
if (srcs == null)
{
return null;
}
if (srcs.ContainsKey(name))
{
return srcs[name];
}
var src = srcs.Values.FirstOrDefault(each => LocationCloseEnoughMatch(name, each.Location));
return src;
}
/// <summary>
/// Communicate to the PackageManagement platform about the package info
/// </summary>
/// <param name="packageReferences"></param>
/// <param name="searchKey"></param>
/// <returns></returns>
internal bool YieldPackages(IEnumerable<PackageItem> packageReferences, string searchKey)
{
var foundPackage = false;
if (packageReferences == null)
{
return false;
}
Debug(Resources.Messages.Iterating, searchKey);
IEnumerable<PackageItem> packageItems = packageReferences;
int count = 0;
foreach (var pkg in packageItems)
{
foundPackage = true;
try
{
if (!YieldPackage(pkg, searchKey))
{
break;
}
count++;
}
catch (Exception e)
{
e.Dump(this);
return false;
}
}
Verbose(Resources.Messages.TotalPackageYield, count, searchKey);
Debug(Resources.Messages.CompletedIterating, searchKey);
return foundPackage;
}
private string MakeTagId(PackageItem pkg)
{
if (pkg == null || pkg.Package == null)
{
return string.Empty;
}
// the tag id will look like this zlib#1.2.8.8#Jean-loup Gailly;Mark Adler
return string.Format(CultureInfo.CurrentCulture, "{0}#{1}", pkg.Package.Id, pkg.Package.Version.ToString());
}
internal bool IsCalledFromPowerShellGet
{
get
{
// not initialized yet
if (!_isCalledFromPowerShellGet.HasValue)
{
_isCalledFromPowerShellGet = Headers.Value.Any(header => header.StartsWith("PSGalleryClientVersion=", StringComparison.OrdinalIgnoreCase));
}
return _isCalledFromPowerShellGet.Value;
}
set
{
_isCalledFromPowerShellGet = true;
}
}
/// <summary>
/// HttpClient with Accept-CharSet and Accept-Encoding Header
/// We want to reuse HttpClient
/// </summary>
internal HttpClient Client
{
get
{
if (_httpClient == null)
{
_httpClient = PathUtility.GetHttpClientHelper(CredentialUsername, CredentialPassword, WebProxy);
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "UTF-8");
// Request for gzip and deflate encoding to make the response lighter.
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip,deflate");
foreach (var header in Headers.Value)
{
// header is in the format "A=B" because OneGet doesn't support Dictionary parameters
if (!String.IsNullOrEmpty(header))
{
var headerSplit = header.Split(new string[] { "=" }, 2, StringSplitOptions.RemoveEmptyEntries);
// ignore wrong entries
if (headerSplit.Count() == 2)
{
_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(headerSplit[0], headerSplit[1]);
}
else
{
Warning(Messages.HeaderIgnored, header);
}
}
}
}
return _httpClient;
}
}
/// <summary>
/// HttpClient without any Accept header (this will only have User-Agent header)
/// </summary>
internal HttpClient ClientWithoutAcceptHeader
{
get
{
if (_httpClientWithoutAcceptHeader == null)
{
_httpClientWithoutAcceptHeader = PathUtility.GetHttpClientHelper(CredentialUsername, CredentialPassword, WebProxy);
}
return _httpClientWithoutAcceptHeader;
}
}
/// <summary>
/// Communicate to the PackageManagement platform about the package info
/// </summary>
/// <param name="pkg"></param>
/// <param name="searchKey"></param>
/// <param name="destinationPath"></param>
/// <returns></returns>
internal bool YieldPackage(PackageItem pkg, string searchKey, string destinationPath = null)
{
try
{
if (YieldSoftwareIdentity(pkg.FastPath, pkg.Package.Id, pkg.Package.Version.ToString(), "semver", pkg.Package.Summary, pkg.PackageSource.Name, searchKey, pkg.FullPath, pkg.PackageFilename) != null)
{
if (pkg.Package.DependencySetList != null)
{
//iterate thru the dependencies and add them to the software identity.
foreach (PackageDependencySet depSet in pkg.Package.DependencySetList)
{
foreach (var dep in depSet.Dependencies)
{
AddDependency(NuGetConstant.ProviderName, dep.Id, dep.DependencyVersion.ToStringSafe(), null, null);
}
}
}
// downlevel machine does not have AddTagId interface in request object so it will return null
// hence we can't check it here.
AddTagId(MakeTagId(pkg));
// if we need to report installation location, add a payload and add directory to that
if (!string.IsNullOrWhiteSpace(destinationPath))
{
string payload = AddPayload();
if (string.IsNullOrWhiteSpace(payload))
{
return false;
}
AddDirectory(payload, Path.GetFileName(destinationPath), Path.GetDirectoryName(destinationPath), null, true);
}
if (AddMetadata(pkg.FastPath, "copyright", pkg.Package.Copyright) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "description", pkg.Package.Description) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "licenseNames", pkg.Package.LicenseNames) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "requireLicenseAcceptance", pkg.Package.RequireLicenseAcceptance.ToString()) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "language", pkg.Package.Language) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "releaseNotes", pkg.Package.ReleaseNotes) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "isLatestVersion", pkg.Package.IsLatestVersion.ToString()) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "isAbsoluteLatestVersion", pkg.Package.IsAbsoluteLatestVersion.ToString()) == null)
{
return false;
}
if (pkg.Package.MinClientVersion != null && AddMetadata(pkg.FastPath, "minClientVersion", pkg.Package.MinClientVersion.ToString()) == null)
{
return false;
}
if (pkg.Package.VersionDownloadCount != -1)
{
if (AddMetadata(pkg.FastPath, "versionDownloadCount", pkg.Package.VersionDownloadCount.ToString(CultureInfo.CurrentCulture)) == null)
{
return false;
}
}
if (pkg.Package.DownloadCount != -1)
{
if (AddMetadata(pkg.FastPath, "downloadCount", pkg.Package.DownloadCount.ToString(CultureInfo.CurrentCulture)) == null)
{
return false;
}
}
if (pkg.Package.PackageSize != -1)
{
if (AddMetadata(pkg.FastPath, "packageSize", pkg.Package.PackageSize.ToString(CultureInfo.CurrentCulture)) == null)
{
return false;
}
}
if (pkg.Package.Published != null)
{
if (AddMetadata(pkg.FastPath, "published", pkg.Package.Published.ToString()) == null)
{
return false;
}
}
if (pkg.Package.Created != null)
{
if (AddMetadata(pkg.FastPath, "created", pkg.Package.Created.ToString()) == null)
{
return false;
}
}
if (pkg.Package.LastEdited != null)
{
if (AddMetadata(pkg.FastPath, "lastEdited", pkg.Package.LastEdited.ToString()) == null)
{
return false;
}
}
if (pkg.Package.LastUpdated != null)
{
if (AddMetadata(pkg.FastPath, "lastUpdated", pkg.Package.LastUpdated.ToString()) == null)
{
return false;
}
}
if (AddMetadata(pkg.FastPath, "tags", pkg.Package.Tags) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "title", pkg.Package.Title) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "developmentDependency", pkg.Package.DevelopmentDependency.ToString()) == null)
{
return false;
}
if (AddMetadata(pkg.FastPath, "FromTrustedSource", pkg.PackageSource.Trusted.ToString()) == null)
{
return false;
}
if (pkg.Package.LicenseUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.LicenseUrl.ToString()))
{
if (AddLink(pkg.Package.LicenseUrl, "license", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.ProjectUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.ProjectUrl.ToString()))
{
if (AddLink(pkg.Package.ProjectUrl, "project", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.ReportAbuseUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.ReportAbuseUrl.ToString()))
{
if (AddLink(pkg.Package.ReportAbuseUrl, "abuse", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.IconUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.IconUrl.ToString()))
{
if (AddLink(pkg.Package.IconUrl, "icon", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.GalleryDetailsUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.GalleryDetailsUrl.ToString()))
{
if (AddLink(pkg.Package.GalleryDetailsUrl, "galleryDetails", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.LicenseReportUrl != null && !String.IsNullOrWhiteSpace(pkg.Package.LicenseReportUrl.ToString()))
{
if (AddLink(pkg.Package.LicenseReportUrl, "licenseReport", null, null, null, null, null) == null)
{
return false;
}
}
if (pkg.Package.Authors.Any(author => AddEntity(author.Trim(), author.Trim(), "author", null) == null))
{
return false;
}
if (pkg.Package.Owners.Any(owner => AddEntity(owner.Trim(), owner.Trim(), "owner", null) == null))
{
return false;
}
var pkgBase = pkg.Package as PackageBase;
if (pkgBase != null)
{
if (pkgBase.AdditionalProperties != null)
{
foreach (var property in pkgBase.AdditionalProperties)
{
if (AddMetadata(pkg.FastPath, property.Key, property.Value) == null)
{
return false;
}
}
}