use crate::config::{EmulatorRule, ManualLink, SaveStructure}; use crate::romm_api::SimpleRomSchema; use chrono::{DateTime, Utc}; use crc32fast::Hasher as Crc32Hasher; use md5::{Digest as Md5Digest, Md5}; use serde::{Deserialize, Serialize}; use sha1::Sha1; use sha2::Sha256; use std::collections::{HashMap, HashSet}; use std::fs::{self, File}; use std::io::{Read, 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 DiscoveredSaveItem { pub local_path: String, pub file_name: String, pub emulator_id: String, pub emulator_name: 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" } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct LocalRomScanResult { pub local_path: String, pub file_name: String, pub size_bytes: u64, pub crc32: Option, pub md5: Option, pub sha1: Option, pub matched_rom_id: Option, pub matched_rom_name: Option, pub matched_platform: Option, pub match_source: String, // "hash" | "filename" | "unmatched" } /// Strips parenthesized/bracketed ROM tags like `(USA)`, `(Rev 1)`, `[!]` and normalizes for matching. pub fn normalize_title(input: &str) -> String { let mut cleaned = String::with_capacity(input.len()); let mut paren_depth = 0usize; let mut bracket_depth = 0usize; for ch in input.chars() { match ch { '(' => paren_depth += 1, ')' => paren_depth = paren_depth.saturating_sub(1), '[' => bracket_depth += 1, ']' => bracket_depth = bracket_depth.saturating_sub(1), _ if paren_depth == 0 && bracket_depth == 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_name_to_roms<'a>( candidate_stem: &str, platform_slugs: &[String], roms: &'a [SimpleRomSchema], ) -> Option<(&'a SimpleRomSchema, f32, &'static str)> { let cand_lower = candidate_stem.trim().to_lowercase(); let cand_norm = normalize_title(candidate_stem); if cand_norm.is_empty() && cand_lower.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.12 } }; // 1. Exact stem match on fs_name_no_ext or fs_name_no_tags if rom.fs_name_no_ext.to_lowercase() == cand_lower || rom.fs_name_no_tags.to_lowercase() == cand_lower { let score = (1.0 + platform_bonus).min(1.0); if best.map_or(true, |(_, bs, _)| score > bs) { best = Some((rom, score, "exact")); } continue; } // 2. Fuzzy similarity against fs_name_no_tags and display name let mut sim = similarity_score(candidate_stem, &rom.fs_name_no_tags); if let Some(ref name) = rom.name { sim = sim.max(similarity_score(candidate_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_saves_for_emulators( emulators: &[EmulatorRule], roms: &[SimpleRomSchema], manual_links: &HashMap, ) -> Vec { let mut results = Vec::new(); for emu in emulators.iter().filter(|e| e.enabled) { // 1. Regular saves let save_root = Path::new(&emu.save_dir); if save_root.exists() { match emu.structure { SaveStructure::FolderPerGame => { let depth = emu.folder_depth.max(1); for entry in WalkDir::new(save_root) .min_depth(depth) .max_depth(depth) .into_iter() .flatten() { let path = entry.path(); if !path.is_dir() { continue; } let leaf_name = entry.file_name().to_string_lossy().to_string(); if leaf_name.starts_with('.') { continue; } let archive_base = if depth > 1 { path.strip_prefix(save_root) .ok() .map(|rel| { rel.components() .map(|c| c.as_os_str().to_string_lossy().to_string()) .collect::>() .join("_") }) .unwrap_or_else(|| leaf_name.clone()) } else { leaf_name.clone() }; let (size, updated) = dir_size_and_mtime(path); if size == 0 { continue; } results.push(build_discovered_item( path, format!("{}.zip", archive_base), &leaf_name, emu, true, false, size, updated, roms, manual_links, )); } } SaveStructure::FilePerGame | SaveStructure::MemoryCard => { for entry in WalkDir::new(save_root) .max_depth(3) .into_iter() .flatten() { let path = entry.path(); if !path.is_file() { continue; } if !matches_extensions(path, &emu.save_extensions) { continue; } let file_name = path .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); if file_name.starts_with('.') { continue; } let stem = path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| file_name.clone()); let (size, updated) = file_size_and_mtime(path); results.push(build_discovered_item( path, file_name, &stem, emu, false, false, size, updated, roms, manual_links, )); } } } } // 2. Save states (when enabled and state_dir exists) if emu.sync_states { if let Some(ref sdir) = emu.state_dir { let state_root = Path::new(sdir); if state_root.exists() && !emu.state_extensions.is_empty() { for entry in WalkDir::new(state_root) .max_depth(3) .into_iter() .flatten() { let path = entry.path(); if !path.is_file() { continue; } if !matches_extensions(path, &emu.state_extensions) { continue; } let file_name = path .file_name() .map(|n| n.to_string_lossy().to_string()) .unwrap_or_default(); if file_name.starts_with('.') { continue; } let stem = path .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_else(|| file_name.clone()); let (size, updated) = file_size_and_mtime(path); results.push(build_discovered_item( path, file_name, &stem, emu, false, true, size, updated, roms, manual_links, )); } } } } } results } #[allow(clippy::too_many_arguments)] fn build_discovered_item( path: &Path, file_name: String, stem: &str, emu: &EmulatorRule, is_directory: bool, is_state: bool, size_bytes: u64, updated_at: String, roms: &[SimpleRomSchema], manual_links: &HashMap, ) -> DiscoveredSaveItem { let path_str = path.to_string_lossy().to_string(); if let Some(link) = manual_links.get(&path_str) { let rom_platform = roms .iter() .find(|r| r.id == link.rom_id) .map(|r| r.platform_display_name.clone()); return DiscoveredSaveItem { local_path: path_str, file_name, emulator_id: emu.id.clone(), emulator_name: emu.name.clone(), 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: rom_platform, match_confidence: 1.0, match_source: "manual".to_string(), }; } if let Some((rom, conf, src)) = match_name_to_roms(stem, &emu.platform_slugs, roms) { DiscoveredSaveItem { local_path: path_str, file_name, emulator_id: emu.id.clone(), emulator_name: emu.name.clone(), is_directory, is_state, size_bytes, updated_at, slot: emu.default_slot.clone(), 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 { DiscoveredSaveItem { local_path: path_str, file_name, emulator_id: emu.id.clone(), emulator_name: emu.name.clone(), is_directory, is_state, size_bytes, updated_at, slot: emu.default_slot.clone(), matched_rom_id: None, matched_rom_name: None, matched_platform: None, match_confidence: 0.0, match_source: "unmatched".to_string(), } } } fn matches_extensions(path: &Path, exts: &[String]) -> bool { if exts.is_empty() { return true; } let ext = match path.extension().and_then(|e| e.to_str()) { Some(e) => e.to_lowercase(), None => return false, }; exts.iter().any(|allowed| allowed.eq_ignore_ascii_case(&ext)) } 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()) } /// Reads a save file or deterministically zips a save directory into bytes, and returns `(bytes, sha256_hex)`. 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 to read {}: {}", path.display(), e))? }; let mut hasher = Sha256::new(); hasher.update(&bytes); let hash = hex::encode(hasher.finalize()); Ok((bytes, hash)) } 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 file_path in files { let rel = file_path .strip_prefix(dir) .map_err(|e| e.to_string())? .to_string_lossy() .replace('\\', "/"); zip.start_file(rel, options).map_err(|e| e.to_string())?; let data = fs::read(&file_path).map_err(|e| e.to_string())?; zip.write_all(&data).map_err(|e| e.to_string())?; } zip.finish().map_err(|e| e.to_string())?; } Ok(cursor.into_inner()) } /// Computes CRC32, MD5, and SHA1 in a single streaming pass over a local ROM file. /// Skips hashing files larger than `max_hash_bytes` (e.g. 512 MB) unless requested, falling back to filename matching. pub fn compute_rom_hashes( path: &Path, max_hash_bytes: u64, ) -> Result<(u64, Option, Option, Option), String> { let meta = fs::metadata(path).map_err(|e| e.to_string())?; let size = meta.len(); if size > max_hash_bytes { return Ok((size, None, None, None)); } let mut file = File::open(path).map_err(|e| e.to_string())?; let mut crc = Crc32Hasher::new(); let mut md5 = Md5::new(); let mut sha1 = Sha1::new(); let mut buf = vec![0u8; 256 * 1024]; loop { let n = file.read(&mut buf).map_err(|e| e.to_string())?; if n == 0 { break; } let chunk = &buf[..n]; crc.update(chunk); md5.update(chunk); sha1.update(chunk); } let crc_hex = format!("{:08x}", crc.finalize()); let md5_hex = hex::encode(md5.finalize()); let sha1_hex = hex::encode(sha1.finalize()); Ok((size, Some(crc_hex), Some(md5_hex), Some(sha1_hex))) } #[cfg(test)] mod tests { use super::*; #[test] fn test_normalize_title_strips_region_and_revision_tags() { assert_eq!( normalize_title("The Legend of Zelda - The Wind Waker (USA) (Rev 1) [!]"), "the legend of zelda the wind waker" ); assert_eq!(normalize_title("Super_Mario_Sunshine.gci"), "super mario sunshine gci"); } #[test] fn test_similarity_score_matches_cleaned_titles() { let score = similarity_score( "Metroid Prime (USA)", "Metroid Prime (Europe) (En,Fr,De,Es,It)", ); assert!(score >= 0.99, "expected >= 0.99, got {}", score); let partial = similarity_score("Paper Mario TTYD", "Super Mario Sunshine"); assert!(partial < 0.55, "expected < 0.55, got {}", partial); } #[test] fn test_folder_per_game_nested_depth() { let base = std::env::temp_dir().join(format!("romm_depth_test_{}", uuid::Uuid::new_v4())); let nested = base.join("00050000").join("101c9400"); fs::create_dir_all(&nested).unwrap(); fs::write(nested.join("save.dat"), b"hello-wiiu").unwrap(); let rule = EmulatorRule { id: "cemu".into(), name: "Cemu".into(), platform_slugs: vec!["wiiu".into()], save_dir: base.to_string_lossy().to_string(), state_dir: None, rom_dir: None, save_extensions: vec![], state_extensions: vec![], structure: SaveStructure::FolderPerGame, folder_depth: 2, enabled: true, is_custom: false, sync_states: false, default_slot: "default".into(), }; let found = discover_saves_for_emulators(&[rule], &[], &HashMap::new()); let _ = fs::remove_dir_all(&base); assert_eq!(found.len(), 1); assert_eq!(found[0].file_name, "00050000_101c9400.zip"); assert!(found[0].is_directory); } }