XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

#if INDEXING_SERVICE_INSTALLER
namespace XFEToolBox.Client.Installer.Utilities;
#else
namespace XFEToolBox.Client.Utilities;
#endif

public sealed record IndexingServiceInstallationResult(bool Succeeded, bool Cancelled, string Message);

/// <summary>Only the isolated service installer is elevated; the desktop client remains asInvoker.</summary>
public static class IndexingServiceInstallation
{
    public const string ServiceExecutableName = "XFEToolBox.Indexing.Service.exe";
    public const string BundleDirectoryName = "IndexingService";

    public static bool IsInstalled
    {
        get
        {
            if (!OperatingSystem.IsWindows()) return false;
            var manager = OpenSCManagerW(null, null, 1);
            if (manager == IntPtr.Zero) return false;
            try
            {
                var service = OpenServiceW(manager, "XFEToolBoxIndexing", 4);
                if (service == IntPtr.Zero) return false;
                CloseServiceHandle(service);
                return true;
            }
            finally { CloseServiceHandle(manager); }
        }
    }

    public static Task<IndexingServiceInstallationResult> InstallAsync(CancellationToken cancellationToken = default) =>
        InstallAsync(AppContext.BaseDirectory, cancellationToken);

    public static Task<IndexingServiceInstallationResult> InstallAsync(string applicationDirectory, CancellationToken cancellationToken = default) =>
        RunAsync(applicationDirectory, install: true, cancellationToken);

    public static Task<IndexingServiceInstallationResult> UninstallAsync(CancellationToken cancellationToken = default) =>
        UninstallAsync(AppContext.BaseDirectory, cancellationToken);

    public static Task<IndexingServiceInstallationResult> UninstallAsync(string applicationDirectory, CancellationToken cancellationToken = default) =>
        RunAsync(applicationDirectory, install: false, cancellationToken);

    internal static ProcessStartInfo CreateStartInfo(string applicationDirectory, bool install)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(applicationDirectory);
        var executable = Path.GetFullPath(Path.Combine(applicationDirectory, BundleDirectoryName, ServiceExecutableName));
        if (!install && !File.Exists(executable))
        {
            // Portable folders may have moved or omitted the optional bundle after installation.
            executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
                "XFEToolBox", "Services", BundleDirectoryName, ServiceExecutableName);
        }
        return new ProcessStartInfo(executable)
        {
            UseShellExecute = true,
            Verb = "runas",
            WorkingDirectory = Path.GetDirectoryName(executable)!,
            Arguments = install ? "--install" : "--uninstall",
            WindowStyle = ProcessWindowStyle.Hidden
        };
    }

    private static async Task<IndexingServiceInstallationResult> RunAsync(string applicationDirectory, bool install,
        CancellationToken cancellationToken)
    {
        if (cancellationToken.IsCancellationRequested)
            return new(false, true, "已取消索引服务操作;普通权限文件搜索仍可使用。");
        try
        {
            var startInfo = CreateStartInfo(applicationDirectory, install);
            if (!File.Exists(startInfo.FileName))
                return new(false, false, "未找到独立索引服务安装文件,请使用包含 IndexingService 目录的完整发行包。普通权限搜索不受影响。");

            // ShellExecute/UAC may wait for user input: never perform it on the WPF dispatcher.
            using var process = await Task.Run(() => Process.Start(startInfo), cancellationToken).ConfigureAwait(false);
            if (process is null)
                return new(false, false, "Windows 未能启动索引服务安装程序;已保留普通权限文件搜索。");
            // Once elevation has been accepted, let the short transactional setup finish rather than
            // killing it mid-upgrade and leaving an incomplete privileged installation.
            await process.WaitForExitAsync().ConfigureAwait(false);
            return process.ExitCode == 0
                ? new(true, false, install ? "高速文件索引服务已安装并启动。主程序继续以普通权限运行。" : "高速文件索引服务已卸载;索引缓存保留以便重新安装,普通权限搜索仍可使用。")
                : new(false, false, $"索引服务{(install ? "安装/更新" : "卸载")}失败(错误码 {process.ExitCode})。请检查服务安装日志;普通权限搜索不受影响。");
        }
        catch (Win32Exception exception) when (exception.NativeErrorCode == 1223)
        {
            return new(false, true, "已取消管理员授权;继续使用普通权限文件搜索。");
        }
        catch (OperationCanceledException)
        {
            return new(false, true, "已取消索引服务操作;继续使用普通权限文件搜索。");
        }
        catch (Exception exception) when (exception is Win32Exception or IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
        {
            return new(false, false, "索引服务操作未完成:" + exception.Message + " 普通权限搜索不受影响。");
        }
    }

    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr OpenSCManagerW(string? machine, string? database, uint access);
    [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    private static extern IntPtr OpenServiceW(IntPtr manager, string name, uint access);
    [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseServiceHandle(IntPtr handle);
}