198 lines
7.4 KiB
Rust
198 lines
7.4 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>,
|
|
pub status: String, // "idle", "pending", "installing", "success", "error"
|
|
pub progress: f32,
|
|
}
|
|
|
|
#[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 fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
|
|
emit_log(handle, "Check Environment", "Initializing system components...", "info");
|
|
|
|
let setup_script = r#"
|
|
# 设置容错
|
|
$ErrorActionPreference = 'SilentlyContinue'
|
|
|
|
Write-Output "Step 1: Enabling TLS 1.2"
|
|
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
|
|
|
Write-Output "Step 2: Forcing load of PackageManagement"
|
|
Import-Module PackageManagement -ErrorAction SilentlyContinue
|
|
Import-Module PowerShellGet -ErrorAction SilentlyContinue
|
|
|
|
Write-Output "Step 3: Checking NuGet provider"
|
|
$provider = Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue
|
|
if ($null -eq $provider) {
|
|
Write-Output "Installing NuGet provider..."
|
|
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false -ErrorAction SilentlyContinue
|
|
}
|
|
|
|
Write-Output "Step 4: Configuring Repository Trust"
|
|
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted -ErrorAction SilentlyContinue
|
|
|
|
Write-Output "Step 5: Setting Execution Policy"
|
|
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force -ErrorAction SilentlyContinue
|
|
|
|
Write-Output "Step 6: Checking Microsoft.WinGet.Client"
|
|
if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client)) {
|
|
Write-Output "Installing Winget Client module (this may take 1-2 minutes)..."
|
|
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
|
|
} else {
|
|
Write-Output "Winget Client module is already present."
|
|
}
|
|
"#;
|
|
|
|
let output = Command::new("powershell")
|
|
.args(["-NoProfile", "-Command", setup_script])
|
|
.creation_flags(0x08000000)
|
|
.output();
|
|
|
|
match output {
|
|
Ok(out) => {
|
|
let msg = String::from_utf8_lossy(&out.stdout).to_string();
|
|
let err = String::from_utf8_lossy(&out.stderr).to_string();
|
|
// 只要最终模块存在,就认为成功,忽略过程中的次要警告
|
|
let check_final = Command::new("powershell")
|
|
.args(["-NoProfile", "-Command", "Get-Module -ListAvailable Microsoft.WinGet.Client"])
|
|
.creation_flags(0x08000000)
|
|
.output();
|
|
|
|
let is_success = check_final.map(|o| !o.stdout.is_empty()).unwrap_or(false);
|
|
|
|
if is_success {
|
|
emit_log(handle, "Environment Setup", "Winget module is ready.", "success");
|
|
Ok(())
|
|
} else {
|
|
emit_log(handle, "Environment Setup Error", &format!("OUT: {}\nERR: {}", msg, err), "error");
|
|
Err("Setup verification failed".to_string())
|
|
}
|
|
},
|
|
Err(e) => {
|
|
emit_log(handle, "Environment Setup Fatal", &e.to_string(), "error");
|
|
Err(e.to_string())
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn list_all_software(handle: &AppHandle) -> Vec<Software> {
|
|
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, "Get All Software", script)
|
|
}
|
|
|
|
pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
|
|
let script = r#"
|
|
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
$ErrorActionPreference = 'SilentlyContinue'
|
|
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
|
|
$pkgs = Get-WinGetPackage -ErrorAction SilentlyContinue | Where-Object { $_.IsUpdateAvailable }
|
|
if ($pkgs) {
|
|
$pkgs | ForEach-Object {
|
|
[PSCustomObject]@{
|
|
Name = [string]$_.Name;
|
|
Id = [string]$_.Id;
|
|
InstalledVersion = [string]$_.InstalledVersion;
|
|
AvailableVersions = $_.AvailableVersions
|
|
}
|
|
} | ConvertTo-Json -Compress
|
|
} else {
|
|
"[]"
|
|
}
|
|
"#;
|
|
|
|
execute_powershell(handle, "Get Updates", script)
|
|
}
|
|
|
|
fn execute_powershell(handle: &AppHandle, cmd_name: &str, script: &str) -> Vec<Software> {
|
|
emit_log(handle, cmd_name, "Executing PowerShell script...", "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, &format!("{} stderr", cmd_name), &stderr, "error");
|
|
}
|
|
|
|
if clean_json.is_empty() || clean_json == "[]" {
|
|
emit_log(handle, cmd_name, "No data returned from PowerShell.", "info");
|
|
return vec![];
|
|
}
|
|
|
|
let result = parse_json_output(clean_json.to_string());
|
|
emit_log(handle, cmd_name, &format!("Success: found {} items", result.len()), "success");
|
|
result
|
|
},
|
|
Err(e) => {
|
|
emit_log(handle, cmd_name, &format!("Execution error: {}", e), "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: None,
|
|
status: "idle".to_string(),
|
|
progress: 0.0,
|
|
}
|
|
}
|