403 lines
15 KiB
Rust
403 lines
15 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
use base64::Engine;
|
|
use std::fs;
|
|
use std::process::Command;
|
|
use std::os::windows::process::CommandExt;
|
|
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
use tauri::{AppHandle, Manager};
|
|
use crate::services::log_service::emit_log;
|
|
|
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
pub struct RegistryValue {
|
|
pub v_type: String, // "String", "Dword", "Qword", "MultiString", "ExpandString"
|
|
pub data: serde_json::Value,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
#[serde(tag = "type")]
|
|
pub enum PostInstallStep {
|
|
#[serde(rename = "registry_batch")]
|
|
RegistryBatch {
|
|
root: String,
|
|
base_path: String,
|
|
values: HashMap<String, RegistryValue>,
|
|
delay_ms: Option<u64>,
|
|
},
|
|
#[serde(rename = "file_copy")]
|
|
FileCopy {
|
|
src: String,
|
|
dest: String,
|
|
delay_ms: Option<u64>,
|
|
},
|
|
#[serde(rename = "file_delete")]
|
|
FileDelete {
|
|
path: String,
|
|
delay_ms: Option<u64>,
|
|
},
|
|
#[serde(rename = "command")]
|
|
Command {
|
|
run: String,
|
|
delay_ms: Option<u64>,
|
|
},
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
pub struct Software {
|
|
pub id: String,
|
|
pub name: String,
|
|
pub description: Option<String>,
|
|
pub category: 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", "configuring", "success", "error"
|
|
#[serde(default = "default_progress")]
|
|
pub progress: f32,
|
|
#[serde(default = "default_false")]
|
|
pub use_manifest: bool,
|
|
pub manifest_url: Option<String>,
|
|
pub post_install: Option<Vec<PostInstallStep>>,
|
|
pub post_install_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
|
|
winget settings --enable LocalManifestFiles
|
|
"#;
|
|
|
|
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'
|
|
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;
|
|
IconUrl = $null
|
|
}
|
|
} | ConvertTo-Json -Compress
|
|
} else {
|
|
"[]"
|
|
}
|
|
"#;
|
|
|
|
execute_powershell(handle, &log_id, "Fetch Updates", script)
|
|
}
|
|
|
|
pub fn get_software_info(handle: &AppHandle, id: &str) -> Option<Software> {
|
|
let log_id = format!("get-info-{}", chrono::Local::now().timestamp_millis());
|
|
let script = format!(r#"
|
|
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
$ErrorActionPreference = 'SilentlyContinue'
|
|
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
|
|
$pkg = Get-WinGetPackage -Id "{}" -ErrorAction SilentlyContinue
|
|
if ($pkg) {{
|
|
[PSCustomObject]@{{
|
|
Name = [string]$pkg.Name;
|
|
Id = [string]$pkg.Id;
|
|
InstalledVersion = [string]$pkg.InstalledVersion;
|
|
AvailableVersions = @()
|
|
}} | ConvertTo-Json -Compress
|
|
}}
|
|
"#, id);
|
|
|
|
let res = execute_powershell(handle, &log_id, "Fetch Single Software Info", &script);
|
|
res.into_iter().next()
|
|
}
|
|
|
|
pub fn get_cached_or_extract_icon(handle: &AppHandle, id: &str, name: &str) -> Option<String> {
|
|
let cache_key = sanitize_cache_key(id);
|
|
let icon_dir = get_icon_cache_dir(handle);
|
|
let icon_path = icon_dir.join(format!("{}.png", cache_key));
|
|
|
|
if let Ok(bytes) = fs::read(&icon_path) {
|
|
return Some(format!(
|
|
"data:image/png;base64,{}",
|
|
base64::engine::general_purpose::STANDARD.encode(bytes)
|
|
));
|
|
}
|
|
|
|
let log_id = format!("icon-{}", cache_key);
|
|
emit_log(handle, &log_id, "Icon Lookup", &format!("Resolving icon for {}...", id), "info");
|
|
|
|
let script = format!(r#"
|
|
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
$ErrorActionPreference = 'SilentlyContinue'
|
|
Add-Type -AssemblyName System.Drawing
|
|
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
|
|
|
|
$packageId = @'
|
|
{id}
|
|
'@
|
|
$packageName = @'
|
|
{name}
|
|
'@
|
|
|
|
$foundPath = ""
|
|
$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
|
|
$matchedLnk = $lnkFiles | Where-Object {{ $_.BaseName -eq $packageName -or $packageName -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 {{
|
|
$foundPath = $matchedLnk.FullName
|
|
}}
|
|
}} catch {{
|
|
$foundPath = $matchedLnk.FullName
|
|
}}
|
|
}}
|
|
|
|
if (-not $foundPath) {{
|
|
$registryPaths = @(
|
|
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
|
|
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*",
|
|
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
|
|
)
|
|
$regItems = Get-ItemProperty $registryPaths
|
|
$matchedReg = $regItems | Where-Object {{ $_.DisplayName -eq $packageName -or $_.PSChildName -eq $packageId }} | 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 }}
|
|
}}
|
|
}}
|
|
}}
|
|
|
|
if ($foundPath -and (Test-Path $foundPath)) {{
|
|
try {{
|
|
$icon = [System.Drawing.Icon]::ExtractAssociatedIcon($foundPath)
|
|
if ($icon) {{
|
|
$bitmap = $icon.ToBitmap()
|
|
$ms = New-Object System.IO.MemoryStream
|
|
$bitmap.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
|
|
[Convert]::ToBase64String($ms.ToArray())
|
|
$ms.Dispose()
|
|
$bitmap.Dispose()
|
|
$icon.Dispose()
|
|
}}
|
|
}} catch {{}}
|
|
}}
|
|
"#, id = id, name = name);
|
|
|
|
let output = Command::new("powershell")
|
|
.args(["-NoProfile", "-Command", &script])
|
|
.creation_flags(0x08000000)
|
|
.output()
|
|
.ok()?;
|
|
|
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
|
let encoded = stdout.trim_start_matches('\u{feff}').trim();
|
|
if encoded.is_empty() {
|
|
return None;
|
|
}
|
|
|
|
let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).ok()?;
|
|
if fs::create_dir_all(&icon_dir).is_err() {
|
|
return Some(format!("data:image/png;base64,{}", encoded));
|
|
}
|
|
let _ = fs::write(&icon_path, &bytes);
|
|
Some(format!("data:image/png;base64,{}", encoded))
|
|
}
|
|
|
|
fn execute_powershell(handle: &AppHandle, log_id: &str, cmd_title: &str, script: &str) -> Vec<Software> {
|
|
emit_log(handle, log_id, cmd_title, "Fetching data from Winget...", "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 get_icon_cache_dir(handle: &AppHandle) -> PathBuf {
|
|
let app_data_dir = handle.path().app_data_dir().unwrap_or_default();
|
|
app_data_dir.join("icons")
|
|
}
|
|
|
|
fn sanitize_cache_key(id: &str) -> String {
|
|
id.chars()
|
|
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
|
|
.collect()
|
|
}
|
|
|
|
fn map_package(p: WingetPackage) -> Software {
|
|
Software {
|
|
id: p.id,
|
|
name: p.name,
|
|
description: None,
|
|
category: 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,
|
|
post_install: None,
|
|
post_install_url: None,
|
|
}
|
|
}
|