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

HaloPixelToolBox

【WinUI3】基于USB HID通讯的花再音响工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Reflection;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using HaloPixelToolBox.Backend.Core.Utilities.Helpers;
using HaloPixelToolBox.Backend.Profiles.CacheProfiles;
using HaloPixelToolBox.Backend.Profiles.CrossVersionProfiles;
using HaloPixelToolBox.Backend.Utilities;
using HaloPixelToolBox.Core.Utilities;
using Microsoft.Win32;
using XFEExtension.NetCore.FileExtension;
using XFEExtension.NetCore.WinUIHelper.Interface.Services;
using XFEExtension.NetCore.WinUIHelper.Utilities;
using XFEExtension.NetCore.WinUIHelper.Utilities.Helper;

namespace HaloPixelToolBox.Backend.ViewModels;

public partial class SettingPageViewModel : ViewModelBase, IDisposable
{
    [ObservableProperty] public partial string ServerAddress { get; set; } = SystemProfile.ServerAddress;
    [ObservableProperty] public partial string Account { get; set; } = CacheProfile.Account;
    [ObservableProperty] public partial string Password { get; set; } = CacheProfile.Password;
    [ObservableProperty] public partial string LoginStatusText { get; set; } = AdministratorSessionManager.StatusText;
    [ObservableProperty] public partial bool IsLoginBusy { get; set; } = AdministratorSessionManager.IsBusy;
    [ObservableProperty] public partial bool IsLoggedIn { get; set; } = AdministratorSessionManager.IsLoggedIn;
    [ObservableProperty] public partial bool IsAutoStartEnable { get; set; } = SystemProfile.AutoStart;
    [ObservableProperty] public partial string AppCacheDirectory { get; set; } = AppPathHelper.AppCache;
    [ObservableProperty] public partial string AppCacheSize { get; set; } = FileHelper.GetDirectorySize(new(AppPathHelper.AppCache)).FileSize();
    [ObservableProperty] public partial string AppDataDirectory { get; set; } = AppPathHelper.AppLocalData;
    [ObservableProperty] public partial string AppDataSize { get; set; } = FileHelper.GetDirectorySize(new(AppPathHelper.AppLocalData)).FileSize();
    public ISettingService SettingService { get; set; } = ServiceManager.GetService<ISettingService>();
    public IDialogService DialogService { get; set; } = ServiceManager.GetService<IDialogService>();

    public SettingPageViewModel()
    {
        AdministratorSessionManager.StateChanged += AdministratorSessionManager_StateChanged;
        _ = InitializeAdministratorSessionAsync();
    }

    private async Task InitializeAdministratorSessionAsync()
    {
        await AdministratorSessionManager.InitializeAsync();
        SynchronizeLoginState();
    }

    private void AdministratorSessionManager_StateChanged(object? sender, EventArgs e) => SynchronizeLoginState();

    public void Dispose() => AdministratorSessionManager.StateChanged -= AdministratorSessionManager_StateChanged;

    private void SynchronizeLoginState()
    {
        LoginStatusText = AdministratorSessionManager.StatusText;
        IsLoginBusy = AdministratorSessionManager.IsBusy;
        IsLoggedIn = AdministratorSessionManager.IsLoggedIn;
    }

    [RelayCommand]
    private async Task LoginAsync()
    {
        if (!TrySaveServerAddress())
            return;

        if (await AdministratorSessionManager.LoginAsync(Account, Password))
        {
            Account = CacheProfile.Account;
            Password = CacheProfile.Password;
        }

        SynchronizeLoginState();
    }

    [RelayCommand]
    private async Task ReconnectAsync()
    {
        if (!TrySaveServerAddress())
            return;

        await AdministratorSessionManager.InitializeAsync(true);
        SynchronizeLoginState();
    }

    [RelayCommand]
    private async Task LogoutAsync()
    {
        await AdministratorSessionManager.LogoutAsync();
        Password = string.Empty;
        SynchronizeLoginState();
    }

    private bool TrySaveServerAddress()
    {
        var serverAddress = ServerAddress.Trim().TrimEnd('/');
        if (!Uri.TryCreate(serverAddress, UriKind.Absolute, out var uri) ||
            (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
        {
            LoginStatusText = "服务器地址无效,请输入完整的 HTTP 或 HTTPS 地址";
            return false;
        }

        ServerAddress = serverAddress;
        SystemProfile.ServerAddress = serverAddress;
        DataManager.Configure(serverAddress);
        return true;
    }

    partial void OnIsAutoStartEnableChanged(bool value)
    {
        SystemProfile.AutoStart = value;
        SetAutoStart(value);
    }

    private static void SetAutoStart(bool enable) => SetAutoStart(enable, Assembly.GetExecutingAssembly().GetName().Name ?? "HaloPixelToolBox");

    private static void SetAutoStart(bool enable, string appName, string exePath = "")
    {
        const string runKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
        using var key = Registry.CurrentUser.OpenSubKey(runKey, true);
        if (enable)
        {
            if (exePath == string.Empty)
                exePath = Environment.ProcessPath ?? string.Empty;

            key?.SetValue(appName, $"\"{exePath}\"");
        }
        else
        {
            if (key?.GetValue(appName) != null)
            {
                key.DeleteValue(appName);
            }
        }
    }

    [RelayCommand]
    private static void OpenPath(string originalPath) => Helper.OpenPath(originalPath);

    [RelayCommand]
    private async Task ClearCache()
    {
        if (await DialogService.ShowDialog("cleanCacheContentDialog") == ContentDialogResult.Primary)
        {
            Directory.Delete(AppPathHelper.AppCache, true);
            AppCacheSize = FileHelper.GetDirectorySize(new(AppPathHelper.AppCache)).FileSize();
        }
    }
}