Files
win-softmgr/src-tauri/src/winget.rs
2026-03-30 22:31:49 -04:00

287 lines
12 KiB
Rust

use serde::{Deserialize, Serialize};
use std::process::Command;
use std::os::windows::process::CommandExt;
use tauri::AppHandle;
use crate::emit_log;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Software {
pub id: String,
pub name: String,
pub description: Option<String>,
pub version: Option<String>,
pub available_version: Option<String>,
pub icon_url: Option<String>,
#[serde(default = "default_status")]
pub status: String, // "idle", "pending", "installing", "success", "error"
#[serde(default = "default_progress")]
pub progress: f32,
#[serde(default = "default_false")]
pub use_manifest: bool,
pub manifest_url: Option<String>,
}
fn default_status() -> String { "idle".to_string() }
fn default_progress() -> f32 { 0.0 }
fn default_false() -> bool { false }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct WingetPackage {
pub id: String,
pub name: String,
pub installed_version: Option<String>,
pub available_versions: Option<Vec<String>>,
pub icon_url: Option<String>,
}
pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
emit_log(handle, "env-check", "Environment Check", "Checking system components...", "info");
// 优化后的极速检测脚本
let setup_script = r#"
# 强制指定输出编码为 UTF8 (无 BOM)
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
# 使用多种方式确认环境是否已就绪
$module = Get-Module -ListAvailable Microsoft.WinGet.Client
$command = Get-Command Get-WinGetPackage -ErrorAction SilentlyContinue
if ($module -or $command) {
Write-Output "CHECK_RESULT:READY"
exit 0
}
# 仅在确实缺失时才输出配置日志并开始安装
Write-Output "CHECK_RESULT:NEED_INSTALL"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Import-Module PackageManagement -ErrorAction SilentlyContinue
if ($null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false
}
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
winget source update --accept-source-agreements
"#;
let output = Command::new("powershell")
.args(["-NoProfile", "-Command", setup_script])
.creation_flags(0x08000000)
.output();
match output {
Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
// 清理输出字符串,移除 BOM 和换行
let clean_stdout = stdout.trim_start_matches('\u{feff}').trim();
if clean_stdout.contains("CHECK_RESULT:READY") {
emit_log(handle, "env-check", "Result", "Environment is already configured. Skipping install.", "success");
Ok(())
} else {
// 如果执行了安装路径,检查最终结果
let check_final = Command::new("powershell")
.args(["-NoProfile", "-Command", "Get-Module -ListAvailable Microsoft.WinGet.Client"])
.creation_flags(0x08000000)
.output();
if check_final.map(|o| !o.stdout.is_empty()).unwrap_or(false) {
emit_log(handle, "env-check", "Result", "Environment configured successfully.", "success");
Ok(())
} else {
emit_log(handle, "env-check", "Error", &format!("OUT: {}\nERR: {}", clean_stdout, stderr), "error");
Err("Setup verification failed".to_string())
}
}
},
Err(e) => {
emit_log(handle, "env-check", "Fatal Error", &e.to_string(), "error");
Err(e.to_string())
}
}
}
pub fn list_installed_software(handle: &AppHandle) -> Vec<Software> {
let log_id = format!("list-installed-{}", chrono::Local::now().timestamp_millis());
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
$pkgs = Get-WinGetPackage -ErrorAction SilentlyContinue
if ($pkgs) {
$pkgs | ForEach-Object {
[PSCustomObject]@{
Name = [string]$_.Name;
Id = [string]$_.Id;
InstalledVersion = [string]$_.InstalledVersion;
AvailableVersions = @()
}
} | ConvertTo-Json -Compress
} else {
"[]"
}
"#;
execute_powershell(handle, &log_id, "Fetch Installed Software", script)
}
pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
let log_id = format!("list-updates-{}", chrono::Local::now().timestamp_millis());
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
Add-Type -AssemblyName System.Drawing
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
$pkgs = Get-WinGetPackage -ErrorAction SilentlyContinue | Where-Object { $_.IsUpdateAvailable }
if ($pkgs) {
$wshShell = New-Object -ComObject WScript.Shell
# 预加载开始菜单快捷方式
$startMenuPaths = @(
"$env:ProgramData\Microsoft\Windows\Start Menu\Programs",
"$env:AppData\Microsoft\Windows\Start Menu\Programs"
)
$lnkFiles = Get-ChildItem -Path $startMenuPaths -Filter "*.lnk" -Recurse -File
# 预加载注册表项
$registryPaths = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
)
$regItems = Get-ItemProperty $registryPaths
$pkgs | ForEach-Object {
$p = $_
$iconUrl = $null
$foundPath = ""
# 策略 1: 寻找并解析开始菜单快捷方式 (去除箭头关键点)
$matchedLnk = $lnkFiles | Where-Object { $_.BaseName -eq $p.Name -or $p.Name -like "*$($_.BaseName)*" } | Select-Object -First 1
if ($matchedLnk) {
try {
# 解析快捷方式指向的真实目标
$target = $wshShell.CreateShortcut($matchedLnk.FullName).TargetPath
if ($target -and (Test-Path $target) -and $target.EndsWith(".exe")) {
$foundPath = $target
} else {
# 如果目标不可读或是 UWP 快捷方式,仍使用快捷方式文件提取
$foundPath = $matchedLnk.FullName
}
} catch {
$foundPath = $matchedLnk.FullName
}
}
# 策略 2: 注册表 DisplayIcon
if (-not $foundPath) {
$matchedReg = $regItems | Where-Object { $_.DisplayName -eq $p.Name -or $_.PSChildName -eq $p.Id } | Select-Object -First 1
if ($matchedReg.DisplayIcon) {
$foundPath = $matchedReg.DisplayIcon.Split(',')[0].Trim('"')
} elseif ($matchedReg.InstallLocation) {
$loc = $matchedReg.InstallLocation.Trim('"')
if (Test-Path $loc) {
$exe = Get-ChildItem -Path $loc -Filter "*.exe" -File | Select-Object -First 1
if ($exe) { $foundPath = $exe.FullName }
}
}
}
# 提取并转 Base64
if ($foundPath -and (Test-Path $foundPath)) {
try {
$icon = [System.Drawing.Icon]::ExtractAssociatedIcon($foundPath)
$bitmap = $icon.ToBitmap()
$ms = New-Object System.IO.MemoryStream
$bitmap.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
$base64 = [Convert]::ToBase64String($ms.ToArray())
$iconUrl = "data:image/png;base64,$base64"
$ms.Dispose(); $bitmap.Dispose(); $icon.Dispose()
} catch {}
}
[PSCustomObject]@{
Name = [string]$p.Name;
Id = [string]$p.Id;
InstalledVersion = [string]$p.InstalledVersion;
AvailableVersions = $p.AvailableVersions;
IconUrl = $iconUrl
}
} | ConvertTo-Json -Compress
} else {
"[]"
}
"#;
execute_powershell(handle, &log_id, "Fetch Updates", script)
}
fn execute_powershell(handle: &AppHandle, log_id: &str, cmd_title: &str, script: &str) -> Vec<Software> {
emit_log(handle, log_id, cmd_title, "Executing PowerShell...", "info");
let output = Command::new("powershell")
.args(["-NoProfile", "-Command", script])
.creation_flags(0x08000000)
.output();
match output {
Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let clean_json = stdout.trim_start_matches('\u{feff}').trim();
if !out.status.success() && !stderr.is_empty() {
emit_log(handle, log_id, "", &format!("STDERR: {}", stderr), "error");
}
if clean_json.is_empty() || clean_json == "[]" {
emit_log(handle, log_id, "Result", "No data returned.", "info");
return vec![];
}
let result = parse_json_output(clean_json.to_string());
emit_log(handle, log_id, "Result", &format!("Successfully parsed {} items.", result.len()), "success");
result
},
Err(e) => {
emit_log(handle, log_id, "Execution Error", &e.to_string(), "error");
vec![]
},
}
}
fn parse_json_output(json_str: String) -> Vec<Software> {
if let Ok(packages) = serde_json::from_str::<Vec<WingetPackage>>(&json_str) {
return packages.into_iter().map(map_package).collect();
}
if let Ok(package) = serde_json::from_str::<WingetPackage>(&json_str) {
return vec![map_package(package)];
}
vec![]
}
fn map_package(p: WingetPackage) -> Software {
Software {
id: p.id,
name: p.name,
description: None,
version: p.installed_version,
available_version: p.available_versions.and_then(|v| v.first().cloned()),
icon_url: p.icon_url,
status: "idle".to_string(),
progress: 0.0,
use_manifest: false,
manifest_url: None,
}
}