use crate::error::AppError; use crate::models::{AppConfig, ChannelCard}; use std::fs; use std::path::PathBuf; pub struct ConfigService { pub config_path: PathBuf, pub cache_path: PathBuf, pub followed_cache_path: PathBuf, } impl ConfigService { pub fn new() -> Result { let mut app_dir = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from(".")); app_dir.push("LDKickWatch"); if let Err(e) = fs::create_dir_all(&app_dir) { log::warn!("LDKickWatch konfigürasyon klasörü oluşturulamadı: {}", e); } let config_path = app_dir.join("config.json"); let cache_path = app_dir.join("cache.json"); let followed_cache_path = app_dir.join("followed_cache.json"); // Migrate legacy KickStreamHub config if present if !config_path.exists() { let mut legacy = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from(".")); legacy.push("KickStreamHub"); legacy.push("config.json"); if legacy.exists() { if let Err(e) = fs::copy(&legacy, &config_path) { log::warn!("Eski yapılandırma kopyalanamadı: {}", e); } } } Ok(Self { config_path, cache_path, followed_cache_path, }) } pub fn load(&self) -> AppConfig { if !self.config_path.exists() { let default_cfg = AppConfig::default(); let _ = self.save(&default_cfg); return default_cfg; } match fs::read_to_string(&self.config_path) { Ok(content) => { match serde_json::from_str::(&content) { Ok(parsed) => parsed, Err(err) => { log::error!( "Yapılandırma dosyası bozuk veya geçersiz JSON! Otomatik kurtarma başlatılıyor: {}", err ); // Self-healing: Backup corrupted config let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S"); let backup_path = self .config_path .with_extension(format!("corrupted.{}.json", timestamp)); let _ = fs::rename(&self.config_path, &backup_path); log::info!( "Bozuk yapılandırma '{}' yoluna yedeklendi.", backup_path.display() ); // Re-initialize with healthy default configuration let default_cfg = AppConfig::default(); if let Err(e) = self.save(&default_cfg) { log::error!("Varsayılan yapılandırma kaydedilemedi: {}", e); } default_cfg } } } Err(e) => { log::warn!( "Yapılandırma dosyası okunamadı: {}. Varsayılan kullanılıyor.", e ); AppConfig::default() } } } pub fn save(&self, config: &AppConfig) -> Result<(), AppError> { let content = serde_json::to_string_pretty(config)?; if let Some(parent) = self.config_path.parent() { let _ = fs::create_dir_all(parent); } let tmp_path = self.config_path.with_extension("tmp"); fs::write(&tmp_path, content)?; // Attempt rename with retry in case of transient file lock (antivirus/indexing) let mut rename_res = fs::rename(&tmp_path, &self.config_path); if rename_res.is_err() { std::thread::sleep(std::time::Duration::from_millis(50)); rename_res = fs::rename(&tmp_path, &self.config_path); } if let Err(e) = rename_res { log::error!("Yapılandırma dosyası atomik olarak yazılamadı: {}", e); let _ = fs::remove_file(&tmp_path); return Err(AppError::Io(e)); } Ok(()) } fn read_cards_file(path: &PathBuf) -> Vec { if !path.exists() { return Vec::new(); } match fs::read_to_string(path) { Ok(content) => serde_json::from_str::>(&content).unwrap_or_default(), Err(err) => { log::warn!("Kanal önbelleği okunamadı: {}", err); Vec::new() } } } fn write_cards_file(path: &PathBuf, tmp_ext: &str, cards: &[ChannelCard]) { let Ok(content) = serde_json::to_string(cards) else { return; }; if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); } let tmp_path = path.with_extension(tmp_ext); if fs::write(&tmp_path, content).is_err() { return; } let mut rename_res = fs::rename(&tmp_path, path); if rename_res.is_err() { std::thread::sleep(std::time::Duration::from_millis(30)); rename_res = fs::rename(&tmp_path, path); } if let Err(err) = rename_res { log::debug!("Kanal önbelleği yazılamadı: {}", err); let _ = fs::remove_file(&tmp_path); } } /// Loads previously cached guest channel cards (`cache.json`) for instant 0 ms UI startup. pub fn load_channel_cache(&self) -> Vec { Self::read_cards_file(&self.cache_path) } /// Persists guest channel cards atomically to `cache.json` (best-effort, non-fatal). pub fn save_channel_cache(&self, cards: &[ChannelCard]) { Self::write_cards_file(&self.cache_path, "cache.tmp", cards); } /// Loads previously cached Kick followed channel cards (`followed_cache.json`). pub fn load_followed_cache(&self) -> Vec { Self::read_cards_file(&self.followed_cache_path) } /// Persists authoritative Kick followed channel cards to `followed_cache.json`. pub fn save_followed_cache(&self, cards: &[ChannelCard]) { Self::write_cards_file(&self.followed_cache_path, "followed.tmp", cards); } /// Removes both channel cache files cleanly (e.g., on logout). pub fn clear_channel_caches(&self) { let _ = fs::remove_file(&self.followed_cache_path); let _ = fs::remove_file(&self.cache_path); } }