Adiciona logs ao provisionamento RustDesk

This commit is contained in:
Esdras Renan 2025-11-11 14:47:53 -03:00
parent ddcb7ac326
commit 0120748cc5

View file

@ -1,14 +1,15 @@
#![cfg(target_os = "windows")] #![cfg(target_os = "windows")]
use crate::RustdeskProvisioningResult; use crate::RustdeskProvisioningResult;
use chrono::Local;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use reqwest::blocking::Client; use reqwest::blocking::Client;
use serde::Deserialize; use serde::Deserialize;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::env; use std::env;
use std::fs::{self, File}; use std::fs::{self, File, OpenOptions};
use std::io::{self}; use std::io::{self, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::thread; use std::thread;
@ -54,26 +55,67 @@ struct ReleaseResponse {
pub fn provision(machine_id: &str) -> Result<RustdeskProvisioningResult, RustdeskError> { pub fn provision(machine_id: &str) -> Result<RustdeskProvisioningResult, RustdeskError> {
let _guard = PROVISION_MUTEX.lock(); let _guard = PROVISION_MUTEX.lock();
log_event("Iniciando provisionamento do RustDesk");
let exe_path = detect_executable_path(); let exe_path = detect_executable_path();
let (installed_version, freshly_installed) = ensure_installed(&exe_path)?; let (installed_version, freshly_installed) = ensure_installed(&exe_path)?;
log_event(if freshly_installed {
"RustDesk instalado a partir do instalador mais recente"
} else {
"RustDesk já instalado, usando binário existente"
});
let config_path = write_config_files()?; let config_path = write_config_files()?;
apply_config(&exe_path, &config_path)?; log_event(&format!(
set_password(&exe_path)?; "Arquivo de configuração atualizado em {}",
config_path.display()
));
if let Err(error) = apply_config(&exe_path, &config_path) {
log_event(&format!("Falha ao aplicar configuração via CLI: {error}"));
} else {
log_event("Configuração aplicada via CLI");
}
if let Err(error) = set_password(&exe_path) {
log_event(&format!("Falha ao definir senha padrão: {error}"));
} else {
log_event("Senha padrão definida com sucesso");
}
let custom_id = set_custom_id(&exe_path, machine_id)?; let custom_id = set_custom_id(&exe_path, machine_id)?;
ensure_service_running()?; log_event(&format!("ID determinístico definido: {custom_id}"));
if let Err(error) = ensure_service_running() {
log_event(&format!("Falha ao reiniciar serviço do RustDesk: {error}"));
} else {
log_event("Serviço RustDesk reiniciado/run ativo");
}
let reported_id = query_id(&exe_path) let reported_id = query_id(&exe_path)
.ok() .ok()
.filter(|value| !value.is_empty()) .filter(|value| !value.is_empty())
.or_else(read_remote_id_from_profiles) .or_else(|| {
let fallback = read_remote_id_from_profiles();
if let Some(value) = &fallback {
log_event(&format!("ID obtido via arquivos de perfil: {value}"));
}
fallback
})
.unwrap_or_else(|| custom_id.clone()); .unwrap_or_else(|| custom_id.clone());
let version = query_version(&exe_path).ok().or(installed_version); let version = query_version(&exe_path).ok().or(installed_version);
Ok(RustdeskProvisioningResult { let result = RustdeskProvisioningResult {
id: reported_id, id: reported_id.clone(),
password: DEFAULT_PASSWORD.to_string(), password: DEFAULT_PASSWORD.to_string(),
installed_version: version, installed_version: version.clone(),
updated: freshly_installed, updated: freshly_installed,
}) };
log_event(&format!("Provisionamento concluído. ID final: {reported_id}. Versão: {:?}", version));
Ok(result)
} }
fn detect_executable_path() -> PathBuf { fn detect_executable_path() -> PathBuf {
@ -138,12 +180,24 @@ fn write_config_files() -> Result<PathBuf, RustdeskError> {
let config_contents = build_config_contents(); let config_contents = build_config_contents();
let main_path = program_data_config_dir().join("RustDesk2.toml"); let main_path = program_data_config_dir().join("RustDesk2.toml");
write_file(&main_path, &config_contents)?; write_file(&main_path, &config_contents)?;
log_event(&format!(
"Config principal gravada em {}",
main_path.display()
));
let service_profile = PathBuf::from(LOCAL_SERVICE_CONFIG).join("RustDesk2.toml"); let service_profile = PathBuf::from(LOCAL_SERVICE_CONFIG).join("RustDesk2.toml");
write_file(&service_profile, &config_contents).ok(); if let Err(error) = write_file(&service_profile, &config_contents) {
log_event(&format!(
"Falha ao gravar config no perfil do serviço: {error}"
));
}
if let Some(appdata_path) = user_appdata_config_path("RustDesk2.toml") { if let Some(appdata_path) = user_appdata_config_path("RustDesk2.toml") {
let _ = write_file(&appdata_path, &config_contents); if let Err(error) = write_file(&appdata_path, &config_contents) {
log_event(&format!(
"Falha ao atualizar config no AppData do usuário: {error}"
));
}
} }
Ok(main_path) Ok(main_path)
@ -278,8 +332,16 @@ fn query_version(exe_path: &Path) -> Result<String, RustdeskError> {
fn ensure_remote_id_files(id: &str) { fn ensure_remote_id_files(id: &str) {
for dir in remote_id_directories() { for dir in remote_id_directories() {
let path = dir.join("RustDesk_local.toml"); let path = dir.join("RustDesk_local.toml");
if let Err(error) = write_remote_id_value(&path, id) { match write_remote_id_value(&path, id) {
eprintln!("[rustdesk] Falha ao atualizar remote_id em {}: {}", path.display(), error); Ok(_) => log_event(&format!(
"remote_id atualizado para {} em {}",
id,
path.display()
)),
Err(error) => log_event(&format!(
"Falha ao atualizar remote_id em {}: {error}",
path.display()
)),
} }
} }
} }
@ -371,3 +433,32 @@ fn run_with_args(exe_path: &Path, args: &[&str]) -> Result<(), RustdeskError> {
} }
Ok(()) Ok(())
} }
fn log_event(message: impl AsRef<str>) {
if let Some(dir) = logs_directory() {
if let Err(error) = append_log(dir, message.as_ref()) {
eprintln!("[rustdesk][log] Falha ao registrar log: {error}");
}
}
}
fn logs_directory() -> Option<PathBuf> {
let base = env::var("LOCALAPPDATA").ok()?;
Some(
Path::new(&base)
.join("br.com.esdrasrenan.sistemadechamados")
.join("logs"),
)
}
fn append_log(dir: PathBuf, message: &str) -> io::Result<()> {
fs::create_dir_all(&dir)?;
let log_path = dir.join("rustdesk.log");
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(log_path)?;
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S");
writeln!(file, "[{timestamp}] {message}")?;
Ok(())
}