3 Commits

Author SHA1 Message Date
qhy040404
98ae857c60 revert to registry 2023-12-28 20:40:37 +08:00
qhy040404
738fe060bc code style 2023-12-28 20:34:23 +08:00
qhy040404
d3f8500ebe webview2 2023-12-28 20:06:36 +08:00
9 changed files with 184 additions and 110 deletions

View File

@@ -18,6 +18,9 @@ jobs:
with:
dotnet-version: '8.x'
- name: Build Tool
run: dotnet publish src/Snap.Hutao.Deployment/Snap.Hutao.Deployment.csproj
- name: Pack
run: dotnet pack src/Snap.Hutao.Deployment.Runtime/Snap.Hutao.Deployment.Runtime.csproj

View File

@@ -2,7 +2,7 @@
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>Snap.Hutao.Deployment.Runtime</id>
<version>1.14.0</version>
<version>1.9.0</version>
<authors>DGP Studio</authors>
<developmentDependency>true</developmentDependency>
<requireLicenseAcceptance>false</requireLicenseAcceptance>

View File

@@ -0,0 +1,95 @@
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Snap.Hutao.Deployment;
internal static partial class EdgeWebView2Dependency
{
private const string EdgeWebView2DownloadUrl = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
private const string EdgeWebView2PerUserPath = @"HKEY_CURRENT_USER\Software\Microsoft\EdgeUpdate\Clients";
private const string EdgeWebView2PerMachinePath = @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients";
private const string EdgeWebView2GuidKey = "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";
public static async Task EnsureAsync(bool installWebView2, bool isUpdateMode)
{
if (!installWebView2 || isUpdateMode)
{
return;
}
if (Registry.GetValue(EdgeWebView2PerUserPath, EdgeWebView2GuidKey, null) is not null || Registry.GetValue(EdgeWebView2PerMachinePath, EdgeWebView2GuidKey, null) is not null)
{
Console.WriteLine("WebView2 already installed.");
return;
}
Console.WriteLine("WebView2 not found, start downloading and installing WebView2...");
await DownloadWebView2InstallerAndInstallAsync().ConfigureAwait(false);
}
private static async Task DownloadWebView2InstallerAndInstallAsync()
{
string webView2InstallerPath = Path.Combine(Path.GetTempPath(), "MicrosoftEdgeWebview2Setup.exe");
try
{
using (HttpClient httpClient = new())
{
HttpShardCopyWorkerOptions<DownloadStatus> options = new()
{
HttpClient = httpClient,
SourceUrl = EdgeWebView2DownloadUrl,
DestinationFilePath = webView2InstallerPath,
StatusFactory = (bytesRead, totalBytes) => new DownloadStatus(bytesRead, totalBytes),
};
using (HttpShardCopyWorker<DownloadStatus> worker = await HttpShardCopyWorker<DownloadStatus>.CreateAsync(options).ConfigureAwait(false))
{
Progress<DownloadStatus> progress = new(ConsoleWriteProgress);
await worker.CopyAsync(progress).ConfigureAwait(false);
}
}
Console.WriteLine("Start installing WebView2...");
Process installerProcess = new()
{
StartInfo = new()
{
Arguments = "/silent /install",
FileName = webView2InstallerPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
},
};
using (installerProcess)
{
installerProcess.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
installerProcess.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data);
installerProcess.Start();
Console.WriteLine("-----> WebView2 Output begin -----");
installerProcess.BeginOutputReadLine();
installerProcess.BeginErrorReadLine();
await installerProcess.WaitForExitAsync().ConfigureAwait(false);
Console.WriteLine("<----- WebView2 Output end -------");
}
}
finally
{
if (File.Exists(webView2InstallerPath))
{
File.Delete(webView2InstallerPath);
}
}
static void ConsoleWriteProgress(DownloadStatus status)
{
Console.Write($"\r{status.ProgressDescription}");
}
}
}

View File

@@ -15,6 +15,7 @@ internal static partial class Invocation
string? path = context.ParseResult.GetValueForOption(InvocationOptions.PackagePath);
string? name = context.ParseResult.GetValueForOption(InvocationOptions.FamilyName);
bool isUpdateMode = context.ParseResult.GetValueForOption(InvocationOptions.UpdateBehavior);
bool installWebView2 = context.ParseResult.GetValueForOption(InvocationOptions.InstallWebView2);
if (!isUpdateMode)
{
@@ -24,7 +25,6 @@ internal static partial class Invocation
ArgumentException.ThrowIfNullOrEmpty(path);
Console.WriteLine($"""
Snap Hutao Deployment Tool [1.14.0]
PackagePath: {path}
FamilyName: {name}
------------------------------------------------------------
@@ -46,11 +46,78 @@ internal static partial class Invocation
}
}
await Certificate.EnsureGlobalSignCodeSigningRootR45Async().ConfigureAwait(false);
await WindowsAppSDKDependency.EnsureAsync(path).ConfigureAwait(false);
await EdgeWebView2Dependency.EnsureAsync(installWebView2, isUpdateMode).ConfigureAwait(false);
await RunDeploymentCoreAsync(path, name, isUpdateMode).ConfigureAwait(false);
await ExitAsync(isUpdateMode).ConfigureAwait(false);
}
private static async Task RunDeploymentCoreAsync(string path, string? name, bool isUpdateMode)
{
try
{
await Certificate.EnsureGlobalSignCodeSigningRootR45Async().ConfigureAwait(false);
await WindowsAppSDKDependency.EnsureAsync(path).ConfigureAwait(false);
await RunDeploymentCoreAsync(path, name, isUpdateMode).ConfigureAwait(false);
Console.WriteLine("Initializing PackageManager...");
PackageManager packageManager = new();
AddPackageOptions addPackageOptions = new()
{
ForceAppShutdown = true,
RetainFilesOnFailure = true,
};
Console.WriteLine("Start deploying...");
IProgress<DeploymentProgress> progress = new Progress<DeploymentProgress>(p =>
{
Console.WriteLine($"[Deploying]: State: {p.state} Progress: {p.percentage}%");
});
DeploymentResult result = await packageManager
.AddPackageByUriAsync(new Uri(path), addPackageOptions)
.AsTask(progress)
.ConfigureAwait(false);
if (result.IsRegistered)
{
Console.WriteLine("Package deployed.");
if (string.IsNullOrEmpty(name))
{
Console.WriteLine("FamilyName not provided, enumerating packages.");
foreach (Windows.ApplicationModel.Package package in packageManager.FindPackages())
{
try
{
if (package is { DisplayName: "Snap Hutao", PublisherDisplayName: "DGP Studio" })
{
name = package.Id.FamilyName;
Console.WriteLine($"Package found: {name}");
}
}
catch (COMException ex)
{
// ERROR_MRM_MAP_NOT_FOUND or ERROR_NOT_FOUND
if (ex.HResult is not unchecked((int)0x80073B1F) or unchecked((int)0x80070490))
{
throw;
}
}
}
}
Console.WriteLine("Starting app...");
Process.Start(new ProcessStartInfo()
{
UseShellExecute = true,
FileName = $@"shell:AppsFolder\{name}!App",
});
}
else
{
Console.WriteLine($"""
ActivityId: {result.ActivityId}
ExtendedErrorCode: {result.ExtendedErrorCode}
ErrorText: {result.ErrorText}
""");
}
}
catch (Exception ex)
{
@@ -59,86 +126,14 @@ internal static partial class Invocation
{ex}
""");
}
finally
{
await ExitAsync(isUpdateMode).ConfigureAwait(false);
}
}
private static async Task RunDeploymentCoreAsync(string path, string? name, bool isUpdateMode)
{
Console.WriteLine("Initializing PackageManager...");
PackageManager packageManager = new();
AddPackageOptions addPackageOptions = new()
{
ForceAppShutdown = true,
RetainFilesOnFailure = true,
};
Console.WriteLine("Start deploying...");
IProgress<DeploymentProgress> progress = new Progress<DeploymentProgress>(p =>
{
Console.WriteLine($"[Deploying]: State: {p.state} Progress: {p.percentage}%");
});
DeploymentResult result = await packageManager
.AddPackageByUriAsync(new Uri(path), addPackageOptions)
.AsTask(progress)
.ConfigureAwait(false);
if (result.IsRegistered)
{
Console.WriteLine("Package deployed.");
if (string.IsNullOrEmpty(name))
{
Console.WriteLine("FamilyName not provided, enumerating packages.");
foreach (Windows.ApplicationModel.Package package in packageManager.FindPackages())
{
try
{
if (package is { DisplayName: "Snap Hutao", PublisherDisplayName: "DGP Studio" })
{
name = package.Id.FamilyName;
Console.WriteLine($"Package found: {name}");
}
}
catch (COMException ex)
{
// ERROR_MRM_MAP_NOT_FOUND or ERROR_NOT_FOUND
if (ex.HResult is not (unchecked((int)0x80073B1F) or unchecked((int)0x80070490)))
{
throw;
}
}
}
}
Console.WriteLine("Starting app...");
Process.Start(new ProcessStartInfo()
{
UseShellExecute = true,
FileName = $@"shell:AppsFolder\{name}!App",
});
}
else
{
Console.WriteLine($"""
ActivityId: {result.ActivityId}
ExtendedErrorCode: {result.ExtendedErrorCode}
ErrorText: {result.ErrorText}
""");
}
}
private static async ValueTask ExitAsync(bool isUpdateMode)
{
if (!isUpdateMode)
{
Console.WriteLine("Press enter to exit...");
while (Console.ReadKey(true).Key != ConsoleKey.Enter)
{
//Pending enter key
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
FreeConsole();
}
else

View File

@@ -19,4 +19,9 @@ internal static class InvocationOptions
"--update-behavior",
() => false,
"Change behavior of the tool into update mode");
public static readonly Option<bool> InstallWebView2 = new(
"--install-webview2",
() => false,
"Install WebView2 if not found.");
}

View File

@@ -16,6 +16,7 @@ internal static partial class Program
root.AddOption(InvocationOptions.PackagePath);
root.AddOption(InvocationOptions.FamilyName);
root.AddOption(InvocationOptions.UpdateBehavior);
root.AddOption(InvocationOptions.InstallWebView2);
root.SetHandler(Invocation.RunDeploymentAsync);

View File

@@ -21,7 +21,6 @@
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.ServiceProcess;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Management.Deployment;
@@ -29,7 +25,7 @@ internal static partial class WindowsAppSDKDependency
return;
}
if (await CheckRuntimeInstalledAndVerifyAsync(packageName, msixVersion).ConfigureAwait(false))
if (CheckRuntimeInstalled(packageName, msixVersion))
{
return;
}
@@ -67,21 +63,19 @@ internal static partial class WindowsAppSDKDependency
return string.Empty;
}
private static async Task<bool> CheckRuntimeInstalledAndVerifyAsync(string packageName, string msixVersion)
private static bool CheckRuntimeInstalled(string packageName, string msixVersion)
{
Version msixMinVersion = new(msixVersion);
List<bool> results = [];
foreach (Windows.ApplicationModel.Package installed in new PackageManager().FindPackages())
{
if (installed.Id.Name == packageName && installed.Id.Version.ToVersion() >= msixMinVersion)
{
results.Add(await installed.VerifyContentIntegrityAsync());
return true;
}
}
return results.Count > 0 && results.Aggregate((result, element) => result || element);
return false;
}
private static async Task DownloadWindowsAppRuntimeInstallAndInstallAsync(string version)
@@ -106,23 +100,6 @@ internal static partial class WindowsAppSDKDependency
}
}
ServiceController serviceController = new("appxsvc");
if (serviceController.CanStop)
{
Console.WriteLine("Stopping AppxSvc...");
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
if (serviceController.Status is not ServiceControllerStatus.Stopped)
{
Console.WriteLine("Can not stop AppxSvc, timeout...");
}
}
else
{
Console.WriteLine("Can not stop AppxSvc, disallowed...");
}
Console.WriteLine("Start installing SDK...");
Process installerProcess = new()
{
@@ -139,13 +116,12 @@ internal static partial class WindowsAppSDKDependency
installerProcess.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
installerProcess.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data);
installerProcess.Start();
Console.WriteLine("-----> WindowsAppRuntimeInstall Output begin");
Console.WriteLine("-----> WindowsAppRuntimeInstall Output begin -----");
installerProcess.BeginOutputReadLine();
installerProcess.BeginErrorReadLine();
await installerProcess.WaitForExitAsync().ConfigureAwait(false);
Marshal.ThrowExceptionForHR(installerProcess.ExitCode);
Console.WriteLine("<----- WindowsAppRuntimeInstall Output end");
Console.WriteLine("<----- WindowsAppRuntimeInstall Output end -------");
}
}
finally