-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathAppxModuleHelper.cs
566 lines (497 loc) · 23.5 KB
/
AppxModuleHelper.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
// -----------------------------------------------------------------------------
// <copyright file="AppxModuleHelper.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. Licensed under the MIT License.
// </copyright>
// -----------------------------------------------------------------------------
namespace Microsoft.WinGet.Client.Engine.Helpers
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.WinGet.Client.Engine.Common;
using Microsoft.WinGet.Client.Engine.Extensions;
using Microsoft.WinGet.Common.Command;
using Octokit;
using Semver;
using static Microsoft.WinGet.Client.Engine.Common.Constants;
/// <summary>
/// Helper to make calls to the Appx module.
/// </summary>
internal class AppxModuleHelper
{
// Cmdlets
private const string ImportModule = "Import-Module";
private const string GetAppxPackage = "Get-AppxPackage";
private const string AddAppxPackage = "Add-AppxPackage";
private const string AddAppxProvisionedPackage = "Add-AppxProvisionedPackage";
private const string GetCommand = "Get-Command";
// Parameters name
private const string Name = "Name";
private const string Path = "Path";
private const string ErrorAction = "ErrorAction";
private const string WarningAction = "WarningAction";
private const string PackagePath = "PackagePath";
private const string LicensePath = "LicensePath";
private const string Module = "Module";
private const string StubPackageOption = "StubPackageOption";
// Parameter Values
private const string Appx = "Appx";
private const string Stop = "Stop";
private const string SilentlyContinue = "SilentlyContinue";
private const string Online = "Online";
private const string UsePreference = "UsePreference";
// Options
private const string UseWindowsPowerShell = "UseWindowsPowerShell";
private const string ForceUpdateFromAnyVersion = "ForceUpdateFromAnyVersion";
private const string Register = "Register";
private const string DisableDevelopmentMode = "DisableDevelopmentMode";
private const string ForceTargetApplicationShutdown = "ForceTargetApplicationShutdown";
private const string AppInstallerName = "Microsoft.DesktopAppInstaller";
private const string AppxManifest = "AppxManifest.xml";
private const string PackageFullName = "PackageFullName";
// Assets
private const string MsixBundleName = "Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle";
private const string License = "License1.xml";
// Dependencies
// VCLibs
private const string VCLibsUWPDesktop = "Microsoft.VCLibs.140.00.UWPDesktop";
private const string VCLibsUWPDesktopVersion = "14.0.30704.0";
private const string VCLibsUWPDesktopX64 = "https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx";
private const string VCLibsUWPDesktopX86 = "https://aka.ms/Microsoft.VCLibs.x86.14.00.Desktop.appx";
private const string VCLibsUWPDesktopArm = "https://aka.ms/Microsoft.VCLibs.arm.14.00.Desktop.appx";
private const string VCLibsUWPDesktopArm64 = "https://aka.ms/Microsoft.VCLibs.arm64.14.00.Desktop.appx";
// Xaml
private const string XamlPackage28 = "Microsoft.UI.Xaml.2.8";
private const string XamlReleaseTag286 = "v2.8.6";
private const string MinimumWinGetReleaseTagForXaml28 = "v1.7.10514";
private const string XamlPackage27 = "Microsoft.UI.Xaml.2.7";
private const string XamlReleaseTag273 = "v2.7.3";
private readonly PowerShellCmdlet pwshCmdlet;
private readonly HttpClientHelper httpClientHelper;
/// <summary>
/// Initializes a new instance of the <see cref="AppxModuleHelper"/> class.
/// </summary>
/// <param name="pwshCmdlet">The calling cmdlet.</param>
public AppxModuleHelper(PowerShellCmdlet pwshCmdlet)
{
this.pwshCmdlet = pwshCmdlet;
this.httpClientHelper = new HttpClientHelper();
}
/// <summary>
/// Calls Get-AppxPackage Microsoft.DesktopAppInstaller.
/// </summary>
/// <returns>Result of Get-AppxPackage.</returns>
public PSObject? GetAppInstallerObject()
{
return this.GetAppxObject(AppInstallerName);
}
/// <summary>
/// Gets the string value a property from the Get-AppxPackage object of AppInstaller.
/// </summary>
/// <param name="propertyName">Property name.</param>
/// <returns>Value, null if doesn't exist.</returns>
public string? GetAppInstallerPropertyValue(string propertyName)
{
string? result = null;
var packageObj = this.GetAppInstallerObject();
if (packageObj is not null)
{
var property = packageObj.Properties.Where(p => p.Name == propertyName).FirstOrDefault();
if (property is not null)
{
result = property.Value as string;
}
}
return result;
}
/// <summary>
/// Calls Add-AppxPackage to register with AppInstaller's AppxManifest.xml.
/// </summary>
/// <param name="releaseTag">Release tag of GitHub release.</param>
public void RegisterAppInstaller(string releaseTag)
{
// Ensure that all dependencies are present when attempting to register.
// If dependencies are missing, a provisioned package can appear to only need registration,
// but will fail to register. `InstallDependenciesAsync` checks for the packages before
// acting, so it should be mostly a no-op if they are already available.
this.InstallDependenciesAsync(releaseTag).Wait();
string? packageFullName = this.GetAppInstallerPropertyValue(PackageFullName);
if (packageFullName == null)
{
throw new ArgumentNullException(PackageFullName);
}
string appxManifestPath = System.IO.Path.Combine(
Utilities.ProgramFilesWindowsAppPath,
packageFullName,
AppxManifest);
_ = this.ExecuteAppxCmdlet(
AddAppxPackage,
new Dictionary<string, object>
{
{ Path, appxManifestPath },
},
new List<string>
{
Register,
DisableDevelopmentMode,
});
}
/// <summary>
/// Install AppInstaller's bundle from a GitHub release.
/// </summary>
/// <param name="releaseTag">Release tag of GitHub release.</param>
/// <param name="allUsers">If install for all users is needed.</param>
/// <param name="isDowngrade">Is downgrade.</param>
/// <param name="force">Force application shutdown.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task InstallFromGitHubReleaseAsync(string releaseTag, bool allUsers, bool isDowngrade, bool force)
{
await this.InstallDependenciesAsync(releaseTag);
if (isDowngrade)
{
// Add-AppxProvisionedPackage doesn't support downgrade.
await this.AddAppInstallerBundleAsync(releaseTag, true, force);
if (allUsers)
{
await this.AddProvisionPackageAsync(releaseTag);
}
}
else
{
if (allUsers)
{
await this.AddProvisionPackageAsync(releaseTag);
}
else
{
await this.AddAppInstallerBundleAsync(releaseTag, false, force);
}
}
}
/// <summary>
/// Gets the Xaml dependency package name and release tag based on the provided WinGet release tag.
/// </summary>
/// <param name="releaseTag">WinGet release tag.</param>
/// <returns>A tuple in the format of (XamlPackageName, XamlReleaseTag).</returns>
private static Tuple<string, string> GetXamlDependencyVersionInfo(string releaseTag)
{
var targetVersion = SemVersion.Parse(releaseTag, SemVersionStyles.AllowLowerV);
if (targetVersion.CompareSortOrderTo(SemVersion.Parse(MinimumWinGetReleaseTagForXaml28, SemVersionStyles.AllowLowerV)) >= 0)
{
return Tuple.Create(XamlPackage28, XamlReleaseTag286);
}
else
{
return Tuple.Create(XamlPackage27, XamlReleaseTag273);
}
}
private async Task AddProvisionPackageAsync(string releaseTag)
{
var githubClient = new GitHubClient(RepositoryOwner.Microsoft, RepositoryName.WinGetCli);
var release = await githubClient.GetReleaseAsync(releaseTag);
var bundleAsset = release.GetAsset(MsixBundleName);
using var bundleFile = new TempFile(fileName: MsixBundleName);
await this.httpClientHelper.DownloadUrlWithProgressAsync(
bundleAsset.BrowserDownloadUrl, bundleFile.FullPath, this.pwshCmdlet);
var licenseAsset = release.GetAssetEndsWith(License);
using var licenseFile = new TempFile(fileName: licenseAsset.Name);
await this.httpClientHelper.DownloadUrlWithProgressAsync(
licenseAsset.BrowserDownloadUrl, licenseFile.FullPath, this.pwshCmdlet);
try
{
this.pwshCmdlet.ExecuteInPowerShellThread(
() =>
{
var ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
ps.AddCommand(AddAppxProvisionedPackage)
.AddParameter(Online)
.AddParameter(PackagePath, bundleFile.FullPath)
.AddParameter(LicensePath, licenseFile.FullPath)
.AddParameter(ErrorAction, Stop)
.Invoke();
});
}
catch (RuntimeException e)
{
this.pwshCmdlet.Write(StreamType.Verbose, $"Failed installing bundle via Add-AppxProvisionedPackage {e}");
throw;
}
}
private async Task AddAppInstallerBundleAsync(string releaseTag, bool downgrade, bool force)
{
var options = new List<string>();
if (downgrade)
{
options.Add(ForceUpdateFromAnyVersion);
}
if (force)
{
options.Add(ForceTargetApplicationShutdown);
}
var parameters = new Dictionary<string, object>();
if (this.IsStubPackageOptionPresent())
{
parameters.Add(StubPackageOption, UsePreference);
}
try
{
var githubClient = new GitHubClient(RepositoryOwner.Microsoft, RepositoryName.WinGetCli);
var release = await githubClient.GetReleaseAsync(releaseTag);
var bundleAsset = release.GetAsset(MsixBundleName);
await this.AddAppxPackageAsUriAsync(bundleAsset.BrowserDownloadUrl, MsixBundleName, parameters, options);
}
catch (RuntimeException e)
{
this.pwshCmdlet.Write(StreamType.Verbose, $"Failed installing bundle via Add-AppxPackage {e}");
throw;
}
}
private PSObject? GetAppxObject(string packageName)
{
return this.ExecuteAppxCmdlet(
GetAppxPackage,
new Dictionary<string, object>
{
{ Name, packageName },
})
.FirstOrDefault();
}
private async Task InstallDependenciesAsync(string releaseTag)
{
// A better implementation would use Add-AppxPackage with -DependencyPath, but
// the Appx module needs to be remoted into Windows PowerShell. When the string[] parameter
// gets deserialized from Core the result is a single string which breaks Add-AppxPackage.
// Here we should: if we are in Windows Powershell then run Add-AppxPackage with -DependencyPath
// if we are in Core, then start powershell.exe and run the same command. Right now, we just
// do Add-AppxPackage for each one.
await this.InstallVCLibsDependenciesAsync();
await this.InstallUiXamlAsync(releaseTag);
}
private async Task InstallVCLibsDependenciesAsync()
{
var result = this.ExecuteAppxCmdlet(
GetAppxPackage,
new Dictionary<string, object>
{
{ Name, VCLibsUWPDesktop },
});
// See if the minimum (or greater) version is installed.
// TODO: Pull the minimum version from the target package
// TODO: This does not check architecture of the package
Version minimumVersion = new Version(VCLibsUWPDesktopVersion);
bool isInstalled = false;
if (result != null &&
result.Count > 0)
{
foreach (dynamic psobject in result)
{
string? versionString = psobject?.Version?.ToString();
if (versionString == null)
{
continue;
}
Version packageVersion = new Version(versionString);
if (packageVersion >= minimumVersion)
{
this.pwshCmdlet.Write(StreamType.Verbose, $"VCLibs dependency satisfied by: {psobject?.PackageFullName ?? "<null>"}");
isInstalled = true;
break;
}
}
}
if (!isInstalled)
{
this.pwshCmdlet.Write(StreamType.Verbose, "Couldn't find required VCLibs package");
var vcLibsDependencies = new List<string>();
var arch = RuntimeInformation.OSArchitecture;
if (arch == Architecture.X64)
{
vcLibsDependencies.Add(VCLibsUWPDesktopX64);
}
else if (arch == Architecture.X86)
{
vcLibsDependencies.Add(VCLibsUWPDesktopX86);
}
else if (arch == Architecture.Arm64)
{
// Deployment please figure out for me.
vcLibsDependencies.Add(VCLibsUWPDesktopX64);
vcLibsDependencies.Add(VCLibsUWPDesktopX86);
vcLibsDependencies.Add(VCLibsUWPDesktopArm);
vcLibsDependencies.Add(VCLibsUWPDesktopArm64);
}
else
{
throw new PSNotSupportedException(arch.ToString());
}
foreach (var vclib in vcLibsDependencies)
{
await this.AddAppxPackageAsUriAsync(vclib, vclib.Substring(vclib.LastIndexOf('/') + 1));
}
}
else
{
this.pwshCmdlet.Write(StreamType.Verbose, $"VCLibs are updated.");
}
}
private async Task InstallUiXamlAsync(string releaseTag)
{
(string xamlPackageName, string xamlReleaseTag) = GetXamlDependencyVersionInfo(releaseTag);
string xamlAssetX64 = string.Format("{0}.x64.appx", xamlPackageName);
string xamlAssetX86 = string.Format("{0}.x86.appx", xamlPackageName);
string xamlAssetArm = string.Format("{0}.arm.appx", xamlPackageName);
string xamlAssetArm64 = string.Format("{0}.arm64.appx", xamlPackageName);
var uiXamlObjs = this.GetAppxObject(xamlPackageName);
if (uiXamlObjs is null)
{
var githubRelease = new GitHubClient(RepositoryOwner.Microsoft, RepositoryName.UiXaml);
var xamlRelease = await githubRelease.GetReleaseAsync(xamlReleaseTag);
var packagesToInstall = new List<ReleaseAsset>();
var arch = RuntimeInformation.OSArchitecture;
if (arch == Architecture.X64)
{
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetX64));
}
else if (arch == Architecture.X86)
{
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetX86));
}
else if (arch == Architecture.Arm64)
{
// Deployment please figure out for me.
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetX64));
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetX86));
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetArm));
packagesToInstall.Add(xamlRelease.GetAsset(xamlAssetArm64));
}
else
{
throw new PSNotSupportedException(arch.ToString());
}
foreach (var package in packagesToInstall)
{
await this.AddAppxPackageAsUriAsync(package.BrowserDownloadUrl, package.Name);
}
}
}
private async Task AddAppxPackageAsUriAsync(string packageUri, string fileName, Dictionary<string, object>? parameters = null, IList<string>? options = null)
{
try
{
var thisParams = new Dictionary<string, object>
{
{ Path, packageUri },
{ ErrorAction, Stop },
};
if (parameters != null)
{
foreach (var param in parameters)
{
thisParams.Add(param.Key, param.Value);
}
}
_ = this.ExecuteAppxCmdlet(
AddAppxPackage,
thisParams,
options);
}
catch (RuntimeException e)
{
// If we couldn't install it via URI, try download and install.
if (e.ErrorRecord.CategoryInfo.Category == ErrorCategory.OpenError)
{
this.pwshCmdlet.Write(StreamType.Verbose, $"Failed adding package [{packageUri}]. Retrying downloading it.");
await this.DownloadPackageAndAddAsync(packageUri, fileName, options);
}
else
{
this.pwshCmdlet.Write(StreamType.Error, e.ErrorRecord);
throw;
}
}
}
private async Task DownloadPackageAndAddAsync(string packageUrl, string fileName, IList<string>? options)
{
using var tempFile = new TempFile(fileName: fileName);
await this.httpClientHelper.DownloadUrlWithProgressAsync(packageUrl, tempFile.FullPath, this.pwshCmdlet);
_ = this.ExecuteAppxCmdlet(
AddAppxPackage,
new Dictionary<string, object>
{
{ Path, tempFile.FullPath },
{ ErrorAction, Stop },
},
options);
}
private Collection<PSObject> ExecuteAppxCmdlet(string cmdlet, Dictionary<string, object>? parameters = null, IList<string>? options = null)
{
Collection<PSObject> result = new Collection<PSObject>();
this.pwshCmdlet.ExecuteInPowerShellThread(
() =>
{
var ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
// There's a bug in the Appx Module that it can't be loaded from Core in pre 10.0.22453.0 builds without
// the -UseWindowsPowerShell option. In post 10.0.22453.0 builds there's really no difference between
// using or not -UseWindowsPowerShell as it will automatically get loaded using WinPSCompatSession remoting session.
// https://github.com/PowerShell/PowerShell/issues/13138.
// Set warning action to silently continue to avoid the console with
// 'Module Appx is loaded in Windows PowerShell using WinPSCompatSession remoting session'
#if !POWERSHELL_WINDOWS
ps.AddCommand(ImportModule)
.AddParameter(Name, Appx)
.AddParameter(UseWindowsPowerShell)
.AddParameter(WarningAction, SilentlyContinue)
.AddStatement();
#endif
string cmd = cmdlet;
ps.AddCommand(cmdlet);
if (parameters != null)
{
foreach (var p in parameters)
{
cmd += $" -{p.Key} {p.Value}";
}
ps.AddParameters(parameters);
}
if (options != null)
{
foreach (var option in options)
{
cmd += $" -{option}";
ps.AddParameter(option);
}
}
this.pwshCmdlet.Write(StreamType.Verbose, $"Executing Appx cmdlet {cmd}");
result = ps.Invoke();
});
return result;
}
private bool IsStubPackageOptionPresent()
{
bool result = false;
this.pwshCmdlet.ExecuteInPowerShellThread(
() =>
{
var ps = PowerShell.Create(RunspaceMode.CurrentRunspace);
#if !POWERSHELL_WINDOWS
ps.AddCommand(ImportModule)
.AddParameter(Name, Appx)
.AddParameter(UseWindowsPowerShell)
.AddParameter(WarningAction, SilentlyContinue)
.AddStatement();
#endif
var cmdInfo = ps.AddCommand(GetCommand)
.AddParameter(Name, AddAppxPackage)
.AddParameter(Module, Appx)
.Invoke<CommandInfo>()
.FirstOrDefault();
result = cmdInfo != null && cmdInfo.Parameters.ContainsKey(StubPackageOption);
});
return result;
}
}
}