use crate::config::{ManualLink, NextUiConfig}; use crate::nextui::{classify_nextui_save_file, discover_nextui_systems}; use crate::romm_api::SimpleRomSchema; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{HashMap, HashSet}; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use walkdir::WalkDir; use zip::write::SimpleFileOptions; use zip::ZipWriter; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DiscoveredNextUiSave { pub local_path: String, pub file_name: String, pub system_tag: String, pub is_directory: bool, pub is_state: bool, pub size_bytes: u64, pub updated_at: String, pub slot: String, pub matched_rom_id: Option, pub matched_rom_name: Option, pub matched_platform: Option, pub match_confidence: f32, pub match_source: String, // "manual" | "exact" | "fuzzy" | "unmatched" } pub fn normalize_title(input: &str) -> String { let mut cleaned = String::with_capacity(input.len()); let mut paren = 0usize; let mut bracket = 0usize; for ch in input.chars() { match ch { '(' => paren += 1, ')' => paren = paren.saturating_sub(1), '[' => bracket += 1, ']' => bracket = bracket.saturating_sub(1), _ if paren == 0 && bracket == 0 => { if ch.is_alphanumeric() { for lc in ch.to_lowercase() { cleaned.push(lc); } } else { cleaned.push(' '); } } _ => {} } } cleaned.split_whitespace().collect::>().join(" ") } fn tokenize(norm: &str) -> HashSet { norm.split_whitespace() .filter(|t| t.len() >= 2) .map(|s| s.to_string()) .collect() } pub fn similarity_score(a: &str, b: &str) -> f32 { let na = normalize_title(a); let nb = normalize_title(b); if na.is_empty() || nb.is_empty() { return 0.0; } if na == nb { return 1.0; } if na.contains(&nb) || nb.contains(&na) { let min_len = na.len().min(nb.len()) as f32; let max_len = na.len().max(nb.len()) as f32; if min_len >= 4.0 { return 0.78 + 0.18 * (min_len / max_len); } } let ta = tokenize(&na); let tb = tokenize(&nb); if ta.is_empty() || tb.is_empty() { return 0.0; } let inter = ta.intersection(&tb).count() as f32; let union = ta.union(&tb).count() as f32; inter / union } pub fn match_stem_to_roms<'a>( stem: &str, platform_slugs: &[String], roms: &'a [SimpleRomSchema], ) -> Option<(&'a SimpleRomSchema, f32, &'static str)> { let stem_lower = stem.trim().to_lowercase(); let stem_norm = normalize_title(stem); if stem_lower.is_empty() && stem_norm.is_empty() { return None; } let mut best: Option<(&SimpleRomSchema, f32, &'static str)> = None; for rom in roms { let platform_bonus: f32 = if platform_slugs.is_empty() { 0.0 } else { let p_slug = rom.platform_slug.to_lowercase(); let p_fs = rom.platform_fs_slug.to_lowercase(); if platform_slugs .iter() .any(|s| s.eq_ignore_ascii_case(&p_slug) || s.eq_ignore_ascii_case(&p_fs)) { 0.08 } else { -0.15 } }; if rom.fs_name_no_ext.to_lowercase() == stem_lower || rom.fs_name_no_tags.to_lowercase() == stem_lower { let score = (1.0 + platform_bonus).min(1.0); if best.map_or(true, |(_, bs, _)| score > bs) { best = Some((rom, score, "exact")); } continue; } let mut sim = similarity_score(stem, &rom.fs_name_no_tags); if let Some(ref name) = rom.name { sim = sim.max(similarity_score(stem, name)); } let adjusted = (sim + platform_bonus).clamp(0.0, 1.0); if sim >= 0.55 && best.map_or(true, |(_, bs, _)| adjusted > bs) { let src = if sim >= 0.99 { "exact" } else { "fuzzy" }; best = Some((rom, adjusted, src)); } } best } pub fn discover_nextui_saves( cfg: &NextUiConfig, roms: &[SimpleRomSchema], ) -> Vec { let systems = discover_nextui_systems(cfg); let mut results = Vec::new(); for sys in systems { let Some(ref save_folder) = sys.save_folder else { continue; }; let save_root = Path::new(save_folder); if !save_root.exists() { continue; } // Special case: PPSSPP SAVEDATA folders under /Saves/PSP/ if sys.tag.eq_ignore_ascii_case("PSP") { let psp_savedata = save_root.join("PSP/SAVEDATA"); let scan_dir = if psp_savedata.exists() { psp_savedata } else { save_root.to_path_buf() }; if let Ok(entries) = fs::read_dir(&scan_dir) { for entry in entries.flatten() { let p = entry.path(); if p.is_dir() { let name = entry.file_name().to_string_lossy().to_string(); if name.starts_with('.') || name == "PSP" { continue; } let (size, updated) = dir_size_and_mtime(&p); if size == 0 { continue; } results.push(build_item( &p, format!("{}.zip", name), &name, &sys.tag, &sys.romm_slugs, true, false, size, updated, &cfg.settings.default_slot, roms, &cfg.manual_links, )); } } } } for entry in WalkDir::new(save_root) .max_depth(2) .into_iter() .flatten() { let path = entry.path(); if !path.is_file() { continue; } let Some((is_state, stem)) = classify_nextui_save_file(path) else { continue; }; if is_state && !cfg.settings.sync_states { continue; } let file_name = path .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); let (size, updated) = file_size_and_mtime(path); results.push(build_item( path, file_name, &stem, &sys.tag, &sys.romm_slugs, false, is_state, size, updated, &cfg.settings.default_slot, roms, &cfg.manual_links, )); } } results } #[allow(clippy::too_many_arguments)] fn build_item( path: &Path, file_name: String, stem: &str, system_tag: &str, platform_slugs: &[String], is_directory: bool, is_state: bool, size_bytes: u64, updated_at: String, default_slot: &str, roms: &[SimpleRomSchema], manual_links: &HashMap, ) -> DiscoveredNextUiSave { let local_path = path.to_string_lossy().to_string(); if let Some(link) = manual_links.get(&local_path) { let plat = roms .iter() .find(|r| r.id == link.rom_id) .map(|r| r.platform_display_name.clone()); return DiscoveredNextUiSave { local_path, file_name, system_tag: system_tag.to_string(), is_directory, is_state, size_bytes, updated_at, slot: link.slot.clone(), matched_rom_id: Some(link.rom_id), matched_rom_name: Some(link.rom_name.clone()), matched_platform: plat, match_confidence: 1.0, match_source: "manual".to_string(), }; } if let Some((rom, conf, src)) = match_stem_to_roms(stem, platform_slugs, roms) { DiscoveredNextUiSave { local_path, file_name, system_tag: system_tag.to_string(), is_directory, is_state, size_bytes, updated_at, slot: default_slot.to_string(), matched_rom_id: Some(rom.id), matched_rom_name: Some(rom.name.clone().unwrap_or_else(|| rom.fs_name_no_ext.clone())), matched_platform: Some(rom.platform_display_name.clone()), match_confidence: conf, match_source: src.to_string(), } } else { DiscoveredNextUiSave { local_path, file_name, system_tag: system_tag.to_string(), is_directory, is_state, size_bytes, updated_at, slot: default_slot.to_string(), matched_rom_id: None, matched_rom_name: None, matched_platform: None, match_confidence: 0.0, match_source: "unmatched".to_string(), } } } fn file_size_and_mtime(path: &Path) -> (u64, String) { match fs::metadata(path) { Ok(m) => { let dt: DateTime = m .modified() .map(DateTime::::from) .unwrap_or_else(|_| Utc::now()); (m.len(), dt.to_rfc3339()) } Err(_) => (0, Utc::now().to_rfc3339()), } } fn dir_size_and_mtime(dir: &Path) -> (u64, String) { let mut total = 0u64; let mut latest: Option = None; for entry in WalkDir::new(dir).into_iter().flatten() { if entry.path().is_file() { if let Ok(m) = entry.metadata() { total += m.len(); if let Ok(mt) = m.modified() { if latest.map_or(true, |l| mt > l) { latest = Some(mt); } } } } } let dt: DateTime = latest.map(DateTime::::from).unwrap_or_else(Utc::now); (total, dt.to_rfc3339()) } pub fn read_save_payload_and_hash(path: &Path, is_directory: bool) -> Result<(Vec, String), String> { let bytes = if is_directory { zip_directory_deterministic(path)? } else { fs::read(path).map_err(|e| format!("Failed reading {}: {}", path.display(), e))? }; let mut hasher = Sha256::new(); hasher.update(&bytes); Ok((bytes, hex::encode(hasher.finalize()))) } fn zip_directory_deterministic(dir: &Path) -> Result, String> { let mut files: Vec = WalkDir::new(dir) .into_iter() .flatten() .filter(|e| e.path().is_file()) .map(|e| e.into_path()) .collect(); files.sort(); let mut cursor = std::io::Cursor::new(Vec::new()); { let mut zip = ZipWriter::new(&mut cursor); let options = SimpleFileOptions::default() .compression_method(zip::CompressionMethod::Deflated) .last_modified_time(zip::DateTime::default()); for f in files { let rel = f .strip_prefix(dir) .map_err(|e| e.to_string())? .to_string_lossy() .replace('\\', "/"); zip.start_file(rel, options).map_err(|e| e.to_string())?; zip.write_all(&fs::read(&f).map_err(|e| e.to_string())?) .map_err(|e| e.to_string())?; } zip.finish().map_err(|e| e.to_string())?; } Ok(cursor.into_inner()) }