add logger
This commit is contained in:
@@ -12,6 +12,24 @@ struct AppState {
|
||||
install_tx: mpsc::Sender<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct LogPayload {
|
||||
pub timestamp: String,
|
||||
pub command: String,
|
||||
pub output: String,
|
||||
pub status: String, // "info", "success", "error"
|
||||
}
|
||||
|
||||
pub fn emit_log(handle: &AppHandle, command: &str, output: &str, status: &str) {
|
||||
let now = chrono::Local::now().format("%H:%M:%S").to_string();
|
||||
let _ = handle.emit("log-event", LogPayload {
|
||||
timestamp: now,
|
||||
command: command.to_string(),
|
||||
output: output.to_string(),
|
||||
status: status.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_essentials(app: AppHandle) -> Vec<Software> {
|
||||
let app_data_dir = app.path().app_data_dir().unwrap_or_default();
|
||||
@@ -28,12 +46,12 @@ fn get_essentials(app: AppHandle) -> Vec<Software> {
|
||||
description: Some("Microsoft PowerToys 是一组实用程序,供高级用户调整和简化其 Windows 10 和 11 体验。".to_string()),
|
||||
version: None,
|
||||
available_version: None,
|
||||
icon_url: Some("https://raw.githubusercontent.com/microsoft/PowerToys/main/doc/images/icons/PowerToys icon/PNG/PowerToysAppList.targetsize-48.png".to_string()),
|
||||
icon_url: Some("https://raw.githubusercontent.com/microsoft/PowerToys/master/doc/images/logo.png".to_string()),
|
||||
status: "idle".to_string(),
|
||||
progress: 0.0,
|
||||
},
|
||||
Software {
|
||||
id: "Google.Chrome.EXE".to_string(),
|
||||
id: "Google.Chrome".to_string(),
|
||||
name: "Google Chrome".to_string(),
|
||||
description: Some("Google Chrome 是一款快速、安全且免费的浏览器。".to_string()),
|
||||
version: None,
|
||||
@@ -52,13 +70,13 @@ fn get_essentials(app: AppHandle) -> Vec<Software> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_all_software() -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_all_software()).await.unwrap_or_default()
|
||||
async fn get_all_software(app: AppHandle) -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_all_software(&app)).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn get_updates() -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_updates()).await.unwrap_or_default()
|
||||
async fn get_updates(app: AppHandle) -> Vec<Software> {
|
||||
tokio::task::spawn_blocking(move || list_updates(&app)).await.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -66,6 +84,12 @@ async fn install_software(id: String, state: State<'_, AppState>) -> Result<(),
|
||||
state.install_tx.send(id).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_logs_history() -> Vec<LogPayload> {
|
||||
// 暂时返回空,后续可以考虑存储
|
||||
vec![]
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
struct InstallProgress {
|
||||
id: String,
|
||||
@@ -78,21 +102,18 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.setup(move |app| {
|
||||
let handle = app.handle().clone();
|
||||
let (tx, mut rx) = mpsc::channel::<String>(100);
|
||||
app.manage(AppState { install_tx: tx });
|
||||
|
||||
// 确保依赖项已安装 (这是一个耗时的过程,建议在异步任务中运行)
|
||||
// 环境初始化逻辑
|
||||
let init_handle = handle.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let _ = tokio::task::spawn_blocking(|| {
|
||||
let _ = ensure_winget_dependencies();
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
let _ = ensure_winget_dependencies(&init_handle);
|
||||
}).await;
|
||||
});
|
||||
|
||||
// 在 setup 闭包中初始化,此时运行时已就绪
|
||||
let (tx, mut rx) = mpsc::channel::<String>(100);
|
||||
|
||||
// 托管状态
|
||||
app.manage(AppState { install_tx: tx });
|
||||
|
||||
// 后台安装队列
|
||||
// 安装队列
|
||||
tauri::async_runtime::spawn(async move {
|
||||
while let Some(id) = rx.recv().await {
|
||||
let _ = handle.emit("install-status", InstallProgress {
|
||||
@@ -101,7 +122,10 @@ pub fn run() {
|
||||
progress: 0.5,
|
||||
});
|
||||
|
||||
emit_log(&handle, &format!("winget install --id {}", id), "Starting installation...", "info");
|
||||
|
||||
let id_for_cmd = id.clone();
|
||||
let h = handle.clone();
|
||||
let status_result = tokio::task::spawn_blocking(move || {
|
||||
let output = Command::new("winget")
|
||||
.args([
|
||||
@@ -113,8 +137,16 @@ pub fn run() {
|
||||
.output();
|
||||
|
||||
match output {
|
||||
Ok(out) if out.status.success() => "success",
|
||||
_ => "error",
|
||||
Ok(out) => {
|
||||
let msg = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
let err = String::from_utf8_lossy(&out.stderr).to_string();
|
||||
emit_log(&h, &format!("Install result for {}", id_for_cmd), &format!("OUT: {}\nERR: {}", msg, err), if out.status.success() { "success" } else { "error" });
|
||||
if out.status.success() { "success" } else { "error" }
|
||||
},
|
||||
Err(e) => {
|
||||
emit_log(&h, &format!("Install error for {}", id_for_cmd), &e.to_string(), "error");
|
||||
"error"
|
||||
},
|
||||
}
|
||||
}).await.unwrap_or("error");
|
||||
|
||||
@@ -132,7 +164,8 @@ pub fn run() {
|
||||
get_essentials,
|
||||
get_all_software,
|
||||
get_updates,
|
||||
install_software
|
||||
install_software,
|
||||
get_logs_history
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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 {
|
||||
@@ -23,30 +25,60 @@ struct WingetPackage {
|
||||
pub available_versions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
pub fn ensure_winget_dependencies() -> Result<(), String> {
|
||||
// 确保执行权限和模块存在
|
||||
pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
|
||||
emit_log(handle, "Check Environment", "Checking Winget and Microsoft.WinGet.Client...", "info");
|
||||
|
||||
let setup_script = r#"
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Write-Output "Step 1: Enabling TLS 1.2"
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
Write-Output "Step 2: Installing NuGet provider"
|
||||
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false
|
||||
|
||||
Write-Output "Step 3: Trusting PSGallery"
|
||||
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
|
||||
|
||||
Write-Output "Step 4: Setting Execution Policy"
|
||||
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
|
||||
|
||||
if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client)) {
|
||||
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser
|
||||
Write-Output "Step 5: Installing Microsoft.WinGet.Client module"
|
||||
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
|
||||
} else {
|
||||
Write-Output "Step 5: Module already installed"
|
||||
}
|
||||
"#;
|
||||
|
||||
let _ = Command::new("powershell")
|
||||
let output = Command::new("powershell")
|
||||
.args(["-NoProfile", "-Command", setup_script])
|
||||
.creation_flags(0x08000000)
|
||||
.status();
|
||||
.output();
|
||||
|
||||
Ok(())
|
||||
match output {
|
||||
Ok(out) => {
|
||||
let msg = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
let err = String::from_utf8_lossy(&out.stderr).to_string();
|
||||
if out.status.success() {
|
||||
emit_log(handle, "Environment Setup", &format!("Success: {}", msg), "success");
|
||||
Ok(())
|
||||
} else {
|
||||
emit_log(handle, "Environment Setup Error", &format!("OUT: {}\nERR: {}", msg, err), "error");
|
||||
Err(format!("Setup failed: {}", err))
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
emit_log(handle, "Environment Setup Fatal", &e.to_string(), "error");
|
||||
Err(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_all_software() -> Vec<Software> {
|
||||
// 使用更健壮的脚本获取 JSON
|
||||
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
|
||||
Import-Module Microsoft.WinGet.Client
|
||||
$pkgs = Get-WinGetPackage
|
||||
if ($pkgs) {
|
||||
$pkgs | ForEach-Object {
|
||||
@@ -62,14 +94,14 @@ pub fn list_all_software() -> Vec<Software> {
|
||||
}
|
||||
"#;
|
||||
|
||||
execute_powershell(script)
|
||||
execute_powershell(handle, "Get All Software", script)
|
||||
}
|
||||
|
||||
pub fn list_updates() -> Vec<Software> {
|
||||
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
|
||||
Import-Module Microsoft.WinGet.Client
|
||||
$pkgs = Get-WinGetPackage | Where-Object { $_.IsUpdateAvailable }
|
||||
if ($pkgs) {
|
||||
$pkgs | ForEach-Object {
|
||||
@@ -85,10 +117,12 @@ pub fn list_updates() -> Vec<Software> {
|
||||
}
|
||||
"#;
|
||||
|
||||
execute_powershell(script)
|
||||
execute_powershell(handle, "Get Updates", script)
|
||||
}
|
||||
|
||||
fn execute_powershell(script: &str) -> Vec<Software> {
|
||||
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)
|
||||
@@ -97,29 +131,37 @@ fn execute_powershell(script: &str) -> Vec<Software> {
|
||||
match output {
|
||||
Ok(out) => {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
// 移除可能存在的 UTF-8 BOM
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
let clean_json = stdout.trim_start_matches('\u{feff}').trim();
|
||||
parse_json_output(clean_json.to_string())
|
||||
|
||||
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 software found (Empty JSON)", "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![]
|
||||
},
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
// 修正:Rust 并没有 .length(),应使用 .len()
|
||||
fn parse_json_output(json_str: String) -> Vec<Software> {
|
||||
if json_str.is_empty() || json_str == "[]" {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
// 尝试解析数组
|
||||
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![]
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user