Compare commits
No commits in common. "884b33c833d2f9d96d993ec6c7cebc206634dde4" and "45bcba6aeea72d39b0e42b7e38f3f68b8e4f395a" have entirely different histories.
884b33c833
...
45bcba6aee
69
.gitignore
vendored
|
|
@ -1,55 +1,24 @@
|
|||
# Dependencies
|
||||
node_modules
|
||||
target/
|
||||
dist
|
||||
dist-ssr
|
||||
dist_server/
|
||||
web_upload/
|
||||
*.local
|
||||
|
||||
# Secrets, Signing Keys & Local Server Scripts (NEVER commit)
|
||||
bağlan.bat
|
||||
*baglan*.bat
|
||||
ba*lan.bat
|
||||
publish.ps1
|
||||
publish.bat
|
||||
release.ps1
|
||||
user_prompt_full.txt
|
||||
.keys/
|
||||
*.key
|
||||
*.pub
|
||||
*.pem
|
||||
*.pfx
|
||||
*.p12
|
||||
*.sig
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets.*
|
||||
config.local.*
|
||||
|
||||
# Release binaries & legacy packaged builds
|
||||
LD-Uninstaller-Setup-*.exe
|
||||
LD Uninstaller v*/
|
||||
|
||||
# .NET artifacts
|
||||
bin/
|
||||
obj/
|
||||
## Visual Studio / .NET
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
*.user
|
||||
*.suo
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
.vs/
|
||||
.idea/
|
||||
|
||||
## User local scripts
|
||||
*.bat
|
||||
bağlan.bat
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
trace.log
|
||||
crash_*.log
|
||||
test_*.json
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.sw?
|
||||
## Release packages & archives
|
||||
*.zip
|
||||
LD Uninstaller v*/
|
||||
dist/
|
||||
publish/
|
||||
|
|
|
|||
3
.vscode/extensions.json
vendored
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>2.8.0</Version>
|
||||
<AssemblyVersion>2.8.0.0</AssemblyVersion>
|
||||
<FileVersion>2.8.0.0</FileVersion>
|
||||
<Version>2.7.1</Version>
|
||||
<AssemblyVersion>2.7.1.0</AssemblyVersion>
|
||||
<FileVersion>2.7.1.0</FileVersion>
|
||||
<Product>LD Uninstaller</Product>
|
||||
<Company>LD Software</Company>
|
||||
<Authors>LD Software</Authors>
|
||||
|
|
|
|||
BIN
LD-Uninstaller-Setup-v2.7.1.exe
Normal file
|
|
@ -15,10 +15,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.UI", "src\LDU
|
|||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Launcher", "src\LDUninstaller.Launcher\LDUninstaller.Launcher.csproj", "{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{8EE5BA1E-6ECC-43C0-95C4-5FF1CE4FF319}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDUninstaller.Tests", "tests\LDUninstaller.Tests\LDUninstaller.Tests.csproj", "{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
|
|
@ -48,10 +44,6 @@ Global
|
|||
{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{CD3DDC8C-4415-46B1-9E3D-C71152DE0902} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0}
|
||||
|
|
@ -59,6 +51,5 @@ Global
|
|||
{715A77F8-93E4-4D03-BAD1-6F749A803288} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0}
|
||||
{894C87C4-22A2-4935-9238-ED19CB1AD23C} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0}
|
||||
{8B9A7CB4-F72E-42F3-ADC9-A253FBE447E3} = {AE9859BA-F5B7-476C-9ACF-870E6CB944B0}
|
||||
{AB7C8AF3-BB19-4ED1-B179-D50D5FED7BA7} = {8EE5BA1E-6ECC-43C0-95C4-5FF1CE4FF319}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
|
|
|||
145
README.md
|
|
@ -1,88 +1,95 @@
|
|||
<div align="center">
|
||||
|
||||
<img src="logo.png" width="96" alt="LD Uninstaller Logo" />
|
||||
|
||||
# LD Uninstaller
|
||||
|
||||
**Windows için 20 katmanlı kalıntı temizleyici, dosya kilit açıcı ve disk kullanım haritası • Windows uninstaller, 20-layer leftover cleaner, file unlocker, and disk treemap analyzer**
|
||||
|
||||
[](./LICENSE)
|
||||
[](https://git.ttmadethat.shop/LilDosto/LD-Uninstaller/releases/latest)
|
||||
[](https://v2.tauri.app)
|
||||
[](https://git.ttmadethat.shop/LilDosto/LD-Uninstaller/releases/latest)
|
||||
|
||||
[🇹🇷 Türkçe](#-türkçe) • [🇬🇧 English](#-english) • [📦 Releases](https://git.ttmadethat.shop/LilDosto/LD-Uninstaller/releases/latest)
|
||||
|
||||
</div>
|
||||
**LD Uninstaller**, Bulk Crap Uninstaller (BCU) mimarisini temel alan; donanım hızlandırmalı modern **Windows 11 Fluent Dark** arayüzü, 20 katmanlı derin kalıntı temizleme motoru, çoklu disk analizi ve akıllı otomasyon ajanıyla güçlendirilmiş açık kaynaklı, gelişmiş sistem yönetimi ve yazılım kaldırma çözümüdür.
|
||||
|
||||
---
|
||||
|
||||
## 🇹🇷 Türkçe
|
||||
## ✨ Öne Çıkan Özellikler
|
||||
|
||||
**LD Uninstaller**, Windows için Tauri v2, Rust ve React 18 ile geliştirilmiş; yüklü yazılımları tam olarak kaldıran, 20 katmanlı artık taraması yapan, kilitli dosya/klasörleri çözen ve disk kullanımını görselleştiren performanslı bir sistem temizleme aracıdır.
|
||||
### 1. 🧹 20 Katmanlı Derin Kalıntı ve Artık Temizleme Motoru (Leftover Cleaner)
|
||||
Kaldırma işlemi (tekli veya çoklu) bittiği anda otomatik olarak açılan kalıntı temizleme ekranı, sistemde hiçbir yazılımın tek bir izini dahi bırakmaz:
|
||||
1. **Ana Kurulum Dizinleri:** Kaldırıcı sonrası silinmeyen klasörler.
|
||||
2. **Kullanıcı Verileri:** `%AppData%`, `%LocalAppData%`, `LocalLow`, `ProgramData`, `Documents`, `Saved Games`.
|
||||
3. **Kullanıcı Gizli Dizinleri (Dot-Folders):** Modern yazılımların `%USERPROFILE%` altındaki `.appname`, `.config`, `.cache` klasörleri.
|
||||
4. **Ortak Kütüphaneler (Common Files):** `Common Files` altında terk edilen DLL ve bileşenler.
|
||||
5. **Geçici Dosyalar (Temp):** `%TEMP%` ve `%LOCALAPPDATA%\Temp` kurulum/kaldırma artıkları.
|
||||
6. **Çoklu Sürücüler & Boş Dizinler:** İkincil disklerdeki (`D:\`, `E:\`) oyun/yazılım artıkları ve içi boş kalan yayıncı klasörleri.
|
||||
7. **Yazılım Kayıt Defteri Anahtarları:** `HKLM`, `HKCU` ve `WOW6432Node` Software dalları.
|
||||
8. **Windows Hizmetleri & Sürücüler:** `HKLM\SYSTEM\CurrentControlSet\Services` taranarak uygulamaya ait arka plan servisleri tespit edilir ve `sc stop` + `sc delete` ile kaldırılır.
|
||||
9. **Görev Zamanlayıcı (Scheduled Tasks):** `C:\Windows\System32\Tasks` içindeki güncelleyici ve otomatik görevler taranarak temizlenir.
|
||||
10. **Uygulama Başlatma Yolları (App Paths):** `App Paths` altındaki yetim kayıtlar.
|
||||
11. **Başlangıç Kayıt Defteri Değerleri (Run & RunOnce):** Otomatik çalıştırma anahtarlarındaki ilgili değerler.
|
||||
12. **Gezgin Sağ Tık & COM Bileşenleri:** `ContextMenuHandlers`, `Approved` shell uzantıları ve ilişkili `CLSID` anahtarları.
|
||||
13. **Windows Shell MuiCache:** MuiCache önbellek ve simge kayıtları.
|
||||
14. **Uyumluluk Katmanı (AppCompatFlags):** Compatibility Assistant ve Layers geçmişi.
|
||||
15. **Windows Güvenlik Duvarı:** `FirewallRules` altındaki ölü kurallar.
|
||||
16. **Windows Prefetch:** `C:\Windows\Prefetch` yürütme önbellek dosyaları.
|
||||
17. **Hata Dökümleri:** `CrashDumps` ve WER arşiv raporları.
|
||||
18. **UserAssist:** ROT13 ile şifrelenen çalıştırma geçmişi.
|
||||
19. **Kısayollar & Son Belgeler:** Masaüstü, Başlat Menüsü, Startup ve Recent kısayolları.
|
||||
20. **Windows Installer (MSI) & Uninstall Kayıtları:** MSI Product/UserData ve Registry Uninstall girdileri.
|
||||
|
||||
### Özellikler
|
||||
### 2. ⚡ Ultra Akıcı Performans & Sıfır Takılma (Fluidity & Optimization)
|
||||
- **Gecikmesiz Arama (Debounced Search):** Arama çubuğuna yazarken UI thread'i dondurmayan 160ms debounce filtreleme.
|
||||
- **Piksel Düzeyinde Pürüzsüz Kaydırma:** DataGrid sanallaştırması `VirtualizingPanel.ScrollUnit="Pixel"` ve `Recycling` modlarıyla 120 FPS akıcılık sağlar.
|
||||
- **Donanım Hızlandırmalı Squarified Treemap:** Vektörel çizim elemanları, dondurulmuş (frozen) Direct3D fırçaları ve statik tipografiler ile anında disk görselleştirmesi.
|
||||
- **Asenkron Başlatma:** Başlangıç yöneticisi ve debloat ayarları arka plan görevlerinde yüklenerek uygulamanın anında açılmasını sağlar.
|
||||
|
||||
- **Uygulama Keşfi & Kaldırma:** Kayıt defteri ve kurulum yollarından yüklü yazılımları listeleme, standart/sessiz kaldırma yürütme ve uygulama listesini CSV olarak dışa aktarma.
|
||||
- **20 Katmanlı Derin Kalıntı Temizliği (`junk_cleaner` & `sift4`):** Kurulum dizinleri, `%AppData%`/`%LocalAppData%`/`ProgramData`, nokta klasörler, Common Files, `%TEMP%`, `HKLM`/`HKCU`/`WOW6432Node` kayıt defteri anahtarları, servisler, zamanlanmış görevler, App Paths, Run/RunOnce, kabuk uzantıları, MuiCache, Prefetch, AppCompatFlags, güvenlik duvarı kuralları, CrashDumps/WER, UserAssist, ölü kısayollar, yetim MSI kayıtları; ayrıca hariç tutma beyaz listesi (`exclusions`).
|
||||
- **Otomatik Kayıt Defteri Yedekleme (`backup_service`):** Silinen kayıt defteri anahtarlarını geri yüklenebilir UTF-8 `.reg` yedekleri olarak saklama ve yedek yöneticisinden tek tıkla geri alma.
|
||||
- **Dosya / Klasör Kilit Açıcı & Shredder (`file_unlocker`):** Windows Restart Manager (`rstrtmgr.dll`) ile kilitleyen süreçleri tespit etme, sonlandırma veya bir sonraki yeniden başlatmada silme (`MoveFileEx`).
|
||||
- **Disk Treemap, Başlangıç & İnce Ayarlar:** Bölüm bazlı görsel disk kullanım haritası (`treemap_service`), Windows başlangıç öğeleri yönetimi (`startup_service`) ve sistem ince ayarları (`tweaks_service`).
|
||||
- **Güvenlik Kalkanı & OTA:** Kanonik yol doğrulaması / kritik sistem dizini koruması (`safety`), döngüsel günlükleme, yönetici yetki denetimi, tekil örnek koruması ve Minisign imzalı OTA güncelleme.
|
||||
### 3. 💾 Çoklu Disk Analizi & Üst Sekmeler (Multi-Drive Tab System)
|
||||
- Bilgisayara takılı tüm aktif diskleri (`C:`, `D:`, harici sürücüler vb.) otomatik tespit eder ve analiz eder.
|
||||
- Birden fazla disk bağlıysa üst kısımda modern sekmeler belirir:
|
||||
- **`🌐 Tüm Diskler`**: Sistemdeki tüm sürücüleri ve tüm yazılımları bir arada sunar.
|
||||
- **`💾 C: (Yerel Disk)`**: C sürücüsündeki yazılımları, kullanılan alanı ve boş kapasiteyi filtreler.
|
||||
- **`💾 D: (Depolama / Oyunlar)`**: İkincil diskteki yazılımları ve Steam/Epic/Games kütüphanelerini listeler.
|
||||
- Disk sekmeleri değiştikçe hem **Yazılım Tablosu** hem de **Disk Haritası (TreeMap)** dinamik olarak güncellenir.
|
||||
|
||||
### Teknoloji Yığını
|
||||
### 4. 🚀 Tek Tıkla Kaldırma & Akıllı Kuyruk Matrisi
|
||||
- Karmaşık butonlar yerine sadece **`🗑️ Kaldır`** butonu. 1 yazılım seçildiğinde tekli, birden fazla seçildiğinde toplu kuyruk yönetimini otomatik üstlenir.
|
||||
- **Çakışma Önleyici Kuyruk (Collision Matrix):** Windows Installer (`_MSIExecute` mutex) kilitlerini, aynı yayıncı ve aynı dizin bağımlılıklarını otomatik olarak sıraya dizer.
|
||||
- **Uninstaller Automatizer Daemon:** UI Automation (FlaUI) arka plan servisi ile kaldırıcı pencerelerindeki "İleri", "Kaldır", "Bitir" adımlarını sessizce otomatik tıklar.
|
||||
|
||||
- **Masaüstü & Çekirdek:** Tauri v2, Rust (`windows` crate Restart Manager/Shell/FileSystem, `winreg`, `sysinfo`, `walkdir`, `trash`, `csv`, `sha2`, `tokio`)
|
||||
- **Arayüz:** React 18, TypeScript, Tailwind CSS, Zustand, Lucide Icons, Vite
|
||||
### 5. ⚡ Başlangıç Yöneticisi & Windows Debloat
|
||||
- **StartupApproved Standardı:** Kayıt defteri ve başlangıç klasörlerindeki programları silmeden güvenle açıp kapatma.
|
||||
- **Debloat Optimizasyonları:** Windows telemetri servislerini (DiagTrack), Cortana/Bing web aramalarını ve sponsorlu arka plan mağaza uygulamalarını tek tıkla kapatma.
|
||||
|
||||
### Kurulum ve Kullanım
|
||||
---
|
||||
|
||||
**Son Kullanıcı:**
|
||||
1. [Releases](https://git.ttmadethat.shop/LilDosto/LD-Uninstaller/releases/latest) sayfasından kurulum paketi `LD-Uninstaller_3.0.2_x64-setup.exe` veya taşınabilir sürüm `LD-Uninstaller-v3.0.2-portable.zip` dosyasını indirin.
|
||||
2. Kaldırmak istediğiniz uygulamayı seçip kalıntı taramasını çalıştırın ve temizlemeden önce yedeklemeleri kontrol edin.
|
||||
## 📦 Dağıtım ve Yayınlama (Release Management)
|
||||
|
||||
Projeyi derlemek ve belirlenen kurallara göre tek klasörde paketlemek için PowerShell otomasyonu:
|
||||
|
||||
**Geliştirici (Kaynaktan Derleme):**
|
||||
```powershell
|
||||
npm install
|
||||
npm run tauri dev # Geliştirme modunda çalıştır
|
||||
npm run tauri build # Kurulum paketi üret
|
||||
# Ufak hata düzeltmesi / bugfix (0.0.1 artırır: v2.4.0 -> v2.4.1)
|
||||
.\release.ps1 -Type patch
|
||||
|
||||
# Orta / yeni özellik güncellemesi (0.1 artırır: v2.4.0 -> v2.5.0)
|
||||
.\release.ps1 -Type minor
|
||||
|
||||
# Büyük mimari güncelleme (1 artırır: v2.4.0 -> v3.0.0)
|
||||
.\release.ps1 -Type major
|
||||
```
|
||||
|
||||
Script, kök dizindeki eski sürümleri temizler, yalnızca en güncel sürüm klasörünü (`LD Uninstaller vX.Y.Z`) oluşturur ve GitHub Releases üzerinde yayınlar.
|
||||
|
||||
---
|
||||
|
||||
## 💻 Başlatma ve Kullanım
|
||||
|
||||
```powershell
|
||||
# Yönetici yetkili başlatıcı:
|
||||
.\LD Uninstaller v2.5.0\LDUninstaller.Launcher.exe
|
||||
|
||||
# veya doğrudan arayüz:
|
||||
.\LD Uninstaller v2.5.0\LDUninstaller.UI.exe
|
||||
|
||||
# SysAdmin ve Otomasyon için CLI aracı:
|
||||
.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe list /F=table
|
||||
.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe export software_inventory.json /F=json
|
||||
.\LD Uninstaller v2.5.0\LDUninstaller.CLI.exe debloat --list
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🇬🇧 English
|
||||
## 📄 Lisans
|
||||
|
||||
**LD Uninstaller** is a high-performance Windows uninstaller and system maintenance utility built with Tauri v2, Rust, and React 18, featuring a 20-layer leftover scanner, Windows Restart Manager file unlocker, registry backups, and disk treemap visualization.
|
||||
|
||||
### Features
|
||||
|
||||
- **Application Discovery & Uninstallation:** Enumerates installed software, triggers native uninstallers, and exports the application inventory to CSV.
|
||||
- **20-Layer Deep Leftover Cleaner (`junk_cleaner` & `sift4`):** Scans leftover install folders, `%AppData%`/`%LocalAppData%`/`ProgramData`, dot-folders, Common Files, `%TEMP%`, `HKLM`/`HKCU`/`WOW6432Node` registry keys, services, scheduled tasks, App Paths, Run/RunOnce entries, shell extensions, MuiCache, Prefetch, AppCompatFlags, firewall rules, CrashDumps/WER, UserAssist, broken shortcuts, and orphan MSI entries, with customizable exclusion rules.
|
||||
- **Automatic Registry Backups (`backup_service`):** Exports removed registry entries to UTF-8 `.reg` backups with one-click restore and backup management.
|
||||
- **File / Folder Unlocker & Shredder (`file_unlocker`):** Detects locking processes via Windows Restart Manager (`rstrtmgr.dll`), safely terminates locks, or schedules deletion on reboot.
|
||||
- **Disk Treemap, Startup & Tweaks:** Visualizes disk space usage per partition (`treemap_service`), toggles Windows startup items (`startup_service`), and manages system tweaks (`tweaks_service`).
|
||||
- **Safety Guardrails & OTA:** Path traversal / system directory protection (`safety`), rotating log files, elevation detection, single-instance guard, and Minisign-verified OTA updates.
|
||||
|
||||
### Tech Stack
|
||||
|
||||
- **Desktop & Backend:** Tauri v2, Rust (`windows` crate Restart Manager/Shell/FileSystem, `winreg`, `sysinfo`, `walkdir`, `trash`, `csv`, `sha2`, `tokio`)
|
||||
- **Frontend:** React 18, TypeScript, Tailwind CSS, Zustand, Lucide Icons, Vite
|
||||
|
||||
### Installation & Usage
|
||||
|
||||
**End Users:**
|
||||
1. Download `LD-Uninstaller_3.0.2_x64-setup.exe` (installer) or `LD-Uninstaller-v3.0.2-portable.zip` (portable) from the [Releases](https://git.ttmadethat.shop/LilDosto/LD-Uninstaller/releases/latest) page.
|
||||
2. Select any installed program to uninstall and scan/clean leftovers with automatic `.reg` backup safety.
|
||||
|
||||
**Developers (Build from Source):**
|
||||
```powershell
|
||||
npm install
|
||||
npm run tauri dev # Run in development mode
|
||||
npm run tauri build # Build Windows installer
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📄 Lisans / License
|
||||
|
||||
Bu proje [MIT Lisansı](./LICENSE) altında lisanslanmıştır. • Licensed under the [MIT License](./LICENSE).
|
||||
Bu proje [MIT Lisansı](LICENSE) kapsamında lisanslanmıştır. Detaylar için [`LICENSE`](LICENSE) dosyasına göz atabilirsiniz.
|
||||
|
|
|
|||
|
|
@ -1,3 +0,0 @@
|
|||
@echo off
|
||||
ssh -i "%USERPROFILE%\.ssh\id_ed25519" root@116.202.14.171
|
||||
pause
|
||||
14
index.html
|
|
@ -1,14 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/png" href="/logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>LD Uninstaller</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -1,14 +1,14 @@
|
|||
#ifndef MyAppVersion
|
||||
#define MyAppVersion "2.8.0"
|
||||
#define MyAppVersion "2.5.0"
|
||||
#endif
|
||||
|
||||
#ifndef SourceDir
|
||||
#define SourceDir "LD Uninstaller v2.8.0"
|
||||
#define SourceDir "LD Uninstaller v2.5.0"
|
||||
#endif
|
||||
|
||||
#define MyAppName "LD Uninstaller"
|
||||
#define MyAppPublisher "LD Software"
|
||||
#define MyAppURL "https://ttmadethat.shop/#ldapps"
|
||||
#define MyAppURL "https://github.com/LilDosto/LD-Unistaller"
|
||||
#define MyAppExeName "LDUninstaller.Launcher.exe"
|
||||
|
||||
[Setup]
|
||||
|
|
@ -17,7 +17,6 @@ AppName={#MyAppName}
|
|||
AppVersion={#MyAppVersion}
|
||||
AppPublisher={#MyAppPublisher}
|
||||
AppPublisherURL={#MyAppURL}
|
||||
AppSupportURL={#MyAppURL}
|
||||
AppUpdatesURL={#MyAppURL}
|
||||
DefaultDirName={autopf}\{#MyAppName}
|
||||
DisableProgramGroupPage=yes
|
||||
|
|
@ -30,8 +29,6 @@ SolidCompression=yes
|
|||
WizardStyle=modern
|
||||
PrivilegesRequired=admin
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
CloseApplications=yes
|
||||
RestartApplications=no
|
||||
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||
|
||||
[Languages]
|
||||
|
|
@ -51,16 +48,3 @@ Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: de
|
|||
|
||||
[Run]
|
||||
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
|
||||
|
||||
[Registry]
|
||||
Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\Directory\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey
|
||||
|
||||
Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\exefile\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey
|
||||
|
||||
Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall"; ValueType: string; ValueData: "💥 LD ile Güçlü Kaldır"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall"; ValueType: string; ValueName: "Icon"; ValueData: """{app}\{#MyAppExeName}"",0"; Flags: uninsdeletekey
|
||||
Root: HKCU; Subkey: "Software\Classes\lnkfile\shell\LDForceUninstall\command"; ValueType: string; ValueData: """{app}\{#MyAppExeName}"" --force-path ""%1"""; Flags: uninsdeletekey
|
||||
|
|
|
|||
3160
package-lock.json
generated
36
package.json
|
|
@ -1,36 +0,0 @@
|
|||
{
|
||||
"name": "ld-uninstaller",
|
||||
"private": true,
|
||||
"version": "3.0.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.2.0",
|
||||
"@tauri-apps/plugin-opener": "^2.2.5",
|
||||
"@tauri-apps/plugin-process": "^2.4.0",
|
||||
"@tauri-apps/plugin-updater": "^2.14.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"tailwind-merge": "^2.5.5",
|
||||
"zustand": "^5.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "^2.2.0",
|
||||
"@types/node": "^22.10.1",
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.49",
|
||||
"tailwindcss": "^3.4.16",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.0.3"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
BIN
public/logo.png
|
Before Width: | Height: | Size: 21 KiB |
|
|
@ -1,6 +0,0 @@
|
|||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
|
|
@ -1 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
312
release.ps1
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
param(
|
||||
[ValidateSet("major", "minor", "patch", "current")]
|
||||
[string]$Type = "current",
|
||||
[string]$Message = ""
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$root = $PSScriptRoot
|
||||
if (-not $root) { $root = (Get-Location).Path }
|
||||
|
||||
$versionFile = Join-Path $root "version.json"
|
||||
$propsFile = Join-Path $root "Directory.Build.props"
|
||||
|
||||
if (-not (Test-Path $versionFile)) {
|
||||
@{ major = 2; minor = 5; patch = 0; version = "2.5.0" } | ConvertTo-Json | Set-Content $versionFile
|
||||
}
|
||||
|
||||
$vData = Get-Content $versionFile -Raw | ConvertFrom-Json
|
||||
$major = [int]$vData.major
|
||||
$minor = [int]$vData.minor
|
||||
$patch = [int]$vData.patch
|
||||
|
||||
switch ($Type.ToLowerInvariant()) {
|
||||
"major" {
|
||||
$major += 1
|
||||
$minor = 0
|
||||
$patch = 0
|
||||
}
|
||||
"minor" {
|
||||
$minor += 1
|
||||
$patch = 0
|
||||
}
|
||||
"patch" {
|
||||
$patch += 1
|
||||
}
|
||||
"current" {
|
||||
# Keep existing version
|
||||
}
|
||||
}
|
||||
|
||||
$newVersion = "$major.$minor.$patch"
|
||||
$vData.major = $major
|
||||
$vData.minor = $minor
|
||||
$vData.patch = $patch
|
||||
$vData.version = $newVersion
|
||||
|
||||
$vData | ConvertTo-Json | Set-Content $versionFile -Encoding UTF8
|
||||
|
||||
# Update Directory.Build.props
|
||||
$propsContent = @"
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<Version>$newVersion</Version>
|
||||
<AssemblyVersion>$newVersion.0</AssemblyVersion>
|
||||
<FileVersion>$newVersion.0</FileVersion>
|
||||
<Product>LD Uninstaller</Product>
|
||||
<Company>LD Software</Company>
|
||||
<Authors>LD Software</Authors>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
"@
|
||||
Set-Content -Path $propsFile -Value $propsContent -Encoding UTF8
|
||||
|
||||
Write-Host "==========================================" -ForegroundColor Cyan
|
||||
Write-Host " LD UNINSTALLER SURUM YAYINLAMA: v$newVersion" -ForegroundColor Yellow
|
||||
Write-Host "==========================================" -ForegroundColor Cyan
|
||||
|
||||
# 1. Ana klasorde eski surumleri temizle
|
||||
$oldFolders = Get-ChildItem -Path $root -Directory -Filter "LD Uninstaller v*"
|
||||
foreach ($old in $oldFolders) {
|
||||
Write-Host "Eski surum klasoru temizleniyor: $($old.Name)..." -ForegroundColor Gray
|
||||
try {
|
||||
Remove-Item -Path $old.FullName -Recurse -Force -ErrorAction SilentlyContinue
|
||||
} catch { }
|
||||
}
|
||||
|
||||
# Eski kurulum exe ve zip dosyalarini temizle
|
||||
Get-ChildItem -Path $root -File -Filter "LD-Uninstaller-Setup-v*.exe" | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
Get-ChildItem -Path $root -File -Filter "LD-Uninstaller-v*.zip" | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
|
||||
$targetFolderName = "LD Uninstaller v$newVersion"
|
||||
$targetDir = Join-Path $root $targetFolderName
|
||||
|
||||
Write-Host "Yeni surum klasoru olusturuluyor: $targetFolderName..." -ForegroundColor Green
|
||||
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
|
||||
|
||||
# 2. Projeleri Release modunda derle ve yayinla
|
||||
Write-Host "Projeler derleniyor ve yayinlaniyor..." -ForegroundColor Cyan
|
||||
|
||||
$projects = @(
|
||||
"src/LDUninstaller.UI/LDUninstaller.UI.csproj",
|
||||
"src/LDUninstaller.CLI/LDUninstaller.CLI.csproj",
|
||||
"src/LDUninstaller.Automatizer/LDUninstaller.Automatizer.csproj",
|
||||
"src/LDUninstaller.Launcher/LDUninstaller.Launcher.csproj"
|
||||
)
|
||||
|
||||
foreach ($proj in $projects) {
|
||||
$projPath = Join-Path $root $proj
|
||||
Write-Host " -> Yayinlaniyor: $proj" -ForegroundColor Gray
|
||||
dotnet publish $projPath -c Release -o $targetDir --nologo -v q
|
||||
}
|
||||
|
||||
# 3. Gereksiz pdb ve log dosyalarini temizle
|
||||
Get-ChildItem -Path $targetDir -Filter "*.pdb" | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
|
||||
# 4. Eski publish ve dist klasorlerini de temizle
|
||||
try { Remove-Item -Path (Join-Path $root "publish") -Recurse -Force -ErrorAction SilentlyContinue } catch { }
|
||||
try { Remove-Item -Path (Join-Path $root "dist") -Recurse -Force -ErrorAction SilentlyContinue } catch { }
|
||||
|
||||
# 5. Windows Kurulum Sihirbazi (Setup.exe) ve ZIP Arsivini Olustur
|
||||
Copy-Item (Join-Path $root "app.ico") (Join-Path $targetDir "app.ico") -Force
|
||||
|
||||
# Inno Setup ile Setup.exe derle
|
||||
$isccCandidates = @(
|
||||
"C:\Users\lildosto\AppData\Local\Programs\Inno Setup 6\ISCC.exe",
|
||||
"C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
|
||||
"C:\Program Files\Inno Setup 6\ISCC.exe"
|
||||
)
|
||||
$isccPath = $null
|
||||
foreach ($cand in $isccCandidates) {
|
||||
if (Test-Path $cand) { $isccPath = $cand; break }
|
||||
}
|
||||
|
||||
$setupName = "LD-Uninstaller-Setup-v$newVersion.exe"
|
||||
$setupPath = Join-Path $root $setupName
|
||||
|
||||
if ($isccPath -and (Test-Path (Join-Path $root "installer.iss"))) {
|
||||
Write-Host "Windows Kurulum Sihirbazi derleniyor: $setupName..." -ForegroundColor Cyan
|
||||
& $isccPath /Q "/DMyAppVersion=$newVersion" "/DSourceDir=$targetDir" (Join-Path $root "installer.iss")
|
||||
if (Test-Path $setupPath) {
|
||||
Write-Host "Kurulum dosyasi basariyla olusturuldu: $setupName" -ForegroundColor Green
|
||||
}
|
||||
}
|
||||
|
||||
# Portable ZIP arsivi
|
||||
$zipName = "LD-Uninstaller-v$newVersion.zip"
|
||||
$zipPath = Join-Path $root $zipName
|
||||
Write-Host "Surum zip arsivi olusturuluyor: $zipName..." -ForegroundColor Cyan
|
||||
Compress-Archive -Path "$targetDir\*" -DestinationPath $zipPath -Force
|
||||
|
||||
# 6. Git Islemleri ve GitHub Push
|
||||
if (Test-Path (Join-Path $root ".git")) {
|
||||
Write-Host "`nGit degisiklikleri isleniyor ve GitHub'a aktariliyor..." -ForegroundColor Cyan
|
||||
try {
|
||||
if ([string]::IsNullOrWhiteSpace($Message)) {
|
||||
$Message = "Release v${newVersion}: Standart Windows Kurulum Sihirbazi ve Otomasyon"
|
||||
}
|
||||
git add .
|
||||
git commit -m $Message
|
||||
git tag -a "v$newVersion" -m "LD Uninstaller v$newVersion - $Message" -f
|
||||
|
||||
$remote = git remote get-url origin 2>$null
|
||||
if ($remote) {
|
||||
Write-Host "GitHub'a gonderiliyor (origin master --tags)..." -ForegroundColor Yellow
|
||||
git push origin master --tags -u -f
|
||||
}
|
||||
} catch {
|
||||
Write-Host "Git islemi uyarisi: $_" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
# 7. GitHub Releases API Uzerinde Surum ve Notlari Yayinla
|
||||
try {
|
||||
Write-Host "`nGitHub Releases API uzerinden surum ve notlar yayinlaniyor..." -ForegroundColor Cyan
|
||||
|
||||
$code = @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
public class GitCredsEngine2
|
||||
{
|
||||
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
public static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct CREDENTIAL
|
||||
{
|
||||
public int Flags;
|
||||
public int Type;
|
||||
public string TargetName;
|
||||
public string Comment;
|
||||
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
|
||||
public int CredentialBlobSize;
|
||||
public IntPtr CredentialBlob;
|
||||
public int Persist;
|
||||
public int AttributeCount;
|
||||
public IntPtr Attributes;
|
||||
public string TargetAlias;
|
||||
public string UserName;
|
||||
}
|
||||
|
||||
public static string GetToken()
|
||||
{
|
||||
IntPtr credPtr;
|
||||
if (CredRead("git:https://github.com", 1, 0, out credPtr))
|
||||
{
|
||||
var cred = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
|
||||
byte[] bytes = new byte[cred.CredentialBlobSize];
|
||||
Marshal.Copy(cred.CredentialBlob, bytes, 0, cred.CredentialBlobSize);
|
||||
return Encoding.Unicode.GetString(bytes).Trim('\0', ' ', '\r', '\n');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
"@
|
||||
if (-not ([System.Management.Automation.PSTypeName]'GitCredsEngine2').Type) {
|
||||
Add-Type -TypeDefinition $code -Language CSharp
|
||||
}
|
||||
|
||||
$token = [GitCredsEngine2]::GetToken()
|
||||
if ($env:GITHUB_TOKEN) { $token = $env:GITHUB_TOKEN }
|
||||
if ($env:GH_TOKEN) { $token = $env:GH_TOKEN }
|
||||
|
||||
if (-not $token) {
|
||||
Write-Host "Uyari: GitHub kimlik belirteci bulunamadi. Release API atlaniyor." -ForegroundColor Yellow
|
||||
} else {
|
||||
$apiHeaders = @{
|
||||
"Authorization" = "Bearer $token"
|
||||
"User-Agent" = "LDUninstaller-ReleaseScript"
|
||||
"Accept" = "application/vnd.github+json"
|
||||
}
|
||||
|
||||
$repoOwner = "LilDosto"
|
||||
$repoName = "LD-Unistaller"
|
||||
|
||||
# Changelog / Surum Notlari (Sablon dosyasindan UTF-8 olarak okunur)
|
||||
$templatePath = Join-Path $root "release_notes_template.md"
|
||||
$releaseNotes = ""
|
||||
if (Test-Path $templatePath) {
|
||||
$releaseNotes = [System.IO.File]::ReadAllText($templatePath, [System.Text.Encoding]::UTF8)
|
||||
$releaseNotes = $releaseNotes.Replace("{VERSION}", $newVersion)
|
||||
} else {
|
||||
$releaseNotes = "LD Uninstaller v$newVersion guncellemesi."
|
||||
}
|
||||
|
||||
$releaseTitle = if (![string]::IsNullOrWhiteSpace($Message)) { $Message } else { "LDUninstaller-v$newVersion - Setup" }
|
||||
|
||||
$releasePayload = @{
|
||||
tag_name = "v$newVersion"
|
||||
name = $releaseTitle
|
||||
body = $releaseNotes
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json -Depth 5
|
||||
|
||||
$jsonBytes = [System.Text.Encoding]::UTF8.GetBytes($releasePayload)
|
||||
|
||||
$releaseUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases/tags/v$newVersion"
|
||||
$ghRelease = $null
|
||||
try {
|
||||
$ghRelease = Invoke-RestMethod -Uri $releaseUrl -Headers $apiHeaders -Method Get -ErrorAction Stop
|
||||
} catch { }
|
||||
|
||||
if ($ghRelease) {
|
||||
Write-Host "Mevcut release guncelleniyor (ID: $($ghRelease.id))..." -ForegroundColor Yellow
|
||||
$patchUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases/$($ghRelease.id)"
|
||||
$ghRelease = Invoke-RestMethod -Uri $patchUrl -Headers $apiHeaders -Method Patch -Body $jsonBytes -ContentType "application/json; charset=utf-8"
|
||||
} else {
|
||||
Write-Host "Yeni release olusturuluyor..." -ForegroundColor Green
|
||||
$postUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases"
|
||||
$ghRelease = Invoke-RestMethod -Uri $postUrl -Headers $apiHeaders -Method Post -Body $jsonBytes -ContentType "application/json; charset=utf-8"
|
||||
}
|
||||
|
||||
# Dosyalari release asset olarak yukle (Setup.exe ve zip)
|
||||
$filesToUpload = @($setupPath, $zipPath) | Where-Object { Test-Path $_ }
|
||||
foreach ($fPath in $filesToUpload) {
|
||||
$fName = Split-Path $fPath -Leaf
|
||||
Write-Host "Release varligi yukleniyor: $fName..." -ForegroundColor Cyan
|
||||
|
||||
if ($ghRelease.assets) {
|
||||
foreach ($asset in $ghRelease.assets) {
|
||||
if ($asset.name -eq $fName) {
|
||||
try {
|
||||
Invoke-RestMethod -Uri "https://api.github.com/repos/$repoOwner/$repoName/releases/assets/$($asset.id)" -Headers $apiHeaders -Method Delete | Out-Null
|
||||
} catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$uploadUri = $ghRelease.upload_url -replace '\{\?name,label\}', "?name=$fName"
|
||||
$contentType = if ($fName.EndsWith(".exe")) { "application/vnd.microsoft.portable-executable" } else { "application/zip" }
|
||||
$uploadHeaders = @{
|
||||
"Authorization" = "Bearer $token"
|
||||
"User-Agent" = "LDUninstaller-ReleaseScript"
|
||||
"Accept" = "application/vnd.github+json"
|
||||
}
|
||||
$fileBytes = [System.IO.File]::ReadAllBytes($fPath)
|
||||
$uploadResult = Invoke-RestMethod -Uri $uploadUri -Headers $uploadHeaders -Method Post -Body $fileBytes -ContentType $contentType
|
||||
Write-Host "Yuklendi: $($uploadResult.browser_download_url)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
Write-Host "`nGitHub Release yayinda:" -ForegroundColor Yellow
|
||||
Write-Host " -> https://github.com/$repoOwner/$repoName/releases/tag/v$newVersion" -ForegroundColor White
|
||||
}
|
||||
} catch {
|
||||
Write-Host "GitHub Releases API islemi uyarisi: $_" -ForegroundColor Yellow
|
||||
}
|
||||
|
||||
Write-Host "`n[+] Basariyla Tamamlandi!" -ForegroundColor Green
|
||||
Write-Host "Ana dizinde olusturulan son guncel surum klasoru:" -ForegroundColor Yellow
|
||||
Write-Host " -> $targetFolderName" -ForegroundColor White
|
||||
Write-Host "Standart Kurulum Paketi (Setup.exe):" -ForegroundColor Cyan
|
||||
Write-Host " -> $setupName" -ForegroundColor White
|
||||
Write-Host "GitHub Release hazir paketi:" -ForegroundColor White
|
||||
Write-Host " -> $zipName" -ForegroundColor Cyan
|
||||
Write-Host "Kullanima hazir yurutulebilir dosyalar:" -ForegroundColor Gray
|
||||
Write-Host " - LDUninstaller.Launcher.exe (Yonetici yetkili baslatici)"
|
||||
Write-Host " - LDUninstaller.UI.exe (Modern Fluent Arayuz)"
|
||||
Write-Host " - LDUninstaller.CLI.exe (Konsol araci)"
|
||||
Write-Host " - LDUninstaller.Automatizer.exe (Otomasyon ajani)`n"
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="2.8.0.0" name="LDUninstaller.CLI"/>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 and Windows 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
|
||||
<!-- Windows 8.1 -->
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
|
||||
<!-- Windows 8 -->
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
|
||||
<!-- Windows 7 -->
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
|
||||
</application>
|
||||
</compatibility>
|
||||
</assembly>
|
||||
|
|
@ -1,656 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.ServiceProcess;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using LDUninstaller.Core.Algorithms;
|
||||
using LDUninstaller.Core.Models;
|
||||
using LDUninstaller.Core.Native;
|
||||
|
||||
namespace LDUninstaller.Core.Bulk
|
||||
{
|
||||
public enum BulkStatus
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Skipped,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
public class BulkUninstallEntry : INotifyPropertyChanged
|
||||
{
|
||||
public ApplicationUninstallerEntry Entry { get; }
|
||||
|
||||
private BulkStatus _status = BulkStatus.Queued;
|
||||
public BulkStatus Status
|
||||
{
|
||||
get => _status;
|
||||
set
|
||||
{
|
||||
if (_status != value)
|
||||
{
|
||||
_status = value;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(StatusBadgeColor));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string _statusMessage = "Kuyrukta";
|
||||
public string StatusMessage
|
||||
{
|
||||
get => _statusMessage;
|
||||
set
|
||||
{
|
||||
if (_statusMessage != value)
|
||||
{
|
||||
_statusMessage = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool PreferQuiet { get; set; } = true;
|
||||
public int ExitCode { get; set; } = -1;
|
||||
public bool IsEffectivelyUninstalled { get; set; }
|
||||
|
||||
public string StatusBadgeColor => Status switch
|
||||
{
|
||||
BulkStatus.Succeeded => "#10B981",
|
||||
BulkStatus.Failed => "#EF4444",
|
||||
BulkStatus.Running => "#3B82F6",
|
||||
BulkStatus.Cancelled => "#F59E0B",
|
||||
_ => "#6B7280"
|
||||
};
|
||||
|
||||
public BulkUninstallEntry(ApplicationUninstallerEntry entry, bool preferQuiet = true)
|
||||
{
|
||||
Entry = entry;
|
||||
PreferQuiet = preferQuiet;
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
protected void OnPropertyChanged([CallerMemberName] string? name = null) =>
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
||||
}
|
||||
|
||||
public class BulkUninstallTask
|
||||
{
|
||||
public List<BulkUninstallEntry> Items { get; }
|
||||
public int MaxConcurrentQuiet { get; set; } = 2;
|
||||
public bool CreateRestorePoint { get; set; } = true;
|
||||
public bool EnableAutomatizer { get; set; } = true;
|
||||
|
||||
public event Action<BulkUninstallEntry>? OnItemStarted;
|
||||
public event Action<BulkUninstallEntry>? OnItemCompleted;
|
||||
public event Action<string>? OnLog;
|
||||
|
||||
private readonly SemaphoreSlim _msiLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _loudLimitLock = new(1, 1);
|
||||
private readonly object _stateLock = new();
|
||||
private readonly HashSet<string> _activePublishers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly HashSet<string> _activeDirectories = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public BulkUninstallTask(IEnumerable<ApplicationUninstallerEntry> entries, bool preferQuiet = true)
|
||||
{
|
||||
Items = entries.Select(e => new BulkUninstallEntry(e, preferQuiet)).ToList();
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
long restoreSeq = 0;
|
||||
if (CreateRestorePoint)
|
||||
{
|
||||
OnLog?.Invoke("Sistem Geri Yükleme Noktası oluşturuluyor...");
|
||||
await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out restoreSeq));
|
||||
}
|
||||
|
||||
if (EnableAutomatizer)
|
||||
{
|
||||
EnsureAutomatizerRunning();
|
||||
}
|
||||
|
||||
var throttler = new SemaphoreSlim(MaxConcurrentQuiet, MaxConcurrentQuiet);
|
||||
var runningTasks = new List<Task>();
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var item in Items)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
item.Status = BulkStatus.Cancelled;
|
||||
item.StatusMessage = "İptal edildi";
|
||||
continue;
|
||||
}
|
||||
|
||||
bool isSerialized = IsSerializedType(item.Entry.UninstallerKind);
|
||||
|
||||
if (isSerialized)
|
||||
{
|
||||
await Task.WhenAll(runningTasks);
|
||||
runningTasks.Clear();
|
||||
|
||||
await RunSingleItemAsync(item, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await throttler.WaitAsync(cancellationToken);
|
||||
|
||||
var t = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunSingleItemAsync(item, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
throttler.Release();
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
runningTasks.Add(t);
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(runningTasks);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (restoreSeq > 0)
|
||||
{
|
||||
Win32.EndRestorePoint(restoreSeq);
|
||||
}
|
||||
|
||||
if (EnableAutomatizer)
|
||||
{
|
||||
StopAutomatizerDaemon();
|
||||
}
|
||||
|
||||
OnLog?.Invoke("Tüm toplu kaldırma işlemleri tamamlandı.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunSingleItemAsync(BulkUninstallEntry item, CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
item.Status = BulkStatus.Cancelled;
|
||||
item.StatusMessage = "İptal edildi";
|
||||
return;
|
||||
}
|
||||
|
||||
string pub = Sift4.NormalizeName(item.Entry.Publisher);
|
||||
bool pubAcquired = false;
|
||||
|
||||
string dir = !string.IsNullOrWhiteSpace(item.Entry.InstallLocation)
|
||||
? Path.GetFullPath(item.Entry.InstallLocation).TrimEnd('\\')
|
||||
: string.Empty;
|
||||
|
||||
while (!pubAcquired && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
bool pubConflict = !string.IsNullOrWhiteSpace(pub) && _activePublishers.Contains(pub);
|
||||
bool dirConflict = !string.IsNullOrWhiteSpace(dir) && _activeDirectories.Any(d =>
|
||||
d.Equals(dir, StringComparison.OrdinalIgnoreCase) ||
|
||||
dir.StartsWith(d + "\\", StringComparison.OrdinalIgnoreCase) ||
|
||||
d.StartsWith(dir + "\\", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!pubConflict && !dirConflict)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Add(pub);
|
||||
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Add(dir);
|
||||
pubAcquired = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pubAcquired)
|
||||
{
|
||||
await Task.Delay(500, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
bool msiLocked = false;
|
||||
if (item.Entry.UninstallerKind == UninstallerType.Msiexec)
|
||||
{
|
||||
await _msiLock.WaitAsync(cancellationToken);
|
||||
msiLocked = true;
|
||||
await WaitForActiveMsiProcesses(cancellationToken);
|
||||
}
|
||||
|
||||
bool isQuiet = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString);
|
||||
bool loudLocked = false;
|
||||
if (!isQuiet)
|
||||
{
|
||||
await _loudLimitLock.WaitAsync(cancellationToken);
|
||||
loudLocked = true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
item.Status = BulkStatus.Running;
|
||||
item.StatusMessage = "Çalıştırılıyor...";
|
||||
OnItemStarted?.Invoke(item);
|
||||
OnLog?.Invoke($"Kaldırma başladı: {item.Entry.DisplayName}");
|
||||
|
||||
// Pre-kill locking processes in install folder (B9, P9)
|
||||
PreKillLockingProcesses(item.Entry);
|
||||
|
||||
// Stop services in install folder (B9)
|
||||
PreStopServices(item.Entry);
|
||||
|
||||
// Execute Uninstaller Process
|
||||
int exitCode = await ExecuteUninstallerProcessAsync(item, cancellationToken);
|
||||
item.ExitCode = exitCode;
|
||||
|
||||
// B18: Valid exit codes for success: 0, 1605 (already uninstalled), 1641, 3010
|
||||
bool exitCodeSuccess = exitCode == 0 || exitCode == 1605 || exitCode == 1641 || exitCode == 3010;
|
||||
|
||||
// B3: Verify whether it is effectively uninstalled
|
||||
bool isTargetGone = IsTargetEffectivelyRemoved(item.Entry);
|
||||
|
||||
if (exitCodeSuccess || isTargetGone)
|
||||
{
|
||||
item.IsEffectivelyUninstalled = true;
|
||||
item.Status = BulkStatus.Succeeded;
|
||||
item.StatusMessage = (exitCode == 3010 || exitCode == 1641)
|
||||
? "Başarılı (Yeniden başlatma gerekli)"
|
||||
: "Başarıyla kaldırıldı";
|
||||
}
|
||||
else
|
||||
{
|
||||
item.IsEffectivelyUninstalled = false;
|
||||
item.Status = BulkStatus.Failed;
|
||||
item.StatusMessage = $"Hata (Çıkış kodu: {exitCode})";
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
item.Status = BulkStatus.Cancelled;
|
||||
item.StatusMessage = "İptal edildi";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
item.Status = BulkStatus.Failed;
|
||||
item.StatusMessage = $"Hata: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Remove(pub);
|
||||
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Remove(dir);
|
||||
}
|
||||
|
||||
if (msiLocked) _msiLock.Release();
|
||||
if (loudLocked) _loudLimitLock.Release();
|
||||
|
||||
OnItemCompleted?.Invoke(item);
|
||||
OnLog?.Invoke($"Tamamlandı [{item.Status}]: {item.Entry.DisplayName}");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsTargetEffectivelyRemoved(ApplicationUninstallerEntry entry)
|
||||
{
|
||||
// If install directory was populated and is now gone:
|
||||
if (!string.IsNullOrWhiteSpace(entry.InstallLocation) && !Directory.Exists(entry.InstallLocation))
|
||||
return true;
|
||||
|
||||
// If registry key existed and is now gone:
|
||||
if (!string.IsNullOrWhiteSpace(entry.RegistryPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
var (hive, subKey, view) = RegistryJunkResult.ParseRegistryPath(entry.RegistryPath);
|
||||
using var baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey(hive, view);
|
||||
using var key = baseKey.OpenSubKey(subKey);
|
||||
if (key == null) return true;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<int> ExecuteUninstallerProcessAsync(BulkUninstallEntry item, CancellationToken token)
|
||||
{
|
||||
string command = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString)
|
||||
? item.Entry.QuietUninstallString
|
||||
: item.Entry.UninstallString;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(command))
|
||||
{
|
||||
// Simple delete fallback for orphaned software (only if specifically marked orphaned)
|
||||
if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation) && !Junk.SafetyBlacklist.IsDangerousDirectory(item.Entry.InstallLocation))
|
||||
{
|
||||
try
|
||||
{
|
||||
Win32.SendToRecycleBin(item.Entry.InstallLocation);
|
||||
return 0;
|
||||
}
|
||||
catch { return -1; }
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// B18: Protocol commands like steam://
|
||||
if (command.StartsWith("steam://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(command) { UseShellExecute = true });
|
||||
await Task.Delay(4000, token);
|
||||
return 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
var (fileName, args) = SplitCommand(command);
|
||||
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
UseShellExecute = true,
|
||||
CreateNoWindow = item.PreferQuiet
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(item.Entry.InstallLocation) && Directory.Exists(item.Entry.InstallLocation))
|
||||
{
|
||||
psi.WorkingDirectory = item.Entry.InstallLocation;
|
||||
}
|
||||
|
||||
Process? process = null;
|
||||
try
|
||||
{
|
||||
process = Process.Start(psi);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
OnLog?.Invoke($"Çalıştırma hatası ({fileName}): {ex.Message}");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (process == null) return -1;
|
||||
|
||||
using (process)
|
||||
{
|
||||
if (EnableAutomatizer)
|
||||
{
|
||||
NotifyAutomatizerDaemon(process.Id);
|
||||
}
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
|
||||
// Wait for main process
|
||||
try
|
||||
{
|
||||
await process.WaitForExitAsync(token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
try { Win32.GentleKillProcess(process, 1500); } catch { }
|
||||
throw;
|
||||
}
|
||||
|
||||
int exitCode = process.ExitCode;
|
||||
|
||||
// B4: Watch for child / temp uninstaller processes (Inno Setup / NSIS)
|
||||
if (sw.ElapsedMilliseconds < 4000 && (exitCode == 0 || exitCode == 3010))
|
||||
{
|
||||
await WaitForPotentialChildUninstallers(item.Entry, token);
|
||||
}
|
||||
|
||||
return exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitForPotentialChildUninstallers(ApplicationUninstallerEntry entry, CancellationToken token)
|
||||
{
|
||||
string tempDir = Path.GetTempPath();
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
if (token.IsCancellationRequested) break;
|
||||
|
||||
bool childActive = false;
|
||||
try
|
||||
{
|
||||
// Inno Setup spawns _iu*.tmp processes
|
||||
// NSIS spawns Au_.exe processes
|
||||
var procs = Process.GetProcesses();
|
||||
foreach (var p in procs)
|
||||
{
|
||||
using (p)
|
||||
{
|
||||
try
|
||||
{
|
||||
string name = p.ProcessName.ToLowerInvariant();
|
||||
if (name.StartsWith("_iu") || name.Equals("au_") || name.Contains("uninstall"))
|
||||
{
|
||||
string? path = Win32.GetProcessPath(p.Id);
|
||||
if (!string.IsNullOrEmpty(path) && path.StartsWith(tempDir, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
childActive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
if (!childActive)
|
||||
{
|
||||
if (i >= 2) break; // If no child after a couple seconds, assume finished
|
||||
}
|
||||
|
||||
await Task.Delay(1000, token);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureAutomatizerRunning()
|
||||
{
|
||||
_ = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var existing = Process.GetProcessesByName("LDUninstaller.Automatizer");
|
||||
if (existing.Length > 0)
|
||||
{
|
||||
foreach (var p in existing) p.Dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
|
||||
string autoExe = Path.Combine(baseDir, "LDUninstaller.Automatizer.exe");
|
||||
if (File.Exists(autoExe))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(autoExe, "--daemon")
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void StopAutomatizerDaemon()
|
||||
{
|
||||
_ = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out);
|
||||
client.Connect(500);
|
||||
using var writer = new StreamWriter(client);
|
||||
writer.WriteLine("SHUTDOWN");
|
||||
writer.Flush();
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void NotifyAutomatizerDaemon(int pid)
|
||||
{
|
||||
_ = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out);
|
||||
client.Connect(1000);
|
||||
using var writer = new StreamWriter(client);
|
||||
writer.WriteLine($"ATTACH:{pid}");
|
||||
writer.Flush();
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void PreKillLockingProcesses(ApplicationUninstallerEntry entry)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
// B9: Add trailing directory separator so C:\Foo doesn't kill C:\FooBar
|
||||
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar;
|
||||
int currentPid = Process.GetCurrentProcess().Id;
|
||||
var procs = Process.GetProcesses();
|
||||
|
||||
foreach (var p in procs)
|
||||
{
|
||||
using (p)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (p.Id == currentPid) continue;
|
||||
|
||||
// P9: Use Win32 QueryFullProcessImageName to avoid Access Denied Win32Exceptions
|
||||
string? exePath = Win32.GetProcessPath(p.Id);
|
||||
if (!string.IsNullOrWhiteSpace(exePath))
|
||||
{
|
||||
if (Path.GetFullPath(exePath).StartsWith(norm, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Win32.GentleKillProcess(p, 2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void PreStopServices(ApplicationUninstallerEntry entry)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
// B9: Add trailing separator and parse clean ImagePath
|
||||
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\') + Path.DirectorySeparatorChar;
|
||||
var services = ServiceController.GetServices();
|
||||
|
||||
foreach (var sc in services)
|
||||
{
|
||||
using (sc)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}");
|
||||
string? rawPath = key?.GetValue("ImagePath")?.ToString();
|
||||
if (!string.IsNullOrWhiteSpace(rawPath))
|
||||
{
|
||||
string cleanPath = rawPath.Replace("\"", "").Trim();
|
||||
if (cleanPath.StartsWith(@"\??\")) cleanPath = cleanPath.Substring(4);
|
||||
|
||||
int exeIdx = cleanPath.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
|
||||
if (exeIdx > 0) cleanPath = cleanPath.Substring(0, exeIdx + 4).Trim();
|
||||
|
||||
if (cleanPath.StartsWith(norm, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (sc.Status == ServiceControllerStatus.Running)
|
||||
{
|
||||
sc.Stop();
|
||||
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static async Task WaitForActiveMsiProcesses(CancellationToken token)
|
||||
{
|
||||
// B15: Timeout after 60 seconds
|
||||
var sw = Stopwatch.StartNew();
|
||||
while (!token.IsCancellationRequested && sw.ElapsedMilliseconds < 60000)
|
||||
{
|
||||
var msiProcs = Process.GetProcessesByName("msiexec");
|
||||
int count = msiProcs.Length;
|
||||
foreach (var p in msiProcs) p.Dispose();
|
||||
|
||||
if (count <= 1)
|
||||
break;
|
||||
await Task.Delay(1000, token);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSerializedType(UninstallerType type)
|
||||
{
|
||||
return type is UninstallerType.WindowsFeature
|
||||
or UninstallerType.WindowsUpdate
|
||||
or UninstallerType.InstallShield
|
||||
or UninstallerType.SdbInst
|
||||
or UninstallerType.PowerShell;
|
||||
}
|
||||
|
||||
private static (string fileName, string arguments) SplitCommand(string command)
|
||||
{
|
||||
string trimmed = command.Trim();
|
||||
if (trimmed.StartsWith("\""))
|
||||
{
|
||||
int endQuote = trimmed.IndexOf('\"', 1);
|
||||
if (endQuote > 0)
|
||||
{
|
||||
string file = trimmed.Substring(1, endQuote - 1);
|
||||
string args = endQuote + 1 < trimmed.Length ? trimmed[(endQuote + 1)..].Trim() : "";
|
||||
return (file, args);
|
||||
}
|
||||
}
|
||||
|
||||
int space = trimmed.IndexOf(' ');
|
||||
if (space > 0)
|
||||
{
|
||||
return (trimmed[..space], trimmed[(space + 1)..].Trim());
|
||||
}
|
||||
|
||||
return (trimmed, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,182 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace LDUninstaller.Core.Junk
|
||||
{
|
||||
public class ExclusionItem
|
||||
{
|
||||
public string Path { get; set; } = string.Empty;
|
||||
public bool IsRegex { get; set; }
|
||||
public DateTime AddedAt { get; set; } = DateTime.Now;
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public static class ExclusionManager
|
||||
{
|
||||
private static readonly object _lock = new();
|
||||
private static readonly HashSet<string> _exactExclusions = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly List<ExclusionItem> _items = new();
|
||||
private static bool _loaded = false;
|
||||
|
||||
public static string ExclusionFilePath => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDUninstaller", "exclusions.json");
|
||||
|
||||
public static void EnsureLoaded()
|
||||
{
|
||||
if (_loaded) return;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_loaded) return;
|
||||
LoadInternal();
|
||||
_loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
private static void LoadInternal()
|
||||
{
|
||||
_exactExclusions.Clear();
|
||||
_items.Clear();
|
||||
|
||||
try
|
||||
{
|
||||
string path = ExclusionFilePath;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
string json = File.ReadAllText(path);
|
||||
var list = JsonSerializer.Deserialize<List<ExclusionItem>>(json);
|
||||
if (list != null)
|
||||
{
|
||||
foreach (var item in list)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(item.Path))
|
||||
{
|
||||
string norm = NormalizePath(item.Path);
|
||||
_exactExclusions.Add(norm);
|
||||
_items.Add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static void Save()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
try
|
||||
{
|
||||
string dir = Path.GetDirectoryName(ExclusionFilePath) ?? "";
|
||||
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
string json = JsonSerializer.Serialize(_items, new JsonSerializerOptions { WriteIndented = true });
|
||||
File.WriteAllText(ExclusionFilePath, json);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsExcluded(string targetPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(targetPath)) return false;
|
||||
EnsureLoaded();
|
||||
|
||||
string norm = NormalizePath(targetPath);
|
||||
lock (_lock)
|
||||
{
|
||||
if (_exactExclusions.Contains(norm))
|
||||
return true;
|
||||
|
||||
foreach (var item in _items)
|
||||
{
|
||||
if (item.IsRegex)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (System.Text.RegularExpressions.Regex.IsMatch(norm, item.Path, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
|
||||
return true;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
else
|
||||
{
|
||||
string itemNorm = NormalizePath(item.Path);
|
||||
if (norm.Equals(itemNorm, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
if (norm.StartsWith(itemNorm + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool AddExclusion(string path, string reason = "Kullanıcı Koruması", bool isRegex = false)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return false;
|
||||
EnsureLoaded();
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
string norm = NormalizePath(path);
|
||||
if (_exactExclusions.Contains(norm))
|
||||
return false;
|
||||
|
||||
var item = new ExclusionItem
|
||||
{
|
||||
Path = path.Trim(),
|
||||
IsRegex = isRegex,
|
||||
AddedAt = DateTime.Now,
|
||||
Reason = reason
|
||||
};
|
||||
|
||||
_items.Add(item);
|
||||
_exactExclusions.Add(norm);
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool RemoveExclusion(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return false;
|
||||
EnsureLoaded();
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
string norm = NormalizePath(path);
|
||||
int removed = _items.RemoveAll(x => NormalizePath(x.Path).Equals(norm, StringComparison.OrdinalIgnoreCase));
|
||||
_exactExclusions.Remove(norm);
|
||||
if (removed > 0)
|
||||
{
|
||||
Save();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static List<ExclusionItem> GetAllExclusions()
|
||||
{
|
||||
EnsureLoaded();
|
||||
lock (_lock)
|
||||
{
|
||||
return new List<ExclusionItem>(_items);
|
||||
}
|
||||
}
|
||||
|
||||
private static string NormalizePath(string p)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(p)) return string.Empty;
|
||||
return p.Replace('/', '\\').Trim().TrimEnd('\\');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,247 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace LDUninstaller.Core.Junk
|
||||
{
|
||||
public static class SafetyBlacklist
|
||||
{
|
||||
private static readonly HashSet<string> BlacklistedDirs = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly List<string> ProtectedPrefixes = new();
|
||||
private static readonly HashSet<string> BlacklistedRegPaths = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static readonly HashSet<string> ProtectedNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"windows", "system32", "syswow64", "winsxs", "microsoft", "windows nt",
|
||||
"windows defender", "windows security", "internet explorer", "microsoft.net",
|
||||
"windowspowershell", "dotnet", "common files", "desktop", "downloads",
|
||||
"documents", "pictures", "music", "videos", "appdata", "locallow", "roaming", "local",
|
||||
"temp", "system volume information", "$recycle.bin", "recovery", "boot", "perflogs",
|
||||
"windowsapps", "package cache", "onedrive"
|
||||
};
|
||||
|
||||
private static readonly string DynamicUsersRoot;
|
||||
private static readonly string UserProfileDir;
|
||||
|
||||
static SafetyBlacklist()
|
||||
{
|
||||
// Windows & System directories
|
||||
string winDir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
|
||||
AddDir(winDir);
|
||||
AddPrefix(winDir); // Any file/folder inside C:\Windows must NEVER be treated as junk!
|
||||
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.System));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86));
|
||||
|
||||
string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
||||
AddDir(pf);
|
||||
if (!string.IsNullOrEmpty(pf))
|
||||
{
|
||||
AddPrefix(Path.Combine(pf, "WindowsApps"));
|
||||
AddDir(Path.Combine(pf, "Common Files"));
|
||||
}
|
||||
|
||||
string pf86 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
|
||||
if (!string.IsNullOrEmpty(pf86) && !pf86.Equals(pf, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
AddDir(pf86);
|
||||
AddPrefix(Path.Combine(pf86, "WindowsApps"));
|
||||
AddDir(Path.Combine(pf86, "Common Files"));
|
||||
}
|
||||
|
||||
UserProfileDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
AddDir(UserProfileDir);
|
||||
|
||||
// Dynamic Users parent directory (e.g. D:\Users or C:\Users on any non-standard drive)
|
||||
string? usersParent = Path.GetDirectoryName(UserProfileDir);
|
||||
DynamicUsersRoot = !string.IsNullOrWhiteSpace(usersParent) ? usersParent : @"C:\Users";
|
||||
AddDir(DynamicUsersRoot);
|
||||
|
||||
// Core user personal folders
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
|
||||
AddDir(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
|
||||
|
||||
// Package Cache
|
||||
string commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
|
||||
if (!string.IsNullOrEmpty(commonAppData))
|
||||
{
|
||||
AddPrefix(Path.Combine(commonAppData, "Package Cache"));
|
||||
}
|
||||
|
||||
// OneDrive Roots
|
||||
string[] oneDriveVars = { "OneDrive", "OneDriveConsumer", "OneDriveCommercial" };
|
||||
foreach (var v in oneDriveVars)
|
||||
{
|
||||
string? envVal = Environment.GetEnvironmentVariable(v);
|
||||
if (!string.IsNullOrWhiteSpace(envVal) && Directory.Exists(envVal))
|
||||
{
|
||||
AddDir(envVal);
|
||||
AddDir(Path.Combine(envVal, "Documents"));
|
||||
AddDir(Path.Combine(envVal, "Masaüstü"));
|
||||
AddDir(Path.Combine(envVal, "Desktop"));
|
||||
AddDir(Path.Combine(envVal, "Resimler"));
|
||||
AddDir(Path.Combine(envVal, "Pictures"));
|
||||
}
|
||||
}
|
||||
|
||||
// Drives roots
|
||||
try
|
||||
{
|
||||
foreach (var drive in DriveInfo.GetDrives())
|
||||
{
|
||||
AddDir(drive.RootDirectory.FullName);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// Registry Core Containers & Blacklists
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SYSTEM\CurrentControlSet");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SYSTEM\CurrentControlSet\Services");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SYSTEM");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Classes");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies\Microsoft");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Policies\Microsoft\Windows");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Policies");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache\Tree");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\RegisteredApplications");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\RegisteredApplications");
|
||||
BlacklistedRegPaths.Add(@"HKCR\*\shellex\ContextMenuHandlers");
|
||||
BlacklistedRegPaths.Add(@"HKCR\Directory\shellex\ContextMenuHandlers");
|
||||
BlacklistedRegPaths.Add(@"HKCR\CLSID");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\Classes\CLSID");
|
||||
BlacklistedRegPaths.Add(@"HKCU\SOFTWARE\Classes\CLSID");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows");
|
||||
BlacklistedRegPaths.Add(@"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion");
|
||||
}
|
||||
|
||||
private static void AddDir(string? path)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
try
|
||||
{
|
||||
BlacklistedDirs.Add(Path.GetFullPath(path).TrimEnd('\\'));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddPrefix(string? path)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
try
|
||||
{
|
||||
string norm = Path.GetFullPath(path).TrimEnd('\\') + Path.DirectorySeparatorChar;
|
||||
if (!ProtectedPrefixes.Contains(norm))
|
||||
ProtectedPrefixes.Add(norm);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsDangerousDirectory(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return true;
|
||||
try
|
||||
{
|
||||
string norm = Path.GetFullPath(path).TrimEnd('\\');
|
||||
|
||||
// 1. Check exact blacklisted system directories
|
||||
if (BlacklistedDirs.Contains(norm))
|
||||
return true;
|
||||
|
||||
// 2. Check protected subfolder prefixes (e.g. C:\Windows\...)
|
||||
string normWithSep = norm + Path.DirectorySeparatorChar;
|
||||
foreach (var pfx in ProtectedPrefixes)
|
||||
{
|
||||
if (normWithSep.StartsWith(pfx, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. User exclusion list
|
||||
if (ExclusionManager.IsExcluded(norm))
|
||||
return true;
|
||||
|
||||
// 4. Protected base folder names
|
||||
string name = Path.GetFileName(norm);
|
||||
if (ProtectedNames.Contains(name))
|
||||
return true;
|
||||
|
||||
// 5. Parent checks: cannot delete drive root, user root, or Users parent
|
||||
var di = new DirectoryInfo(norm);
|
||||
if (di.Parent == null) return true; // e.g. C:\ or D:\
|
||||
if (di.Parent.FullName.Equals(DynamicUsersRoot, StringComparison.OrdinalIgnoreCase)) return true; // e.g. C:\Users\Username directly
|
||||
if (norm.Equals(UserProfileDir, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsDangerousRegistryPath(string regPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(regPath)) return true;
|
||||
|
||||
// Normalize HKLM_32 to standard WOW6432Node representation
|
||||
string norm = regPath.Replace("/", "\\").TrimEnd('\\');
|
||||
if (norm.StartsWith("HKLM_32\\Software", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
norm = "HKLM\\SOFTWARE\\WOW6432Node" + norm.Substring("HKLM_32\\Software".Length);
|
||||
}
|
||||
else if (norm.StartsWith("HKLM_32\\", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
norm = "HKLM\\" + norm.Substring("HKLM_32\\".Length);
|
||||
}
|
||||
|
||||
// User exclusion check
|
||||
if (ExclusionManager.IsExcluded(norm))
|
||||
return true;
|
||||
|
||||
foreach (var bl in BlacklistedRegPaths)
|
||||
{
|
||||
if (norm.Equals(bl, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
|
||||
// Root hives or 1-level subkeys under hives (e.g. HKLM\SOFTWARE, HKCU\Software, etc.)
|
||||
int slashCount = 0;
|
||||
for (int i = 0; i < norm.Length; i++)
|
||||
{
|
||||
if (norm[i] == '\\') slashCount++;
|
||||
}
|
||||
|
||||
if (slashCount <= 1) return true; // HKLM, HKLM\SOFTWARE
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,606 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.ServiceProcess;
|
||||
using System.Threading;
|
||||
using LDUninstaller.Core.Junk;
|
||||
using LDUninstaller.Core.Native;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace LDUninstaller.Core.Services
|
||||
{
|
||||
public class ProcessLockInfo
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
public string ExecutablePath { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public bool IsService { get; set; }
|
||||
public string ServiceName { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class UnlockAndDestroyResult
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string TargetPath { get; set; } = string.Empty;
|
||||
public int KilledProcessesCount { get; set; }
|
||||
public int StoppedServicesCount { get; set; }
|
||||
public int DeletedFilesCount { get; set; }
|
||||
public List<string> ErrorMessages { get; } = new();
|
||||
public bool ScheduledForReboot { get; set; }
|
||||
}
|
||||
|
||||
public static class FileUnlockerService
|
||||
{
|
||||
#region Windows Restart Manager Interop
|
||||
private const int CCH_RM_SESSION_KEY = 32;
|
||||
|
||||
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
|
||||
|
||||
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern int RmRegisterResources(
|
||||
uint pSessionHandle,
|
||||
uint nFiles,
|
||||
string[]? rgsFileNames,
|
||||
uint nApplications,
|
||||
RM_UNIQUE_PROCESS[]? rgApplications,
|
||||
uint nServices,
|
||||
string[]? rgsServiceNames);
|
||||
|
||||
[DllImport("rstrtmgr.dll")]
|
||||
private static extern int RmGetList(
|
||||
uint pSessionHandle,
|
||||
out uint pnProcInfoNeeded,
|
||||
ref uint pnProcInfo,
|
||||
[In, Out] RM_PROCESS_INFO[]? rgAffectedApps,
|
||||
out uint lpdwRebootReasons);
|
||||
|
||||
[DllImport("rstrtmgr.dll")]
|
||||
private static extern int RmEndSession(uint pSessionHandle);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct RM_UNIQUE_PROCESS
|
||||
{
|
||||
public int dwProcessId;
|
||||
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct RM_PROCESS_INFO
|
||||
{
|
||||
public RM_UNIQUE_PROCESS Process;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
|
||||
public string strAppName;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
|
||||
public string strServiceShortName;
|
||||
public int ApplicationType;
|
||||
public uint AppStatus;
|
||||
public uint TSSessionId;
|
||||
[MarshalAs(UnmanagedType.Bool)]
|
||||
public bool bRestartable;
|
||||
}
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Kısayol (.lnk) veya dosya/klasör yolunu analiz ederek asıl kurulum klasörünü ve hedefi çözümler.
|
||||
/// </summary>
|
||||
public static (string targetFolder, string? primaryFile, string? originalLnk) ResolveTarget(string inputPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(inputPath))
|
||||
return (string.Empty, null, null);
|
||||
|
||||
string norm = Path.GetFullPath(inputPath).TrimEnd('\\');
|
||||
|
||||
// Eğer .lnk kısayolu ise, hedef exe'yi ve onun üst klasörünü çöz
|
||||
if (norm.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) && File.Exists(norm))
|
||||
{
|
||||
string? resolved = ResolveShortcutTarget(norm);
|
||||
if (!string.IsNullOrWhiteSpace(resolved))
|
||||
{
|
||||
if (Directory.Exists(resolved))
|
||||
{
|
||||
return (resolved, null, norm);
|
||||
}
|
||||
if (File.Exists(resolved))
|
||||
{
|
||||
string? parent = Path.GetDirectoryName(resolved);
|
||||
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
|
||||
{
|
||||
return (parent, resolved, norm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Normal dosya ise üst klasörünü hedef klasör al (ör. C:\Program Files\App\app.exe)
|
||||
if (File.Exists(norm))
|
||||
{
|
||||
string? parent = Path.GetDirectoryName(norm);
|
||||
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
|
||||
{
|
||||
return (parent, norm, null);
|
||||
}
|
||||
}
|
||||
|
||||
// Normal klasör ise doğrudan kendisi
|
||||
return (norm, null, null);
|
||||
}
|
||||
|
||||
public static string? ResolveShortcutTarget(string lnkPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
Type? shellType = Type.GetTypeFromProgID("WScript.Shell");
|
||||
if (shellType != null)
|
||||
{
|
||||
dynamic? shell = Activator.CreateInstance(shellType);
|
||||
if (shell != null)
|
||||
{
|
||||
dynamic? shortcut = shell.CreateShortcut(lnkPath);
|
||||
string? target = shortcut?.TargetPath;
|
||||
if (!string.IsNullOrWhiteSpace(target))
|
||||
return target;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hedef klasör ve içindeki dosyaları o an kilitleyen tüm süreçleri ve servisleri listeler.
|
||||
/// </summary>
|
||||
public static List<ProcessLockInfo> InspectLocks(string targetPath)
|
||||
{
|
||||
var results = new Dictionary<int, ProcessLockInfo>();
|
||||
if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath)))
|
||||
return results.Values.ToList();
|
||||
|
||||
string normDir = Path.GetFullPath(targetPath).TrimEnd('\\');
|
||||
|
||||
// 1. Klasör içi imaj yoluna sahip süreçler
|
||||
try
|
||||
{
|
||||
foreach (var proc in Process.GetProcesses())
|
||||
{
|
||||
try
|
||||
{
|
||||
string? img = Win32.GetProcessPath(proc.Id);
|
||||
if (!string.IsNullOrEmpty(img))
|
||||
{
|
||||
string normImg = img.TrimEnd('\\');
|
||||
if (normImg.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) ||
|
||||
normImg.Equals(normDir, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (!results.ContainsKey(proc.Id))
|
||||
{
|
||||
results[proc.Id] = new ProcessLockInfo
|
||||
{
|
||||
ProcessId = proc.Id,
|
||||
ProcessName = proc.ProcessName,
|
||||
ExecutablePath = img,
|
||||
Description = "Klasör içinde çalışan aktif süreç"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
finally { proc.Dispose(); }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// 2. Windows Restart Manager ile kilitli DLL/dosya tutan dış süreçler
|
||||
try
|
||||
{
|
||||
var filesToCheck = new List<string>();
|
||||
if (File.Exists(targetPath))
|
||||
{
|
||||
filesToCheck.Add(targetPath);
|
||||
}
|
||||
else if (Directory.Exists(targetPath))
|
||||
{
|
||||
// En kritik kilit adaylarını topla (exe, dll, sys, log, db)
|
||||
var topFiles = Directory.EnumerateFiles(targetPath, "*.*", SearchOption.AllDirectories)
|
||||
.Where(f =>
|
||||
{
|
||||
string ext = Path.GetExtension(f).ToLowerInvariant();
|
||||
return ext is ".exe" or ".dll" or ".sys" or ".dat" or ".db" or ".log";
|
||||
})
|
||||
.Take(64)
|
||||
.ToList();
|
||||
|
||||
filesToCheck.AddRange(topFiles);
|
||||
}
|
||||
|
||||
if (filesToCheck.Count > 0)
|
||||
{
|
||||
var rmProcs = GetProcessesLockingFilesWithRm(filesToCheck);
|
||||
foreach (var rm in rmProcs)
|
||||
{
|
||||
if (!results.ContainsKey(rm.ProcessId))
|
||||
results[rm.ProcessId] = rm;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// 3. Klasör içi dosyaları kullanan Windows Servisleri
|
||||
try
|
||||
{
|
||||
var services = FindServicesInDirectory(normDir);
|
||||
foreach (var s in services)
|
||||
{
|
||||
// Servise ait bir PID varsa listeye ekle veya yeni bilgi oluştur
|
||||
if (s.ProcessId > 0 && results.TryGetValue(s.ProcessId, out var existing))
|
||||
{
|
||||
existing.IsService = true;
|
||||
existing.ServiceName = s.ServiceName;
|
||||
}
|
||||
else
|
||||
{
|
||||
results[s.ProcessId > 0 ? s.ProcessId : -Math.Abs(s.ServiceName.GetHashCode())] = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return results.Values.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 4 Aşamalı kilit kırma boru hattını çalıştırır, süreç ve servisleri sonlandırır ve klasörü tamamen siler.
|
||||
/// </summary>
|
||||
public static UnlockAndDestroyResult UnlockAndDestroy(
|
||||
string targetPath,
|
||||
bool sendToRecycleBin = true,
|
||||
Action<string>? onLog = null)
|
||||
{
|
||||
var res = new UnlockAndDestroyResult { TargetPath = targetPath };
|
||||
|
||||
if (string.IsNullOrWhiteSpace(targetPath) || (!Directory.Exists(targetPath) && !File.Exists(targetPath)))
|
||||
{
|
||||
res.Success = true;
|
||||
return res;
|
||||
}
|
||||
|
||||
// GÜVENLİK KALKANI: Kritik sistem veya kullanıcı kök dizini ise asla silme!
|
||||
if (SafetyBlacklist.IsDangerousDirectory(targetPath))
|
||||
{
|
||||
string msg = $"GÜVENLİK ENGELİ: '{targetPath}' kritik bir Windows sistem veya profil kök dizinidir ve silinemez!";
|
||||
onLog?.Invoke(msg);
|
||||
res.ErrorMessages.Add(msg);
|
||||
res.Success = false;
|
||||
return res;
|
||||
}
|
||||
|
||||
string normPath = Path.GetFullPath(targetPath).TrimEnd('\\');
|
||||
onLog?.Invoke($"[1/4] Kilit kırma başlatılıyor: {normPath}");
|
||||
|
||||
// AŞAMA 1 & 2: Süreçleri Sonlandırma (Restart Manager + Process Tree Kill)
|
||||
var locks = InspectLocks(normPath);
|
||||
int currentPid = Process.GetCurrentProcess().Id;
|
||||
|
||||
foreach (var lockInfo in locks)
|
||||
{
|
||||
if (lockInfo.ProcessId <= 4 || lockInfo.ProcessId == currentPid)
|
||||
continue;
|
||||
|
||||
// explorer.exe kontrolü
|
||||
if (lockInfo.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
onLog?.Invoke("Dosya Gezgini (explorer.exe) kilit tutuyor; tutamaç serbest bırakılacak.");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var proc = Process.GetProcessById(lockInfo.ProcessId);
|
||||
onLog?.Invoke($"Süreç sonlandırılıyor: {proc.ProcessName} (PID: {proc.Id})");
|
||||
proc.Kill(entireProcessTree: true);
|
||||
proc.WaitForExit(1500);
|
||||
res.KilledProcessesCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// AŞAMA 3: İlgili Windows Servislerini Durdurma ve Kaldırma
|
||||
var services = FindServicesInDirectory(normPath);
|
||||
foreach (var svc in services)
|
||||
{
|
||||
try
|
||||
{
|
||||
onLog?.Invoke($"Servis durduruluyor ve kaldırılıyor: {svc.ServiceName}");
|
||||
using var sc = new ServiceController(svc.ServiceName);
|
||||
if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending)
|
||||
{
|
||||
sc.Stop();
|
||||
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
|
||||
}
|
||||
|
||||
// sc delete ile servisi sistemden temizle
|
||||
RunCommandSilent("sc.exe", $"delete \"{svc.ServiceName}\"");
|
||||
res.StoppedServicesCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// AŞAMA 4: İzinleri Sıfırlama ve Agresif Silme Döngüsü
|
||||
onLog?.Invoke("[4/4] Dosya öznitelikleri sıfırlanıyor ve sahiplik alınıyor...");
|
||||
ResetAttributesAndTakeOwnership(normPath);
|
||||
|
||||
// 5 Aşamalı Agresif Silme Döngüsü
|
||||
for (int attempt = 1; attempt <= 5; attempt++)
|
||||
{
|
||||
if (!Directory.Exists(normPath) && !File.Exists(normPath))
|
||||
{
|
||||
res.Success = true;
|
||||
onLog?.Invoke("Hedef başarıyla silindi ve yok edildi!");
|
||||
return res;
|
||||
}
|
||||
|
||||
onLog?.Invoke($"Silme denemesi {attempt}/5...");
|
||||
|
||||
bool deleted = false;
|
||||
if (sendToRecycleBin)
|
||||
{
|
||||
deleted = Win32.SendToRecycleBin(normPath);
|
||||
}
|
||||
|
||||
if (!deleted)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(normPath))
|
||||
{
|
||||
File.Delete(normPath);
|
||||
deleted = !File.Exists(normPath);
|
||||
}
|
||||
else if (Directory.Exists(normPath))
|
||||
{
|
||||
Directory.Delete(normPath, true);
|
||||
deleted = !Directory.Exists(normPath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
res.ErrorMessages.Add($"Deneme {attempt} hatası: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (deleted || (!Directory.Exists(normPath) && !File.Exists(normPath)))
|
||||
{
|
||||
res.Success = true;
|
||||
onLog?.Invoke("Hedef klasör tamamen temizlendi.");
|
||||
return res;
|
||||
}
|
||||
|
||||
// Silinemeyen dosya kaldıysa tekrar Restart Manager ile kilitleyen süreci avla
|
||||
var remainingLocks = InspectLocks(normPath);
|
||||
foreach (var rmProc in remainingLocks)
|
||||
{
|
||||
if (rmProc.ProcessId > 4 && rmProc.ProcessId != currentPid && !rmProc.ProcessName.Equals("explorer", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var p = Process.GetProcessById(rmProc.ProcessId);
|
||||
p.Kill(entireProcessTree: true);
|
||||
res.KilledProcessesCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(300);
|
||||
}
|
||||
|
||||
// Eğer hala silinemeyen bir kernel driver veya sistem dosyası kaldıysa, yeniden başlatmada silinmeye ayarla
|
||||
if (Directory.Exists(normPath) || File.Exists(normPath))
|
||||
{
|
||||
onLog?.Invoke("Bazı dosyalar çekirdek düzeyinde kilitli; ilk sistem yeniden başlatmasında (MoveFileEx) silinmek üzere zamanlanıyor...");
|
||||
ScheduleAllForRebootDelete(normPath);
|
||||
res.ScheduledForReboot = true;
|
||||
res.Success = true;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private static List<ProcessLockInfo> GetProcessesLockingFilesWithRm(List<string> filePaths)
|
||||
{
|
||||
var list = new List<ProcessLockInfo>();
|
||||
string sessionKey = Guid.NewGuid().ToString();
|
||||
|
||||
int res = RmStartSession(out uint sessionHandle, 0, sessionKey);
|
||||
if (res != 0) return list;
|
||||
|
||||
try
|
||||
{
|
||||
int regRes = RmRegisterResources(sessionHandle, (uint)filePaths.Count, filePaths.ToArray(), 0, null, 0, null);
|
||||
if (regRes != 0) return list;
|
||||
|
||||
uint procInfoNeeded = 0;
|
||||
uint procInfo = 0;
|
||||
RM_PROCESS_INFO[]? processInfo = null;
|
||||
|
||||
res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out uint rebootReasons);
|
||||
if (res == 234) // ERROR_MORE_DATA
|
||||
{
|
||||
processInfo = new RM_PROCESS_INFO[procInfoNeeded];
|
||||
procInfo = procInfoNeeded;
|
||||
res = RmGetList(sessionHandle, out procInfoNeeded, ref procInfo, processInfo, out rebootReasons);
|
||||
}
|
||||
|
||||
if (res == 0 && processInfo != null)
|
||||
{
|
||||
foreach (var pi in processInfo)
|
||||
{
|
||||
int pid = pi.Process.dwProcessId;
|
||||
if (pid <= 4) continue;
|
||||
|
||||
string exePath = Win32.GetProcessPath(pid) ?? "";
|
||||
list.Add(new ProcessLockInfo
|
||||
{
|
||||
ProcessId = pid,
|
||||
ProcessName = string.IsNullOrEmpty(pi.strAppName) ? Path.GetFileNameWithoutExtension(exePath) : pi.strAppName,
|
||||
ExecutablePath = exePath,
|
||||
ServiceName = pi.strServiceShortName,
|
||||
IsService = !string.IsNullOrEmpty(pi.strServiceShortName),
|
||||
Description = "Restart Manager tarafından yakalanan kilitli süreç"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
RmEndSession(sessionHandle);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<ProcessLockInfo> FindServicesInDirectory(string dirPath)
|
||||
{
|
||||
var services = new List<ProcessLockInfo>();
|
||||
string normDir = dirPath.TrimEnd('\\');
|
||||
|
||||
try
|
||||
{
|
||||
using var servicesKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
|
||||
if (servicesKey == null) return services;
|
||||
|
||||
foreach (var svcName in servicesKey.GetSubKeyNames())
|
||||
{
|
||||
try
|
||||
{
|
||||
using var svcKey = servicesKey.OpenSubKey(svcName);
|
||||
string? imagePath = svcKey?.GetValue("ImagePath")?.ToString();
|
||||
if (string.IsNullOrWhiteSpace(imagePath)) continue;
|
||||
|
||||
string clean = imagePath.Replace("\"", "").Trim();
|
||||
if (clean.StartsWith(@"\??\")) clean = clean.Substring(4);
|
||||
|
||||
int exeIdx = clean.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
|
||||
if (exeIdx > 0) clean = clean.Substring(0, exeIdx + 4).Trim();
|
||||
|
||||
if (clean.StartsWith(normDir + "\\", StringComparison.OrdinalIgnoreCase) ||
|
||||
clean.Equals(normDir, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
int pid = GetServicePid(svcName);
|
||||
services.Add(new ProcessLockInfo
|
||||
{
|
||||
ProcessId = pid,
|
||||
ProcessName = svcName,
|
||||
ExecutablePath = clean,
|
||||
ServiceName = svcName,
|
||||
IsService = true,
|
||||
Description = $"Windows Servisi ({svcName})"
|
||||
});
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static int GetServicePid(string serviceName)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var sc = new ServiceController(serviceName);
|
||||
// ServiceProcessId is available via reflection or sc queryex
|
||||
string output = RunCommandSilent("sc.exe", $"queryex \"{serviceName}\"");
|
||||
foreach (var line in output.Split('\n'))
|
||||
{
|
||||
if (line.Contains("PID", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
int colon = line.IndexOf(':');
|
||||
if (colon > 0 && int.TryParse(line.Substring(colon + 1).Trim(), out int pid))
|
||||
return pid;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void ResetAttributesAndTakeOwnership(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.SetAttributes(path, FileAttributes.Normal);
|
||||
}
|
||||
else if (Directory.Exists(path))
|
||||
{
|
||||
var di = new DirectoryInfo(path) { Attributes = FileAttributes.Normal };
|
||||
foreach (var info in di.GetFileSystemInfos("*", SearchOption.AllDirectories))
|
||||
{
|
||||
try { info.Attributes = FileAttributes.Normal; } catch { }
|
||||
}
|
||||
|
||||
// Sahiplik alma (Take Ownership)
|
||||
RunCommandSilent("takeown.exe", $"/f \"{path}\" /r /d y");
|
||||
RunCommandSilent("icacls.exe", $"\"{path}\" /grant administrators:F /t /c /q");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void ScheduleAllForRebootDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
|
||||
}
|
||||
else if (Directory.Exists(path))
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
|
||||
{
|
||||
Win32.MoveFileEx(file, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
|
||||
}
|
||||
foreach (var dir in Directory.GetDirectories(path, "*", SearchOption.AllDirectories).OrderByDescending(d => d.Length))
|
||||
{
|
||||
Win32.MoveFileEx(dir, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
|
||||
}
|
||||
Win32.MoveFileEx(path, null, Win32.MOVEFILE_DELAY_UNTIL_REBOOT);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static string RunCommandSilent(string fileName, string arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo(fileName, arguments)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
using var proc = Process.Start(psi);
|
||||
if (proc == null) return string.Empty;
|
||||
string output = proc.StandardOutput.ReadToEnd();
|
||||
proc.WaitForExit(3000);
|
||||
return output;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using LDUninstaller.Core.Models;
|
||||
|
||||
namespace LDUninstaller.Core.Services
|
||||
{
|
||||
public static class ReportService
|
||||
{
|
||||
public static string ReportsDirectory => Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDUninstaller",
|
||||
"Reports");
|
||||
|
||||
public static string GenerateHtmlReport(
|
||||
IEnumerable<ApplicationUninstallerEntry> uninstalledApps,
|
||||
IEnumerable<IJunkResult> cleanedJunks,
|
||||
string backupFolder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(ReportsDirectory))
|
||||
Directory.CreateDirectory(ReportsDirectory);
|
||||
|
||||
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
|
||||
string filename = Path.Combine(ReportsDirectory, $"CleanupReport_{timestamp}.html");
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine("<!DOCTYPE html>");
|
||||
sb.AppendLine("<html lang=\"tr\">");
|
||||
sb.AppendLine("<head>");
|
||||
sb.AppendLine("<meta charset=\"UTF-8\" />");
|
||||
sb.AppendLine("<title>LD Uninstaller - Kaldırma ve Temizlik Raporu</title>");
|
||||
sb.AppendLine("<style>");
|
||||
sb.AppendLine("body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background-color: #0F172A; color: #E2E8F0; padding: 30px; margin: 0; }");
|
||||
sb.AppendLine(".container { max-width: 900px; margin: 0 auto; background: #1E293B; border-radius: 12px; padding: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.5); }");
|
||||
sb.AppendLine("h1 { color: #38BDF8; margin-top: 0; font-size: 22px; display: flex; align-items: center; gap: 10px; }");
|
||||
sb.AppendLine(".meta { color: #94A3B8; font-size: 13px; margin-bottom: 20px; border-bottom: 1px solid #334155; padding-bottom: 12px; }");
|
||||
sb.AppendLine(".badge { display: inline-block; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: bold; background: #064E3B; color: #34D399; }");
|
||||
sb.AppendLine("table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 13px; }");
|
||||
sb.AppendLine("th { background-color: #0F172A; color: #94A3B8; text-align: left; padding: 10px; border-bottom: 2px solid #334155; }");
|
||||
sb.AppendLine("td { padding: 9px 10px; border-bottom: 1px solid #334155; word-break: break-all; }");
|
||||
sb.AppendLine("tr:hover { background-color: #273549; }");
|
||||
sb.AppendLine(".footer { margin-top: 25px; font-size: 12px; color: #64748B; text-align: center; }");
|
||||
sb.AppendLine("</style>");
|
||||
sb.AppendLine("</head>");
|
||||
sb.AppendLine("<body>");
|
||||
sb.AppendLine("<div class=\"container\">");
|
||||
sb.AppendLine("<h1>🛡️ LD Uninstaller - Kaldırma ve Temizlik Raporu</h1>");
|
||||
sb.AppendLine($"<div class=\"meta\">İşlem Tarihi: {DateTime.Now:yyyy-MM-dd HH:mm:ss} | Kayıt Defteri Yedek Dizini: <code>{backupFolder}</code></div>");
|
||||
|
||||
sb.AppendLine("<h3>📦 Kaldırılan Yazılımlar</h3>");
|
||||
sb.AppendLine("<table>");
|
||||
sb.AppendLine("<tr><th>Yazılım Adı</th><th>Yayıncı</th><th>Sürüm</th><th>Kaldırıcı Türü</th></tr>");
|
||||
foreach (var app in uninstalledApps)
|
||||
{
|
||||
sb.AppendLine($"<tr><td><strong>{app.DisplayName}</strong></td><td>{app.Publisher}</td><td>{app.DisplayVersion}</td><td>{app.UninstallerKind}</td></tr>");
|
||||
}
|
||||
sb.AppendLine("</table>");
|
||||
|
||||
var junkList = cleanedJunks.ToList();
|
||||
sb.AppendLine($"<h3 style=\"margin-top: 30px;\">🧹 Temizlenen Kalıntılar ve Artıklar ({junkList.Count} Öğe)</h3>");
|
||||
if (junkList.Count > 0)
|
||||
{
|
||||
sb.AppendLine("<table>");
|
||||
sb.AppendLine("<tr><th>Tür</th><th>Güven</th><th>Açıklama</th><th>Yol</th></tr>");
|
||||
foreach (var junk in junkList)
|
||||
{
|
||||
sb.AppendLine($"<tr><td>{junk.TypeDisplay}</td><td><span class=\"badge\">{junk.ConfidenceDisplay}</span></td><td>{junk.Reason}</td><td><code>{junk.Path}</code></td></tr>");
|
||||
}
|
||||
sb.AppendLine("</table>");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.AppendLine("<p style=\"color: #10B981;\">Kalıntı veya artık bulunamadı, sistem temiz.</p>");
|
||||
}
|
||||
|
||||
sb.AppendLine("<div class=\"footer\">LD Uninstaller 2.8.0 • Güvenli ve Derinlemesine Sistem Temizliği</div>");
|
||||
sb.AppendLine("</div>");
|
||||
sb.AppendLine("</body>");
|
||||
sb.AppendLine("</html>");
|
||||
|
||||
File.WriteAllText(filename, sb.ToString(), Encoding.UTF8);
|
||||
return filename;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace LDUninstaller.Core.Services
|
||||
{
|
||||
public static class ShellIntegrationManager
|
||||
{
|
||||
public const string ContextMenuKey = "LDForceUninstall";
|
||||
public const string MenuText = "💥 LD ile Güçlü Kaldır";
|
||||
|
||||
private static readonly string[] Targets = { "Directory", "exefile", "lnkfile" };
|
||||
|
||||
public static bool IsRegistered()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\Directory\shell\{ContextMenuKey}");
|
||||
return key != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Register(string appExePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(appExePath) || !File.Exists(appExePath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var target in Targets)
|
||||
{
|
||||
string subPath = $@"Software\Classes\{target}\shell\{ContextMenuKey}";
|
||||
using var menuKey = Registry.CurrentUser.CreateSubKey(subPath);
|
||||
if (menuKey == null) continue;
|
||||
|
||||
menuKey.SetValue("", MenuText, RegistryValueKind.String);
|
||||
menuKey.SetValue("Icon", $"\"{appExePath}\",0", RegistryValueKind.String);
|
||||
|
||||
using var cmdKey = menuKey.CreateSubKey("command");
|
||||
cmdKey?.SetValue("", $"\"{appExePath}\" --force-path \"%1\"", RegistryValueKind.String);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool Unregister()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var target in Targets)
|
||||
{
|
||||
string subPath = $@"Software\Classes\{target}\shell";
|
||||
using var shellKey = Registry.CurrentUser.OpenSubKey(subPath, true);
|
||||
shellKey?.DeleteSubKeyTree(ContextMenuKey, false);
|
||||
|
||||
// Eski menü adı varsa onu da temizle
|
||||
shellKey?.DeleteSubKeyTree("LDUninstaller", false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LDUninstaller.Core.Services
|
||||
{
|
||||
public class UpdateInfo
|
||||
{
|
||||
public bool HasUpdate { get; set; }
|
||||
public string LatestVersion { get; set; } = string.Empty;
|
||||
public string DownloadUrl { get; set; } = string.Empty;
|
||||
public string HomepageUrl { get; set; } = "https://ttmadethat.shop/#ldapps";
|
||||
public string ReleaseNotes { get; set; } = string.Empty;
|
||||
public string Sha256 { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public static class UpdateChecker
|
||||
{
|
||||
private static readonly HttpClient _httpClient = new()
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(5)
|
||||
};
|
||||
|
||||
private static readonly string[] Endpoints = new[]
|
||||
{
|
||||
"https://ttmadethat.shop/ldapps/version.json",
|
||||
"https://ttmadethat.shop/version.json",
|
||||
"https://ttmadethat.shop/api/ldapps/version"
|
||||
};
|
||||
|
||||
public static async Task<UpdateInfo?> CheckForUpdatesAsync(Version currentVersion, CancellationToken cancellationToken = default)
|
||||
{
|
||||
foreach (var url in Endpoints)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
request.Headers.Add("User-Agent", "LDUninstaller-Client");
|
||||
|
||||
using var response = await _httpClient.SendAsync(request, cancellationToken);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
continue;
|
||||
|
||||
string json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
string versionStr = GetStringProp(root, "version");
|
||||
string downloadUrl = GetStringProp(root, "downloadUrl");
|
||||
if (string.IsNullOrEmpty(downloadUrl)) downloadUrl = GetStringProp(root, "url");
|
||||
|
||||
string homepageUrl = GetStringProp(root, "homepageUrl");
|
||||
if (string.IsNullOrEmpty(homepageUrl)) homepageUrl = "https://ttmadethat.shop/#ldapps";
|
||||
|
||||
string notes = GetStringProp(root, "releaseNotes");
|
||||
if (string.IsNullOrEmpty(notes)) notes = GetStringProp(root, "notes");
|
||||
|
||||
string sha256 = GetStringProp(root, "sha256");
|
||||
|
||||
if (Version.TryParse(versionStr, out var remoteVer))
|
||||
{
|
||||
bool hasUpdate = remoteVer > currentVersion;
|
||||
return new UpdateInfo
|
||||
{
|
||||
HasUpdate = hasUpdate,
|
||||
LatestVersion = versionStr,
|
||||
DownloadUrl = string.IsNullOrEmpty(downloadUrl) ? homepageUrl : downloadUrl,
|
||||
HomepageUrl = homepageUrl,
|
||||
ReleaseNotes = notes,
|
||||
Sha256 = sha256
|
||||
};
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Try next endpoint or return null if all fail
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string GetStringProp(JsonElement element, string propName)
|
||||
{
|
||||
if (element.TryGetProperty(propName, out var prop))
|
||||
{
|
||||
return prop.GetString() ?? string.Empty;
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using LDUninstaller.Core.Models;
|
||||
|
||||
namespace LDUninstaller.Core.Services
|
||||
{
|
||||
public class WingetUpgradeItem
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public string Version { get; set; } = string.Empty;
|
||||
public string AvailableVersion { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public static class WingetService
|
||||
{
|
||||
public static bool IsWingetAvailable()
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("winget", "--version")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
using var proc = Process.Start(psi);
|
||||
if (proc == null) return false;
|
||||
proc.WaitForExit(3000);
|
||||
return proc.ExitCode == 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<List<WingetUpgradeItem>> GetAvailableUpgradesAsync()
|
||||
{
|
||||
var results = new List<WingetUpgradeItem>();
|
||||
if (!IsWingetAvailable()) return results;
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("winget", "upgrade --include-unknown")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
StandardOutputEncoding = System.Text.Encoding.UTF8
|
||||
};
|
||||
|
||||
using var proc = Process.Start(psi);
|
||||
if (proc == null) return;
|
||||
|
||||
string output = proc.StandardOutput.ReadToEnd();
|
||||
proc.WaitForExit(15000);
|
||||
|
||||
// Parse table output: Name | Id | Version | Available | Source
|
||||
using var reader = new StringReader(output);
|
||||
string? line;
|
||||
bool inTable = false;
|
||||
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
if (line.StartsWith("---") || line.Contains("------"))
|
||||
{
|
||||
inTable = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!inTable || string.IsNullOrWhiteSpace(line)) continue;
|
||||
|
||||
// Match columns separated by 2+ spaces
|
||||
var parts = Regex.Split(line.Trim(), @"\s{2,}");
|
||||
if (parts.Length >= 4)
|
||||
{
|
||||
results.Add(new WingetUpgradeItem
|
||||
{
|
||||
Name = parts[0],
|
||||
Id = parts[1],
|
||||
Version = parts[2],
|
||||
AvailableVersion = parts[3]
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public static string GenerateWingetExportScript(IEnumerable<ApplicationUninstallerEntry> apps)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
sb.AppendLine("@echo off");
|
||||
sb.AppendLine("chcp 65001 >nul");
|
||||
sb.AppendLine("echo === LD Uninstaller - Toplu Yazilim Kurulum Scripti ===");
|
||||
sb.AppendLine("echo Bu script bilgisayarinizda kayitli yazilimlari Winget ile otomatik kurar.");
|
||||
sb.AppendLine("echo.");
|
||||
|
||||
foreach (var app in apps)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(app.DisplayName) || app.SystemComponent || app.IsOrphaned)
|
||||
continue;
|
||||
|
||||
// Escape quotes
|
||||
string safeName = app.DisplayName.Replace("\"", "").Trim();
|
||||
sb.AppendLine($"echo [{safeName}] kuruluyor...");
|
||||
sb.AppendLine($"winget install --name \"{safeName}\" -e --accept-package-agreements --accept-source-agreements");
|
||||
sb.AppendLine();
|
||||
}
|
||||
|
||||
sb.AppendLine("echo Tum kurulum komutlari tamamlandi!");
|
||||
sb.AppendLine("pause");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,193 +0,0 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
namespace LDUninstaller.UI
|
||||
{
|
||||
public partial class App : Application
|
||||
{
|
||||
[DllImport("shell32.dll", SetLastError = true)]
|
||||
private static extern int SetCurrentProcessExplicitAppUserModelID([MarshalAs(UnmanagedType.LPWStr)] string AppID);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetForegroundWindow(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
||||
|
||||
private const int SW_RESTORE = 9;
|
||||
private static Mutex? _instanceMutex;
|
||||
private static readonly object _logLock = new();
|
||||
|
||||
public static string LogFilePath { get; } = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
|
||||
"LDUninstaller",
|
||||
"logs",
|
||||
"trace.log");
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// Shell Context Menu: Direct Force Shredder & Unlocker Mode
|
||||
string? forcePath = GetForcePathParam(e.Args);
|
||||
if (!string.IsNullOrEmpty(forcePath))
|
||||
{
|
||||
InitLogging();
|
||||
Log($"Direct force-path invoked: {forcePath}");
|
||||
var forceWin = new Dialogs.ForceDeleteWindow(forcePath);
|
||||
forceWin.Show();
|
||||
return;
|
||||
}
|
||||
|
||||
// B24: Global single-instance Mutex (Main Application)
|
||||
bool isFirstInstance;
|
||||
try
|
||||
{
|
||||
_instanceMutex = new Mutex(true, @"Global\LDUninstaller_SingleInstance_Mutex", out isFirstInstance);
|
||||
}
|
||||
catch
|
||||
{
|
||||
isFirstInstance = true;
|
||||
}
|
||||
|
||||
if (!isFirstInstance)
|
||||
{
|
||||
// Activate running instance
|
||||
try
|
||||
{
|
||||
var current = Process.GetCurrentProcess();
|
||||
foreach (var proc in Process.GetProcessesByName(current.ProcessName))
|
||||
{
|
||||
if (proc.Id != current.Id && proc.MainWindowHandle != IntPtr.Zero)
|
||||
{
|
||||
ShowWindow(proc.MainWindowHandle, SW_RESTORE);
|
||||
SetForegroundWindow(proc.MainWindowHandle);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Unify taskbar grouping with shortcuts and ensure correct icon binding
|
||||
SetCurrentProcessExplicitAppUserModelID("LDSoftware.LDUninstaller");
|
||||
}
|
||||
catch { }
|
||||
|
||||
base.OnStartup(e);
|
||||
|
||||
// B30: %LocalAppData%\LDUninstaller\logs\trace.log with rolling size limit
|
||||
InitLogging();
|
||||
|
||||
AppDomain.CurrentDomain.ProcessExit += (s, args) =>
|
||||
{
|
||||
Log("Process exit triggered.");
|
||||
};
|
||||
|
||||
AppDomain.CurrentDomain.UnhandledException += (s, args) =>
|
||||
{
|
||||
Log($"UNHANDLED: {args.ExceptionObject}");
|
||||
};
|
||||
|
||||
DispatcherUnhandledException += (s, args) =>
|
||||
{
|
||||
Log($"DISPATCHER UNHANDLED: {args.Exception}");
|
||||
MessageBox.Show(
|
||||
$"Arayüz Hatası:\n{args.Exception.Message}\n\nDetaylar log dosyasına kaydedildi:\n{LogFilePath}",
|
||||
"Hata - LD Uninstaller",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Error);
|
||||
args.Handled = true;
|
||||
};
|
||||
}
|
||||
|
||||
private static void InitLogging()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(LogFilePath);
|
||||
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
// Roll if > 5 MB
|
||||
if (File.Exists(LogFilePath))
|
||||
{
|
||||
var fi = new FileInfo(LogFilePath);
|
||||
if (fi.Length > 5 * 1024 * 1024)
|
||||
{
|
||||
string oldLog = Path.Combine(dir!, "trace.old.log");
|
||||
if (File.Exists(oldLog)) File.Delete(oldLog);
|
||||
File.Move(LogFilePath, oldLog);
|
||||
}
|
||||
}
|
||||
|
||||
Log($"=== LD Uninstaller Başlatıldı - {DateTime.Now:yyyy-MM-dd HH:mm:ss} ===");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public static void Log(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_logLock)
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(LogFilePath);
|
||||
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
string line = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}{Environment.NewLine}";
|
||||
File.AppendAllText(LogFilePath, line);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static string? GetForcePathParam(string[] args)
|
||||
{
|
||||
if (args == null || args.Length == 0) return null;
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
{
|
||||
string arg = args[i];
|
||||
if (arg.Equals("--force-path", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.Equals("/force-path", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.Equals("-force-path", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.Equals("/target", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (i + 1 < args.Length)
|
||||
return args[i + 1].Trim('\"');
|
||||
}
|
||||
else if (arg.StartsWith("--force-path=", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.StartsWith("/force-path=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
int eq = arg.IndexOf('=');
|
||||
return arg[(eq + 1)..].Trim('\"');
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
_instanceMutex?.ReleaseMutex();
|
||||
_instanceMutex?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
|
||||
base.OnExit(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
<Window x:Class="LDUninstaller.UI.Dialogs.BackupRestoreWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="Yedekleme ve Koruma Merkezi - LD Uninstaller"
|
||||
Height="560" Width="850"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False"
|
||||
Background="{StaticResource BrushBgDark}"
|
||||
Foreground="{StaticResource BrushTextPrimary}"
|
||||
FontFamily="Segoe UI"
|
||||
Icon="pack://application:,,,/LDUninstaller.UI;component/Resources/app.ico"
|
||||
BorderBrush="{StaticResource BrushBorder}"
|
||||
BorderThickness="1">
|
||||
|
||||
<WindowChrome.WindowChrome>
|
||||
<WindowChrome CaptionHeight="50" ResizeBorderThickness="6" CornerRadius="8" GlassFrameThickness="0" UseAeroCaptionButtons="False" />
|
||||
</WindowChrome.WindowChrome>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="50" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="60" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Custom Title Bar -->
|
||||
<Border Grid.Row="0" Background="{StaticResource BrushBgSidebar}" MouseDown="TitleBar_MouseDown" Padding="20,0">
|
||||
<Grid>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Border Background="{StaticResource BrushGlassSapphire}" CornerRadius="6" Width="28" Height="28" Margin="0,0,12,0">
|
||||
<TextBlock Text="🛡️" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="Yedekleme, Geri Yükleme ve Koruma Merkezi" FontSize="14.5" FontWeight="SemiBold" Foreground="{StaticResource BrushTextPrimary}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<Button Content="✕" Width="30" Height="30" HorizontalAlignment="Right" Background="Transparent" Foreground="{StaticResource BrushTextMuted}" BorderThickness="0" FontSize="14" Cursor="Hand" Click="BtnClose_Click" WindowChrome.IsHitTestVisibleInChrome="True" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Tab Control -->
|
||||
<TabControl Grid.Row="1" Background="Transparent" BorderThickness="0" Margin="20,10,20,10">
|
||||
<TabControl.Resources>
|
||||
<Style TargetType="TabItem">
|
||||
<Setter Property="Background" Value="#171A22" />
|
||||
<Setter Property="Foreground" Value="{StaticResource BrushTextSecondary}" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Padding" Value="16,8" />
|
||||
<Setter Property="Margin" Value="0,0,4,0" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="TabItem">
|
||||
<Border x:Name="bd" Background="{TemplateBinding Background}" CornerRadius="6,6,0,0" Padding="{TemplateBinding Padding}" Margin="{TemplateBinding Margin}">
|
||||
<ContentPresenter ContentSource="Header" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="bd" Property="Background" Value="#1E293B" />
|
||||
<Setter Property="Foreground" Value="{StaticResource BrushTextPrimary}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</TabControl.Resources>
|
||||
|
||||
<!-- TAB 1: BACKUPS -->
|
||||
<TabItem Header="💾 Kayıt Defteri Yedekleri (.reg)">
|
||||
<Grid Margin="0,15,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<DataGrid x:Name="dgBackups" Grid.Row="0" Background="Transparent" RowBackground="#13161D" AlternatingRowBackground="#171A22"
|
||||
BorderThickness="1" BorderBrush="{StaticResource BrushBorder}" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True"
|
||||
HeadersVisibility="Column" GridLinesVisibility="None" Foreground="{StaticResource BrushTextPrimary}" FontSize="12.5"
|
||||
SelectionMode="Single">
|
||||
<DataGrid.ColumnHeaderStyle>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter Property="Background" Value="#1B1F28" />
|
||||
<Setter Property="Foreground" Value="{StaticResource BrushTextSecondary}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="10,8" />
|
||||
<Setter Property="BorderThickness" Value="0,0,0,1" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BrushBorder}" />
|
||||
</Style>
|
||||
</DataGrid.ColumnHeaderStyle>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Yedek Dosyası" Binding="{Binding Name}" Width="320" />
|
||||
<DataGridTextColumn Header="Oluşturulma Tarihi" Binding="{Binding LastWriteTime, StringFormat='yyyy-MM-dd HH:mm:ss'}" Width="160" />
|
||||
<DataGridTextColumn Header="Boyut" Binding="{Binding SizeDisplay}" Width="110" />
|
||||
<DataGridTextColumn Header="Tam Yol" Binding="{Binding FullPath}" Width="*" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,12,0,0">
|
||||
<Button x:Name="btnRestore" Content="🔄 Seçili Yedeği Geri Yükle" Style="{StaticResource ModernBtnPrimary}" Margin="0,0,10,0" Click="BtnRestore_Click" />
|
||||
<Button x:Name="btnOpenFolder" Content="📂 Yedek Klasörünü Aç" Style="{StaticResource ModernBtnSecondary}" Margin="0,0,10,0" Click="BtnOpenFolder_Click" />
|
||||
<Button x:Name="btnDeleteBackup" Content="🗑️ Yedeği Sil" Style="{StaticResource ModernBtnSecondary}" Click="BtnDeleteBackup_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<!-- TAB 2: EXCLUSION LIST -->
|
||||
<TabItem Header="⛔ Koruma Listesi (Exclusions)">
|
||||
<Grid Margin="0,15,0,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<DataGrid x:Name="dgExclusions" Grid.Row="0" Background="Transparent" RowBackground="#13161D" AlternatingRowBackground="#171A22"
|
||||
BorderThickness="1" BorderBrush="{StaticResource BrushBorder}" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True"
|
||||
HeadersVisibility="Column" GridLinesVisibility="None" Foreground="{StaticResource BrushTextPrimary}" FontSize="12.5"
|
||||
SelectionMode="Single">
|
||||
<DataGrid.ColumnHeaderStyle>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter Property="Background" Value="#1B1F28" />
|
||||
<Setter Property="Foreground" Value="{StaticResource BrushTextSecondary}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="10,8" />
|
||||
<Setter Property="BorderThickness" Value="0,0,0,1" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BrushBorder}" />
|
||||
</Style>
|
||||
</DataGrid.ColumnHeaderStyle>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Korunan Yol veya Desen" Binding="{Binding Path}" Width="350" />
|
||||
<DataGridTextColumn Header="Açıklama" Binding="{Binding Reason}" Width="250" />
|
||||
<DataGridTextColumn Header="Eklenme Tarihi" Binding="{Binding AddedAt, StringFormat='yyyy-MM-dd HH:mm'}" Width="*" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,12,0,0">
|
||||
<Button x:Name="btnRemoveExclusion" Content="❌ Korumayı Kaldır" Style="{StaticResource ModernBtnSecondary}" Margin="0,0,10,0" Click="BtnRemoveExclusion_Click" />
|
||||
<Button x:Name="btnAddExclusion" Content="➕ Manuel Koruma Kuralı Ekle" Style="{StaticResource ModernBtnPrimary}" Click="BtnAddExclusion_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" Background="{StaticResource BrushBgSidebar}" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{StaticResource BrushBorder}">
|
||||
<Button Content="Kapat" Style="{StaticResource ModernBtnSecondary}" HorizontalAlignment="Right" Click="BtnClose_Click" />
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
|
@ -1,185 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using LDUninstaller.Core.Junk;
|
||||
using LDUninstaller.Core.Models;
|
||||
|
||||
namespace LDUninstaller.UI.Dialogs
|
||||
{
|
||||
public class BackupFileItem
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string FullPath { get; set; } = string.Empty;
|
||||
public DateTime LastWriteTime { get; set; }
|
||||
public long Size { get; set; }
|
||||
public string SizeDisplay => FileSize.FromBytes(Size).ToString();
|
||||
}
|
||||
|
||||
public partial class BackupRestoreWindow : Window
|
||||
{
|
||||
public BackupRestoreWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Loaded += BackupRestoreWindow_Loaded;
|
||||
}
|
||||
|
||||
private void BackupRestoreWindow_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
LoadBackups();
|
||||
LoadExclusions();
|
||||
}
|
||||
|
||||
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.ChangedButton == MouseButton.Left)
|
||||
DragMove();
|
||||
}
|
||||
|
||||
private void BtnClose_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private void LoadBackups()
|
||||
{
|
||||
string backupDir = JunkManager.BackupDirectory;
|
||||
if (!Directory.Exists(backupDir))
|
||||
{
|
||||
dgBackups.ItemsSource = new List<BackupFileItem>();
|
||||
return;
|
||||
}
|
||||
|
||||
var di = new DirectoryInfo(backupDir);
|
||||
var items = di.GetFiles("*.reg")
|
||||
.Concat(di.GetFiles("*.txt"))
|
||||
.OrderByDescending(f => f.LastWriteTime)
|
||||
.Select(f => new BackupFileItem
|
||||
{
|
||||
Name = f.Name,
|
||||
FullPath = f.FullName,
|
||||
LastWriteTime = f.LastWriteTime,
|
||||
Size = f.Length
|
||||
})
|
||||
.ToList();
|
||||
|
||||
dgBackups.ItemsSource = items;
|
||||
}
|
||||
|
||||
private void LoadExclusions()
|
||||
{
|
||||
var items = ExclusionManager.GetAllExclusions();
|
||||
dgExclusions.ItemsSource = items;
|
||||
}
|
||||
|
||||
private void BtnRestore_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgBackups.SelectedItem is not BackupFileItem item)
|
||||
{
|
||||
MessageBox.Show("Lütfen geri yüklemek istediğiniz bir .reg yedek dosyası seçin.", "Yedek Seçilmedi", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!item.Name.EndsWith(".reg", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
MessageBox.Show("Yalnızca .reg biçimindeki kayıt defteri yedekleri doğrudan geri yüklenebilir.", "Uyarı", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
return;
|
||||
}
|
||||
|
||||
var confirm = MessageBox.Show(
|
||||
$"'{item.Name}' yedeğini Windows Kayıt Defteri'ne geri aktarmak istiyor musunuz?\n\nDosya: {item.FullPath}",
|
||||
"Geri Yükleme Onayı",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (confirm != MessageBoxResult.Yes) return;
|
||||
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("reg.exe", $"import \"{item.FullPath}\"")
|
||||
{
|
||||
UseShellExecute = true,
|
||||
Verb = "runas"
|
||||
};
|
||||
|
||||
using var proc = Process.Start(psi);
|
||||
proc?.WaitForExit(5000);
|
||||
|
||||
if (proc != null && proc.ExitCode == 0)
|
||||
{
|
||||
MessageBox.Show("Kayıt defteri yedeği başarıyla geri yüklendi!", "Başarılı", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show($"Geri yükleme işlemi tamamlanamadı (Çıkış kodu: {proc?.ExitCode}).", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Geri yükleme sırasında hata oluştu: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void BtnOpenFolder_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
string backupDir = JunkManager.BackupDirectory;
|
||||
if (!Directory.Exists(backupDir))
|
||||
Directory.CreateDirectory(backupDir);
|
||||
|
||||
Process.Start("explorer.exe", backupDir);
|
||||
}
|
||||
|
||||
private void BtnDeleteBackup_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgBackups.SelectedItem is not BackupFileItem item)
|
||||
{
|
||||
MessageBox.Show("Lütfen silmek istediğiniz bir yedek dosyası seçin.", "Yedek Seçilmedi", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
var confirm = MessageBox.Show($"'{item.Name}' dosyasını silmek istediğinize emin misiniz?", "Yedek Silme Onayı", MessageBoxButton.YesNo, MessageBoxImage.Warning);
|
||||
if (confirm != MessageBoxResult.Yes) return;
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(item.FullPath))
|
||||
File.Delete(item.FullPath);
|
||||
|
||||
LoadBackups();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Dosya silinemedi: {ex.Message}", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void BtnRemoveExclusion_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgExclusions.SelectedItem is not ExclusionItem item)
|
||||
{
|
||||
MessageBox.Show("Lütfen koruma listesinden kaldırmak istediğiniz bir kural seçin.", "Kural Seçilmedi", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return;
|
||||
}
|
||||
|
||||
ExclusionManager.RemoveExclusion(item.Path);
|
||||
LoadExclusions();
|
||||
}
|
||||
|
||||
private void BtnAddExclusion_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var dialog = new Microsoft.Win32.OpenFolderDialog
|
||||
{
|
||||
Title = "Korumaya almak istediğiniz klasörü seçin:"
|
||||
};
|
||||
|
||||
if (dialog.ShowDialog() == true && !string.IsNullOrWhiteSpace(dialog.FolderName))
|
||||
{
|
||||
ExclusionManager.AddExclusion(dialog.FolderName, "Kullanıcı Manuel Koruması");
|
||||
LoadExclusions();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
<Window x:Class="LDUninstaller.UI.Dialogs.ForceDeleteWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="LD Güçlü Kaldır ve Kilit Kırıcı"
|
||||
Height="540" Width="720"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
Topmost="True"
|
||||
Background="{StaticResource BrushBgDark}"
|
||||
Foreground="{StaticResource BrushTextPrimary}"
|
||||
FontFamily="Segoe UI"
|
||||
Icon="pack://application:,,,/LDUninstaller.UI;component/Resources/app.ico"
|
||||
BorderBrush="#EF4444"
|
||||
BorderThickness="1">
|
||||
|
||||
<WindowChrome.WindowChrome>
|
||||
<WindowChrome CaptionHeight="50" ResizeBorderThickness="6" CornerRadius="8" GlassFrameThickness="0" UseAeroCaptionButtons="False" />
|
||||
</WindowChrome.WindowChrome>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="50" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="65" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Custom Title Bar -->
|
||||
<Border Grid.Row="0" Background="{StaticResource BrushBgSidebar}" MouseDown="TitleBar_MouseDown" Padding="20,0" BorderThickness="0,0,0,1" BorderBrush="{StaticResource BrushBorder}">
|
||||
<Grid>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Border Background="#450A0A" BorderBrush="#EF4444" BorderThickness="1" CornerRadius="6" Width="28" Height="28" Margin="0,0,12,0">
|
||||
<TextBlock Text="💥" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="LD Güçlü Kaldır ve Kilit Kırıcı (Force Shredder)" FontSize="14.5" FontWeight="SemiBold" Foreground="{StaticResource BrushTextPrimary}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<Button Content="✕" Width="30" Height="30" HorizontalAlignment="Right" Background="Transparent" Foreground="{StaticResource BrushTextMuted}" BorderThickness="0" FontSize="14" Cursor="Hand" Click="BtnClose_Click" WindowChrome.IsHitTestVisibleInChrome="True" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Target Info Banner -->
|
||||
<Border Grid.Row="1" Background="#161921" Margin="20,15,20,10" Padding="16,12" CornerRadius="8" BorderThickness="1" BorderBrush="{StaticResource BrushBorder}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<StackPanel>
|
||||
<TextBlock x:Name="txtTargetTitle" Text="Hedef Dizin / Dosya" FontSize="12" FontWeight="SemiBold" Foreground="{StaticResource BrushTextMuted}" />
|
||||
<TextBlock x:Name="txtTargetPath" Text="C:\..." FontSize="13" FontWeight="Bold" Foreground="{StaticResource BrushAccentRed}" TextWrapping="Wrap" Margin="0,4,0,2" />
|
||||
<TextBlock x:Name="txtLnkNote" Text="" FontSize="11" Foreground="{StaticResource BrushAccentBlueLight}" Visibility="Collapsed" />
|
||||
</StackPanel>
|
||||
|
||||
<Border x:Name="bdLockStatus" Grid.Column="1" VerticalAlignment="Center" CornerRadius="6" Padding="8,4" Background="#1F2937">
|
||||
<TextBlock x:Name="txtLockStatus" Text="Kilitler Taranıyor..." FontSize="11.5" FontWeight="SemiBold" Foreground="{StaticResource BrushTextSecondary}" />
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Locks List or Ready State -->
|
||||
<Grid Grid.Row="2" Margin="20,0,20,10">
|
||||
<DataGrid x:Name="dgLocks" Background="#11141A" RowBackground="#13161D" AlternatingRowBackground="#171A22"
|
||||
BorderThickness="1" BorderBrush="{StaticResource BrushBorder}" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True"
|
||||
HeadersVisibility="Column" GridLinesVisibility="None" Foreground="{StaticResource BrushTextPrimary}" FontSize="12">
|
||||
<DataGrid.ColumnHeaderStyle>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter Property="Background" Value="#1B1F28" />
|
||||
<Setter Property="Foreground" Value="{StaticResource BrushTextSecondary}" />
|
||||
<Setter Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="FontSize" Value="11.5" />
|
||||
<Setter Property="Padding" Value="8,6" />
|
||||
<Setter Property="BorderThickness" Value="0,0,0,1" />
|
||||
<Setter Property="BorderBrush" Value="{StaticResource BrushBorder}" />
|
||||
</Style>
|
||||
</DataGrid.ColumnHeaderStyle>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="PID" Binding="{Binding ProcessId}" Width="60" />
|
||||
<DataGridTextColumn Header="Süreç / Servis Adı" Binding="{Binding ProcessName}" Width="160" />
|
||||
<DataGridTextColumn Header="Açıklama / Durum" Binding="{Binding Description}" Width="200" />
|
||||
<DataGridTextColumn Header="Yürütülebilir Dosya Yolu" Binding="{Binding ExecutablePath}" Width="*" />
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
|
||||
<!-- When no locks found -->
|
||||
<Border x:Name="pnlNoLocks" Background="#11141A" BorderBrush="{StaticResource BrushBorder}" BorderThickness="1" CornerRadius="6" Visibility="Collapsed">
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
|
||||
<TextBlock Text="🔓" FontSize="32" HorizontalAlignment="Center" Margin="0,0,0,6" />
|
||||
<TextBlock Text="Klasörü kilitleyen aktif süreç veya servis tespit edilmedi." FontSize="13" FontWeight="SemiBold" Foreground="#34D399" HorizontalAlignment="Center" />
|
||||
<TextBlock Text="Klasör ve kalıntıları doğrudan yok edilmeye hazır." FontSize="11.5" Foreground="{StaticResource BrushTextMuted}" HorizontalAlignment="Center" Margin="0,3,0,0" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<!-- Options & Status Panel -->
|
||||
<Border Grid.Row="3" Background="#13161C" Margin="20,0,20,10" Padding="14,10" CornerRadius="6" BorderThickness="1" BorderBrush="{StaticResource BrushBorder}">
|
||||
<StackPanel>
|
||||
<CheckBox x:Name="chkRecycle" Content="Geri Dönüşüm Kutusu'na Gönder (Kalıcı veri kaybını önler)" IsChecked="True" Style="{StaticResource ModernCheckBox}" Margin="0,0,0,6" />
|
||||
<CheckBox x:Name="chkCleanJunk" Content="Kayıt Defteri ve AppData / ProgramData kalıntılarını da otomatik temizle" IsChecked="True" Style="{StaticResource ModernCheckBox}" />
|
||||
<ProgressBar x:Name="pbProgress" Height="4" Margin="0,8,0,0" Background="#1E293B" Foreground="#EF4444" BorderThickness="0" Visibility="Collapsed" IsIndeterminate="True" />
|
||||
<TextBlock x:Name="txtLog" Text="" FontSize="11.5" Foreground="{StaticResource BrushTextMuted}" Margin="0,6,0,0" TextWrapping="Wrap" Visibility="Collapsed" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- Footer Buttons -->
|
||||
<Border Grid.Row="4" Background="{StaticResource BrushBgSidebar}" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{StaticResource BrushBorder}">
|
||||
<Grid>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center">
|
||||
<Button x:Name="btnDestroy" Content="💥 Kilitleri Kır, Yok Et ve Kalıntıları Temizle" Style="{StaticResource ModernBtnPrimary}" Background="#DC2626" BorderBrush="#EF4444" Margin="0,0,10,0" Click="BtnDestroy_Click" />
|
||||
<Button x:Name="btnCancel" Content="İptal" Style="{StaticResource ModernBtnSecondary}" Click="BtnClose_Click" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
|
@ -1,179 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using LDUninstaller.Core.Junk;
|
||||
using LDUninstaller.Core.Models;
|
||||
using LDUninstaller.Core.Native;
|
||||
using LDUninstaller.Core.Services;
|
||||
|
||||
namespace LDUninstaller.UI.Dialogs
|
||||
{
|
||||
public partial class ForceDeleteWindow : Window
|
||||
{
|
||||
private readonly string _rawInputPath;
|
||||
private string _targetFolder = string.Empty;
|
||||
private string? _primaryFile;
|
||||
private string? _originalLnk;
|
||||
private bool _isDangerous;
|
||||
|
||||
public ForceDeleteWindow(string rawPath)
|
||||
{
|
||||
InitializeComponent();
|
||||
_rawInputPath = rawPath ?? string.Empty;
|
||||
Loaded += ForceDeleteWindow_Loaded;
|
||||
}
|
||||
|
||||
private async void ForceDeleteWindow_Loaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var (folder, file, lnk) = FileUnlockerService.ResolveTarget(_rawInputPath);
|
||||
_targetFolder = folder;
|
||||
_primaryFile = file;
|
||||
_originalLnk = lnk;
|
||||
|
||||
txtTargetPath.Text = _targetFolder;
|
||||
|
||||
if (!string.IsNullOrEmpty(_originalLnk))
|
||||
{
|
||||
txtLnkNote.Text = $"🔗 Masaüstü/Başlat kısayolu çözümlendi: '{Path.GetFileName(_originalLnk)}' ve ana kurulum klasörü birlikte yok edilecek.";
|
||||
txtLnkNote.Visibility = Visibility.Visible;
|
||||
}
|
||||
|
||||
// Güvenlik Kara Liste Kontrolü
|
||||
if (SafetyBlacklist.IsDangerousDirectory(_targetFolder))
|
||||
{
|
||||
_isDangerous = true;
|
||||
btnDestroy.IsEnabled = false;
|
||||
txtLockStatus.Text = "⛔ Kritik Sistem Klasörü";
|
||||
txtLockStatus.Foreground = new SolidColorBrush(Color.FromRgb(248, 113, 113));
|
||||
bdLockStatus.Background = new SolidColorBrush(Color.FromRgb(69, 10, 10));
|
||||
|
||||
MessageBox.Show(
|
||||
$"GÜVENLİK ENGELİ:\n\n'{_targetFolder}'\n\nBu klasör Windows sistem dosyalarını, kullanıcı profil kökünü veya kritik bir sürücü kökünü içerdiğinden LD Uninstaller tarafından SİLİNEMEZ!",
|
||||
"Kritik Sistem Koruması Devrede",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Hand);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await RefreshLocksAsync();
|
||||
}
|
||||
|
||||
private async Task RefreshLocksAsync()
|
||||
{
|
||||
txtLockStatus.Text = "Kilitler taranıyor...";
|
||||
|
||||
var locks = await Task.Run(() => FileUnlockerService.InspectLocks(_targetFolder));
|
||||
|
||||
if (locks.Count > 0)
|
||||
{
|
||||
dgLocks.ItemsSource = locks;
|
||||
dgLocks.Visibility = Visibility.Visible;
|
||||
pnlNoLocks.Visibility = Visibility.Collapsed;
|
||||
|
||||
txtLockStatus.Text = $"⚠️ {locks.Count} Kilitli Süreç / Servis";
|
||||
txtLockStatus.Foreground = new SolidColorBrush(Color.FromRgb(248, 113, 113));
|
||||
bdLockStatus.Background = new SolidColorBrush(Color.FromRgb(69, 10, 10));
|
||||
}
|
||||
else
|
||||
{
|
||||
dgLocks.Visibility = Visibility.Collapsed;
|
||||
pnlNoLocks.Visibility = Visibility.Visible;
|
||||
|
||||
txtLockStatus.Text = "✓ Aktif Kilit Yok";
|
||||
txtLockStatus.Foreground = new SolidColorBrush(Color.FromRgb(52, 211, 153));
|
||||
bdLockStatus.Background = new SolidColorBrush(Color.FromRgb(6, 78, 59));
|
||||
}
|
||||
}
|
||||
|
||||
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.ChangedButton == MouseButton.Left)
|
||||
DragMove();
|
||||
}
|
||||
|
||||
private void BtnClose_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private async void BtnDestroy_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_isDangerous) return;
|
||||
|
||||
var res = MessageBox.Show(
|
||||
$"Hedef:\n{_targetFolder}\n\nBu klasörle ilişkili tüm çalışan süreçler ve servisler anında sonlandırılacak, klasör ve kalıntıları tamamen yok edilecektir.\n\nİşlemi onaylıyor musunuz?",
|
||||
"💥 Güçlü Kaldırma Onayı",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Warning);
|
||||
|
||||
if (res != MessageBoxResult.Yes) return;
|
||||
|
||||
btnDestroy.IsEnabled = false;
|
||||
btnCancel.IsEnabled = false;
|
||||
chkRecycle.IsEnabled = false;
|
||||
chkCleanJunk.IsEnabled = false;
|
||||
pbProgress.Visibility = Visibility.Visible;
|
||||
txtLog.Visibility = Visibility.Visible;
|
||||
|
||||
bool sendToRecycle = chkRecycle.IsChecked == true;
|
||||
bool cleanJunk = chkCleanJunk.IsChecked == true;
|
||||
|
||||
var destroyResult = await Task.Run(() =>
|
||||
{
|
||||
return FileUnlockerService.UnlockAndDestroy(
|
||||
_targetFolder,
|
||||
sendToRecycle,
|
||||
msg => Dispatcher.Invoke(() => txtLog.Text = msg));
|
||||
});
|
||||
|
||||
// Kısayol dosyasını da temizle
|
||||
if (!string.IsNullOrEmpty(_originalLnk) && File.Exists(_originalLnk))
|
||||
{
|
||||
try { Win32.SendToRecycleBin(_originalLnk); } catch { }
|
||||
}
|
||||
|
||||
// Kalıntı temizleme (Junk Scan & Clean)
|
||||
int leftoverCount = 0;
|
||||
if (cleanJunk)
|
||||
{
|
||||
Dispatcher.Invoke(() => txtLog.Text = "Kayıt Defteri ve sistem kalıntıları temizleniyor...");
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
string appName = Path.GetFileName(_targetFolder);
|
||||
var entry = new ApplicationUninstallerEntry
|
||||
{
|
||||
DisplayName = appName,
|
||||
InstallLocation = _targetFolder
|
||||
};
|
||||
|
||||
var jm = new JunkManager();
|
||||
var junks = jm.ScanJunk(entry);
|
||||
var cleanable = junks.Where(j => j.Confidence >= ConfidenceLevel.Good).ToList();
|
||||
leftoverCount = JunkManager.CleanJunk(cleanable, JunkManager.BackupDirectory);
|
||||
});
|
||||
}
|
||||
|
||||
pbProgress.Visibility = Visibility.Collapsed;
|
||||
|
||||
string summaryMsg = $"İşlem Başarıyla Tamamlandı!\n\n" +
|
||||
$"• Sonlandırılan Süreç: {destroyResult.KilledProcessesCount}\n" +
|
||||
$"• Durdurulan/Silinen Servis: {destroyResult.StoppedServicesCount}\n" +
|
||||
$"• Temizlenen Kalıntı Kayıt/Dosya: {leftoverCount}\n";
|
||||
|
||||
if (destroyResult.ScheduledForReboot)
|
||||
{
|
||||
summaryMsg += "\nNOT: Bazı kilitli çekirdek dosyalar ilk sistem yeniden başlatmasında (MoveFileEx) silinmek üzere zamanlandı.";
|
||||
}
|
||||
|
||||
MessageBox.Show(summaryMsg, "💥 Güçlü Kaldırma Tamamlandı", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,208 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using LDUninstaller.Core.Junk;
|
||||
using LDUninstaller.Core.Models;
|
||||
|
||||
namespace LDUninstaller.UI.Dialogs
|
||||
{
|
||||
public partial class LeftoverCleanWindow : Window
|
||||
{
|
||||
private readonly List<IJunkResult> _junkItems;
|
||||
|
||||
public LeftoverCleanWindow(ApplicationUninstallerEntry app, List<IJunkResult> junkItems)
|
||||
{
|
||||
_junkItems = junkItems ?? new List<IJunkResult>();
|
||||
InitializeComponent();
|
||||
|
||||
txtTitle.Text = $"'{app.DisplayName}' Artık ve Kalıntı Dosyaları";
|
||||
|
||||
if (_junkItems.Count > 0)
|
||||
{
|
||||
dgJunk.Visibility = Visibility.Visible;
|
||||
pnlNoJunk.Visibility = Visibility.Collapsed;
|
||||
btnClean.Visibility = Visibility.Visible;
|
||||
chkSelectAll.Visibility = Visibility.Visible;
|
||||
|
||||
// U2: Yalnızca Çok Yüksek (VeryGood) güven seviyesine sahip olanlar varsayılan olarak seçili gelir
|
||||
foreach (var j in _junkItems)
|
||||
{
|
||||
j.Selected = (j.Confidence == ConfidenceLevel.VeryGood);
|
||||
}
|
||||
|
||||
dgJunk.ItemsSource = _junkItems;
|
||||
chkSelectAll.IsChecked = _junkItems.All(x => x.Selected);
|
||||
UpdateCount();
|
||||
}
|
||||
else
|
||||
{
|
||||
dgJunk.Visibility = Visibility.Collapsed;
|
||||
pnlNoJunk.Visibility = Visibility.Visible;
|
||||
btnClean.Visibility = Visibility.Collapsed;
|
||||
chkSelectAll.Visibility = Visibility.Collapsed;
|
||||
btnExclude.Visibility = Visibility.Collapsed;
|
||||
txtCount.Text = "0 kalıntı bulundu (Sistem tertemiz)";
|
||||
}
|
||||
}
|
||||
|
||||
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.ChangedButton == MouseButton.Left)
|
||||
DragMove();
|
||||
}
|
||||
|
||||
private void BtnClose_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private void ChkSelectAll_Changed(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (_junkItems == null || dgJunk == null || txtCount == null) return;
|
||||
|
||||
bool sel = chkSelectAll?.IsChecked == true;
|
||||
foreach (var j in _junkItems)
|
||||
{
|
||||
if (j.Confidence > ConfidenceLevel.Bad)
|
||||
j.Selected = sel;
|
||||
}
|
||||
dgJunk.Items.Refresh();
|
||||
UpdateCount();
|
||||
}
|
||||
|
||||
private void JunkItemCheckBox_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
UpdateCount();
|
||||
}
|
||||
|
||||
private void UpdateCount()
|
||||
{
|
||||
if (_junkItems == null || txtCount == null || btnClean == null) return;
|
||||
|
||||
int count = _junkItems.Count(x => x.Selected);
|
||||
txtCount.Text = $"{count} / {_junkItems.Count} öğe seçildi";
|
||||
btnClean.IsEnabled = count > 0;
|
||||
}
|
||||
|
||||
private void MenuCopyPath_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgJunk.SelectedItem is IJunkResult item && !string.IsNullOrWhiteSpace(item.Path))
|
||||
{
|
||||
Clipboard.SetText(item.Path);
|
||||
}
|
||||
}
|
||||
|
||||
private void MenuExclude_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgJunk.SelectedItem is IJunkResult item)
|
||||
{
|
||||
ExcludeItem(item);
|
||||
}
|
||||
}
|
||||
|
||||
private void BtnExclude_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (dgJunk.SelectedItem is IJunkResult item)
|
||||
{
|
||||
ExcludeItem(item);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Lütfen korumaya almak istediğiniz bir kalıntı öğesini seçin.", "Öğe Seçilmedi", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
}
|
||||
|
||||
private void ExcludeItem(IJunkResult item)
|
||||
{
|
||||
ExclusionManager.AddExclusion(item.Path, $"Kullanıcı Koruması: {item.EntryName}");
|
||||
_junkItems.Remove(item);
|
||||
dgJunk.ItemsSource = null;
|
||||
dgJunk.ItemsSource = _junkItems;
|
||||
UpdateCount();
|
||||
|
||||
MessageBox.Show(
|
||||
$"Hedef koruma listesine (Exclusion List) eklendi:\n{item.Path}\n\nBu yol sonraki tüm taramalarda otomatik olarak korunacaktır.",
|
||||
"Korumaya Alındı",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
}
|
||||
|
||||
private async void BtnClean_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
var toDelete = _junkItems.Where(x => x.Selected && x.Confidence > ConfidenceLevel.Bad).ToList();
|
||||
if (toDelete.Count == 0) return;
|
||||
|
||||
var res = MessageBox.Show(
|
||||
$"{toDelete.Count} adet kalıntı öğe Geri Dönüşüm Kutusu'na gönderilecek ve kayıt defteri anahtarları silinmeden önce .reg dosyası olarak yedeklenecektir.\n\nDevam edilsin mi?",
|
||||
"Kalıntı Temizleme Onayı",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (res != MessageBoxResult.Yes) return;
|
||||
|
||||
btnClean.IsEnabled = false;
|
||||
btnClose.IsEnabled = false;
|
||||
btnExclude.IsEnabled = false;
|
||||
pbCleanProgress.Visibility = Visibility.Visible;
|
||||
pbCleanProgress.Maximum = toDelete.Count;
|
||||
pbCleanProgress.Value = 0;
|
||||
|
||||
string backupDir = JunkManager.BackupDirectory;
|
||||
int successCount = 0;
|
||||
var failedItems = new List<string>();
|
||||
|
||||
await Task.Run(() =>
|
||||
{
|
||||
foreach (var item in toDelete)
|
||||
{
|
||||
try
|
||||
{
|
||||
bool ok = item.Delete(backupDir);
|
||||
if (ok)
|
||||
successCount++;
|
||||
else
|
||||
failedItems.Add(item.Path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failedItems.Add($"{item.Path} ({ex.Message})");
|
||||
}
|
||||
|
||||
Dispatcher.Invoke(() =>
|
||||
{
|
||||
pbCleanProgress.Value++;
|
||||
txtCount.Text = $"{pbCleanProgress.Value} / {toDelete.Count} temizleniyor...";
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
pbCleanProgress.Visibility = Visibility.Collapsed;
|
||||
btnClose.IsEnabled = true;
|
||||
|
||||
if (failedItems.Count == 0)
|
||||
{
|
||||
MessageBox.Show(
|
||||
$"{successCount} adet kalıntı dosya ve kayıt defteri anahtarı başarıyla temizlendi!\nKayıt defteri yedekleri:\n{backupDir}",
|
||||
"Temizlik Tamamlandı",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
string failedSummary = string.Join("\n", failedItems.Take(5));
|
||||
if (failedItems.Count > 5) failedSummary += $"\n... ve {failedItems.Count - 5} diğer öğe";
|
||||
|
||||
MessageBox.Show(
|
||||
$"{successCount} adet öğe başarıyla temizlendi.\n{failedItems.Count} öğe silinemedi (dosya kilitli veya erişim engellendi):\n\n{failedSummary}\n\nKayıt defteri yedekleri:\n{backupDir}",
|
||||
"Kalıntı Temizleme Raporu",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
<Window x:Class="LDUninstaller.UI.Dialogs.LogViewerWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="Sistem ve İşlem Günlüğü - LD Uninstaller"
|
||||
Height="550" Width="820"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
ShowInTaskbar="False"
|
||||
Background="{StaticResource BrushBgDark}"
|
||||
Foreground="{StaticResource BrushTextPrimary}"
|
||||
FontFamily="Segoe UI"
|
||||
Icon="pack://application:,,,/LDUninstaller.UI;component/Resources/app.ico"
|
||||
BorderBrush="{StaticResource BrushBorder}"
|
||||
BorderThickness="1">
|
||||
|
||||
<WindowChrome.WindowChrome>
|
||||
<WindowChrome CaptionHeight="50" ResizeBorderThickness="6" CornerRadius="8" GlassFrameThickness="0" UseAeroCaptionButtons="False" />
|
||||
</WindowChrome.WindowChrome>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="50" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="60" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Custom Title Bar -->
|
||||
<Border Grid.Row="0" Background="{StaticResource BrushBgSidebar}" MouseDown="TitleBar_MouseDown" Padding="20,0">
|
||||
<Grid>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Border Background="{StaticResource BrushGlassSapphire}" CornerRadius="6" Width="28" Height="28" Margin="0,0,12,0">
|
||||
<TextBlock Text="📜" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="Sistem ve İşlem Günlüğü (trace.log)" FontSize="14.5" FontWeight="SemiBold" Foreground="{StaticResource BrushTextPrimary}" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<Button Content="✕" Width="30" Height="30" HorizontalAlignment="Right" Background="Transparent" Foreground="{StaticResource BrushTextMuted}" BorderThickness="0" FontSize="14" Cursor="Hand" Click="BtnClose_Click" WindowChrome.IsHitTestVisibleInChrome="True" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Log Content Box -->
|
||||
<Border Grid.Row="1" Margin="20,15,20,10" Background="#11141A" BorderBrush="{StaticResource BrushBorder}" BorderThickness="1" CornerRadius="6">
|
||||
<TextBox x:Name="txtLog" Background="Transparent" Foreground="#E2E8F0" FontFamily="Consolas, Cascadia Code, Courier New" FontSize="12"
|
||||
IsReadOnly="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
|
||||
BorderThickness="0" Padding="12" />
|
||||
</Border>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" Background="{StaticResource BrushBgSidebar}" Padding="20,12" BorderThickness="0,1,0,0" BorderBrush="{StaticResource BrushBorder}">
|
||||
<Grid>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<Button Content="🔄 Yenile" Style="{StaticResource ModernBtnSecondary}" Margin="0,0,10,0" Click="BtnRefresh_Click" />
|
||||
<Button Content="📋 Kopyala" Style="{StaticResource ModernBtnSecondary}" Margin="0,0,10,0" Click="BtnCopy_Click" />
|
||||
<Button Content="📂 Not Defterinde Aç" Style="{StaticResource ModernBtnSecondary}" Margin="0,0,10,0" Click="BtnOpenExternal_Click" />
|
||||
<Button Content="🗑️ Temizle" Style="{StaticResource ModernBtnSecondary}" Click="BtnClear_Click" />
|
||||
</StackPanel>
|
||||
<Button Content="Kapat" Style="{StaticResource ModernBtnPrimary}" HorizontalAlignment="Right" VerticalAlignment="Center" Click="BtnClose_Click" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace LDUninstaller.UI.Dialogs
|
||||
{
|
||||
public partial class LogViewerWindow : Window
|
||||
{
|
||||
public LogViewerWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Loaded += (s, e) => LoadLog();
|
||||
}
|
||||
|
||||
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
|
||||
{
|
||||
if (e.ChangedButton == MouseButton.Left)
|
||||
DragMove();
|
||||
}
|
||||
|
||||
private void BtnClose_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private void LoadLog()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(App.LogFilePath))
|
||||
{
|
||||
using var fs = new FileStream(App.LogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(fs);
|
||||
txtLog.Text = reader.ReadToEnd();
|
||||
txtLog.ScrollToEnd();
|
||||
}
|
||||
else
|
||||
{
|
||||
txtLog.Text = "Henüz bir log kaydı oluşturulmadı.";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
txtLog.Text = $"Log dosyası okunamadı: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void BtnRefresh_Click(object sender, RoutedEventArgs e) => LoadLog();
|
||||
|
||||
private void BtnCopy_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(txtLog.Text))
|
||||
{
|
||||
Clipboard.SetText(txtLog.Text);
|
||||
MessageBox.Show("Log metni panoya kopyalandı.", "Kopyalandı", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
}
|
||||
|
||||
private void BtnOpenExternal_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(App.LogFilePath))
|
||||
Process.Start(new ProcessStartInfo("notepad.exe", App.LogFilePath) { UseShellExecute = true });
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void BtnClear_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(App.LogFilePath))
|
||||
File.WriteAllText(App.LogFilePath, string.Empty);
|
||||
LoadLog();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,29 +0,0 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="2.8.0.0" name="LDUninstaller.UI"/>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 and Windows 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
|
||||
<!-- Windows 8.1 -->
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />
|
||||
<!-- Windows 8 -->
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />
|
||||
<!-- Windows 7 -->
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
|
||||
</application>
|
||||
</compatibility>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
|
|
@ -1,2 +0,0 @@
|
|||
[build]
|
||||
target-dir = "C:/Users/lildosto/ld_target"
|
||||
7
src-tauri/.gitignore
vendored
|
|
@ -1,7 +0,0 @@
|
|||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
6064
src-tauri/Cargo.lock
generated
|
|
@ -1,51 +0,0 @@
|
|||
[package]
|
||||
name = "ld_uninstaller"
|
||||
version = "3.0.2"
|
||||
description = "LD Uninstaller - Modern High Performance Windows Uninstaller & System Cleaner"
|
||||
authors = ["LD Team"]
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "ld_uninstaller_lib"
|
||||
crate-type = ["rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-process = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
winreg = "0.52"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
trash = "5.2"
|
||||
sysinfo = "0.32"
|
||||
walkdir = "2.5"
|
||||
regex = "1.11"
|
||||
reqwest = { version = "0.12", features = ["json"] }
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
csv = "1.3"
|
||||
windows = { version = "0.58", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_System_RestartManager",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_Storage_FileSystem"
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
opt-level = 3
|
||||
panic = "abort"
|
||||
strip = true
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-destroy",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-maximize",
|
||||
"core:window:allow-unmaximize",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-show",
|
||||
"core:window:allow-set-focus",
|
||||
"core:window:allow-unminimize",
|
||||
"opener:default",
|
||||
"updater:default",
|
||||
"process:default"
|
||||
]
|
||||
}
|
||||
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 2 KiB |
|
Before Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 7.9 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 4.6 KiB |
|
Before Width: | Height: | Size: 85 KiB |
|
Before Width: | Height: | Size: 263 KiB |
|
|
@ -1,85 +0,0 @@
|
|||
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<Vec<ApplicationEntry>> {
|
||||
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)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn uninstall_application(
|
||||
app_id: String,
|
||||
quiet: bool,
|
||||
state: State<'_, AppState>,
|
||||
) -> AppResult<bool> {
|
||||
// 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)))?
|
||||
};
|
||||
|
||||
// 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<String> {
|
||||
let apps = {
|
||||
let cache = state.cached_apps.read().await;
|
||||
cache.clone()
|
||||
};
|
||||
|
||||
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)
|
||||
};
|
||||
|
||||
let target_path_str = target_path.to_string_lossy().to_string();
|
||||
|
||||
tokio::task::spawn_blocking(move || -> AppResult<String> {
|
||||
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)))?
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{CleanReport, JunkItem, JunkScanResult};
|
||||
use crate::services::JunkCleanerService;
|
||||
use crate::state::AppState;
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn scan_app_leftovers(
|
||||
app_name: String,
|
||||
publisher: String,
|
||||
install_location: String,
|
||||
state: State<'_, AppState>,
|
||||
) -> AppResult<JunkScanResult> {
|
||||
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]
|
||||
pub async fn clean_leftovers(
|
||||
items: Vec<JunkItem>,
|
||||
use_recycle_bin: bool,
|
||||
state: State<'_, AppState>,
|
||||
) -> AppResult<CleanReport> {
|
||||
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]
|
||||
pub async fn get_exclusions(state: State<'_, AppState>) -> AppResult<Vec<String>> {
|
||||
let list = match state.exclusions.read() {
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn add_exclusion(path_or_key: String, state: State<'_, AppState>) -> AppResult<bool> {
|
||||
state.add_exclusion(path_or_key)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn remove_exclusion(path_or_key: String, state: State<'_, AppState>) -> AppResult<bool> {
|
||||
state.remove_exclusion(&path_or_key)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
pub mod app_commands;
|
||||
pub mod junk_commands;
|
||||
pub mod system_commands;
|
||||
pub mod unlocker_commands;
|
||||
pub mod update_commands;
|
||||
|
||||
pub use app_commands::*;
|
||||
pub use junk_commands::*;
|
||||
pub use system_commands::*;
|
||||
pub use unlocker_commands::*;
|
||||
pub use update_commands::*;
|
||||
|
|
@ -1,141 +0,0 @@
|
|||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::{BackupEntry, DrivePartition, StartupItem, SystemDiagnostics, SystemTweak, TreemapItem};
|
||||
use crate::services::{safety::SafetyBlacklist, BackupService, StartupService, TreemapService, TweaksService};
|
||||
use crate::state::AppState;
|
||||
use tauri::State;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_startup_items() -> AppResult<Vec<StartupItem>> {
|
||||
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<bool> {
|
||||
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<Vec<SystemTweak>> {
|
||||
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<bool> {
|
||||
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<Vec<DrivePartition>> {
|
||||
tokio::task::spawn_blocking(TreemapService::get_disk_partitions)
|
||||
.await
|
||||
.map_err(|e| AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_treemap_data(state: State<'_, AppState>) -> AppResult<Vec<TreemapItem>> {
|
||||
let cache = state.cached_apps.read().await;
|
||||
TreemapService::generate_apps_treemap(&cache)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn list_backups(state: State<'_, AppState>) -> AppResult<Vec<BackupEntry>> {
|
||||
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<bool> {
|
||||
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<bool> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
BackupService::delete_backup(&file_path)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn is_admin_elevated() -> bool {
|
||||
SafetyBlacklist::is_elevated()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn relaunch_as_admin() -> AppResult<bool> {
|
||||
SafetyBlacklist::relaunch_as_admin()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_logs_folder(state: State<'_, AppState>) -> AppResult<bool> {
|
||||
let logs_dir = state.config_dir.join("Logs");
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _ = std::process::Command::new("explorer")
|
||||
.arg(logs_dir)
|
||||
.spawn();
|
||||
Ok(true)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_system_diagnostics(state: State<'_, AppState>) -> AppResult<SystemDiagnostics> {
|
||||
let is_elevated = SafetyBlacklist::is_elevated();
|
||||
let config_dir = state.config_dir.to_string_lossy().to_string();
|
||||
|
||||
let log_file = state.config_dir.join("Logs").join("app.log");
|
||||
let log_file_size_kb = if let Ok(meta) = std::fs::metadata(log_file) {
|
||||
meta.len() / 1024
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
let cached_apps_count = {
|
||||
let cache = state.cached_apps.read().await;
|
||||
cache.len()
|
||||
};
|
||||
|
||||
let total_exclusions_count = match state.exclusions.read() {
|
||||
Ok(guard) => guard.len(),
|
||||
Err(_) => 0,
|
||||
};
|
||||
|
||||
let os_version = std::env::var("OS")
|
||||
.unwrap_or_else(|_| "Windows 11 / 10".to_string());
|
||||
|
||||
Ok(SystemDiagnostics {
|
||||
is_elevated,
|
||||
os_version,
|
||||
config_dir,
|
||||
log_file_size_kb,
|
||||
cached_apps_count,
|
||||
total_exclusions_count,
|
||||
})
|
||||
}
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::services::FileUnlockerService;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn force_unlock_and_shred(path: String) -> AppResult<bool> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
FileUnlockerService::force_unlock_and_delete(&path)
|
||||
}).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_locking_processes(path: String) -> AppResult<Vec<u32>> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
FileUnlockerService::terminate_locking_processes(&path)
|
||||
}).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn browse_target_path(folder_only: bool) -> AppResult<Option<String>> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let script = if folder_only {
|
||||
"[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null; $f = New-Object System.Windows.Forms.FolderBrowserDialog; $f.Description = 'Silmek veya kilidini açmak istediğiniz klasörü seçin'; if ($f.ShowDialog() -eq 'OK') { $f.SelectedPath }"
|
||||
} else {
|
||||
"[System.Reflection.Assembly]::LoadWithPartialName('System.windows.forms') | Out-Null; $f = New-Object System.Windows.Forms.OpenFileDialog; $f.Title = 'Silmek veya kilidini açmak istediğiniz dosyayı seçin'; if ($f.ShowDialog() -eq 'OK') { $f.FileName }"
|
||||
};
|
||||
let output = std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-Command", script])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()?;
|
||||
let res = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if res.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(res))
|
||||
}
|
||||
}).await.map_err(|e| crate::error::AppError::Execution(e.to_string()))?
|
||||
}
|
||||
|
|
@ -1,13 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::UpdateCheckResult;
|
||||
use crate::services::UpdateService;
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn check_for_updates() -> AppResult<UpdateCheckResult> {
|
||||
UpdateService::check_for_updates().await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_update(download_url: String, sha256: String) -> AppResult<bool> {
|
||||
UpdateService::download_and_install_update(&download_url, &sha256).await
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AppError {
|
||||
#[error("I/O Hatası: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("Kayıt Defteri Hatası: {0}")]
|
||||
Registry(String),
|
||||
|
||||
#[error("Serileştirme Hatası: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
|
||||
#[error("Ağ Hatası: {0}")]
|
||||
Network(String),
|
||||
|
||||
#[error("Yeniden Başlatma Yöneticisi (Restart Manager) Hatası: {0}")]
|
||||
RestartManager(String),
|
||||
|
||||
#[error("Güvenlik Koruması Engelledi: {0}")]
|
||||
Security(String),
|
||||
|
||||
#[error("Öğe Bulunamadı: {0}")]
|
||||
NotFound(String),
|
||||
|
||||
#[error("Çalıştırma Hatası: {0}")]
|
||||
Execution(String),
|
||||
|
||||
#[error("Doğrulama Hatası: {0}")]
|
||||
Validation(String),
|
||||
|
||||
#[error("Genel Sistem Hatası: {0}")]
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
impl Serialize for AppError {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub type AppResult<T> = Result<T, AppError>;
|
||||
|
|
@ -1,55 +0,0 @@
|
|||
pub mod commands;
|
||||
pub mod error;
|
||||
pub mod models;
|
||||
pub mod services;
|
||||
pub mod state;
|
||||
|
||||
use commands::*;
|
||||
use state::AppState;
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
use tauri::Manager;
|
||||
if let Some(w) = app.get_webview_window("main") {
|
||||
let _ = w.unminimize();
|
||||
let _ = w.show();
|
||||
let _ = w.set_focus();
|
||||
}
|
||||
}))
|
||||
.manage(AppState::new())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_installed_apps,
|
||||
uninstall_application,
|
||||
export_apps_csv,
|
||||
scan_app_leftovers,
|
||||
clean_leftovers,
|
||||
get_exclusions,
|
||||
add_exclusion,
|
||||
remove_exclusion,
|
||||
force_unlock_and_shred,
|
||||
get_locking_processes,
|
||||
browse_target_path,
|
||||
get_startup_items,
|
||||
toggle_startup_item,
|
||||
get_tweaks,
|
||||
toggle_tweak,
|
||||
get_disk_partitions,
|
||||
get_treemap_data,
|
||||
list_backups,
|
||||
restore_backup,
|
||||
delete_backup,
|
||||
is_admin_elevated,
|
||||
relaunch_as_admin,
|
||||
open_logs_folder,
|
||||
get_system_diagnostics,
|
||||
check_for_updates,
|
||||
install_update,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("Tauri uygulaması başlatılırken hata oluştu");
|
||||
}
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
ld_uninstaller_lib::run();
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum ApplicationKind {
|
||||
Registry,
|
||||
StoreApp,
|
||||
Steam,
|
||||
Winget,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum UninstallerKind {
|
||||
Msi,
|
||||
InnoSetup,
|
||||
Nsis,
|
||||
InstallShield,
|
||||
Store,
|
||||
Steam,
|
||||
Custom,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApplicationEntry {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
pub display_version: String,
|
||||
pub publisher: String,
|
||||
pub install_location: String,
|
||||
pub uninstall_string: String,
|
||||
pub quiet_uninstall_string: String,
|
||||
pub install_date: String,
|
||||
pub estimated_size_kb: u64,
|
||||
pub is_system_component: bool,
|
||||
pub is_64bit: bool,
|
||||
pub kind: ApplicationKind,
|
||||
pub uninstaller_kind: UninstallerKind,
|
||||
pub registry_key_path: Option<String>,
|
||||
pub display_icon: Option<String>,
|
||||
pub url_info_about: Option<String>,
|
||||
pub help_link: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UninstallProgressEvent {
|
||||
pub app_id: String,
|
||||
pub app_name: String,
|
||||
pub status: String,
|
||||
pub percentage: f32,
|
||||
pub is_finished: bool,
|
||||
pub error_message: Option<String>,
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct BackupEntry {
|
||||
pub id: String,
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub created_at: String,
|
||||
pub size_bytes: u64,
|
||||
pub description: String,
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum JunkType {
|
||||
File,
|
||||
Directory,
|
||||
RegistryKey,
|
||||
RegistryValue,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum ConfidenceLevel {
|
||||
Bad = 0,
|
||||
Low = 1,
|
||||
Medium = 2,
|
||||
High = 3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JunkItem {
|
||||
pub id: String,
|
||||
pub item_type: JunkType,
|
||||
pub path: String,
|
||||
pub confidence: ConfidenceLevel,
|
||||
pub reason: String,
|
||||
pub size_bytes: u64,
|
||||
pub is_selected: bool,
|
||||
pub app_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JunkScanResult {
|
||||
pub items: Vec<JunkItem>,
|
||||
pub total_size_bytes: u64,
|
||||
pub total_files: usize,
|
||||
pub total_dirs: usize,
|
||||
pub total_registry_entries: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CleanReport {
|
||||
pub deleted_items_count: usize,
|
||||
pub freed_bytes: u64,
|
||||
pub backup_file_path: Option<String>,
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
pub mod app;
|
||||
pub mod backup;
|
||||
pub mod junk;
|
||||
pub mod startup;
|
||||
pub mod system;
|
||||
pub mod treemap;
|
||||
pub mod tweak;
|
||||
pub mod update;
|
||||
|
||||
pub use app::*;
|
||||
pub use backup::*;
|
||||
pub use junk::*;
|
||||
pub use startup::*;
|
||||
pub use system::*;
|
||||
pub use treemap::*;
|
||||
pub use tweak::*;
|
||||
pub use update::*;
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum StartupLocation {
|
||||
RegistryCurrentUser,
|
||||
RegistryLocalMachine,
|
||||
UserStartupFolder,
|
||||
CommonStartupFolder,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StartupItem {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub command: String,
|
||||
pub location: StartupLocation,
|
||||
pub is_enabled: bool,
|
||||
pub publisher: String,
|
||||
pub file_path: String,
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SystemDiagnostics {
|
||||
pub is_elevated: bool,
|
||||
pub os_version: String,
|
||||
pub config_dir: String,
|
||||
pub log_file_size_kb: u64,
|
||||
pub cached_apps_count: usize,
|
||||
pub total_exclusions_count: usize,
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DrivePartition {
|
||||
pub name: String,
|
||||
pub mount_point: String,
|
||||
pub total_bytes: u64,
|
||||
pub free_bytes: u64,
|
||||
pub used_bytes: u64,
|
||||
pub file_system: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TreemapItem {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub value: u64,
|
||||
pub formatted_size: String,
|
||||
pub color: String,
|
||||
pub children: Vec<TreemapItem>,
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TweakCategory {
|
||||
Privacy,
|
||||
Performance,
|
||||
System,
|
||||
Gaming,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SystemTweak {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub category: TweakCategory,
|
||||
pub is_applied: bool,
|
||||
pub requires_restart: bool,
|
||||
}
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UpdateCheckResult {
|
||||
pub has_update: bool,
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub download_url: String,
|
||||
pub release_notes: String,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UpdateDownloadProgress {
|
||||
pub percentage: f32,
|
||||
pub downloaded_bytes: u64,
|
||||
pub total_bytes: u64,
|
||||
pub is_completed: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
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 {
|
||||
pub fn list_backups(state: &AppState) -> AppResult<Vec<BackupEntry>> {
|
||||
let backup_dir = state.config_dir.join("Backups");
|
||||
if !backup_dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut backups = Vec::new();
|
||||
|
||||
if let Ok(entries) = fs::read_dir(backup_dir) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
let file_name = entry.file_name().to_string_lossy().to_string();
|
||||
|
||||
if file_name.ends_with(".reg") {
|
||||
let meta = entry.metadata().ok();
|
||||
let size_bytes = meta.as_ref().map(|m| m.len()).unwrap_or(0);
|
||||
let created_str = if let Some(m) = meta {
|
||||
if let Ok(time) = m.created() {
|
||||
let dt: chrono::DateTime<chrono::Local> = time.into();
|
||||
dt.format("%d.%m.%Y %H:%M:%S").to_string()
|
||||
} else {
|
||||
"Bilinmiyor".to_string()
|
||||
}
|
||||
} else {
|
||||
"Bilinmiyor".to_string()
|
||||
};
|
||||
|
||||
backups.push(BackupEntry {
|
||||
id: file_name.clone(),
|
||||
file_name: file_name.clone(),
|
||||
file_path: path.to_string_lossy().to_string(),
|
||||
created_at: created_str,
|
||||
size_bytes,
|
||||
description: format!("Kayıt Defteri Temizlik Yedeği ({:.2} KB)", size_bytes as f64 / 1024.0),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
backups.sort_by(|a, b| b.file_name.cmp(&a.file_name));
|
||||
Ok(backups)
|
||||
}
|
||||
|
||||
pub fn restore_backup(file_path: &str) -> AppResult<bool> {
|
||||
let path = Path::new(file_path);
|
||||
if !path.exists() {
|
||||
return Err(AppError::NotFound("Yedek dosyası diskte bulunamadı".to_string()));
|
||||
}
|
||||
|
||||
// reg import "<path>"
|
||||
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)))?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
Err(AppError::Execution(format!("Yedek geri yüklenirken hata oluştu: {}", err)))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn delete_backup(file_path: &str) -> AppResult<bool> {
|
||||
let path = Path::new(file_path);
|
||||
if path.exists() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,298 +0,0 @@
|
|||
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 {
|
||||
pub fn scan_all_applications() -> AppResult<Vec<ApplicationEntry>> {
|
||||
let mut apps: Vec<ApplicationEntry> = Vec::new();
|
||||
|
||||
// 1. Kayıt defteri taraması
|
||||
let _ = Self::scan_registry_hive(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall", true, &mut apps);
|
||||
let _ = Self::scan_registry_hive(HKEY_LOCAL_MACHINE, "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall", false, &mut apps);
|
||||
let _ = Self::scan_registry_hive(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall", true, &mut apps);
|
||||
|
||||
// 2. Steam oyunları taraması
|
||||
let _ = Self::scan_steam_games(&mut apps);
|
||||
|
||||
// 3. Windows Store uygulamaları taraması
|
||||
let _ = Self::scan_store_apps(&mut apps);
|
||||
|
||||
// Benzersizleştir (Aynı DisplayName ve InstallLocation olanları birleştir)
|
||||
apps.sort_by_key(|a| a.display_name.to_lowercase());
|
||||
apps.dedup_by(|a, b| {
|
||||
!a.display_name.is_empty()
|
||||
&& a.display_name.eq_ignore_ascii_case(&b.display_name)
|
||||
&& a.display_version == b.display_version
|
||||
});
|
||||
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn scan_registry_hive(
|
||||
hive: HKEY,
|
||||
path: &str,
|
||||
is_64bit: bool,
|
||||
apps: &mut Vec<ApplicationEntry>,
|
||||
) -> AppResult<()> {
|
||||
let root = RegKey::predef(hive);
|
||||
let uninstall_key = match root.open_subkey_with_flags(path, KEY_READ) {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
let hive_prefix = if hive == HKEY_LOCAL_MACHINE { "HKLM" } else { "HKCU" };
|
||||
|
||||
for subkey_name in uninstall_key.enum_keys().filter_map(|k| k.ok()) {
|
||||
let key = match uninstall_key.open_subkey_with_flags(&subkey_name, KEY_READ) {
|
||||
Ok(k) => k,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let display_name: String = match key.get_value("DisplayName") {
|
||||
Ok(name) => name,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let trimmed_name = display_name.trim();
|
||||
if trimmed_name.is_empty() || trimmed_name.starts_with("KB") && trimmed_name.contains("Security Update") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let display_version: String = key.get_value("DisplayVersion").unwrap_or_default();
|
||||
let publisher: String = key.get_value("Publisher").unwrap_or_default();
|
||||
let install_location: String = key.get_value("InstallLocation").unwrap_or_default();
|
||||
let uninstall_string: String = key.get_value("UninstallString").unwrap_or_default();
|
||||
let quiet_uninstall_string: String = key.get_value("QuietUninstallString").unwrap_or_default();
|
||||
let install_date: String = key.get_value("InstallDate").unwrap_or_default();
|
||||
let display_icon: Option<String> = key.get_value("DisplayIcon").ok();
|
||||
let url_info_about: Option<String> = key.get_value("URLInfoAbout").ok();
|
||||
let help_link: Option<String> = key.get_value("HelpLink").ok();
|
||||
|
||||
let estimated_size_kb: u64 = key.get_value::<u32, _>("EstimatedSize").unwrap_or(0) as u64;
|
||||
let system_component: u32 = key.get_value("SystemComponent").unwrap_or(0);
|
||||
let windows_installer: u32 = key.get_value("WindowsInstaller").unwrap_or(0);
|
||||
|
||||
// Uninstall türünü belirle
|
||||
let uninstaller_kind = if windows_installer == 1 || uninstall_string.to_lowercase().contains("msiexec.exe") {
|
||||
UninstallerKind::Msi
|
||||
} else if uninstall_string.to_lowercase().contains("unins000.exe") || install_location.to_lowercase().contains("unins000.exe") {
|
||||
UninstallerKind::InnoSetup
|
||||
} else if uninstall_string.to_lowercase().contains("uninst.exe") || uninstall_string.to_lowercase().contains("uninstall.exe") {
|
||||
UninstallerKind::Nsis
|
||||
} else if uninstall_string.to_lowercase().contains("isuninst.exe") {
|
||||
UninstallerKind::InstallShield
|
||||
} else {
|
||||
UninstallerKind::Custom
|
||||
};
|
||||
|
||||
let full_reg_path = format!("{}\\{}\\{}", hive_prefix, path, subkey_name);
|
||||
let id = format!("{:x}", md5_hash(&format!("{}_{}_{}", trimmed_name, display_version, full_reg_path)));
|
||||
|
||||
apps.push(ApplicationEntry {
|
||||
id,
|
||||
display_name: trimmed_name.to_string(),
|
||||
display_version,
|
||||
publisher,
|
||||
install_location,
|
||||
uninstall_string,
|
||||
quiet_uninstall_string,
|
||||
install_date,
|
||||
estimated_size_kb,
|
||||
is_system_component: system_component == 1,
|
||||
is_64bit,
|
||||
kind: ApplicationKind::Registry,
|
||||
uninstaller_kind,
|
||||
registry_key_path: Some(full_reg_path),
|
||||
display_icon,
|
||||
url_info_about,
|
||||
help_link,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scan_steam_games(apps: &mut Vec<ApplicationEntry>) -> AppResult<()> {
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let steam_key = match hkcu.open_subkey("Software\\Valve\\Steam") {
|
||||
Ok(k) => k,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
let steam_path_str: String = match steam_key.get_value("SteamPath") {
|
||||
Ok(p) => p,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
let steam_dir = PathBuf::from(steam_path_str.replace('/', "\\"));
|
||||
if !steam_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut library_dirs = vec![steam_dir.clone()];
|
||||
|
||||
// libraryfolders.vdf ayrıştır
|
||||
let vdf_path = steam_dir.join("steamapps").join("libraryfolders.vdf");
|
||||
if vdf_path.exists() {
|
||||
if let Ok(content) = fs::read_to_string(&vdf_path) {
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with("\"path\"") {
|
||||
let parts: Vec<&str> = trimmed.split('"').collect();
|
||||
if parts.len() >= 4 {
|
||||
let lib_path = PathBuf::from(parts[3].replace("\\\\", "\\"));
|
||||
if lib_path.exists() && !library_dirs.contains(&lib_path) {
|
||||
library_dirs.push(lib_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Her kütüphanedeki appmanifest_*.acf dosyalarını oku
|
||||
for lib in library_dirs {
|
||||
let steamapps = lib.join("steamapps");
|
||||
if !steamapps.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(entries) = fs::read_dir(steamapps) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let file_name = entry.file_name().to_string_lossy().to_string();
|
||||
if file_name.starts_with("appmanifest_") && file_name.ends_with(".acf") {
|
||||
if let Ok(content) = fs::read_to_string(entry.path()) {
|
||||
let mut app_id = String::new();
|
||||
let mut name = String::new();
|
||||
let mut installdir = String::new();
|
||||
let mut size_bytes: u64 = 0;
|
||||
|
||||
for line in content.lines() {
|
||||
let t = line.trim();
|
||||
if t.starts_with("\"appid\"") {
|
||||
let p: Vec<&str> = t.split('"').collect();
|
||||
if p.len() >= 4 { app_id = p[3].to_string(); }
|
||||
} else if t.starts_with("\"name\"") {
|
||||
let p: Vec<&str> = t.split('"').collect();
|
||||
if p.len() >= 4 { name = p[3].to_string(); }
|
||||
} else if t.starts_with("\"installdir\"") {
|
||||
let p: Vec<&str> = t.split('"').collect();
|
||||
if p.len() >= 4 { installdir = p[3].to_string(); }
|
||||
} else if t.starts_with("\"SizeOnDisk\"") {
|
||||
let p: Vec<&str> = t.split('"').collect();
|
||||
if p.len() >= 4 { size_bytes = p[3].parse().unwrap_or(0); }
|
||||
}
|
||||
}
|
||||
|
||||
if !app_id.is_empty() && !name.is_empty() && app_id != "228980" { // Steamworks Common Redistributables hariç
|
||||
let install_path = lib.join("steamapps").join("common").join(&installdir);
|
||||
apps.push(ApplicationEntry {
|
||||
id: format!("steam_{}", app_id),
|
||||
display_name: name,
|
||||
display_version: "Steam".to_string(),
|
||||
publisher: "Valve / Steam".to_string(),
|
||||
install_location: install_path.to_string_lossy().to_string(),
|
||||
uninstall_string: format!("steam://uninstall/{}", app_id),
|
||||
quiet_uninstall_string: format!("steam://uninstall/{}", app_id),
|
||||
install_date: String::new(),
|
||||
estimated_size_kb: size_bytes / 1024,
|
||||
is_system_component: false,
|
||||
is_64bit: true,
|
||||
kind: ApplicationKind::Steam,
|
||||
uninstaller_kind: UninstallerKind::Steam,
|
||||
registry_key_path: None,
|
||||
display_icon: None,
|
||||
url_info_about: Some(format!("https://store.steampowered.com/app/{}", app_id)),
|
||||
help_link: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scan_store_apps(apps: &mut Vec<ApplicationEntry>) -> 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,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
if !output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let json_str = String::from_utf8_lossy(&output.stdout);
|
||||
let parsed: serde_json::Value = match serde_json::from_str(&json_str) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
|
||||
let items = if let Some(arr) = parsed.as_array() {
|
||||
arr.clone()
|
||||
} else if parsed.is_object() {
|
||||
vec![parsed]
|
||||
} else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for item in items {
|
||||
let name = item["Name"].as_str().unwrap_or_default().trim();
|
||||
let package_full_name = item["PackageFullName"].as_str().unwrap_or_default();
|
||||
let install_loc = item["InstallLocation"].as_str().unwrap_or_default();
|
||||
let publisher = item["Publisher"].as_str().unwrap_or_default();
|
||||
|
||||
if name.is_empty() || package_full_name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
apps.push(ApplicationEntry {
|
||||
id: format!("uwp_{}", package_full_name),
|
||||
display_name: name.to_string(),
|
||||
display_version: "UWP/Store".to_string(),
|
||||
publisher: publisher.to_string(),
|
||||
install_location: install_loc.to_string(),
|
||||
uninstall_string: format!("powershell -NoProfile -Command \"Remove-AppxPackage -Package {}\"", package_full_name),
|
||||
quiet_uninstall_string: format!("powershell -NoProfile -Command \"Remove-AppxPackage -Package {}\"", package_full_name),
|
||||
install_date: String::new(),
|
||||
estimated_size_kb: 0,
|
||||
is_system_component: false,
|
||||
is_64bit: true,
|
||||
kind: ApplicationKind::StoreApp,
|
||||
uninstaller_kind: UninstallerKind::Store,
|
||||
registry_key_path: None,
|
||||
display_icon: None,
|
||||
url_info_about: None,
|
||||
help_link: None,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn md5_hash(input: &str) -> u128 {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(input.as_bytes());
|
||||
let res = hasher.finalize();
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes.copy_from_slice(&res[0..16]);
|
||||
u128::from_le_bytes(bytes)
|
||||
}
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
use crate::error::{AppError, AppResult};
|
||||
use crate::services::safety::SafetyBlacklist;
|
||||
use std::fs;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
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};
|
||||
use windows::Win32::System::RestartManager::{
|
||||
RmEndSession, RmGetList, RmRegisterResources, RmStartSession, RM_PROCESS_INFO,
|
||||
};
|
||||
use windows::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE};
|
||||
|
||||
pub struct FileUnlockerService;
|
||||
|
||||
impl FileUnlockerService {
|
||||
pub fn force_unlock_and_delete(path_str: &str) -> AppResult<bool> {
|
||||
let clean_path = SafetyBlacklist::normalize_canonical_path(path_str);
|
||||
if clean_path.is_empty() {
|
||||
return Err(AppError::Validation("Geçersiz veya boş dosya yolu".to_string()));
|
||||
}
|
||||
|
||||
let path = Path::new(&clean_path);
|
||||
if !path.exists() {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// Güvenlik Kalkanı: Kritik Windows klasörlerini zorla silmeye karşı koru
|
||||
if SafetyBlacklist::is_dangerous_file_path(&clean_path) {
|
||||
return Err(AppError::Security(format!(
|
||||
"Kritik sistem yolu zorla silinemez: {}",
|
||||
clean_path
|
||||
)));
|
||||
}
|
||||
|
||||
// 1. Restart Manager ile kilitleyen süreçleri bul ve sonlandır
|
||||
let _ = Self::terminate_locking_processes(&clean_path);
|
||||
|
||||
// 2. Salt okunur (read-only) ve sistem özniteliklerini temizle
|
||||
Self::clear_file_attributes(&clean_path);
|
||||
|
||||
// 3. Klasör veya dosyayı silmeyi dene
|
||||
if path.is_dir() {
|
||||
match fs::remove_dir_all(path) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => {
|
||||
// Yeniden deneme döngüsü (5 iterasyon)
|
||||
for _ in 0..5 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
if fs::remove_dir_all(path).is_ok() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
// Son çare: Reboot silme sırasına al
|
||||
Self::schedule_delete_on_reboot(path_str)?;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match fs::remove_file(path) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(_) => {
|
||||
for _ in 0..5 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||
if fs::remove_file(path).is_ok() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Self::schedule_delete_on_reboot(path_str)?;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminate_locking_processes(path_str: &str) -> AppResult<Vec<u32>> {
|
||||
let mut session_handle = 0u32;
|
||||
let mut session_key = [0u16; 33];
|
||||
|
||||
unsafe {
|
||||
let res = RmStartSession(&mut session_handle, 0, PWSTR(session_key.as_mut_ptr()));
|
||||
if res != ERROR_SUCCESS {
|
||||
return Err(AppError::RestartManager("RmStartSession başarısız".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
let wide_path: Vec<u16> = std::ffi::OsStr::new(path_str)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let paths = [PCWSTR(wide_path.as_ptr())];
|
||||
|
||||
unsafe {
|
||||
let reg_res = RmRegisterResources(session_handle, Some(&paths), None, None);
|
||||
if reg_res != ERROR_SUCCESS {
|
||||
let _ = RmEndSession(session_handle);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
let mut n_proc_info_needed = 0u32;
|
||||
let mut n_proc_info = 0u32;
|
||||
let mut reboot_reasons = 0u32;
|
||||
|
||||
unsafe {
|
||||
let _ = RmGetList(
|
||||
session_handle,
|
||||
&mut n_proc_info_needed,
|
||||
&mut n_proc_info,
|
||||
None,
|
||||
&mut reboot_reasons,
|
||||
);
|
||||
}
|
||||
|
||||
let mut terminated_pids = Vec::new();
|
||||
|
||||
if n_proc_info_needed > 0 {
|
||||
let mut proc_info: Vec<RM_PROCESS_INFO> = vec![unsafe { std::mem::zeroed() }; n_proc_info_needed as usize];
|
||||
n_proc_info = n_proc_info_needed;
|
||||
|
||||
let list_res = unsafe {
|
||||
RmGetList(
|
||||
session_handle,
|
||||
&mut n_proc_info_needed,
|
||||
&mut n_proc_info,
|
||||
Some(proc_info.as_mut_ptr()),
|
||||
&mut reboot_reasons,
|
||||
)
|
||||
};
|
||||
|
||||
if list_res == ERROR_SUCCESS || list_res == ERROR_MORE_DATA {
|
||||
let current_pid = std::process::id();
|
||||
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 {
|
||||
if let Ok(handle) = OpenProcess(PROCESS_TERMINATE, false, pid) {
|
||||
if !handle.is_invalid() {
|
||||
let _ = TerminateProcess(handle, 1);
|
||||
let _ = CloseHandle(handle);
|
||||
terminated_pids.push(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let _ = RmEndSession(session_handle);
|
||||
}
|
||||
|
||||
Ok(terminated_pids)
|
||||
}
|
||||
|
||||
fn clear_file_attributes(path_str: &str) {
|
||||
// attrib -r -s -h "<path>" /s /d
|
||||
let _ = std::process::Command::new("attrib")
|
||||
.args(["-r", "-s", "-h", path_str, "/s", "/d"])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output();
|
||||
}
|
||||
|
||||
fn schedule_delete_on_reboot(path_str: &str) -> AppResult<()> {
|
||||
let wide: Vec<u16> = std::ffi::OsStr::new(path_str)
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect();
|
||||
let success = unsafe {
|
||||
MoveFileExW(
|
||||
windows::core::PCWSTR(wide.as_ptr()),
|
||||
windows::core::PCWSTR::null(),
|
||||
MOVEFILE_DELAY_UNTIL_REBOOT,
|
||||
)
|
||||
};
|
||||
|
||||
if success.is_ok() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AppError::Execution("Yeniden başlatmada silme işlemi kaydedilemedi".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,384 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::{CleanReport, ConfidenceLevel, JunkItem, JunkScanResult, JunkType};
|
||||
use crate::services::safety::SafetyBlacklist;
|
||||
use crate::services::sift4::Sift4;
|
||||
use chrono::Local;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
pub struct JunkCleanerService;
|
||||
|
||||
impl JunkCleanerService {
|
||||
pub fn scan_leftovers(
|
||||
app_name: &str,
|
||||
publisher: &str,
|
||||
install_location: &str,
|
||||
exclusions: &[String],
|
||||
) -> AppResult<JunkScanResult> {
|
||||
let mut items: Vec<JunkItem> = Vec::new();
|
||||
|
||||
let tokens = Sift4::tokenize(app_name);
|
||||
let pub_tokens = Sift4::tokenize(publisher);
|
||||
|
||||
// 1. Dosya Sistemi Taraması
|
||||
let search_dirs = Self::get_standard_search_directories();
|
||||
for dir in search_dirs {
|
||||
if !dir.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(entries) = fs::read_dir(&dir) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let path = entry.path();
|
||||
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) || Self::is_excluded(&path_str, exclusions) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let folder_name = entry.file_name().to_string_lossy().to_string();
|
||||
let folder_lower = folder_name.to_lowercase();
|
||||
|
||||
let is_dir = path.is_dir();
|
||||
let mut matched = false;
|
||||
let mut confidence = ConfidenceLevel::Low;
|
||||
let mut match_reason = String::new();
|
||||
|
||||
// Doğrudan yükleme klasörü eşleşmesi
|
||||
if !install_location.is_empty() && path_str.eq_ignore_ascii_case(install_location) {
|
||||
matched = true;
|
||||
confidence = ConfidenceLevel::High;
|
||||
match_reason = "Doğrudan Yükleme Klasörü".to_string();
|
||||
} else if folder_lower == app_name.to_lowercase() {
|
||||
matched = true;
|
||||
confidence = ConfidenceLevel::High;
|
||||
match_reason = "Birebir Klasör Adı Eşleşmesi".to_string();
|
||||
} else {
|
||||
// Token ve Sift4 eşleşmesi
|
||||
for token in &tokens {
|
||||
if Sift4::contains_word_boundary(&folder_lower, token) {
|
||||
matched = true;
|
||||
confidence = ConfidenceLevel::Medium;
|
||||
match_reason = format!("'{}' kelimesi klasör adında bulundu", token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if matched {
|
||||
let size = if is_dir { Self::calculate_dir_size(&path) } else { entry.metadata().map(|m| m.len()).unwrap_or(0) };
|
||||
items.push(JunkItem {
|
||||
id: format!("{:x}", Self::hash_str(&path_str)),
|
||||
item_type: if is_dir { JunkType::Directory } else { JunkType::File },
|
||||
path: path_str,
|
||||
confidence: confidence.clone(),
|
||||
reason: match_reason,
|
||||
size_bytes: size,
|
||||
is_selected: confidence >= ConfidenceLevel::Medium,
|
||||
app_id: app_name.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Kayıt Defteri Taraması
|
||||
Self::scan_registry_leftovers(app_name, publisher, &tokens, &pub_tokens, exclusions, &mut items);
|
||||
|
||||
let mut total_size = 0u64;
|
||||
let mut total_files = 0;
|
||||
let mut total_dirs = 0;
|
||||
let mut total_reg = 0;
|
||||
|
||||
for item in &items {
|
||||
total_size += item.size_bytes;
|
||||
match item.item_type {
|
||||
JunkType::File => total_files += 1,
|
||||
JunkType::Directory => total_dirs += 1,
|
||||
JunkType::RegistryKey | JunkType::RegistryValue => total_reg += 1,
|
||||
}
|
||||
}
|
||||
|
||||
Ok(JunkScanResult {
|
||||
items,
|
||||
total_size_bytes: total_size,
|
||||
total_files,
|
||||
total_dirs,
|
||||
total_registry_entries: total_reg,
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_registry_leftovers(
|
||||
app_name: &str,
|
||||
_publisher: &str,
|
||||
tokens: &[String],
|
||||
_pub_tokens: &[String],
|
||||
exclusions: &[String],
|
||||
items: &mut Vec<JunkItem>,
|
||||
) {
|
||||
let targets = [
|
||||
(HKEY_CURRENT_USER, "HKCU", "Software"),
|
||||
(HKEY_LOCAL_MACHINE, "HKLM", "Software"),
|
||||
(HKEY_LOCAL_MACHINE, "HKLM", "Software\\WOW6432Node"),
|
||||
];
|
||||
|
||||
for (hive, hive_name, sub_path) in targets {
|
||||
let root = RegKey::predef(hive);
|
||||
let sw_key = match root.open_subkey_with_flags(sub_path, KEY_READ) {
|
||||
Ok(k) => k,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
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) || Self::is_excluded(&full_path, exclusions) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let sub_lower = subkey.to_lowercase();
|
||||
let mut matched = false;
|
||||
let mut confidence = ConfidenceLevel::Low;
|
||||
let mut reason = String::new();
|
||||
|
||||
if sub_lower == app_name.to_lowercase() {
|
||||
matched = true;
|
||||
confidence = ConfidenceLevel::High;
|
||||
reason = "Birebir Kayıt Defteri Anahtarı".to_string();
|
||||
} else {
|
||||
for token in tokens {
|
||||
if Sift4::contains_word_boundary(&sub_lower, token) {
|
||||
matched = true;
|
||||
confidence = ConfidenceLevel::Medium;
|
||||
reason = format!("'{}' kayıt defteri dalında bulundu", token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if matched {
|
||||
items.push(JunkItem {
|
||||
id: format!("{:x}", Self::hash_str(&full_path)),
|
||||
item_type: JunkType::RegistryKey,
|
||||
path: full_path,
|
||||
confidence: confidence.clone(),
|
||||
reason,
|
||||
size_bytes: 0,
|
||||
is_selected: confidence >= ConfidenceLevel::Medium,
|
||||
app_id: app_name.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clean_selected_items(
|
||||
items: &[JunkItem],
|
||||
use_recycle_bin: bool,
|
||||
backup_dir: &Path,
|
||||
) -> AppResult<CleanReport> {
|
||||
let mut deleted_count = 0;
|
||||
let mut freed_bytes = 0u64;
|
||||
let mut errors = Vec::new();
|
||||
|
||||
// 1. Registry anahtarları için .reg yedeği oluştur
|
||||
let reg_items: Vec<&JunkItem> = items
|
||||
.iter()
|
||||
.filter(|i| i.is_selected && (i.item_type == JunkType::RegistryKey || i.item_type == JunkType::RegistryValue))
|
||||
.collect();
|
||||
|
||||
let backup_path = if !reg_items.is_empty() {
|
||||
match Self::create_registry_backup(®_items, backup_dir) {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
errors.push(format!("Yedekleme oluşturulamadı: {}", e));
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 2. Silme işlemlerini gerçekleştir
|
||||
for item in items.iter().filter(|i| i.is_selected) {
|
||||
match item.item_type {
|
||||
JunkType::File => {
|
||||
let p = Path::new(&item.path);
|
||||
if p.exists() {
|
||||
if use_recycle_bin {
|
||||
if let Err(e) = trash::delete(p) {
|
||||
errors.push(format!("Geri Dönüşüm Kutusuna taşınamadı ({}): {}", item.path, e));
|
||||
} else {
|
||||
deleted_count += 1;
|
||||
freed_bytes += item.size_bytes;
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = fs::remove_file(p) {
|
||||
errors.push(format!("Dosya silinemedi ({}): {}", item.path, e));
|
||||
} else {
|
||||
deleted_count += 1;
|
||||
freed_bytes += item.size_bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
JunkType::Directory => {
|
||||
let p = Path::new(&item.path);
|
||||
if p.exists() {
|
||||
if use_recycle_bin {
|
||||
if let Err(e) = trash::delete(p) {
|
||||
errors.push(format!("Klasör Geri Dönüşüm Kutusuna taşınamadı ({}): {}", item.path, e));
|
||||
} else {
|
||||
deleted_count += 1;
|
||||
freed_bytes += item.size_bytes;
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = fs::remove_dir_all(p) {
|
||||
errors.push(format!("Klasör silinemedi ({}): {}", item.path, e));
|
||||
} else {
|
||||
deleted_count += 1;
|
||||
freed_bytes += item.size_bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
JunkType::RegistryKey => {
|
||||
if let Err(e) = Self::delete_registry_key(&item.path) {
|
||||
errors.push(format!("Kayıt defteri anahtarı silinemedi ({}): {}", item.path, e));
|
||||
} else {
|
||||
deleted_count += 1;
|
||||
}
|
||||
}
|
||||
JunkType::RegistryValue => {
|
||||
deleted_count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CleanReport {
|
||||
deleted_items_count: deleted_count,
|
||||
freed_bytes,
|
||||
backup_file_path: backup_path,
|
||||
errors,
|
||||
})
|
||||
}
|
||||
|
||||
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<String> {
|
||||
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 _ = 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");
|
||||
|
||||
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<u16> = 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, combined_content)?;
|
||||
Ok(backup_file.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
fn delete_registry_key(path_str: &str) -> AppResult<()> {
|
||||
let (hive, sub) = if path_str.starts_with("HKCU\\") || path_str.starts_with("HKEY_CURRENT_USER\\") {
|
||||
let part = path_str.split_once('\\').map(|x| x.1).unwrap_or("");
|
||||
(HKEY_CURRENT_USER, part)
|
||||
} else if path_str.starts_with("HKLM\\") || path_str.starts_with("HKEY_LOCAL_MACHINE\\") {
|
||||
let part = path_str.split_once('\\').map(|x| x.1).unwrap_or("");
|
||||
(HKEY_LOCAL_MACHINE, part)
|
||||
} else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
if SafetyBlacklist::is_dangerous_registry_path(path_str) {
|
||||
return Err(crate::error::AppError::Security(format!("Kritik kayıt defteri anahtarı silinemez: {}", path_str)));
|
||||
}
|
||||
|
||||
let root = RegKey::predef(hive);
|
||||
let _ = root.delete_subkey_all(sub);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn calculate_dir_size(path: &Path) -> u64 {
|
||||
let mut size = 0u64;
|
||||
for entry in walkdir::WalkDir::new(path).into_iter().filter_map(|e| e.ok()) {
|
||||
if let Ok(meta) = entry.metadata() {
|
||||
if meta.is_file() {
|
||||
size += meta.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
size
|
||||
}
|
||||
|
||||
fn get_standard_search_directories() -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if let Ok(val) = std::env::var("LOCALAPPDATA") { dirs.push(PathBuf::from(val)); }
|
||||
if let Ok(val) = std::env::var("APPDATA") { dirs.push(PathBuf::from(val)); }
|
||||
if let Ok(val) = std::env::var("ProgramData") { dirs.push(PathBuf::from(val)); }
|
||||
if let Ok(val) = std::env::var("ProgramFiles") { dirs.push(PathBuf::from(val)); }
|
||||
if let Ok(val) = std::env::var("ProgramFiles(x86)") { dirs.push(PathBuf::from(val)); }
|
||||
dirs
|
||||
}
|
||||
|
||||
fn hash_str(val: &str) -> u128 {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(val.as_bytes());
|
||||
let res = hasher.finalize();
|
||||
let mut b = [0u8; 16];
|
||||
b.copy_from_slice(&res[0..16]);
|
||||
u128::from_le_bytes(b)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
use chrono::Local;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
|
||||
static LOGGER: Mutex<Option<AppLogger>> = Mutex::new(None);
|
||||
|
||||
pub struct AppLogger {
|
||||
pub log_file: PathBuf,
|
||||
}
|
||||
|
||||
impl AppLogger {
|
||||
pub fn init(config_dir: &std::path::Path) {
|
||||
let logs_dir = config_dir.join("Logs");
|
||||
let _ = fs::create_dir_all(&logs_dir);
|
||||
let log_file = logs_dir.join("app.log");
|
||||
|
||||
let logger = AppLogger { log_file };
|
||||
let mut guard = match LOGGER.lock() {
|
||||
Ok(g) => g,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
*guard = Some(logger);
|
||||
}
|
||||
|
||||
pub fn log(level: &str, message: &str) {
|
||||
let guard = match LOGGER.lock() {
|
||||
Ok(g) => g,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
|
||||
if let Some(logger) = guard.as_ref() {
|
||||
// Log rotation: 5 MB aşılırsa app.log.old olarak döndür
|
||||
if let Ok(meta) = fs::metadata(&logger.log_file) {
|
||||
if meta.len() > 5 * 1024 * 1024 {
|
||||
let old_file = logger.log_file.with_extension("log.old");
|
||||
let _ = fs::rename(&logger.log_file, old_file);
|
||||
}
|
||||
}
|
||||
|
||||
let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
|
||||
let line = format!("[{}] [{}] {}\n", timestamp, level, message);
|
||||
|
||||
if let Ok(mut file) = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&logger.log_file)
|
||||
{
|
||||
let _ = file.write_all(line.as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn log_info(msg: &str) {
|
||||
AppLogger::log("INFO", msg);
|
||||
}
|
||||
|
||||
pub fn log_warn(msg: &str) {
|
||||
AppLogger::log("WARN", msg);
|
||||
}
|
||||
|
||||
pub fn log_error(msg: &str) {
|
||||
AppLogger::log("ERROR", msg);
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
pub mod backup_service;
|
||||
pub mod discovery;
|
||||
pub mod file_unlocker;
|
||||
pub mod junk_cleaner;
|
||||
pub mod logger;
|
||||
pub mod safety;
|
||||
pub mod sift4;
|
||||
pub mod startup_service;
|
||||
pub mod treemap_service;
|
||||
pub mod tweaks_service;
|
||||
pub mod uninstaller;
|
||||
pub mod update_service;
|
||||
|
||||
pub use backup_service::BackupService;
|
||||
pub use discovery::DiscoveryService;
|
||||
pub use file_unlocker::FileUnlockerService;
|
||||
pub use junk_cleaner::JunkCleanerService;
|
||||
pub use safety::SafetyBlacklist;
|
||||
pub use sift4::Sift4;
|
||||
pub use startup_service::StartupService;
|
||||
pub use treemap_service::TreemapService;
|
||||
pub use tweaks_service::TweaksService;
|
||||
pub use uninstaller::UninstallerService;
|
||||
pub use update_service::UpdateService;
|
||||
|
|
@ -1,239 +0,0 @@
|
|||
use std::path::Path;
|
||||
|
||||
pub struct SafetyBlacklist;
|
||||
|
||||
impl SafetyBlacklist {
|
||||
/// Path Traversal (../) ve göreceli yolları güvenli bir şekilde normalize eder.
|
||||
pub fn normalize_canonical_path(raw_path: &str) -> String {
|
||||
let trimmed = raw_path.trim().trim_matches('"');
|
||||
if trimmed.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let replaced = trimmed.replace('/', "\\");
|
||||
let path = Path::new(&replaced);
|
||||
|
||||
// Diskte mevcutsa Windows symlink ve .. çözümlemesini yap
|
||||
if let Ok(canon) = path.canonicalize() {
|
||||
let s = canon.to_string_lossy().to_string();
|
||||
let clean = if let Some(stripped) = s.strip_prefix(r"\\?\") {
|
||||
stripped.to_string()
|
||||
} else {
|
||||
s
|
||||
};
|
||||
return clean.to_lowercase();
|
||||
}
|
||||
|
||||
// Diskte henüz mevcut değilse mantıksal olarak .. ve . bileşenlerini çözümle
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
for comp in replaced.split('\\') {
|
||||
if comp.is_empty() || comp == "." {
|
||||
continue;
|
||||
} else if comp == ".." {
|
||||
parts.pop();
|
||||
} else {
|
||||
parts.push(comp);
|
||||
}
|
||||
}
|
||||
parts.join("\\").to_lowercase()
|
||||
}
|
||||
|
||||
pub fn is_dangerous_file_path(raw_path: &str) -> bool {
|
||||
let normalized = Self::normalize_canonical_path(raw_path);
|
||||
if normalized.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let path = Path::new(&normalized);
|
||||
|
||||
// Kök dizin kontrolü (örn. C:\ veya D:\)
|
||||
if normalized.len() <= 3 && (normalized.ends_with(':') || normalized.ends_with(":\\")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Sistem yolları
|
||||
let system_root = std::env::var("SystemRoot")
|
||||
.unwrap_or_else(|_| "C:\\Windows".to_string())
|
||||
.to_lowercase();
|
||||
if normalized == system_root || normalized.starts_with(&format!("{}\\", system_root)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let win_dir = std::env::var("WINDIR")
|
||||
.unwrap_or_else(|_| "C:\\Windows".to_string())
|
||||
.to_lowercase();
|
||||
if normalized == win_dir || normalized.starts_with(&format!("{}\\", win_dir)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Program Files kökleri
|
||||
let pf = std::env::var("ProgramFiles")
|
||||
.unwrap_or_else(|_| "C:\\Program Files".to_string())
|
||||
.to_lowercase();
|
||||
let pfx86 = std::env::var("ProgramFiles(x86)")
|
||||
.unwrap_or_else(|_| "C:\\Program Files (x86)".to_string())
|
||||
.to_lowercase();
|
||||
|
||||
if normalized == pf || normalized == pfx86 {
|
||||
return true;
|
||||
}
|
||||
|
||||
// WindowsApps & Package Cache koruması
|
||||
if normalized.contains("\\windowsapps") || normalized.contains("\\package cache") {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Kullanıcı kök dizini (C:\Users veya C:\Users\KullanıcıAdı)
|
||||
let user_profile = std::env::var("USERPROFILE")
|
||||
.unwrap_or_else(|_| "C:\\Users\\Default".to_string())
|
||||
.to_lowercase();
|
||||
if normalized == user_profile {
|
||||
return true;
|
||||
}
|
||||
|
||||
let users_root = if let Some(parent) = Path::new(&user_profile).parent() {
|
||||
parent.to_string_lossy().to_string().to_lowercase()
|
||||
} else {
|
||||
"c:\\users".to_string()
|
||||
};
|
||||
if normalized == users_root {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Kullanıcı kritik klasörleri: Belgelerim, Masaüstü, OneDrive kökü, İndirilenler
|
||||
let documents = format!("{}\\documents", user_profile);
|
||||
let desktop = format!("{}\\desktop", user_profile);
|
||||
let downloads = format!("{}\\downloads", user_profile);
|
||||
let onedrive = std::env::var("OneDrive")
|
||||
.unwrap_or_default()
|
||||
.to_lowercase();
|
||||
|
||||
if normalized == documents || normalized == desktop || normalized == downloads {
|
||||
return true;
|
||||
}
|
||||
if !onedrive.is_empty() && (normalized == onedrive || normalized == format!("{}\\desktop", onedrive) || normalized == format!("{}\\documents", onedrive)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Genel hassas klasörler
|
||||
let dangerous_leafs = [
|
||||
"system32", "syswow64", "winsxs", "boot", "recovery", "$recycle.bin",
|
||||
"system volume information", "windows nt", "microsoft", "common files",
|
||||
];
|
||||
|
||||
if let Some(file_name) = path.file_name() {
|
||||
let name_str = file_name.to_string_lossy().to_lowercase();
|
||||
if dangerous_leafs.contains(&name_str.as_str()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub fn is_dangerous_registry_path(raw_path: &str) -> bool {
|
||||
let trimmed = raw_path.trim().trim_matches('\\');
|
||||
if trimmed.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let normalized = trimmed.to_lowercase();
|
||||
|
||||
let dangerous_exact_or_prefix = [
|
||||
"hklm\\software\\microsoft\\windows nt\\currentversion",
|
||||
"hklm\\software\\microsoft\\windows\\currentversion",
|
||||
"hkcu\\software\\microsoft\\windows\\currentversion\\explorer",
|
||||
"hkcu\\software\\microsoft\\windows\\currentversion",
|
||||
"hklm\\system",
|
||||
"hklm\\sam",
|
||||
"hklm\\security",
|
||||
"hklm\\hardware",
|
||||
"hkey_local_machine\\system",
|
||||
"hkey_local_machine\\sam",
|
||||
"hkey_local_machine\\security",
|
||||
"hkey_local_machine\\hardware",
|
||||
"hkey_classes_root",
|
||||
"hkcr",
|
||||
];
|
||||
|
||||
for dangerous in &dangerous_exact_or_prefix {
|
||||
if normalized == *dangerous || normalized.starts_with(&format!("{}\\", dangerous)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Sadece Root kovanlar silinemez
|
||||
let roots = [
|
||||
"hkey_local_machine", "hklm",
|
||||
"hkey_current_user", "hkcu",
|
||||
"hkey_classes_root", "hkcr",
|
||||
"hkey_users", "hku",
|
||||
"hkey_current_config", "hkcc",
|
||||
"hklm\\software", "hkcu\\software",
|
||||
"hklm\\software\\wow6432node",
|
||||
];
|
||||
|
||||
for root in &roots {
|
||||
if normalized == *root {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Windows işlem token'ı üzerinden uygulamanın Yönetici (Administrator) olarak çalışıp çalışmadığını doğrular
|
||||
pub fn is_elevated() -> bool {
|
||||
use windows::Win32::Foundation::HANDLE;
|
||||
use windows::Win32::Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY};
|
||||
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
|
||||
|
||||
unsafe {
|
||||
let mut token = HANDLE::default();
|
||||
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).is_ok() {
|
||||
let mut elevation = TOKEN_ELEVATION::default();
|
||||
let mut return_length = 0u32;
|
||||
let success = GetTokenInformation(
|
||||
token,
|
||||
TokenElevation,
|
||||
Some(&mut elevation as *mut _ as *mut _),
|
||||
std::mem::size_of::<TOKEN_ELEVATION>() as u32,
|
||||
&mut return_length,
|
||||
);
|
||||
let _ = windows::Win32::Foundation::CloseHandle(token);
|
||||
if success.is_ok() {
|
||||
return elevation.TokenIsElevated != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Uygulamayı kullanıcı onayıyla (UAC 'runas') Yönetici yetkileriyle yeniden başlatır
|
||||
pub fn relaunch_as_admin() -> crate::error::AppResult<bool> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows::core::PCWSTR;
|
||||
use windows::Win32::UI::Shell::ShellExecuteW;
|
||||
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
|
||||
|
||||
let current_exe = std::env::current_exe()?;
|
||||
let exe_wide: Vec<u16> = current_exe.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let verb_wide: Vec<u16> = std::ffi::OsStr::new("runas").encode_wide().chain(std::iter::once(0)).collect();
|
||||
|
||||
unsafe {
|
||||
let instance = ShellExecuteW(
|
||||
None,
|
||||
PCWSTR(verb_wide.as_ptr()),
|
||||
PCWSTR(exe_wide.as_ptr()),
|
||||
PCWSTR::null(),
|
||||
PCWSTR::null(),
|
||||
SW_SHOWNORMAL,
|
||||
);
|
||||
if instance.0 as usize > 32 {
|
||||
std::process::exit(0);
|
||||
} else {
|
||||
Err(crate::error::AppError::Security("Yönetici yetkisi verilmedi veya UAC iptal edildi.".to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
pub struct Sift4;
|
||||
|
||||
impl Sift4 {
|
||||
/// Sift4 mesafe algoritması (küçük değer = daha yakın eşleşme)
|
||||
pub fn distance(s1: &str, s2: &str, max_offset: usize) -> usize {
|
||||
let c1: Vec<char> = s1.chars().collect();
|
||||
let c2: Vec<char> = s2.chars().collect();
|
||||
|
||||
let l1 = c1.len();
|
||||
let l2 = c2.len();
|
||||
|
||||
if l1 == 0 {
|
||||
return l2;
|
||||
}
|
||||
if l2 == 0 {
|
||||
return l1;
|
||||
}
|
||||
|
||||
let mut c1_idx = 0;
|
||||
let mut c2_idx = 0;
|
||||
let mut lcss = 0;
|
||||
let mut local_cs = 0;
|
||||
let mut trans = 0;
|
||||
|
||||
let mut offset_arr: Vec<(usize, usize)> = Vec::new();
|
||||
|
||||
while c1_idx < l1 && c2_idx < l2 {
|
||||
if c1[c1_idx] == c2[c2_idx] {
|
||||
local_cs += 1;
|
||||
let i = 0;
|
||||
while i < offset_arr.len() {
|
||||
let ofs = offset_arr[i];
|
||||
if c1_idx <= ofs.0 || c2_idx <= ofs.1 {
|
||||
let is_trans = c1_idx.abs_diff(c2_idx) >= ofs.0.abs_diff(ofs.1);
|
||||
if is_trans {
|
||||
trans += 1;
|
||||
} else if ofs.0 <= c1_idx && ofs.1 <= c2_idx {
|
||||
offset_arr.remove(i);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
offset_arr.remove(i);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
offset_arr.push((c1_idx, c2_idx));
|
||||
c1_idx += 1;
|
||||
c2_idx += 1;
|
||||
} else {
|
||||
lcss += local_cs;
|
||||
local_cs = 0;
|
||||
if c1_idx != c2_idx {
|
||||
c1_idx = c1_idx.min(c2_idx);
|
||||
c2_idx = c1_idx;
|
||||
}
|
||||
|
||||
for i in 0..max_offset {
|
||||
if c1_idx + i < l1 && c2_idx < l2 && c1[c1_idx + i] == c2[c2_idx] {
|
||||
c1_idx += i;
|
||||
local_cs += 1;
|
||||
break;
|
||||
}
|
||||
if c2_idx + i < l2 && c1_idx < l1 && c1[c1_idx] == c2[c2_idx + i] {
|
||||
c2_idx += i;
|
||||
local_cs += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
c1_idx += 1;
|
||||
c2_idx += 1;
|
||||
}
|
||||
}
|
||||
lcss += local_cs;
|
||||
(l1.max(l2) - lcss) + trans
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
let ignored = [
|
||||
"the", "app", "pro", "free", "soft", "software", "suite", "setup", "install",
|
||||
"installer", "uninstaller", "client", "edition", "system", "windows", "corporation",
|
||||
"ltd", "inc", "microsoft", "google", "version", "x64", "x86", "64bit", "32bit",
|
||||
];
|
||||
|
||||
let mut tokens = Vec::new();
|
||||
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);
|
||||
}
|
||||
}
|
||||
tokens
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -1,203 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::{StartupItem, StartupLocation};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
pub struct StartupService;
|
||||
|
||||
impl StartupService {
|
||||
pub fn get_startup_items() -> AppResult<Vec<StartupItem>> {
|
||||
let mut items = Vec::new();
|
||||
|
||||
// 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()) {
|
||||
items.push(StartupItem {
|
||||
id: format!("hkcu_{}", name),
|
||||
name: name.clone(),
|
||||
command: val.to_string(),
|
||||
location: StartupLocation::RegistryCurrentUser,
|
||||
is_enabled: true,
|
||||
publisher: "Kayıt Defteri (Kullanıcı)".to_string(),
|
||||
file_path: val.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
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 & 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()) {
|
||||
items.push(StartupItem {
|
||||
id: format!("hklm_{}", name),
|
||||
name: name.clone(),
|
||||
command: val.to_string(),
|
||||
location: StartupLocation::RegistryLocalMachine,
|
||||
is_enabled: true,
|
||||
publisher: "Kayıt Defteri (Sistem)".to_string(),
|
||||
file_path: val.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
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") {
|
||||
let startup_dir = PathBuf::from(appdata).join("Microsoft\\Windows\\Start Menu\\Programs\\Startup");
|
||||
if startup_dir.exists() {
|
||||
if let Ok(entries) = fs::read_dir(startup_dir) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
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: clean_name,
|
||||
command: path.to_string_lossy().to_string(),
|
||||
location: StartupLocation::UserStartupFolder,
|
||||
is_enabled: !is_disabled,
|
||||
publisher: "Başlangıç Klasörü (Kullanıcı)".to_string(),
|
||||
file_path: path.to_string_lossy().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Common Startup Folder
|
||||
if let Ok(progdata) = std::env::var("ProgramData") {
|
||||
let common_startup = PathBuf::from(progdata).join("Microsoft\\Windows\\Start Menu\\Programs\\Startup");
|
||||
if common_startup.exists() {
|
||||
if let Ok(entries) = fs::read_dir(common_startup) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
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: clean_name,
|
||||
command: path.to_string_lossy().to_string(),
|
||||
location: StartupLocation::CommonStartupFolder,
|
||||
is_enabled: !is_disabled,
|
||||
publisher: "Başlangıç Klasörü (Ortak)".to_string(),
|
||||
file_path: path.to_string_lossy().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
pub fn toggle_startup_item(id: &str, enable: bool) -> AppResult<bool> {
|
||||
let items = Self::get_startup_items()?;
|
||||
let target = match items.iter().find(|i| i.id == id) {
|
||||
Some(t) => t,
|
||||
None => return Err(crate::error::AppError::NotFound("Başlangıç öğesi bulunamadı".to_string())),
|
||||
};
|
||||
|
||||
match target.location {
|
||||
StartupLocation::UserStartupFolder | StartupLocation::CommonStartupFolder => {
|
||||
let current_path = PathBuf::from(&target.file_path);
|
||||
if enable && target.file_path.ends_with(".disabled") {
|
||||
let new_path = target.file_path.trim_end_matches(".disabled");
|
||||
fs::rename(¤t_path, new_path)?;
|
||||
Ok(true)
|
||||
} else if !enable && !target.file_path.ends_with(".disabled") {
|
||||
let new_path = format!("{}.disabled", target.file_path);
|
||||
fs::rename(¤t_path, new_path)?;
|
||||
Ok(true)
|
||||
} else {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
StartupLocation::RegistryCurrentUser => {
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
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::<String, _>(&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) {
|
||||
if let Ok(val) = run_key.get_value::<String, _>(&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 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::<String, _>(&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) {
|
||||
if let Ok(val) = run_key.get_value::<String, _>(&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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,74 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::{ApplicationEntry, DrivePartition, TreemapItem};
|
||||
use sysinfo::Disks;
|
||||
|
||||
pub struct TreemapService;
|
||||
|
||||
impl TreemapService {
|
||||
pub fn get_disk_partitions() -> AppResult<Vec<DrivePartition>> {
|
||||
let disks = Disks::new_with_refreshed_list();
|
||||
let mut partitions = Vec::new();
|
||||
|
||||
for disk in disks.list() {
|
||||
let total = disk.total_space();
|
||||
let free = disk.available_space();
|
||||
let used = total.saturating_sub(free);
|
||||
|
||||
partitions.push(DrivePartition {
|
||||
name: disk.name().to_string_lossy().to_string(),
|
||||
mount_point: disk.mount_point().to_string_lossy().to_string(),
|
||||
total_bytes: total,
|
||||
free_bytes: free,
|
||||
used_bytes: used,
|
||||
file_system: disk.file_system().to_string_lossy().to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(partitions)
|
||||
}
|
||||
|
||||
pub fn generate_apps_treemap(apps: &[ApplicationEntry]) -> AppResult<Vec<TreemapItem>> {
|
||||
let mut items = Vec::new();
|
||||
|
||||
let colors = [
|
||||
"#38bdf8", "#818cf8", "#c084fc", "#f43f5e",
|
||||
"#fb923c", "#facc15", "#4ade80", "#2dd4bf",
|
||||
];
|
||||
|
||||
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.into_iter().enumerate() {
|
||||
|
||||
let size_bytes = app.estimated_size_kb * 1024;
|
||||
let color = colors[idx % colors.len()];
|
||||
|
||||
items.push(TreemapItem {
|
||||
id: app.id.clone(),
|
||||
name: app.display_name.clone(),
|
||||
value: size_bytes,
|
||||
formatted_size: Self::format_size(size_bytes),
|
||||
color: color.to_string(),
|
||||
children: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
fn format_size(bytes: u64) -> String {
|
||||
const KB: u64 = 1024;
|
||||
const MB: u64 = KB * 1024;
|
||||
const GB: u64 = MB * 1024;
|
||||
|
||||
if bytes >= GB {
|
||||
format!("{:.2} GB", bytes as f64 / GB as f64)
|
||||
} else if bytes >= MB {
|
||||
format!("{:.2} MB", bytes as f64 / MB as f64)
|
||||
} else if bytes >= KB {
|
||||
format!("{:.2} KB", bytes as f64 / KB as f64)
|
||||
} else {
|
||||
format!("{} B", bytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,183 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::{SystemTweak, TweakCategory};
|
||||
use winreg::enums::*;
|
||||
use winreg::{RegKey, HKEY};
|
||||
|
||||
pub struct TweaksService;
|
||||
|
||||
impl TweaksService {
|
||||
pub fn get_available_tweaks() -> AppResult<Vec<SystemTweak>> {
|
||||
let mut tweaks = Vec::new();
|
||||
|
||||
// 1. Telemetry
|
||||
let telemetry_applied = Self::check_dword(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\DataCollection",
|
||||
"AllowTelemetry",
|
||||
0,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_telemetry".to_string(),
|
||||
title: "Windows Telemetri ve Tanılama Verilerini Kapat".to_string(),
|
||||
description: "Microsoft'a arka planda sistem ve kullanım verisi gönderilmesini engeller.".to_string(),
|
||||
category: TweakCategory::Privacy,
|
||||
is_applied: telemetry_applied,
|
||||
requires_restart: false,
|
||||
});
|
||||
|
||||
// 2. Cortana
|
||||
let cortana_applied = Self::check_dword(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\Windows Search",
|
||||
"AllowCortana",
|
||||
0,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_cortana".to_string(),
|
||||
title: "Cortana Sesli Asistanı Devre Dışı Bırak".to_string(),
|
||||
description: "Cortana arka plan süreçlerini ve ses dinleme servislerini kapatır.".to_string(),
|
||||
category: TweakCategory::Privacy,
|
||||
is_applied: cortana_applied,
|
||||
requires_restart: true,
|
||||
});
|
||||
|
||||
// 3. Bing Search
|
||||
let bing_applied = Self::check_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer",
|
||||
"DisableSearchBoxSuggestions",
|
||||
1,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_bing_search".to_string(),
|
||||
title: "Başlat Menüsünde Bing Web Aramalarını Kapat".to_string(),
|
||||
description: "Başlat menüsünde arama yaparken web sonuçları yerine yalnızca yerel dosyaları aratır.".to_string(),
|
||||
category: TweakCategory::Performance,
|
||||
is_applied: bing_applied,
|
||||
requires_restart: false,
|
||||
});
|
||||
|
||||
// 4. Game DVR
|
||||
let gamedvr_applied = Self::check_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"System\\GameConfigStore",
|
||||
"GameDVR_Enabled",
|
||||
0,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_gamedvr".to_string(),
|
||||
title: "Xbox Game DVR Arka Plan Kaydını Kapat".to_string(),
|
||||
description: "Oyun oynarken FPS düşüşlerini önlemek için sürekli ekran kaydetme servisini kapatır.".to_string(),
|
||||
category: TweakCategory::Gaming,
|
||||
is_applied: gamedvr_applied,
|
||||
requires_restart: false,
|
||||
});
|
||||
|
||||
// 5. Advertising ID
|
||||
let ad_applied = Self::check_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"Software\\Microsoft\\Windows\\CurrentVersion\\AdvertisingInfo",
|
||||
"Enabled",
|
||||
0,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_adid".to_string(),
|
||||
title: "Kişiselleştirilmiş Reklam Kimliğini Kapat".to_string(),
|
||||
description: "Uygulamaların kullanıcı alışkanlıklarına göre reklam kimliği oluşturmasını engeller.".to_string(),
|
||||
category: TweakCategory::Privacy,
|
||||
is_applied: ad_applied,
|
||||
requires_restart: false,
|
||||
});
|
||||
|
||||
// 6. Windows 11 Widgets
|
||||
let widgets_applied = Self::check_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced",
|
||||
"TaskbarDa",
|
||||
0,
|
||||
);
|
||||
tweaks.push(SystemTweak {
|
||||
id: "tweak_widgets".to_string(),
|
||||
title: "Windows 11 Haberler ve Araçlar (Widgets) Kapat".to_string(),
|
||||
description: "Görev çubuğundaki araçlar panelini ve gereksiz bellek tüketen webview bileşenini kapatır.".to_string(),
|
||||
category: TweakCategory::Performance,
|
||||
is_applied: widgets_applied,
|
||||
requires_restart: false,
|
||||
});
|
||||
|
||||
Ok(tweaks)
|
||||
}
|
||||
|
||||
pub fn apply_tweak(tweak_id: &str, enable: bool) -> AppResult<bool> {
|
||||
match tweak_id {
|
||||
"tweak_telemetry" => {
|
||||
Self::set_dword(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\DataCollection",
|
||||
"AllowTelemetry",
|
||||
if enable { 0 } else { 3 },
|
||||
)
|
||||
}
|
||||
"tweak_cortana" => {
|
||||
Self::set_dword(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\Windows Search",
|
||||
"AllowCortana",
|
||||
if enable { 0 } else { 1 },
|
||||
)
|
||||
}
|
||||
"tweak_bing_search" => {
|
||||
Self::set_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"SOFTWARE\\Policies\\Microsoft\\Windows\\Explorer",
|
||||
"DisableSearchBoxSuggestions",
|
||||
if enable { 1 } else { 0 },
|
||||
)
|
||||
}
|
||||
"tweak_gamedvr" => {
|
||||
Self::set_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"System\\GameConfigStore",
|
||||
"GameDVR_Enabled",
|
||||
if enable { 0 } else { 1 },
|
||||
)
|
||||
}
|
||||
"tweak_adid" => {
|
||||
Self::set_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"Software\\Microsoft\\Windows\\CurrentVersion\\AdvertisingInfo",
|
||||
"Enabled",
|
||||
if enable { 0 } else { 1 },
|
||||
)
|
||||
}
|
||||
"tweak_widgets" => {
|
||||
Self::set_dword(
|
||||
HKEY_CURRENT_USER,
|
||||
"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced",
|
||||
"TaskbarDa",
|
||||
if enable { 0 } else { 1 },
|
||||
)
|
||||
}
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_dword(hive: HKEY, subkey: &str, name: &str, expected: u32) -> bool {
|
||||
let root = RegKey::predef(hive);
|
||||
if let Ok(key) = root.open_subkey_with_flags(subkey, KEY_READ) {
|
||||
if let Ok(val) = key.get_value::<u32, _>(name) {
|
||||
return val == expected;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn set_dword(hive: HKEY, subkey: &str, name: &str, value: u32) -> AppResult<bool> {
|
||||
let root = RegKey::predef(hive);
|
||||
let (key, _) = root.create_subkey(subkey)
|
||||
.map_err(|e| crate::error::AppError::Registry(format!("Ayar anahtarı açılamadı: {}", e)))?;
|
||||
key.set_value(name, &value)
|
||||
.map_err(|e| crate::error::AppError::Registry(format!("Ayar değeri yazılamadı: {}", e)))?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,112 +0,0 @@
|
|||
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 {
|
||||
pub fn uninstall(app: &ApplicationEntry, quiet: bool) -> AppResult<bool> {
|
||||
let cmd_string = if quiet && !app.quiet_uninstall_string.is_empty() {
|
||||
&app.quiet_uninstall_string
|
||||
} else {
|
||||
&app.uninstall_string
|
||||
};
|
||||
|
||||
if cmd_string.trim().is_empty() {
|
||||
return Err(AppError::NotFound("Kaldırma komutu (UninstallString) bulunamadı".to_string()));
|
||||
}
|
||||
|
||||
match app.uninstaller_kind {
|
||||
UninstallerKind::Steam => {
|
||||
// Steam URI protokolü çağrılır
|
||||
let _ = Command::new("cmd")
|
||||
.args(["/c", "start", "", cmd_string])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.spawn()?;
|
||||
Ok(true)
|
||||
}
|
||||
UninstallerKind::Store => {
|
||||
// Komut enjeksiyonunu önlemek için PackageFullName karakterlerini sıkı doğrula
|
||||
let pkg_name = cmd_string
|
||||
.trim()
|
||||
.strip_prefix("powershell -NoProfile -Command \"Remove-AppxPackage -Package ")
|
||||
.and_then(|s| s.strip_suffix('"'))
|
||||
.unwrap_or(cmd_string);
|
||||
|
||||
let is_valid = !pkg_name.is_empty()
|
||||
&& pkg_name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.');
|
||||
|
||||
if !is_valid {
|
||||
return Err(AppError::Security(format!("Geçersiz veya güvenilmeyen Store paket adı: {}", pkg_name)));
|
||||
}
|
||||
|
||||
let safe_cmd = format!("Remove-AppxPackage -Package {}", pkg_name);
|
||||
let output = Command::new("powershell")
|
||||
.args(["-NoProfile", "-Command", &safe_cmd])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()?;
|
||||
if output.status.success() {
|
||||
Ok(true)
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&output.stderr);
|
||||
Err(AppError::Execution(format!("Store uygulaması kaldırılamadı: {}", err)))
|
||||
}
|
||||
}
|
||||
UninstallerKind::Msi => {
|
||||
let mut command_to_run = cmd_string.to_string();
|
||||
if quiet && !command_to_run.contains("/qn") && !command_to_run.contains("/quiet") {
|
||||
command_to_run.push_str(" /qn /norestart");
|
||||
}
|
||||
Self::run_shell_wait(&command_to_run, Duration::from_secs(300))
|
||||
}
|
||||
UninstallerKind::InnoSetup => {
|
||||
let mut command_to_run = cmd_string.to_string();
|
||||
if quiet && !command_to_run.to_lowercase().contains("/verysilent") {
|
||||
command_to_run.push_str(" /VERYSILENT /SUPPRESSMSGBOXES /NORESTART");
|
||||
}
|
||||
Self::run_shell_wait(&command_to_run, Duration::from_secs(300))
|
||||
}
|
||||
UninstallerKind::Nsis => {
|
||||
let mut command_to_run = cmd_string.to_string();
|
||||
if quiet && !command_to_run.contains("/S") {
|
||||
command_to_run.push_str(" /S");
|
||||
}
|
||||
Self::run_shell_wait(&command_to_run, Duration::from_secs(300))
|
||||
}
|
||||
_ => {
|
||||
Self::run_shell_wait(cmd_string, Duration::from_secs(300))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_shell_wait(raw_cmd: &str, timeout: Duration) -> AppResult<bool> {
|
||||
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)))?;
|
||||
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
return Ok(status.success() || status.code() == Some(3010)); // 3010 = ERROR_SUCCESS_REBOOT_REQUIRED
|
||||
}
|
||||
Ok(None) => {
|
||||
if start.elapsed() > timeout {
|
||||
let _ = child.kill();
|
||||
return Err(AppError::Execution("Kaldırma işlemi zaman aşımına uğradı (5 dakika).".to_string()));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(AppError::Execution(format!("Süreç beklenirken hata oluştu: {}", e)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
use crate::error::{AppError, AppResult};
|
||||
use crate::models::UpdateCheckResult;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::process::Command;
|
||||
|
||||
pub struct UpdateService;
|
||||
|
||||
const CURRENT_VERSION: &str = "3.0.2";
|
||||
const UPDATE_URL: &str = "https://ttmadethat.shop/ldapps/version.json";
|
||||
|
||||
impl UpdateService {
|
||||
pub async fn check_for_updates() -> AppResult<UpdateCheckResult> {
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.build()
|
||||
.map_err(|e| AppError::Network(format!("HTTP istemcisi oluşturulamadı: {}", e)))?;
|
||||
|
||||
let res = client.get(UPDATE_URL).send().await
|
||||
.map_err(|e| AppError::Network(format!("Güncelleme sunucusuna erişilemedi: {}", e)))?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
return Err(AppError::Network(format!("Sunucu yanıt kodu: {}", res.status())));
|
||||
}
|
||||
|
||||
let json_val: serde_json::Value = res.json().await
|
||||
.map_err(|e| AppError::Network(format!("Güncelleme verisi çözümlenemedi: {}", e)))?;
|
||||
|
||||
let remote_version = json_val["version"].as_str().unwrap_or("0.0.0");
|
||||
let download_url = json_val["downloadUrl"].as_str().unwrap_or_default();
|
||||
let release_notes = json_val["releaseNotes"].as_str().unwrap_or_default();
|
||||
let sha256 = json_val["sha256"].as_str().unwrap_or_default();
|
||||
|
||||
let has_update = Self::is_version_newer(CURRENT_VERSION, remote_version);
|
||||
|
||||
Ok(UpdateCheckResult {
|
||||
has_update,
|
||||
current_version: CURRENT_VERSION.to_string(),
|
||||
latest_version: remote_version.to_string(),
|
||||
download_url: download_url.to_string(),
|
||||
release_notes: release_notes.to_string(),
|
||||
sha256: sha256.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn download_and_install_update(download_url: &str, expected_sha256: &str) -> AppResult<bool> {
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let update_installer_path = temp_dir.join("LD-Uninstaller-Update.exe");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let res = client.get(download_url).send().await
|
||||
.map_err(|e| AppError::Network(format!("Güncelleme dosyası indirilemedi: {}", e)))?;
|
||||
|
||||
let bytes = res.bytes().await
|
||||
.map_err(|e| AppError::Network(format!("İndirme akışı tamamlanamadı: {}", e)))?;
|
||||
|
||||
// SHA256 Doğrulaması
|
||||
if !expected_sha256.is_empty() {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(&bytes);
|
||||
let calculated_hash = hex::encode(hasher.finalize());
|
||||
|
||||
if !calculated_hash.eq_ignore_ascii_case(expected_sha256) {
|
||||
return Err(AppError::Validation(format!(
|
||||
"İndirilen güncelleme dosyasının SHA256 sağlama değeri uyuşmuyor! Beklenen: {}, Hesaplanan: {}",
|
||||
expected_sha256, calculated_hash
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let mut file = File::create(&update_installer_path)?;
|
||||
file.write_all(&bytes)?;
|
||||
|
||||
// Kurulum dosyasını /SILENT /CLOSEAPPLICATIONS ile başlat
|
||||
Command::new(&update_installer_path)
|
||||
.args(["/SILENT", "/CLOSEAPPLICATIONS"])
|
||||
.spawn()
|
||||
.map_err(|e| AppError::Execution(format!("Güncelleyici başlatılamadı: {}", e)))?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn is_version_newer(current: &str, remote: &str) -> bool {
|
||||
let c_parts: Vec<u32> = current.split('.').filter_map(|x| x.parse().ok()).collect();
|
||||
let r_parts: Vec<u32> = remote.split('.').filter_map(|x| x.parse().ok()).collect();
|
||||
|
||||
for i in 0..c_parts.len().max(r_parts.len()) {
|
||||
let c = c_parts.get(i).copied().unwrap_or(0);
|
||||
let r = r_parts.get(i).copied().unwrap_or(0);
|
||||
if r > c {
|
||||
return true;
|
||||
} else if r < c {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
use crate::error::AppResult;
|
||||
use crate::models::ApplicationEntry;
|
||||
use crate::services::logger::{log_error, log_info, log_warn, AppLogger};
|
||||
use chrono::Local;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::RwLock;
|
||||
use tokio::sync::RwLock as AsyncRwLock;
|
||||
|
||||
pub struct AppState {
|
||||
pub exclusions: RwLock<Vec<String>>,
|
||||
pub cached_apps: AsyncRwLock<Vec<ApplicationEntry>>,
|
||||
pub config_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new() -> Self {
|
||||
let local_appdata = std::env::var("LOCALAPPDATA")
|
||||
.unwrap_or_else(|_| "C:\\Users\\Default\\AppData\\Local".to_string());
|
||||
let config_dir = PathBuf::from(local_appdata).join("LDUninstaller");
|
||||
|
||||
let _ = fs::create_dir_all(&config_dir);
|
||||
let _ = fs::create_dir_all(config_dir.join("Backups"));
|
||||
let _ = fs::create_dir_all(config_dir.join("Logs"));
|
||||
|
||||
// Günlükleyiciyi (Logger) başlat
|
||||
AppLogger::init(&config_dir);
|
||||
log_info("=== LD Uninstaller v3.0.2 Başlatıldı ===");
|
||||
|
||||
// Kendini İyileştiren Yapılandırma Yöneticisi (Self-Healing Config)
|
||||
let exclusions_file = config_dir.join("exclusions.json");
|
||||
let exclusions = if exclusions_file.exists() {
|
||||
match fs::read_to_string(&exclusions_file) {
|
||||
Ok(content) => match serde_json::from_str::<Vec<String>>(&content) {
|
||||
Ok(list) => {
|
||||
log_info(&format!("{} adet kullanıcı istisnası başarıyla yüklendi.", list.len()));
|
||||
list
|
||||
}
|
||||
Err(e) => {
|
||||
let timestamp = Local::now().format("%Y%m%d_%H%M%S");
|
||||
let backup_bad = config_dir.join(format!("exclusions.json.bad_{}", timestamp));
|
||||
let _ = fs::copy(&exclusions_file, &backup_bad);
|
||||
log_warn(&format!(
|
||||
"Bozuk exclusions.json tespit edildi (Hata: {}). '{}' olarak yedeklendi ve temiz liste oluşturuldu.",
|
||||
e, backup_bad.display()
|
||||
));
|
||||
Vec::new()
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log_error(&format!("exclusions.json okunamadı: {}", e));
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
Self {
|
||||
exclusions: RwLock::new(exclusions),
|
||||
cached_apps: AsyncRwLock::new(Vec::new()),
|
||||
config_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save_exclusions(&self) -> AppResult<()> {
|
||||
let exclusions_file = self.config_dir.join("exclusions.json");
|
||||
let list = match self.exclusions.read() {
|
||||
Ok(guard) => guard.clone(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
let json = serde_json::to_string_pretty(&list)?;
|
||||
fs::write(exclusions_file, json)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_exclusion(&self, path_or_key: String) -> AppResult<()> {
|
||||
let normalized = path_or_key.trim().to_lowercase();
|
||||
if normalized.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if let Ok(mut guard) = self.exclusions.write() {
|
||||
if !guard.iter().any(|item| item.to_lowercase() == normalized) {
|
||||
guard.push(path_or_key);
|
||||
}
|
||||
}
|
||||
self.save_exclusions()
|
||||
}
|
||||
|
||||
pub fn remove_exclusion(&self, path_or_key: &str) -> AppResult<()> {
|
||||
let normalized = path_or_key.trim().to_lowercase();
|
||||
if let Ok(mut guard) = self.exclusions.write() {
|
||||
guard.retain(|item| item.to_lowercase() != normalized);
|
||||
}
|
||||
self.save_exclusions()
|
||||
}
|
||||
|
||||
pub fn is_excluded(&self, path_or_key: &str) -> bool {
|
||||
let target = path_or_key.trim().to_lowercase();
|
||||
if let Ok(guard) = self.exclusions.read() {
|
||||
guard.iter().any(|ex| {
|
||||
let ex_lower = ex.trim().to_lowercase();
|
||||
target == ex_lower || target.starts_with(&format!("{}\\", ex_lower))
|
||||
})
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AppState {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "LD Uninstaller",
|
||||
"version": "3.0.2",
|
||||
"identifier": "com.lduninstaller.app",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"label": "main",
|
||||
"title": "LD Uninstaller",
|
||||
"decorations": false,
|
||||
"width": 1200,
|
||||
"height": 800,
|
||||
"minWidth": 960,
|
||||
"minHeight": 640,
|
||||
"center": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["nsis"],
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDYxQzZFNzFEMTNFRjBCMEEKUldRS0MrOFRIZWZHWVYrOWZuRnhXbXZWMkFxNk41TGNyYmE3QWt5bDNvclkyRURZUkpCYTJCbDEK",
|
||||
"endpoints": [
|
||||
"https://ttmadethat.shop/updates/ld-uninstaller/latest.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
use ld_uninstaller_lib::models::ConfidenceLevel;
|
||||
use ld_uninstaller_lib::services::{SafetyBlacklist, Sift4};
|
||||
use ld_uninstaller_lib::state::AppState;
|
||||
|
||||
#[test]
|
||||
fn test_safety_blacklist_critical_system_paths() {
|
||||
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Windows"));
|
||||
assert!(SafetyBlacklist::is_dangerous_file_path("C:\\Windows\\System32"));
|
||||
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"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_safety_blacklist_safe_application_paths() {
|
||||
assert!(!SafetyBlacklist::is_dangerous_file_path("C:\\Program Files\\Notepad++"));
|
||||
assert!(!SafetyBlacklist::is_dangerous_file_path("C:\\Program Files (x86)\\Steam\\steamapps\\common\\Counter-Strike"));
|
||||
assert!(!SafetyBlacklist::is_dangerous_file_path("C:\\Users\\User\\AppData\\Local\\Discord"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_safety_blacklist_registry() {
|
||||
assert!(SafetyBlacklist::is_dangerous_registry_path("HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"));
|
||||
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"));
|
||||
assert!(!SafetyBlacklist::is_dangerous_registry_path("HKLM\\Software\\WOW6432Node\\VideoLAN\\VLC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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]
|
||||
fn test_sift4_tokenize() {
|
||||
let tokens = Sift4::tokenize("Google Chrome Setup Pro x64");
|
||||
assert_eq!(tokens, vec!["chrome"]);
|
||||
|
||||
let vlc_tokens = Sift4::tokenize("VideoLAN VLC Media Player");
|
||||
assert!(vlc_tokens.contains(&"videolan".to_string()));
|
||||
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]
|
||||
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]
|
||||
fn test_app_state_exclusions() {
|
||||
let state = AppState::new();
|
||||
let safe_folder = "C:\\Program Files\\MySpecialTool";
|
||||
|
||||
assert!(!state.is_excluded(safe_folder));
|
||||
|
||||
let _ = state.add_exclusion(safe_folder.to_string());
|
||||
assert!(state.is_excluded(safe_folder));
|
||||
assert!(state.is_excluded("C:\\Program Files\\MySpecialTool\\subfolder"));
|
||||
|
||||
let _ = state.remove_exclusion(safe_folder);
|
||||
assert!(!state.is_excluded(safe_folder));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_confidence_level_ordering() {
|
||||
assert!(ConfidenceLevel::High > ConfidenceLevel::Medium);
|
||||
assert!(ConfidenceLevel::Medium > ConfidenceLevel::Low);
|
||||
assert!(ConfidenceLevel::Low > ConfidenceLevel::Bad);
|
||||
}
|
||||
29
src/App.css
|
|
@ -1,29 +0,0 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
background-color: #0d1117;
|
||||
color: #f1f5f9;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom modern sleek scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border-radius: 4px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.24);
|
||||
}
|
||||
79
src/App.tsx
|
|
@ -1,79 +0,0 @@
|
|||
import React, { useEffect } from 'react';
|
||||
import { Titlebar } from './components/Titlebar';
|
||||
import { Sidebar } from './components/Sidebar';
|
||||
import { ToastContainer } from './components/ToastContainer';
|
||||
import { LeftoversModal } from './components/LeftoversModal';
|
||||
import { UpdateModal } from './components/UpdateModal';
|
||||
import { UpdateBanner } from './components/UpdateBanner';
|
||||
import { AppsView } from './pages/AppsView';
|
||||
import { TreemapView } from './pages/TreemapView';
|
||||
import { StartupView } from './pages/StartupView';
|
||||
import { TweaksView } from './pages/TweaksView';
|
||||
import { ShredderView } from './pages/ShredderView';
|
||||
import { BackupsView } from './pages/BackupsView';
|
||||
import { SettingsView } from './pages/SettingsView';
|
||||
import { useAppStore } from './store/useAppStore';
|
||||
|
||||
export const App: React.FC = () => {
|
||||
const { currentTab, loadApps, loadExclusions, checkForUpdatesOTA, checkElevation } = useAppStore();
|
||||
|
||||
useEffect(() => {
|
||||
// Uygulama açılışında arka plan yüklemeleri
|
||||
checkElevation();
|
||||
loadApps();
|
||||
loadExclusions();
|
||||
// Kullanıcı isteği doğrultusunda açılışta güncellemeleri otomatik ve sessizce denetle
|
||||
checkForUpdatesOTA(false);
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'F5') {
|
||||
e.preventDefault();
|
||||
loadApps();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, []);
|
||||
|
||||
const renderActiveView = () => {
|
||||
switch (currentTab) {
|
||||
case 'apps':
|
||||
return <AppsView />;
|
||||
case 'treemap':
|
||||
return <TreemapView />;
|
||||
case 'startup':
|
||||
return <StartupView />;
|
||||
case 'tweaks':
|
||||
return <TweaksView />;
|
||||
case 'shredder':
|
||||
return <ShredderView />;
|
||||
case 'backups':
|
||||
return <BackupsView />;
|
||||
case 'settings':
|
||||
return <SettingsView />;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen w-screen bg-ld-bg text-slate-100 select-none overflow-hidden font-sans">
|
||||
{/* Özel Pencere Başlık Çubuğu & OTA Bildirim Bannerı */}
|
||||
<Titlebar />
|
||||
<UpdateBanner />
|
||||
|
||||
{/* Ana Arayüz */}
|
||||
<div className="flex flex-1 h-full w-full overflow-hidden">
|
||||
<Sidebar />
|
||||
<main className="flex-1 h-full overflow-hidden flex flex-col">
|
||||
{renderActiveView()}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
{/* Modallar ve Bildirimler */}
|
||||
<LeftoversModal />
|
||||
<UpdateModal />
|
||||
<ToastContainer />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
|
|
@ -1,12 +1,9 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.Management;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FlaUI.Core.AutomationElements;
|
||||
|
|
@ -38,9 +35,6 @@ namespace LDUninstaller.Automatizer
|
|||
"anket", "survey", "homepage", "launch", "çalıştır"
|
||||
};
|
||||
|
||||
private static DateTime _lastActivity = DateTime.Now;
|
||||
private static bool _exitRequested = false;
|
||||
|
||||
[STAThread]
|
||||
static void Main(string[] args)
|
||||
{
|
||||
|
|
@ -62,26 +56,11 @@ namespace LDUninstaller.Automatizer
|
|||
using var automation = new UIA3Automation();
|
||||
Console.WriteLine("Daemon aktif. Named Pipe '\\\\.\\pipe\\LDUninstallerDaemon' dinleniyor...");
|
||||
|
||||
while (!_exitRequested)
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var pids = MonitoredProcesses.ToArray();
|
||||
if (pids.Length > 0)
|
||||
{
|
||||
_lastActivity = DateTime.Now;
|
||||
}
|
||||
else
|
||||
{
|
||||
// P12: If idle for 2 minutes and no active tasks, exit to free RAM
|
||||
if ((DateTime.Now - _lastActivity).TotalMinutes > 2)
|
||||
{
|
||||
Console.WriteLine("[Daemon] Boşta kalma süresi aşıldı, otomatik sonlandırılıyor.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var kvp in pids)
|
||||
foreach (var kvp in MonitoredProcesses.ToArray())
|
||||
{
|
||||
int pid = kvp.Key;
|
||||
DateTime startTime = kvp.Value;
|
||||
|
|
@ -110,24 +89,8 @@ namespace LDUninstaller.Automatizer
|
|||
continue;
|
||||
}
|
||||
|
||||
// Automate UI windows for this PID and its children (B19)
|
||||
var allPids = new List<int> { proc.Id };
|
||||
try
|
||||
{
|
||||
allPids.AddRange(GetChildProcessIds(proc.Id));
|
||||
}
|
||||
catch { }
|
||||
|
||||
foreach (int targetPid in allPids)
|
||||
{
|
||||
try
|
||||
{
|
||||
var targetProc = Process.GetProcessById(targetPid);
|
||||
if (!targetProc.HasExited)
|
||||
AutomateProcessWindows(automation, targetProc);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
// Automate UI windows for this PID
|
||||
AutomateProcessWindows(automation, proc);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
|
|
@ -145,25 +108,9 @@ namespace LDUninstaller.Automatizer
|
|||
}
|
||||
}
|
||||
|
||||
private static List<int> GetChildProcessIds(int parentId)
|
||||
{
|
||||
var results = new List<int>();
|
||||
try
|
||||
{
|
||||
using var searcher = new ManagementObjectSearcher(
|
||||
$"SELECT ProcessId FROM Win32_Process WHERE ParentProcessId={parentId}");
|
||||
foreach (var mo in searcher.Get())
|
||||
{
|
||||
results.Add(Convert.ToInt32(mo["ProcessId"]));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return results;
|
||||
}
|
||||
|
||||
private static void StartPipeServer(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && !_exitRequested)
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
|
@ -172,22 +119,13 @@ namespace LDUninstaller.Automatizer
|
|||
using var reader = new StreamReader(server);
|
||||
string? line = reader.ReadLine();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
if (line.StartsWith("ATTACH:", StringComparison.OrdinalIgnoreCase))
|
||||
if (!string.IsNullOrWhiteSpace(line) && line.StartsWith("ATTACH:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string pidStr = line["ATTACH:".Length..].Trim();
|
||||
if (int.TryParse(pidStr, out int pid))
|
||||
{
|
||||
Console.WriteLine($"[IPC] Takip edilecek PID alındı: {pid}");
|
||||
MonitoredProcesses.TryAdd(pid, DateTime.Now);
|
||||
_lastActivity = DateTime.Now;
|
||||
}
|
||||
}
|
||||
else if (line.Equals("SHUTDOWN", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_exitRequested = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -264,12 +202,12 @@ namespace LDUninstaller.Automatizer
|
|||
}
|
||||
}
|
||||
|
||||
// Check standard buttons (B19: strict word/exact match)
|
||||
// Check standard buttons
|
||||
var buttons = win.FindAllDescendants(cf => cf.ByControlType(ControlType.Button));
|
||||
foreach (var btn in buttons)
|
||||
{
|
||||
string btnId = btn.AutomationId ?? "";
|
||||
string btnText = btn.Name?.Trim() ?? "";
|
||||
string btnText = btn.Name?.Trim().ToLowerInvariant() ?? "";
|
||||
|
||||
// Prioritize NSIS standard Next button ID 1 or Close/Finish
|
||||
if (btnId == "1" || IsGoodButton(btnText))
|
||||
|
|
@ -291,25 +229,13 @@ namespace LDUninstaller.Automatizer
|
|||
private static bool IsGoodButton(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string clean = text.Trim().ToLowerInvariant();
|
||||
|
||||
foreach (var g in GoodButtonTexts)
|
||||
{
|
||||
if (clean.Equals(g, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
|
||||
// Word boundary check for short words to avoid "book", "look", "token", etc.
|
||||
if (Regex.IsMatch(clean, $@"\b{Regex.Escape(g)}\b", RegexOptions.IgnoreCase))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return GoodButtonTexts.Any(g => text.Equals(g, StringComparison.OrdinalIgnoreCase) || text.Contains(g, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static bool IsBadButton(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string clean = text.Trim().ToLowerInvariant();
|
||||
return BadButtonTexts.Any(b => clean.Contains(b, StringComparison.OrdinalIgnoreCase));
|
||||
return BadButtonTexts.Any(b => text.Contains(b, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -7,7 +7,6 @@
|
|||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<RootNamespace>LDUninstaller.CLI</RootNamespace>
|
||||
<AssemblyName>LDUninstaller.CLI</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -247,18 +247,6 @@ Parametreler:
|
|||
}
|
||||
|
||||
if (!unattended)
|
||||
{
|
||||
if (Console.IsInputRedirected)
|
||||
{
|
||||
Console.Write("\nDevam etmek istiyor musunuz? [E/H]: ");
|
||||
string? line = Console.ReadLine()?.Trim();
|
||||
if (string.IsNullOrEmpty(line) || (!line.StartsWith("e", StringComparison.OrdinalIgnoreCase) && !line.StartsWith("y", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Console.WriteLine("İşlem iptal edildi.");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.Write("\nDevam etmek istiyor musunuz? [E/H]: ");
|
||||
var key = Console.ReadKey();
|
||||
|
|
@ -269,23 +257,17 @@ Parametreler:
|
|||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var bulkTask = new BulkUninstallTask(appsToUninstall, quiet);
|
||||
bulkTask.OnLog += msg => Console.WriteLine($"[Toplu Görev] {msg}");
|
||||
await bulkTask.ExecuteAsync();
|
||||
|
||||
var uninstalledApps = bulkTask.Items
|
||||
.Where(i => i.IsEffectivelyUninstalled)
|
||||
.Select(i => i.Entry)
|
||||
.ToList();
|
||||
|
||||
// Automatic Junk Clean (only for effectively uninstalled apps)
|
||||
if (uninstalledApps.Count > 0 && !string.IsNullOrWhiteSpace(junkLevelStr) && Enum.TryParse<ConfidenceLevel>(junkLevelStr, true, out var minConfidence))
|
||||
// Automatic Junk Clean
|
||||
if (!string.IsNullOrWhiteSpace(junkLevelStr) && Enum.TryParse<ConfidenceLevel>(junkLevelStr, true, out var minConfidence))
|
||||
{
|
||||
Console.WriteLine($"\nArtık temizleme motoru çalıştırılıyor (Asgari Güven: {minConfidence})...");
|
||||
var junkManager = new JunkManager();
|
||||
foreach (var a in uninstalledApps)
|
||||
foreach (var a in appsToUninstall)
|
||||
{
|
||||
var junks = junkManager.ScanJunk(a);
|
||||
var cleanable = junks.Where(j => j.Confidence >= minConfidence).ToList();
|
||||
|
|
@ -71,17 +71,6 @@ namespace LDUninstaller.Core.Algorithms
|
|||
string clean1 = NormalizeName(s1);
|
||||
string clean2 = NormalizeName(s2);
|
||||
|
||||
return GetSimilarityNormalized(clean1, clean2, maxOffset);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// OPTIMIZATION (P2): Önceden normalize edilmiş metinler için regex çağrılarını atlayan ultra hızlı benzerlik fonksiyonu.
|
||||
/// </summary>
|
||||
public static double GetSimilarityNormalized(string clean1, string clean2, int maxOffset = 5)
|
||||
{
|
||||
if (string.IsNullOrEmpty(clean1) && string.IsNullOrEmpty(clean2)) return 1.0;
|
||||
if (string.IsNullOrEmpty(clean1) || string.IsNullOrEmpty(clean2)) return 0.0;
|
||||
|
||||
if (clean1.Equals(clean2, StringComparison.OrdinalIgnoreCase))
|
||||
return 1.0;
|
||||
|
||||
401
src/LDUninstaller.Core/Bulk/BulkUninstallTask.cs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Pipes;
|
||||
using System.Linq;
|
||||
using System.ServiceProcess;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using LDUninstaller.Core.Algorithms;
|
||||
using LDUninstaller.Core.Models;
|
||||
using LDUninstaller.Core.Native;
|
||||
|
||||
namespace LDUninstaller.Core.Bulk
|
||||
{
|
||||
public enum BulkStatus
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Succeeded,
|
||||
Failed,
|
||||
Skipped,
|
||||
Cancelled
|
||||
}
|
||||
|
||||
public class BulkUninstallEntry
|
||||
{
|
||||
public ApplicationUninstallerEntry Entry { get; }
|
||||
public BulkStatus Status { get; set; } = BulkStatus.Queued;
|
||||
public string StatusMessage { get; set; } = "Kuyrukta";
|
||||
public bool PreferQuiet { get; set; } = true;
|
||||
public int ExitCode { get; set; } = -1;
|
||||
|
||||
public BulkUninstallEntry(ApplicationUninstallerEntry entry, bool preferQuiet = true)
|
||||
{
|
||||
Entry = entry;
|
||||
PreferQuiet = preferQuiet;
|
||||
}
|
||||
}
|
||||
|
||||
public class BulkUninstallTask
|
||||
{
|
||||
public List<BulkUninstallEntry> Items { get; }
|
||||
public int MaxConcurrentQuiet { get; set; } = 2;
|
||||
public bool CreateRestorePoint { get; set; } = true;
|
||||
public bool EnableAutomatizer { get; set; } = true;
|
||||
|
||||
public event Action<BulkUninstallEntry>? OnItemStarted;
|
||||
public event Action<BulkUninstallEntry>? OnItemCompleted;
|
||||
public event Action<string>? OnLog;
|
||||
|
||||
private readonly SemaphoreSlim _msiLock = new(1, 1);
|
||||
private readonly SemaphoreSlim _loudLimitLock = new(1, 1);
|
||||
private readonly object _stateLock = new();
|
||||
private readonly HashSet<string> _activePublishers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly HashSet<string> _activeDirectories = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public BulkUninstallTask(IEnumerable<ApplicationUninstallerEntry> entries, bool preferQuiet = true)
|
||||
{
|
||||
Items = entries.Select(e => new BulkUninstallEntry(e, preferQuiet)).ToList();
|
||||
}
|
||||
|
||||
public async Task ExecuteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (CreateRestorePoint)
|
||||
{
|
||||
OnLog?.Invoke("Sistem Geri Yükleme Noktası oluşturuluyor...");
|
||||
await Task.Run(() => Win32.CreateRestorePoint("LD Uninstaller Bulk Pre-Restore Point", out _));
|
||||
}
|
||||
|
||||
var throttler = new SemaphoreSlim(MaxConcurrentQuiet, MaxConcurrentQuiet);
|
||||
var runningTasks = new List<Task>();
|
||||
|
||||
foreach (var item in Items)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
item.Status = BulkStatus.Cancelled;
|
||||
item.StatusMessage = "İptal edildi";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check serialized types
|
||||
bool isSerialized = IsSerializedType(item.Entry.UninstallerKind);
|
||||
|
||||
if (isSerialized)
|
||||
{
|
||||
// Wait for all currently running background tasks to finish
|
||||
await Task.WhenAll(runningTasks);
|
||||
runningTasks.Clear();
|
||||
|
||||
await RunSingleItemAsync(item, cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await throttler.WaitAsync(cancellationToken);
|
||||
|
||||
var t = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await RunSingleItemAsync(item, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
throttler.Release();
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
runningTasks.Add(t);
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(runningTasks);
|
||||
OnLog?.Invoke("Tüm toplu kaldırma işlemleri tamamlandı.");
|
||||
}
|
||||
|
||||
private async Task RunSingleItemAsync(BulkUninstallEntry item, CancellationToken cancellationToken)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
item.Status = BulkStatus.Cancelled;
|
||||
item.StatusMessage = "İptal edildi";
|
||||
return;
|
||||
}
|
||||
|
||||
// Concurrency Collision Prevention:
|
||||
// 1. Publisher Lock
|
||||
string pub = Sift4.NormalizeName(item.Entry.Publisher);
|
||||
bool pubAcquired = false;
|
||||
|
||||
// 2. Directory Hierarchy Lock
|
||||
string dir = !string.IsNullOrWhiteSpace(item.Entry.InstallLocation)
|
||||
? Path.GetFullPath(item.Entry.InstallLocation).TrimEnd('\\')
|
||||
: string.Empty;
|
||||
|
||||
while (!pubAcquired && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
bool pubConflict = !string.IsNullOrWhiteSpace(pub) && _activePublishers.Contains(pub);
|
||||
bool dirConflict = !string.IsNullOrWhiteSpace(dir) && _activeDirectories.Any(d =>
|
||||
d.Equals(dir, StringComparison.OrdinalIgnoreCase) ||
|
||||
dir.StartsWith(d + "\\", StringComparison.OrdinalIgnoreCase) ||
|
||||
d.StartsWith(dir + "\\", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!pubConflict && !dirConflict)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Add(pub);
|
||||
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Add(dir);
|
||||
pubAcquired = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pubAcquired)
|
||||
{
|
||||
await Task.Delay(500, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. MSI Lock
|
||||
bool msiLocked = false;
|
||||
if (item.Entry.UninstallerKind == UninstallerType.Msiexec)
|
||||
{
|
||||
await _msiLock.WaitAsync(cancellationToken);
|
||||
msiLocked = true;
|
||||
await WaitForActiveMsiProcesses(cancellationToken);
|
||||
}
|
||||
|
||||
// 4. One Loud Limit (if uninstaller requires GUI)
|
||||
bool isQuiet = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString);
|
||||
bool loudLocked = false;
|
||||
if (!isQuiet)
|
||||
{
|
||||
await _loudLimitLock.WaitAsync(cancellationToken);
|
||||
loudLocked = true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
item.Status = BulkStatus.Running;
|
||||
item.StatusMessage = "Çalıştırılıyor...";
|
||||
OnItemStarted?.Invoke(item);
|
||||
OnLog?.Invoke($"Kaldırma başladı: {item.Entry.DisplayName}");
|
||||
|
||||
// Pre-kill locking processes in install folder
|
||||
PreKillLockingProcesses(item.Entry);
|
||||
|
||||
// Stop services in install folder
|
||||
PreStopServices(item.Entry);
|
||||
|
||||
// Execute Uninstaller Process
|
||||
int exitCode = await ExecuteUninstallerProcessAsync(item, cancellationToken);
|
||||
item.ExitCode = exitCode;
|
||||
|
||||
if (exitCode == 0 || exitCode == 3010) // 3010 is ERROR_SUCCESS_REBOOT_REQUIRED
|
||||
{
|
||||
item.Status = BulkStatus.Succeeded;
|
||||
item.StatusMessage = exitCode == 3010 ? "Başarılı (Yeniden başlatma gerekli)" : "Başarıyla kaldırıldı";
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Status = BulkStatus.Failed;
|
||||
item.StatusMessage = $"Hata (Çıkış kodu: {exitCode})";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
item.Status = BulkStatus.Failed;
|
||||
item.StatusMessage = $"Hata: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_stateLock)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pub)) _activePublishers.Remove(pub);
|
||||
if (!string.IsNullOrWhiteSpace(dir)) _activeDirectories.Remove(dir);
|
||||
}
|
||||
|
||||
if (msiLocked) _msiLock.Release();
|
||||
if (loudLocked) _loudLimitLock.Release();
|
||||
|
||||
OnItemCompleted?.Invoke(item);
|
||||
OnLog?.Invoke($"Tamamlandı [{item.Status}]: {item.Entry.DisplayName}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> ExecuteUninstallerProcessAsync(BulkUninstallEntry item, CancellationToken token)
|
||||
{
|
||||
string command = item.PreferQuiet && !string.IsNullOrWhiteSpace(item.Entry.QuietUninstallString)
|
||||
? item.Entry.QuietUninstallString
|
||||
: item.Entry.UninstallString;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(command))
|
||||
{
|
||||
// Simple delete fallback for orphaned software
|
||||
if (item.Entry.IsOrphaned && Directory.Exists(item.Entry.InstallLocation))
|
||||
{
|
||||
Directory.Delete(item.Entry.InstallLocation, true);
|
||||
return 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
var (fileName, args) = SplitCommand(command);
|
||||
|
||||
var psi = new ProcessStartInfo
|
||||
{
|
||||
FileName = fileName,
|
||||
Arguments = args,
|
||||
UseShellExecute = true,
|
||||
CreateNoWindow = item.PreferQuiet
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(item.Entry.InstallLocation) && Directory.Exists(item.Entry.InstallLocation))
|
||||
{
|
||||
psi.WorkingDirectory = item.Entry.InstallLocation;
|
||||
}
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process == null) return -1;
|
||||
|
||||
if (EnableAutomatizer)
|
||||
{
|
||||
NotifyAutomatizerDaemon(process.Id);
|
||||
}
|
||||
|
||||
await process.WaitForExitAsync(token);
|
||||
return process.ExitCode;
|
||||
}
|
||||
|
||||
private static void NotifyAutomatizerDaemon(int pid)
|
||||
{
|
||||
_ = Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new NamedPipeClientStream(".", "LDUninstallerDaemon", PipeDirection.Out);
|
||||
client.Connect(1000);
|
||||
using var writer = new StreamWriter(client);
|
||||
writer.WriteLine($"ATTACH:{pid}");
|
||||
writer.Flush();
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
|
||||
private static void PreKillLockingProcesses(ApplicationUninstallerEntry entry)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\');
|
||||
int currentPid = Process.GetCurrentProcess().Id;
|
||||
var procs = Process.GetProcesses();
|
||||
foreach (var p in procs)
|
||||
{
|
||||
using (p)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (p.Id == currentPid) continue;
|
||||
string? mainModule = p.MainModule?.FileName;
|
||||
if (!string.IsNullOrWhiteSpace(mainModule))
|
||||
{
|
||||
if (Path.GetFullPath(mainModule).StartsWith(norm, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Win32.GentleKillProcess(p, 2000);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void PreStopServices(ApplicationUninstallerEntry entry)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(entry.InstallLocation) || !Directory.Exists(entry.InstallLocation))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
string norm = Path.GetFullPath(entry.InstallLocation).TrimEnd('\\');
|
||||
var services = ServiceController.GetServices();
|
||||
foreach (var sc in services)
|
||||
{
|
||||
using (sc)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\{sc.ServiceName}");
|
||||
string? path = key?.GetValue("ImagePath")?.ToString();
|
||||
if (!string.IsNullOrWhiteSpace(path) && path.StartsWith(norm, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (sc.Status == ServiceControllerStatus.Running)
|
||||
{
|
||||
sc.Stop();
|
||||
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(3));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static async Task WaitForActiveMsiProcesses(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
var msiProcs = Process.GetProcessesByName("msiexec");
|
||||
int count = msiProcs.Length;
|
||||
foreach (var p in msiProcs) p.Dispose();
|
||||
|
||||
if (count <= 1)
|
||||
break;
|
||||
await Task.Delay(1000, token);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsSerializedType(UninstallerType type)
|
||||
{
|
||||
return type is UninstallerType.WindowsFeature
|
||||
or UninstallerType.WindowsUpdate
|
||||
or UninstallerType.InstallShield
|
||||
or UninstallerType.SdbInst
|
||||
or UninstallerType.PowerShell;
|
||||
}
|
||||
|
||||
private static (string fileName, string arguments) SplitCommand(string command)
|
||||
{
|
||||
string trimmed = command.Trim();
|
||||
if (trimmed.StartsWith("\""))
|
||||
{
|
||||
int endQuote = trimmed.IndexOf('\"', 1);
|
||||
if (endQuote > 0)
|
||||
{
|
||||
string file = trimmed.Substring(1, endQuote - 1);
|
||||
string args = endQuote + 1 < trimmed.Length ? trimmed[(endQuote + 1)..].Trim() : "";
|
||||
return (file, args);
|
||||
}
|
||||
}
|
||||
|
||||
int space = trimmed.IndexOf(' ');
|
||||
if (space > 0)
|
||||
{
|
||||
return (trimmed[..space], trimmed[(space + 1)..].Trim());
|
||||
}
|
||||
|
||||
return (trimmed, "");
|
||||
}
|
||||
}
|
||||
}
|
||||