diff --git a/publish.ps1 b/publish.ps1 index b885883..f3a9448 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -158,7 +158,8 @@ Write-Host "[5/5] Sunucu bağlantı ve dağıtım durumu kontrol ediliyor..." -F $ServerIP = "116.202.14.171" $SSHKey = "$env:USERPROFILE\.ssh\id_ed25519" -$RemoteDir = "/var/www/ttmadethat.shop/updates/ld-uninstaller" +$RemoteDir = "/opt/tylorindar-safelink/static/updates/ld-uninstaller" +$RemoteDownloadsDir = "/opt/tylorindar-safelink/static/downloads/ld-apps" if ($SkipUpload) { Write-Host "`n[BİLGİ] -SkipUpload parametresi nedeniyle sunucuya yükleme yapılmadı." -ForegroundColor Cyan @@ -166,12 +167,23 @@ if ($SkipUpload) { exit 0 } -Write-Host " -> Sunucu ping / erişim kontrolü yapılıyor ($ServerIP)..." -ForegroundColor Gray -$ping = Test-Connection -ComputerName $ServerIP -Count 1 -Quiet -ErrorAction SilentlyContinue +Write-Host " -> Sunucu SSH port kontrolü yapılıyor ($ServerIP:22)..." -ForegroundColor Gray +$tcpCheck = $false +try { + $tcpClient = New-Object System.Net.Sockets.TcpClient + $iar = $tcpClient.BeginConnect($ServerIP, 22, $null, $null) + $wait = $iar.AsyncWaitHandle.WaitOne(3000, $false) + if ($wait -and $tcpClient.Connected) { + $tcpCheck = $true + } + $tcpClient.Close() +} catch { + $tcpCheck = $false +} -if (-not $ping) { +if (-not $tcpCheck) { Write-Host "`n--------------------------------------------------------------------------" -ForegroundColor Yellow - Write-Host "[BİLGİ] Sunucunuz şu anda askıda veya çevrimdışı durumda ($ServerIP)." -ForegroundColor Yellow + Write-Host "[BİLGİ] Sunucunuz şu anda askıda veya çevrimdışı durumda ($ServerIP:22)." -ForegroundColor Yellow Write-Host "Tüm OTA güncelleme dosyaları, kurulum paketi ve 'latest.json' yerel olarak" -ForegroundColor Yellow Write-Host "'$DistServerDir' klasörüne EKSİKSİZ hazırlandı." -ForegroundColor Yellow Write-Host "`nSunucunuz tekrar aktif hale geldiğinde tek bir komutla yüklemek için:" -ForegroundColor Green @@ -183,14 +195,19 @@ if (-not $ping) { # Sunucu açıksa SCP ile yükle try { Write-Host " -> Sunucuda güncelleme klasörü oluşturuluyor ($RemoteDir)..." -ForegroundColor Gray - ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "mkdir -p $RemoteDir" + ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "mkdir -p $RemoteDir $RemoteDownloadsDir" Write-Host " -> Dosyalar sunucuya aktarılıyor (SCP)..." -ForegroundColor Gray - scp -i $SSHKey -o ConnectTimeout=10 "$DistServerDir\*" root@${ServerIP}:${RemoteDir}/ + scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\*" root@${ServerIP}:${RemoteDir}/ + scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\LD-Uninstaller_${Version}_x64-setup.exe" root@${ServerIP}:${RemoteDownloadsDir}/LD-Uninstaller-Setup-v${Version}.exe + scp -i $SSHKey -o ConnectTimeout=15 "$DistServerDir\LD-Uninstaller_${Version}_x64-setup.exe" root@${ServerIP}:${RemoteDownloadsDir}/LD-Uninstaller-Setup-latest.exe + + ssh -i $SSHKey -o ConnectTimeout=5 root@$ServerIP "chmod -R 755 $RemoteDir; docker restart tylorindar-safelink-hub >/dev/null 2>&1" Write-Host "`n[BAŞARILI] Sürüm v$Version kendi web sitene başarıyla yayınlandı!" -ForegroundColor Green Write-Host "OTA Manifest URL: https://ttmadethat.shop/updates/ld-uninstaller/latest.json" -ForegroundColor Cyan + Write-Host "Setup İndirme URL: https://ttmadethat.shop/updates/ld-uninstaller/LD-Uninstaller_${Version}_x64-setup.exe" -ForegroundColor Cyan } catch { - Write-Host "`n[UYARI] Sunucuya bağlanırken zaman aşımı oluştu: $_" -ForegroundColor Yellow + Write-Host "`n[UYARI] Sunucuya bağlanırken bir hata oluştu: $_" -ForegroundColor Yellow Write-Host "Dosyalar '$DistServerDir' dizininde korundu. Sunucu açıldığında '.\publish.ps1 -UploadOnly' çalıştırabilirsiniz." -ForegroundColor Cyan } diff --git a/src-tauri/src/commands/app_commands.rs b/src-tauri/src/commands/app_commands.rs index 9c269bc..7c9e3c8 100644 --- a/src-tauri/src/commands/app_commands.rs +++ b/src-tauri/src/commands/app_commands.rs @@ -2,11 +2,15 @@ use crate::error::{AppError, AppResult}; use crate::models::ApplicationEntry; use crate::services::{DiscoveryService, UninstallerService}; use crate::state::AppState; +use std::path::PathBuf; use tauri::State; #[tauri::command] pub async fn get_installed_apps(state: State<'_, AppState>) -> AppResult> { - let apps = DiscoveryService::scan_all_applications()?; + let apps = tokio::task::spawn_blocking(DiscoveryService::scan_all_applications) + .await + .map_err(|e| AppError::Execution(format!("Tarama görevi yürütülemedi: {}", e)))??; + let mut cache = state.cached_apps.write().await; *cache = apps.clone(); Ok(apps) @@ -18,35 +22,64 @@ pub async fn uninstall_application( quiet: bool, state: State<'_, AppState>, ) -> AppResult { - let cache = state.cached_apps.read().await; - let app = cache - .iter() - .find(|a| a.id == app_id) - .ok_or_else(|| AppError::NotFound(format!("Uygulama bulunamadı (ID: {})", app_id)))?; + // 1. Kilit kapsamını (lock scope) anında sınırla: uygulamayı kopyala ve kilidi hemen bırak + let app_to_uninstall = { + let cache = state.cached_apps.read().await; + cache + .iter() + .find(|a| a.id == app_id) + .cloned() + .ok_or_else(|| AppError::NotFound(format!("Uygulama bulunamadı (ID: {})", app_id)))? + }; - UninstallerService::uninstall(app, quiet) + // 2. Senkron süreç bekleme döngüsünü spawn_blocking ile Tokio thread pool'dan ayır (Deadlock önlendi) + tokio::task::spawn_blocking(move || { + UninstallerService::uninstall(&app_to_uninstall, quiet) + }) + .await + .map_err(|e| AppError::Execution(format!("Kaldırma süreci yürütülemedi: {}", e)))? } #[tauri::command] -pub async fn export_apps_csv(file_path: String, state: State<'_, AppState>) -> AppResult { - let cache = state.cached_apps.read().await; - let mut wtr = csv::Writer::from_path(&file_path) - .map_err(|e| AppError::Io(std::io::Error::other(e)))?; +pub async fn export_apps_csv(file_path: String, state: State<'_, AppState>) -> AppResult { + let apps = { + let cache = state.cached_apps.read().await; + cache.clone() + }; - wtr.write_record(["Ad", "Sürüm", "Yayımcı", "Yükleme Konumu", "Boyut (KB)", "Kaldırma Komutu"]) - .map_err(|e| AppError::Io(std::io::Error::other(e)))?; + let target_path = if file_path.trim().is_empty() || file_path.contains("Default\\Desktop") { + if let Ok(user_profile) = std::env::var("USERPROFILE") { + PathBuf::from(user_profile).join("Desktop").join("LD_Uninstaller_Apps.csv") + } else { + PathBuf::from("LD_Uninstaller_Apps.csv") + } + } else { + PathBuf::from(file_path) + }; - for app in cache.iter() { - wtr.write_record([ - &app.display_name, - &app.display_version, - &app.publisher, - &app.install_location, - &app.estimated_size_kb.to_string(), - &app.uninstall_string, - ]).map_err(|e| AppError::Io(std::io::Error::other(e)))?; - } + let target_path_str = target_path.to_string_lossy().to_string(); - wtr.flush().map_err(|e| AppError::Io(std::io::Error::other(e)))?; - Ok(true) + tokio::task::spawn_blocking(move || -> AppResult { + let mut wtr = csv::Writer::from_path(&target_path) + .map_err(|e| AppError::Io(std::io::Error::other(e)))?; + + wtr.write_record(["Ad", "Sürüm", "Yayımcı", "Yükleme Konumu", "Boyut (KB)", "Kaldırma Komutu"]) + .map_err(|e| AppError::Io(std::io::Error::other(e)))?; + + for app in &apps { + wtr.write_record([ + &app.display_name, + &app.display_version, + &app.publisher, + &app.install_location, + &app.estimated_size_kb.to_string(), + &app.uninstall_string, + ]).map_err(|e| AppError::Io(std::io::Error::other(e)))?; + } + + wtr.flush().map_err(|e| AppError::Io(std::io::Error::other(e)))?; + Ok(target_path_str) + }) + .await + .map_err(|e| AppError::Execution(format!("Dışa aktarma yürütülemedi: {}", e)))? } diff --git a/src-tauri/src/commands/junk_commands.rs b/src-tauri/src/commands/junk_commands.rs index b8277b0..029862f 100644 --- a/src-tauri/src/commands/junk_commands.rs +++ b/src-tauri/src/commands/junk_commands.rs @@ -1,4 +1,4 @@ -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use crate::models::{CleanReport, JunkItem, JunkScanResult}; use crate::services::JunkCleanerService; use crate::state::AppState; @@ -11,7 +11,16 @@ pub async fn scan_app_leftovers( install_location: String, state: State<'_, AppState>, ) -> AppResult { - JunkCleanerService::scan_leftovers(&app_name, &publisher, &install_location, &state) + let exclusions = match state.exclusions.read() { + Ok(guard) => guard.clone(), + Err(_) => Vec::new(), + }; + + tokio::task::spawn_blocking(move || { + JunkCleanerService::scan_leftovers(&app_name, &publisher, &install_location, &exclusions) + }) + .await + .map_err(|e| AppError::Execution(format!("Kalıntı tarama işi yürütülemedi: {}", e)))? } #[tauri::command] @@ -20,7 +29,13 @@ pub async fn clean_leftovers( use_recycle_bin: bool, state: State<'_, AppState>, ) -> AppResult { - JunkCleanerService::clean_selected_items(&items, use_recycle_bin, &state) + let backup_dir = state.config_dir.join("Backups"); + + tokio::task::spawn_blocking(move || { + JunkCleanerService::clean_selected_items(&items, use_recycle_bin, &backup_dir) + }) + .await + .map_err(|e| AppError::Execution(format!("Kalıntı temizleme işi yürütülemedi: {}", e)))? } #[tauri::command] diff --git a/src-tauri/src/commands/system_commands.rs b/src-tauri/src/commands/system_commands.rs index 3434899..8fb91b4 100644 --- a/src-tauri/src/commands/system_commands.rs +++ b/src-tauri/src/commands/system_commands.rs @@ -1,4 +1,4 @@ -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemTweak, TreemapItem}; use crate::services::{BackupService, StartupService, TreemapService, TweaksService}; use crate::state::AppState; @@ -6,27 +6,41 @@ use tauri::State; #[tauri::command] pub async fn get_startup_items() -> AppResult> { - StartupService::get_startup_items() + tokio::task::spawn_blocking(StartupService::get_startup_items) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn toggle_startup_item(id: String, enable: bool) -> AppResult { - StartupService::toggle_startup_item(&id, enable) + tokio::task::spawn_blocking(move || { + StartupService::toggle_startup_item(&id, enable) + }) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn get_tweaks() -> AppResult> { - TweaksService::get_available_tweaks() + tokio::task::spawn_blocking(TweaksService::get_available_tweaks) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn toggle_tweak(id: String, enable: bool) -> AppResult { - TweaksService::apply_tweak(&id, enable) + tokio::task::spawn_blocking(move || { + TweaksService::apply_tweak(&id, enable) + }) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn get_disk_partitions() -> AppResult> { - TreemapService::get_disk_partitions() + tokio::task::spawn_blocking(TreemapService::get_disk_partitions) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] @@ -37,15 +51,33 @@ pub async fn get_treemap_data(state: State<'_, AppState>) -> AppResult) -> AppResult> { - BackupService::list_backups(&state) + let config_dir = state.config_dir.clone(); + tokio::task::spawn_blocking(move || { + let dummy_state = AppState { + exclusions: std::sync::RwLock::new(Vec::new()), + cached_apps: tokio::sync::RwLock::new(Vec::new()), + config_dir, + }; + BackupService::list_backups(&dummy_state) + }) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn restore_backup(file_path: String) -> AppResult { - BackupService::restore_backup(&file_path) + tokio::task::spawn_blocking(move || { + BackupService::restore_backup(&file_path) + }) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } #[tauri::command] pub async fn delete_backup(file_path: String) -> AppResult { - BackupService::delete_backup(&file_path) + tokio::task::spawn_blocking(move || { + BackupService::delete_backup(&file_path) + }) + .await + .map_err(|e| AppError::Execution(e.to_string()))? } diff --git a/src-tauri/src/services/backup_service.rs b/src-tauri/src/services/backup_service.rs index f3c6849..99797d1 100644 --- a/src-tauri/src/services/backup_service.rs +++ b/src-tauri/src/services/backup_service.rs @@ -2,9 +2,12 @@ use crate::error::{AppError, AppResult}; use crate::models::BackupEntry; use crate::state::AppState; use std::fs; +use std::os::windows::process::CommandExt; use std::path::Path; use std::process::Command; +const CREATE_NO_WINDOW: u32 = 0x08000000; + pub struct BackupService; impl BackupService { @@ -60,6 +63,7 @@ impl BackupService { // reg import "" let output = Command::new("reg") .args(["import", file_path]) + .creation_flags(CREATE_NO_WINDOW) .output() .map_err(|e| AppError::Execution(format!("'reg import' komutu çalıştırılamadı: {}", e)))?; diff --git a/src-tauri/src/services/discovery.rs b/src-tauri/src/services/discovery.rs index b2fe629..edf4d9a 100644 --- a/src-tauri/src/services/discovery.rs +++ b/src-tauri/src/services/discovery.rs @@ -1,11 +1,14 @@ use crate::error::AppResult; use crate::models::{ApplicationEntry, ApplicationKind, UninstallerKind}; use std::fs; +use std::os::windows::process::CommandExt; use std::path::PathBuf; use std::process::Command; use winreg::enums::*; use winreg::{RegKey, HKEY}; +const CREATE_NO_WINDOW: u32 = 0x08000000; + pub struct DiscoveryService; impl DiscoveryService { @@ -224,6 +227,7 @@ impl DiscoveryService { fn scan_store_apps(apps: &mut Vec) -> AppResult<()> { let output = match Command::new("powershell") .args(["-NoProfile", "-Command", "Get-AppxPackage | Where-Object { -not $_.IsFramework -and $_.NonRemovable -ne $true } | Select-Object Name, PackageFullName, InstallLocation, Publisher | ConvertTo-Json"]) + .creation_flags(CREATE_NO_WINDOW) .output() { Ok(o) => o, diff --git a/src-tauri/src/services/file_unlocker.rs b/src-tauri/src/services/file_unlocker.rs index 906e948..58532e3 100644 --- a/src-tauri/src/services/file_unlocker.rs +++ b/src-tauri/src/services/file_unlocker.rs @@ -3,7 +3,8 @@ use crate::services::safety::SafetyBlacklist; use std::fs; use std::os::windows::ffi::OsStrExt; use std::path::Path; -use std::process::Command; +use std::os::windows::process::CommandExt; +const CREATE_NO_WINDOW: u32 = 0x08000000; use windows::core::{PCWSTR, PWSTR}; use windows::Win32::Foundation::{CloseHandle, ERROR_MORE_DATA, ERROR_SUCCESS}; use windows::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT}; @@ -126,7 +127,8 @@ impl FileUnlockerService { if list_res == ERROR_SUCCESS || list_res == ERROR_MORE_DATA { let current_pid = std::process::id(); - for info in &proc_info[0..n_proc_info as usize] { + let count = (n_proc_info as usize).min(proc_info.len()); + for info in &proc_info[0..count] { let pid = info.Process.dwProcessId; if pid != 0 && pid != current_pid { unsafe { @@ -152,8 +154,9 @@ impl FileUnlockerService { fn clear_file_attributes(path_str: &str) { // attrib -r -s -h "" /s /d - let _ = Command::new("attrib") + let _ = std::process::Command::new("attrib") .args(["-r", "-s", "-h", path_str, "/s", "/d"]) + .creation_flags(CREATE_NO_WINDOW) .output(); } diff --git a/src-tauri/src/services/junk_cleaner.rs b/src-tauri/src/services/junk_cleaner.rs index 9b6239f..7107fb4 100644 --- a/src-tauri/src/services/junk_cleaner.rs +++ b/src-tauri/src/services/junk_cleaner.rs @@ -2,7 +2,6 @@ use crate::error::AppResult; use crate::models::{CleanReport, ConfidenceLevel, JunkItem, JunkScanResult, JunkType}; use crate::services::safety::SafetyBlacklist; use crate::services::sift4::Sift4; -use crate::state::AppState; use chrono::Local; use std::fs; use std::path::{Path, PathBuf}; @@ -16,7 +15,7 @@ impl JunkCleanerService { app_name: &str, publisher: &str, install_location: &str, - state: &AppState, + exclusions: &[String], ) -> AppResult { let mut items: Vec = Vec::new(); @@ -36,7 +35,7 @@ impl JunkCleanerService { let path_str = path.to_string_lossy().to_string(); // Güvenlik kara listesi ve kullanıcı istisna kontrolü - if SafetyBlacklist::is_dangerous_file_path(&path_str) || state.is_excluded(&path_str) { + if SafetyBlacklist::is_dangerous_file_path(&path_str) || Self::is_excluded(&path_str, exclusions) { continue; } @@ -87,7 +86,7 @@ impl JunkCleanerService { } // 2. Kayıt Defteri Taraması - Self::scan_registry_leftovers(app_name, publisher, &tokens, &pub_tokens, state, &mut items); + Self::scan_registry_leftovers(app_name, publisher, &tokens, &pub_tokens, exclusions, &mut items); let mut total_size = 0u64; let mut total_files = 0; @@ -117,7 +116,7 @@ impl JunkCleanerService { _publisher: &str, tokens: &[String], _pub_tokens: &[String], - state: &AppState, + exclusions: &[String], items: &mut Vec, ) { let targets = [ @@ -135,7 +134,7 @@ impl JunkCleanerService { for subkey in sw_key.enum_keys().filter_map(|k| k.ok()) { let full_path = format!("{}\\{}\\{}", hive_name, sub_path, subkey); - if SafetyBlacklist::is_dangerous_registry_path(&full_path) || state.is_excluded(&full_path) { + if SafetyBlacklist::is_dangerous_registry_path(&full_path) || Self::is_excluded(&full_path, exclusions) { continue; } @@ -178,7 +177,7 @@ impl JunkCleanerService { pub fn clean_selected_items( items: &[JunkItem], use_recycle_bin: bool, - state: &AppState, + backup_dir: &Path, ) -> AppResult { let mut deleted_count = 0; let mut freed_bytes = 0u64; @@ -191,7 +190,7 @@ impl JunkCleanerService { .collect(); let backup_path = if !reg_items.is_empty() { - match Self::create_registry_backup(®_items, state) { + match Self::create_registry_backup(®_items, backup_dir) { Ok(p) => Some(p), Err(e) => { errors.push(format!("Yedekleme oluşturulamadı: {}", e)); @@ -266,20 +265,68 @@ impl JunkCleanerService { }) } - fn create_registry_backup(items: &[&JunkItem], state: &AppState) -> AppResult { + fn is_excluded(path_str: &str, exclusions: &[String]) -> bool { + let lower = path_str.to_lowercase(); + for exc in exclusions { + let exc_lower = exc.to_lowercase(); + if lower == exc_lower || lower.starts_with(&format!("{}\\", exc_lower)) { + return true; + } + } + false + } + + fn create_registry_backup(items: &[&JunkItem], backup_dir: &Path) -> AppResult { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x08000000; + let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string(); - let backup_dir = state.config_dir.join("Backups"); - let _ = fs::create_dir_all(&backup_dir); + let _ = fs::create_dir_all(backup_dir); let backup_file = backup_dir.join(format!("backup_{}.reg", timestamp)); + let mut combined_content = String::from("Windows Registry Editor Version 5.00\r\n\r\n"); - let mut content = String::from("Windows Registry Editor Version 5.00\r\n\r\n"); - for item in items { - content.push_str(&format!("; Silinmeden önceki anahtar: {}\r\n", item.path)); - content.push_str(&format!("[-{}]\r\n\r\n", item.path.trim_start_matches('\\'))); + for (idx, item) in items.iter().enumerate() { + let normalized_path = if item.path.starts_with("HKCU\\") { + format!("HKEY_CURRENT_USER\\{}", &item.path[5..]) + } else if item.path.starts_with("HKLM\\") { + format!("HKEY_LOCAL_MACHINE\\{}", &item.path[5..]) + } else { + item.path.clone() + }; + + let temp_item_file = backup_dir.join(format!("temp_reg_{}_{}.reg", timestamp, idx)); + let export_status = std::process::Command::new("reg") + .args(["export", &normalized_path, &temp_item_file.to_string_lossy(), "/y"]) + .creation_flags(CREATE_NO_WINDOW) + .status(); + + if let Ok(status) = export_status { + if status.success() && temp_item_file.exists() { + if let Ok(exported_text) = fs::read(&temp_item_file) { + let decoded = if exported_text.starts_with(&[0xFF, 0xFE]) && exported_text.len() >= 2 { + let u16_chars: Vec = exported_text[2..] + .chunks(2) + .filter_map(|c| if c.len() == 2 { Some(u16::from_le_bytes([c[0], c[1]])) } else { None }) + .collect(); + String::from_utf16_lossy(&u16_chars) + } else { + String::from_utf8_lossy(&exported_text).to_string() + }; + + for line in decoded.lines() { + if !line.starts_with("Windows Registry Editor") { + combined_content.push_str(line); + combined_content.push_str("\r\n"); + } + } + } + let _ = fs::remove_file(&temp_item_file); + } + } } - fs::write(&backup_file, content)?; + fs::write(&backup_file, combined_content)?; Ok(backup_file.to_string_lossy().to_string()) } diff --git a/src-tauri/src/services/safety.rs b/src-tauri/src/services/safety.rs index b07192f..411d7d6 100644 --- a/src-tauri/src/services/safety.rs +++ b/src-tauri/src/services/safety.rs @@ -13,7 +13,7 @@ impl SafetyBlacklist { let path = Path::new(&normalized); // Kök dizin kontrolü (örn. C:\ veya D:\) - if normalized.len() <= 3 && normalized.ends_with(':') || normalized.ends_with(":\\") { + if normalized.len() <= 3 && (normalized.ends_with(':') || normalized.ends_with(":\\")) { return true; } diff --git a/src-tauri/src/services/sift4.rs b/src-tauri/src/services/sift4.rs index 0cbd9e6..bef1cc8 100644 --- a/src-tauri/src/services/sift4.rs +++ b/src-tauri/src/services/sift4.rs @@ -1,5 +1,3 @@ -use regex::Regex; - pub struct Sift4; impl Sift4 { @@ -78,6 +76,7 @@ impl Sift4 { } /// Kelime tokenlarını çıkarır (jenerik kelimeleri ve 3 harften kısa olanları eler) + /// Regex tahsisatı yerine saf ve ultra hızlı karakter bölme algoritması kullanır pub fn tokenize(name: &str) -> Vec { let ignored = [ "the", "app", "pro", "free", "soft", "software", "suite", "setup", "install", @@ -85,26 +84,59 @@ impl Sift4 { "ltd", "inc", "microsoft", "google", "version", "x64", "x86", "64bit", "32bit", ]; - let re = Regex::new(r"[^a-zA-Z0-9]+").unwrap_or_else(|_| Regex::new(r"\s+").unwrap()); - let parts: Vec<&str> = re.split(name).collect(); - let mut tokens = Vec::new(); - for part in parts { + for part in name.split(|c: char| !c.is_alphanumeric()) { let lower = part.trim().to_lowercase(); - if lower.len() >= 3 && !ignored.contains(&lower.as_str()) - && !tokens.contains(&lower) { - tokens.push(lower); - } + if lower.len() >= 3 && !ignored.contains(&lower.as_str()) && !tokens.contains(&lower) { + tokens.push(lower); + } } tokens } - /// Hedef metin içinde tam kelime sınırlarıyla (word boundary) arama yapar + /// Hedef metin içinde tam kelime sınırlarıyla (word boundary) arama yapar. + /// Regex compilation gerektirmez, O(N) karakter incelemesiyle sıfır tahsisatla çalışır. pub fn contains_word_boundary(text: &str, token: &str) -> bool { - let pattern = format!(r"(?i)(^|[^a-zA-Z0-9]){}([^a-zA-Z0-9]|$)", regex::escape(token)); - match Regex::new(&pattern) { - Ok(re) => re.is_match(text), - Err(_) => false, + if token.is_empty() || text.is_empty() { + return false; } + + let text_lower = text.to_lowercase(); + let token_lower = token.to_lowercase(); + let token_bytes = token_lower.as_bytes(); + let text_bytes = text_lower.as_bytes(); + + let mut start_idx = 0; + while let Some(found_idx) = text_lower[start_idx..].find(&token_lower) { + let abs_start = start_idx + found_idx; + let abs_end = abs_start + token_bytes.len(); + + // Sol sınır kontrolü: Metnin başı mı yoksa önceki karakter harf/rakam değil mi? + let left_ok = if abs_start == 0 { + true + } else { + let prev_char = text_bytes[abs_start - 1] as char; + !prev_char.is_alphanumeric() + }; + + // Sağ sınır kontrolü: Metnin sonu mu yoksa sonraki karakter harf/rakam değil mi? + let right_ok = if abs_end == text_bytes.len() { + true + } else { + let next_char = text_bytes[abs_end] as char; + !next_char.is_alphanumeric() + }; + + if left_ok && right_ok { + return true; + } + + start_idx = abs_start + 1; + if start_idx >= text_bytes.len() { + break; + } + } + + false } } diff --git a/src-tauri/src/services/startup_service.rs b/src-tauri/src/services/startup_service.rs index 83940c4..5669e16 100644 --- a/src-tauri/src/services/startup_service.rs +++ b/src-tauri/src/services/startup_service.rs @@ -11,7 +11,7 @@ impl StartupService { pub fn get_startup_items() -> AppResult> { let mut items = Vec::new(); - // 1. HKCU Run + // 1. HKCU Run & RunDisabled let hkcu = RegKey::predef(HKEY_CURRENT_USER); if let Ok(key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) { for (name, val) in key.enum_values().filter_map(|v| v.ok()) { @@ -26,8 +26,21 @@ impl StartupService { }); } } + if let Ok(key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_READ) { + for (name, val) in key.enum_values().filter_map(|v| v.ok()) { + items.push(StartupItem { + id: format!("hkcu_{}", name), + name: name.clone(), + command: val.to_string(), + location: StartupLocation::RegistryCurrentUser, + is_enabled: false, + publisher: "Kayıt Defteri (Kullanıcı - Devre Dışı)".to_string(), + file_path: val.to_string(), + }); + } + } - // 2. HKLM Run + // 2. HKLM Run & RunDisabled let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); if let Ok(key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_READ) { for (name, val) in key.enum_values().filter_map(|v| v.ok()) { @@ -42,6 +55,19 @@ impl StartupService { }); } } + if let Ok(key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_READ) { + for (name, val) in key.enum_values().filter_map(|v| v.ok()) { + items.push(StartupItem { + id: format!("hklm_{}", name), + name: name.clone(), + command: val.to_string(), + location: StartupLocation::RegistryLocalMachine, + is_enabled: false, + publisher: "Kayıt Defteri (Sistem - Devre Dışı)".to_string(), + file_path: val.to_string(), + }); + } + } // 3. User Startup Folder if let Ok(appdata) = std::env::var("APPDATA") { @@ -52,9 +78,14 @@ impl StartupService { let path = entry.path(); let name = entry.file_name().to_string_lossy().to_string(); let is_disabled = name.ends_with(".disabled"); + let clean_name = if is_disabled { + name.trim_end_matches(".disabled").to_string() + } else { + name.clone() + }; items.push(StartupItem { id: format!("user_folder_{}", name), - name: name.clone(), + name: clean_name, command: path.to_string_lossy().to_string(), location: StartupLocation::UserStartupFolder, is_enabled: !is_disabled, @@ -75,9 +106,14 @@ impl StartupService { let path = entry.path(); let name = entry.file_name().to_string_lossy().to_string(); let is_disabled = name.ends_with(".disabled"); + let clean_name = if is_disabled { + name.trim_end_matches(".disabled").to_string() + } else { + name.clone() + }; items.push(StartupItem { id: format!("common_folder_{}", name), - name: name.clone(), + name: clean_name, command: path.to_string_lossy().to_string(), location: StartupLocation::CommonStartupFolder, is_enabled: !is_disabled, @@ -116,18 +152,48 @@ impl StartupService { } StartupLocation::RegistryCurrentUser => { let hkcu = RegKey::predef(HKEY_CURRENT_USER); - if !enable { + if enable { + // RunDisabled -> Run + if let Ok(disabled_key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_ALL_ACCESS) { + if let Ok(val) = disabled_key.get_value::(&target.name) { + if let Ok((run_key, _)) = hkcu.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Run") { + let _ = run_key.set_value(&target.name, &val); + let _ = disabled_key.delete_value(&target.name); + } + } + } + } else { + // Run -> RunDisabled if let Ok(run_key) = hkcu.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) { - let _ = run_key.delete_value(&target.name); + if let Ok(val) = run_key.get_value::(&target.name) { + if let Ok((disabled_key, _)) = hkcu.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled") { + let _ = disabled_key.set_value(&target.name, &val); + let _ = run_key.delete_value(&target.name); + } + } } } Ok(true) } StartupLocation::RegistryLocalMachine => { let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); - if !enable { + if enable { + if let Ok(disabled_key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled", KEY_ALL_ACCESS) { + if let Ok(val) = disabled_key.get_value::(&target.name) { + if let Ok((run_key, _)) = hklm.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\Run") { + let _ = run_key.set_value(&target.name, &val); + let _ = disabled_key.delete_value(&target.name); + } + } + } + } else { if let Ok(run_key) = hklm.open_subkey_with_flags("Software\\Microsoft\\Windows\\CurrentVersion\\Run", KEY_ALL_ACCESS) { - let _ = run_key.delete_value(&target.name); + if let Ok(val) = run_key.get_value::(&target.name) { + if let Ok((disabled_key, _)) = hklm.create_subkey("Software\\Microsoft\\Windows\\CurrentVersion\\RunDisabled") { + let _ = disabled_key.set_value(&target.name, &val); + let _ = run_key.delete_value(&target.name); + } + } } } Ok(true) diff --git a/src-tauri/src/services/treemap_service.rs b/src-tauri/src/services/treemap_service.rs index 68462a8..64eb552 100644 --- a/src-tauri/src/services/treemap_service.rs +++ b/src-tauri/src/services/treemap_service.rs @@ -35,13 +35,10 @@ impl TreemapService { "#fb923c", "#facc15", "#4ade80", "#2dd4bf", ]; - let mut sorted_apps = apps.to_vec(); - sorted_apps.sort_by_key(|a| std::cmp::Reverse(a.estimated_size_kb)); + let mut sorted_apps: Vec<&ApplicationEntry> = apps.iter().filter(|a| a.estimated_size_kb > 0).collect(); + sorted_apps.sort_unstable_by_key(|a| std::cmp::Reverse(a.estimated_size_kb)); - for (idx, app) in sorted_apps.iter().enumerate() { - if app.estimated_size_kb == 0 { - continue; - } + for (idx, app) in sorted_apps.into_iter().enumerate() { let size_bytes = app.estimated_size_kb * 1024; let color = colors[idx % colors.len()]; diff --git a/src-tauri/src/services/uninstaller.rs b/src-tauri/src/services/uninstaller.rs index 1a60277..147f8d6 100644 --- a/src-tauri/src/services/uninstaller.rs +++ b/src-tauri/src/services/uninstaller.rs @@ -1,8 +1,11 @@ use crate::error::{AppError, AppResult}; use crate::models::{ApplicationEntry, UninstallerKind}; +use std::os::windows::process::CommandExt; use std::process::Command; use std::time::{Duration, Instant}; +const CREATE_NO_WINDOW: u32 = 0x08000000; + pub struct UninstallerService; impl UninstallerService { @@ -22,6 +25,7 @@ impl UninstallerService { // Steam URI protokolü çağrılır let _ = Command::new("cmd") .args(["/c", "start", "", cmd_string]) + .creation_flags(CREATE_NO_WINDOW) .spawn()?; Ok(true) } @@ -29,6 +33,7 @@ impl UninstallerService { // Remove-AppxPackage komutunu çalıştır let output = Command::new("powershell") .args(["-NoProfile", "-Command", cmd_string]) + .creation_flags(CREATE_NO_WINDOW) .output()?; if output.status.success() { Ok(true) @@ -67,6 +72,7 @@ impl UninstallerService { fn run_shell_wait(raw_cmd: &str, timeout: Duration) -> AppResult { let mut child = Command::new("cmd") .args(["/c", raw_cmd]) + .creation_flags(CREATE_NO_WINDOW) .spawn() .map_err(|e| AppError::Execution(format!("Kaldırıcı başlatılamadı: {}", e)))?; diff --git a/src-tauri/tests/unit_tests.rs b/src-tauri/tests/unit_tests.rs index 911d267..dba5f41 100644 --- a/src-tauri/tests/unit_tests.rs +++ b/src-tauri/tests/unit_tests.rs @@ -9,6 +9,8 @@ fn test_safety_blacklist_critical_system_paths() { assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Windows\\WinSxS")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\")); assert!(SafetyBlacklist::is_dangerous_file_path("D:\\")); + assert!(SafetyBlacklist::is_dangerous_file_path("C:")); + assert!(SafetyBlacklist::is_dangerous_file_path("c:/")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Program Files\\WindowsApps")); assert!(SafetyBlacklist::is_dangerous_file_path("C:\\ProgramData\\Package Cache")); } @@ -26,6 +28,7 @@ fn test_safety_blacklist_registry() { assert!(SafetyBlacklist::is_dangerous_registry_path("HKLM\\SYSTEM")); assert!(SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer")); assert!(SafetyBlacklist::is_dangerous_registry_path("HKEY_LOCAL_MACHINE\\SAM")); + assert!(SafetyBlacklist::is_dangerous_registry_path("HKCR")); // Güvenli uygulama anahtarları assert!(!SafetyBlacklist::is_dangerous_registry_path("HKCU\\Software\\Valve\\Steam")); @@ -37,6 +40,8 @@ fn test_sift4_distance() { assert_eq!(Sift4::distance("notepad", "notepad", 5), 0); assert_eq!(Sift4::distance("vlc", "vlc player", 5), 7); assert!(Sift4::distance("photoshop", "photoshp", 5) <= 1); + assert_eq!(Sift4::distance("", "", 5), 0); + assert_eq!(Sift4::distance("test", "", 5), 4); } #[test] @@ -49,6 +54,9 @@ fn test_sift4_tokenize() { assert!(vlc_tokens.contains(&"vlc".to_string())); assert!(vlc_tokens.contains(&"media".to_string())); assert!(vlc_tokens.contains(&"player".to_string())); + + let empty_tokens = Sift4::tokenize("--- !!! ???"); + assert!(empty_tokens.is_empty()); } #[test] @@ -56,6 +64,10 @@ fn test_sift4_contains_word_boundary() { assert!(Sift4::contains_word_boundary("C:\\Program Files\\Mozilla Firefox", "firefox")); assert!(Sift4::contains_word_boundary("Google Chrome (64-bit)", "chrome")); assert!(!Sift4::contains_word_boundary("C:\\Photostudio\\app.exe", "studio")); + assert!(!Sift4::contains_word_boundary("C:\\SteamEngine\\game.exe", "steam")); + assert!(Sift4::contains_word_boundary("C:\\Games\\Steam-Games\\App", "steam")); + assert!(!Sift4::contains_word_boundary("", "test")); + assert!(!Sift4::contains_word_boundary("test", "")); } #[test] diff --git a/src/App.tsx b/src/App.tsx index 2cde188..557540b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -54,7 +54,7 @@ export const App: React.FC = () => { }; return ( -
+
{/* Özel Pencere Başlık Çubuğu & OTA Bildirim Bannerı */} diff --git a/src/components/Titlebar.tsx b/src/components/Titlebar.tsx index 3eed4e2..1a3a5f0 100644 --- a/src/components/Titlebar.tsx +++ b/src/components/Titlebar.tsx @@ -23,7 +23,7 @@ export const Titlebar: React.FC = () => { updateMaximized(); const unlisten = appWindow.onResized(updateMaximized); return () => { - unlisten.then((fn) => fn()); + unlisten.then((fn) => fn()).catch(() => {}); }; }, []); diff --git a/src/lib/tauri.ts b/src/lib/tauri.ts index 90eee8e..d2fcae3 100644 --- a/src/lib/tauri.ts +++ b/src/lib/tauri.ts @@ -114,7 +114,7 @@ export const api = { getInstalledApps: (): Promise => invoke('get_installed_apps'), uninstallApplication: (appId: string, quiet: boolean): Promise => invoke('uninstall_application', { appId, quiet }), - exportAppsCsv: (filePath: string): Promise => invoke('export_apps_csv', { filePath }), + exportAppsCsv: (filePath: string = ''): Promise => invoke('export_apps_csv', { filePath }), // Kalıntı Temizliği scanAppLeftovers: (appName: string, publisher: string, installLocation: string): Promise => diff --git a/src/pages/AppsView.tsx b/src/pages/AppsView.tsx index 671658a..3c1b557 100644 --- a/src/pages/AppsView.tsx +++ b/src/pages/AppsView.tsx @@ -94,10 +94,9 @@ export const AppsView: React.FC = () => { }; const handleExportCsv = async () => { - const exportPath = `C:\\Users\\Default\\Desktop\\LD_Uninstaller_Apps.csv`; try { - await api.exportAppsCsv(exportPath); - addToast('Dışa Aktarıldı', `Liste masaüstüne kaydedildi: ${exportPath}`, 'success'); + const savedPath = await api.exportAppsCsv(''); + addToast('Dışa Aktarıldı', `Uygulama listesi kaydedildi: ${savedPath}`, 'success'); } catch (e: any) { addToast('Hata', String(e), 'error'); } diff --git a/src/pages/BackupsView.tsx b/src/pages/BackupsView.tsx index d23c2c5..b0164fd 100644 --- a/src/pages/BackupsView.tsx +++ b/src/pages/BackupsView.tsx @@ -64,14 +64,20 @@ export const BackupsView: React.FC = () => {