Initial commit: RomM Companion desktop v0.1.0
This commit is contained in:
commit
0603108e5c
41 files changed
+17214
No files matched your search
Generated
+5800
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "romm-companion"
|
||||
version = "0.1.0"
|
||||
description = "Cross-platform RomM 5.1.0 companion for save/state sync, ROM matching, and emulator detection"
|
||||
authors = ["RomM Companion"]
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "romm_companion_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = ["tray-icon", "image-png"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "stream", "rustls-tls"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
directories = "6"
|
||||
walkdir = "2"
|
||||
notify = "8"
|
||||
notify-debouncer-mini = "0.6"
|
||||
sha2 = "0.10"
|
||||
sha1 = "0.10"
|
||||
md-5 = "0.10"
|
||||
crc32fast = "1"
|
||||
hex = "0.4"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
hostname = "0.4"
|
||||
thiserror = "2"
|
||||
futures-util = "0.3"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"dialog:default",
|
||||
"opener:default"
|
||||
]
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 507 B |
Binary file not shown.
|
After Width: | Height: | Size: 529 B |
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,197 @@
|
||||
use directories::ProjectDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ConnectionConfig {
|
||||
pub server_url: String,
|
||||
pub access_token: Option<String>,
|
||||
pub refresh_token: Option<String>,
|
||||
pub username: Option<String>,
|
||||
pub device_id: Option<String>,
|
||||
pub device_name: String,
|
||||
pub client_device_identifier: String,
|
||||
}
|
||||
|
||||
impl Default for ConnectionConfig {
|
||||
fn default() -> Self {
|
||||
let host = hostname::get()
|
||||
.ok()
|
||||
.and_then(|h| h.into_string().ok())
|
||||
.unwrap_or_else(|| "My Computer".to_string());
|
||||
Self {
|
||||
server_url: String::new(),
|
||||
access_token: None,
|
||||
refresh_token: None,
|
||||
username: None,
|
||||
device_id: None,
|
||||
device_name: format!("{} (RomM Companion)", host),
|
||||
client_device_identifier: Uuid::new_v4().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SaveStructure {
|
||||
/// Individual save files named after the ROM (e.g. `Game (USA).sav`, `Game.mcr`)
|
||||
FilePerGame,
|
||||
/// Directory per game (e.g. RPCS3, Ryujinx, Cemu, Azahar, PPSSPP) — zipped as a single archive for RomM sync
|
||||
FolderPerGame,
|
||||
/// Shared memory card / system file (e.g. PCSX2 Mcd001.ps2, Dolphin MemoryCardA.USA.raw)
|
||||
MemoryCard,
|
||||
}
|
||||
|
||||
fn default_folder_depth() -> usize {
|
||||
1
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmulatorRule {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub platform_slugs: Vec<String>,
|
||||
pub save_dir: String,
|
||||
pub state_dir: Option<String>,
|
||||
pub rom_dir: Option<String>,
|
||||
pub save_extensions: Vec<String>,
|
||||
pub state_extensions: Vec<String>,
|
||||
pub structure: SaveStructure,
|
||||
#[serde(default = "default_folder_depth")]
|
||||
pub folder_depth: usize,
|
||||
pub enabled: bool,
|
||||
pub is_custom: bool,
|
||||
pub sync_states: bool,
|
||||
/// Optional default slot name sent to RomM `/api/sync/negotiate`
|
||||
pub default_slot: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ManualLink {
|
||||
pub local_path: String,
|
||||
pub rom_id: i64,
|
||||
pub rom_name: String,
|
||||
pub emulator_id: String,
|
||||
pub slot: String,
|
||||
pub is_state: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct WatcherSettings {
|
||||
pub enabled: bool,
|
||||
pub debounce_seconds: u64,
|
||||
pub auto_sync_on_change: bool,
|
||||
pub max_backups_per_save: usize,
|
||||
pub minimize_to_tray: bool,
|
||||
pub default_rom_download_dir: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for WatcherSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
debounce_seconds: 5,
|
||||
auto_sync_on_change: true,
|
||||
max_backups_per_save: 10,
|
||||
minimize_to_tray: true,
|
||||
default_rom_download_dir: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncLogEntry {
|
||||
pub id: String,
|
||||
pub timestamp: String,
|
||||
pub level: String, // "info" | "success" | "warning" | "error"
|
||||
pub action: String,
|
||||
pub message: String,
|
||||
pub rom_id: Option<i64>,
|
||||
pub file_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppConfig {
|
||||
pub connection: ConnectionConfig,
|
||||
pub emulators: Vec<EmulatorRule>,
|
||||
pub manual_links: HashMap<String, ManualLink>,
|
||||
pub settings: WatcherSettings,
|
||||
/// Tracks last-known local content hash per canonical path for state/save change detection
|
||||
pub synced_state_hashes: HashMap<String, String>,
|
||||
pub sync_logs: Vec<SyncLogEntry>,
|
||||
}
|
||||
|
||||
pub fn app_data_dir() -> PathBuf {
|
||||
if let Some(proj) = ProjectDirs::from("com", "romm", "RomMCompanion") {
|
||||
let dir = proj.data_local_dir().to_path_buf();
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
dir
|
||||
} else {
|
||||
let dir = PathBuf::from(".romm-companion");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backups_dir() -> PathBuf {
|
||||
let dir = app_data_dir().join("backups");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
pub fn config_file_path() -> PathBuf {
|
||||
app_data_dir().join("config.json")
|
||||
}
|
||||
|
||||
pub fn load_config() -> AppConfig {
|
||||
let path = config_file_path();
|
||||
if let Ok(raw) = fs::read_to_string(&path) {
|
||||
if let Ok(cfg) = serde_json::from_str::<AppConfig>(&raw) {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
AppConfig::default()
|
||||
}
|
||||
|
||||
pub fn save_config(cfg: &AppConfig) -> Result<(), String> {
|
||||
let path = config_file_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(cfg).map_err(|e| e.to_string())?;
|
||||
fs::write(&path, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn push_log(
|
||||
cfg: &mut AppConfig,
|
||||
level: &str,
|
||||
action: &str,
|
||||
message: impl Into<String>,
|
||||
rom_id: Option<i64>,
|
||||
file_path: Option<String>,
|
||||
) {
|
||||
cfg.sync_logs.insert(
|
||||
0,
|
||||
SyncLogEntry {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
timestamp: chrono::Utc::now().to_rfc3339(),
|
||||
level: level.to_string(),
|
||||
action: action.to_string(),
|
||||
message: message.into(),
|
||||
rom_id,
|
||||
file_path,
|
||||
},
|
||||
);
|
||||
if cfg.sync_logs.len() > 250 {
|
||||
cfg.sync_logs.truncate(250);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
use crate::config::{EmulatorRule, SaveStructure};
|
||||
use directories::BaseDirs;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmulatorPresetInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub category: String, // "console" | "handheld"
|
||||
pub platform_slugs: Vec<String>,
|
||||
pub detected: bool,
|
||||
pub detected_save_dir: Option<String>,
|
||||
pub detected_state_dir: Option<String>,
|
||||
pub default_save_dir: String,
|
||||
pub default_state_dir: Option<String>,
|
||||
pub save_extensions: Vec<String>,
|
||||
pub state_extensions: Vec<String>,
|
||||
pub structure: SaveStructure,
|
||||
pub folder_depth: usize,
|
||||
pub notes: String,
|
||||
}
|
||||
|
||||
fn home_dir() -> PathBuf {
|
||||
BaseDirs::new()
|
||||
.map(|b| b.home_dir().to_path_buf())
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
}
|
||||
|
||||
fn config_dir() -> PathBuf {
|
||||
BaseDirs::new()
|
||||
.map(|b| b.config_dir().to_path_buf())
|
||||
.unwrap_or_else(home_dir)
|
||||
}
|
||||
|
||||
fn data_dir() -> PathBuf {
|
||||
BaseDirs::new()
|
||||
.map(|b| b.data_dir().to_path_buf())
|
||||
.unwrap_or_else(home_dir)
|
||||
}
|
||||
|
||||
fn data_local_dir() -> PathBuf {
|
||||
BaseDirs::new()
|
||||
.map(|b| b.data_local_dir().to_path_buf())
|
||||
.unwrap_or_else(home_dir)
|
||||
}
|
||||
|
||||
fn first_existing(candidates: &[PathBuf]) -> Option<PathBuf> {
|
||||
candidates.iter().find(|p| p.exists()).cloned()
|
||||
}
|
||||
|
||||
fn path_to_string(p: &Path) -> String {
|
||||
p.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
struct PresetDef {
|
||||
id: &'static str,
|
||||
name: &'static str,
|
||||
category: &'static str,
|
||||
platform_slugs: Vec<&'static str>,
|
||||
save_candidates: Vec<PathBuf>,
|
||||
state_candidates: Vec<PathBuf>,
|
||||
save_extensions: Vec<&'static str>,
|
||||
state_extensions: Vec<&'static str>,
|
||||
structure: SaveStructure,
|
||||
folder_depth: usize,
|
||||
notes: &'static str,
|
||||
}
|
||||
|
||||
fn build_preset_defs() -> Vec<PresetDef> {
|
||||
let home = home_dir();
|
||||
let cfg = config_dir();
|
||||
let data = data_dir();
|
||||
let local = data_local_dir();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let app_support = home.join("Library/Application Support");
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let app_support = data.clone();
|
||||
|
||||
let docs = home.join("Documents");
|
||||
|
||||
vec![
|
||||
// ---------- Standalone Console Emulators ----------
|
||||
PresetDef {
|
||||
id: "dolphin",
|
||||
name: "Dolphin (GameCube / Wii)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["ngc", "gc", "gamecube", "wii"],
|
||||
save_candidates: vec![
|
||||
app_support.join("Dolphin/GC"),
|
||||
docs.join("Dolphin Emulator/GC"),
|
||||
data.join("dolphin-emu/GC"),
|
||||
home.join(".local/share/dolphin-emu/GC"),
|
||||
home.join(".var/app/org.DolphinEmu.dolphin-emu/data/dolphin-emu/GC"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("Dolphin/StateSaves"),
|
||||
docs.join("Dolphin Emulator/StateSaves"),
|
||||
data.join("dolphin-emu/StateSaves"),
|
||||
home.join(".local/share/dolphin-emu/StateSaves"),
|
||||
home.join(".var/app/org.DolphinEmu.dolphin-emu/data/dolphin-emu/StateSaves"),
|
||||
],
|
||||
save_extensions: vec!["gci", "raw", "sav", "bin"],
|
||||
state_extensions: vec!["s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", "sav"],
|
||||
structure: SaveStructure::FilePerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Supports GCI Folder mode (recommended for per-game matching) and raw memory cards.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "pcsx2",
|
||||
name: "PCSX2 (PlayStation 2)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["ps2"],
|
||||
save_candidates: vec![
|
||||
app_support.join("PCSX2/memcards"),
|
||||
docs.join("PCSX2/memcards"),
|
||||
cfg.join("PCSX2/memcards"),
|
||||
home.join(".config/PCSX2/memcards"),
|
||||
home.join(".var/app/net.pcsx2.PCSX2/config/PCSX2/memcards"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("PCSX2/sstates"),
|
||||
docs.join("PCSX2/sstates"),
|
||||
cfg.join("PCSX2/sstates"),
|
||||
home.join(".config/PCSX2/sstates"),
|
||||
home.join(".var/app/net.pcsx2.PCSX2/config/PCSX2/sstates"),
|
||||
],
|
||||
save_extensions: vec!["ps2", "mcd"],
|
||||
state_extensions: vec!["p2s"],
|
||||
structure: SaveStructure::MemoryCard,
|
||||
folder_depth: 1,
|
||||
notes: "Tip: Enable Folder Memory Cards in PCSX2 or link individual .ps2 cards to ROMs.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "rpcs3",
|
||||
name: "RPCS3 (PlayStation 3)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["ps3"],
|
||||
save_candidates: vec![
|
||||
app_support.join("rpcs3/dev_hdd0/home/00000001/savedata"),
|
||||
cfg.join("rpcs3/dev_hdd0/home/00000001/savedata"),
|
||||
home.join(".config/rpcs3/dev_hdd0/home/00000001/savedata"),
|
||||
home.join(".var/app/net.rpcs3.RPCS3/config/rpcs3/dev_hdd0/home/00000001/savedata"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("rpcs3/savestates"),
|
||||
cfg.join("rpcs3/savestates"),
|
||||
home.join(".config/rpcs3/savestates"),
|
||||
home.join(".var/app/net.rpcs3.RPCS3/config/rpcs3/savestates"),
|
||||
],
|
||||
save_extensions: vec![],
|
||||
state_extensions: vec!["sav"],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Each PS3 title stores a folder inside savedata; zipped automatically for RomM sync.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "cemu",
|
||||
name: "Cemu (Wii U)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["wiiu"],
|
||||
save_candidates: vec![
|
||||
app_support.join("Cemu/mlc01/usr/save"),
|
||||
data.join("Cemu/mlc01/usr/save"),
|
||||
local.join("Cemu/mlc01/usr/save"),
|
||||
home.join(".local/share/Cemu/mlc01/usr/save"),
|
||||
home.join(".var/app/info.cemu.Cemu/data/Cemu/mlc01/usr/save"),
|
||||
],
|
||||
state_candidates: vec![],
|
||||
save_extensions: vec![],
|
||||
state_extensions: vec![],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 2,
|
||||
notes: "Wii U title save directories inside mlc01/usr/save/<high>/<low> (depth 2) are zipped per title for RomM.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "duckstation",
|
||||
name: "DuckStation (PlayStation)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["psx", "ps1", "ps"],
|
||||
save_candidates: vec![
|
||||
app_support.join("DuckStation/memcards"),
|
||||
docs.join("DuckStation/memcards"),
|
||||
data.join("duckstation/memcards"),
|
||||
home.join(".local/share/duckstation/memcards"),
|
||||
home.join(".var/app/org.duckstation.DuckStation/data/duckstation/memcards"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("DuckStation/savestates"),
|
||||
docs.join("DuckStation/savestates"),
|
||||
data.join("duckstation/savestates"),
|
||||
home.join(".local/share/duckstation/savestates"),
|
||||
home.join(".var/app/org.duckstation.DuckStation/data/duckstation/savestates"),
|
||||
],
|
||||
save_extensions: vec!["mcd", "mcr", "srm"],
|
||||
state_extensions: vec!["sav"],
|
||||
structure: SaveStructure::FilePerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Works best with 'Separate Card Per Game (Title)' enabled in DuckStation.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "ppsspp",
|
||||
name: "PPSSPP (PSP)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["psp"],
|
||||
save_candidates: vec![
|
||||
cfg.join("ppsspp/PSP/SAVEDATA"),
|
||||
home.join(".config/ppsspp/PSP/SAVEDATA"),
|
||||
docs.join("PPSSPP/PSP/SAVEDATA"),
|
||||
home.join(".var/app/org.ppsspp.PPSSPP/config/ppsspp/PSP/SAVEDATA"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
cfg.join("ppsspp/PSP/PPSSPP_STATE"),
|
||||
home.join(".config/ppsspp/PSP/PPSSPP_STATE"),
|
||||
docs.join("PPSSPP/PSP/PPSSPP_STATE"),
|
||||
home.join(".var/app/org.ppsspp.PPSSPP/config/ppsspp/PSP/PPSSPP_STATE"),
|
||||
],
|
||||
save_extensions: vec![],
|
||||
state_extensions: vec!["ppst"],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 1,
|
||||
notes: "PSP savedata folders are zipped per game; PPSSPP_STATE .ppst files sync as save states.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "ryujinx",
|
||||
name: "Ryujinx (Nintendo Switch)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["switch", "ns", "nintendo-switch"],
|
||||
save_candidates: vec![
|
||||
app_support.join("Ryujinx/bis/user/save"),
|
||||
cfg.join("Ryujinx/bis/user/save"),
|
||||
data.join("Ryujinx/bis/user/save"),
|
||||
home.join(".config/Ryujinx/bis/user/save"),
|
||||
],
|
||||
state_candidates: vec![],
|
||||
save_extensions: vec![],
|
||||
state_extensions: vec![],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Switch save folders under bis/user/save are archived per title; link Title IDs in Saves view.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "azahar",
|
||||
name: "Azahar / Citra (Nintendo 3DS)",
|
||||
category: "console",
|
||||
platform_slugs: vec!["3ds", "n3ds"],
|
||||
save_candidates: vec![
|
||||
app_support.join("Azahar/sdmc/Nintendo 3DS"),
|
||||
app_support.join("Citra/sdmc/Nintendo 3DS"),
|
||||
data.join("azahar-emu/sdmc/Nintendo 3DS"),
|
||||
data.join("citra-emu/sdmc/Nintendo 3DS"),
|
||||
home.join(".local/share/azahar-emu/sdmc/Nintendo 3DS"),
|
||||
home.join(".local/share/citra-emu/sdmc/Nintendo 3DS"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("Azahar/states"),
|
||||
app_support.join("Citra/states"),
|
||||
data.join("azahar-emu/states"),
|
||||
data.join("citra-emu/states"),
|
||||
home.join(".local/share/azahar-emu/states"),
|
||||
],
|
||||
save_extensions: vec!["sav", "dat"],
|
||||
state_extensions: vec!["cst"],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 5,
|
||||
notes: "Detects both Azahar and legacy Citra 3DS directories (depth 5 reaches <id0>/<id1>/title/<high>/<low>).",
|
||||
},
|
||||
// ---------- Handheld & PC-Adjacent Emulators ----------
|
||||
PresetDef {
|
||||
id: "melonds",
|
||||
name: "melonDS (Nintendo DS / DSi)",
|
||||
category: "handheld",
|
||||
platform_slugs: vec!["nds", "ds", "dsi"],
|
||||
save_candidates: vec![
|
||||
app_support.join("melonDS"),
|
||||
cfg.join("melonDS"),
|
||||
home.join(".config/melonDS"),
|
||||
home.join(".var/app/net.kuribo64.melonDS/config/melonDS"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("melonDS"),
|
||||
cfg.join("melonDS"),
|
||||
home.join(".config/melonDS"),
|
||||
],
|
||||
save_extensions: vec!["sav", "dsv"],
|
||||
state_extensions: vec!["ml0", "ml1", "ml2", "ml3", "ml4", "ml5", "ml6", "ml7", "ml8", "mln"],
|
||||
structure: SaveStructure::FilePerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Point to your melonDS saves folder (or ROM folder if saves live alongside .nds files).",
|
||||
},
|
||||
PresetDef {
|
||||
id: "mgba",
|
||||
name: "mGBA (GB / GBC / GBA)",
|
||||
category: "handheld",
|
||||
platform_slugs: vec!["gba", "gbc", "gb"],
|
||||
save_candidates: vec![
|
||||
app_support.join("mGBA"),
|
||||
cfg.join("mgba"),
|
||||
home.join(".config/mgba"),
|
||||
home.join(".var/app/io.mgba.mGBA/config/mgba"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("mGBA"),
|
||||
cfg.join("mgba"),
|
||||
home.join(".config/mgba"),
|
||||
],
|
||||
save_extensions: vec!["sav", "srm"],
|
||||
state_extensions: vec!["ss0", "ss1", "ss2", "ss3", "ss4", "ss5", "ss6", "ss7", "ss8", "ss9"],
|
||||
structure: SaveStructure::FilePerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Matches .sav/.srm files by ROM name; set save directory to your mGBA save/ROM path.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "flycast",
|
||||
name: "Flycast (Dreamcast / Naomi)",
|
||||
category: "handheld",
|
||||
platform_slugs: vec!["dc", "dreamcast", "naomi"],
|
||||
save_candidates: vec![
|
||||
app_support.join("Flycast/data"),
|
||||
data.join("flycast/data"),
|
||||
home.join(".local/share/flycast/data"),
|
||||
home.join(".var/app/org.flycast.Flycast/data/flycast/data"),
|
||||
],
|
||||
state_candidates: vec![
|
||||
app_support.join("Flycast/data"),
|
||||
data.join("flycast/data"),
|
||||
home.join(".local/share/flycast/data"),
|
||||
],
|
||||
save_extensions: vec!["bin", "vmu"],
|
||||
state_extensions: vec!["state", "state1", "state2", "state3"],
|
||||
structure: SaveStructure::FilePerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Enable 'Per-Game VMUs' in Flycast for automatic per-game ROM matching.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "xemu",
|
||||
name: "xemu (Original Xbox)",
|
||||
category: "handheld",
|
||||
platform_slugs: vec!["xbox"],
|
||||
save_candidates: vec![
|
||||
app_support.join("xemu/xemu"),
|
||||
data.join("xemu/xemu"),
|
||||
home.join(".local/share/xemu/xemu"),
|
||||
home.join(".var/app/app.xemu.xemu/data/xemu/xemu"),
|
||||
],
|
||||
state_candidates: vec![],
|
||||
save_extensions: vec!["qcow2", "bin", "sav"],
|
||||
state_extensions: vec![],
|
||||
structure: SaveStructure::MemoryCard,
|
||||
folder_depth: 1,
|
||||
notes: "Tracks xemu memory unit / extracted save folders.",
|
||||
},
|
||||
PresetDef {
|
||||
id: "xenia",
|
||||
name: "Xenia (Xbox 360)",
|
||||
category: "handheld",
|
||||
platform_slugs: vec!["xbox360", "x360"],
|
||||
save_candidates: vec![
|
||||
docs.join("Xenia/content"),
|
||||
local.join("Xenia/content"),
|
||||
data.join("xenia/content"),
|
||||
],
|
||||
state_candidates: vec![],
|
||||
save_extensions: vec![],
|
||||
state_extensions: vec![],
|
||||
structure: SaveStructure::FolderPerGame,
|
||||
folder_depth: 1,
|
||||
notes: "Xbox 360 title save folders under Xenia/content are archived per game.",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
pub fn detect_emulator_presets() -> Vec<EmulatorPresetInfo> {
|
||||
build_preset_defs()
|
||||
.into_iter()
|
||||
.map(|d| {
|
||||
let detected_save = first_existing(&d.save_candidates);
|
||||
let detected_state = first_existing(&d.state_candidates);
|
||||
let default_save = detected_save
|
||||
.as_ref()
|
||||
.or_else(|| d.save_candidates.first())
|
||||
.map(|p| path_to_string(p))
|
||||
.unwrap_or_default();
|
||||
let default_state = detected_state
|
||||
.as_ref()
|
||||
.or_else(|| d.state_candidates.first())
|
||||
.map(|p| path_to_string(p));
|
||||
EmulatorPresetInfo {
|
||||
id: d.id.to_string(),
|
||||
name: d.name.to_string(),
|
||||
category: d.category.to_string(),
|
||||
platform_slugs: d.platform_slugs.into_iter().map(String::from).collect(),
|
||||
detected: detected_save.is_some(),
|
||||
detected_save_dir: detected_save.map(|p| path_to_string(&p)),
|
||||
detected_state_dir: detected_state.map(|p| path_to_string(&p)),
|
||||
default_save_dir: default_save,
|
||||
default_state_dir: default_state,
|
||||
save_extensions: d.save_extensions.into_iter().map(String::from).collect(),
|
||||
state_extensions: d.state_extensions.into_iter().map(String::from).collect(),
|
||||
structure: d.structure,
|
||||
folder_depth: d.folder_depth,
|
||||
notes: d.notes.to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn preset_to_rule(preset: &EmulatorPresetInfo) -> EmulatorRule {
|
||||
EmulatorRule {
|
||||
id: preset.id.clone(),
|
||||
name: preset.name.clone(),
|
||||
platform_slugs: preset.platform_slugs.clone(),
|
||||
save_dir: preset
|
||||
.detected_save_dir
|
||||
.clone()
|
||||
.unwrap_or_else(|| preset.default_save_dir.clone()),
|
||||
state_dir: preset
|
||||
.detected_state_dir
|
||||
.clone()
|
||||
.or_else(|| preset.default_state_dir.clone()),
|
||||
rom_dir: None,
|
||||
save_extensions: preset.save_extensions.clone(),
|
||||
state_extensions: preset.state_extensions.clone(),
|
||||
structure: preset.structure.clone(),
|
||||
folder_depth: preset.folder_depth,
|
||||
enabled: preset.detected,
|
||||
is_custom: false,
|
||||
sync_states: preset.default_state_dir.is_some(),
|
||||
default_slot: "default".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
mod commands;
|
||||
mod config;
|
||||
mod emulators;
|
||||
mod matcher;
|
||||
mod nextui_sd;
|
||||
mod romm_api;
|
||||
mod sync_engine;
|
||||
mod watcher;
|
||||
|
||||
use commands::{refresh_watcher_internal, AppState};
|
||||
use config::load_config;
|
||||
use std::sync::Mutex;
|
||||
use tauri::menu::{Menu, MenuItem};
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri::{Emitter, Manager, WindowEvent};
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
let cfg = load_config();
|
||||
let app_state = AppState {
|
||||
config: Mutex::new(cfg),
|
||||
rom_cache: Mutex::new(Vec::new()),
|
||||
conflicts: Mutex::new(Vec::new()),
|
||||
watcher: Mutex::new(None),
|
||||
};
|
||||
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.manage(app_state)
|
||||
.setup(|app| {
|
||||
// Start background file watcher if enabled
|
||||
let state = app.state::<AppState>();
|
||||
let _ = refresh_watcher_internal(app.handle().clone(), &state);
|
||||
|
||||
// Build cross-platform system tray menu
|
||||
let show_item = MenuItem::with_id(app, "show", "Open RomM Companion", true, None::<&str>)?;
|
||||
let sync_item = MenuItem::with_id(app, "sync", "Sync Saves Now", true, None::<&str>)?;
|
||||
let quit_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?;
|
||||
let menu = Menu::with_items(app, &[&show_item, &sync_item, &quit_item])?;
|
||||
|
||||
let mut tray_builder = TrayIconBuilder::with_id("main-tray")
|
||||
.menu(&menu)
|
||||
.tooltip("RomM Companion — Save Sync");
|
||||
|
||||
if let Some(icon) = app.default_window_icon() {
|
||||
tray_builder = tray_builder.icon(icon.clone());
|
||||
}
|
||||
|
||||
tray_builder
|
||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||
"show" => {
|
||||
if let Some(win) = app.get_webview_window("main") {
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
"sync" => {
|
||||
let _ = app.emit("tray:sync-now", ());
|
||||
}
|
||||
"quit" => {
|
||||
app.exit(0);
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.on_tray_icon_event(|tray, event| {
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Up,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
let app = tray.app_handle();
|
||||
if let Some(win) = app.get_webview_window("main") {
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
}
|
||||
}
|
||||
})
|
||||
.build(app)?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
let state = window.state::<AppState>();
|
||||
let minimize = state.config.lock().unwrap().settings.minimize_to_tray;
|
||||
if minimize {
|
||||
let _ = window.hide();
|
||||
api.prevent_close();
|
||||
}
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::get_app_state,
|
||||
commands::test_server,
|
||||
commands::start_device_auth,
|
||||
commands::poll_device_auth,
|
||||
commands::exchange_pair_code,
|
||||
commands::connect_with_token,
|
||||
commands::login_with_password,
|
||||
commands::disconnect,
|
||||
commands::get_emulator_presets,
|
||||
commands::auto_populate_detected_emulators,
|
||||
commands::upsert_emulator_rule,
|
||||
commands::delete_emulator_rule,
|
||||
commands::fetch_platforms,
|
||||
commands::fetch_roms,
|
||||
commands::refresh_rom_cache,
|
||||
commands::scan_local_rom_folder,
|
||||
commands::download_rom_to_folder,
|
||||
commands::download_single_save,
|
||||
commands::download_single_state,
|
||||
commands::upload_single_save,
|
||||
commands::discover_local_saves,
|
||||
commands::link_save_to_rom,
|
||||
commands::unlink_save,
|
||||
commands::fetch_remote_saves_and_states,
|
||||
commands::run_full_sync,
|
||||
commands::resolve_sync_conflict,
|
||||
commands::list_backups,
|
||||
commands::restore_backup,
|
||||
commands::save_settings,
|
||||
commands::clear_sync_logs,
|
||||
commands::restart_watcher,
|
||||
commands::detect_nextui_volumes,
|
||||
commands::inspect_nextui_card,
|
||||
commands::rename_nextui_handheld,
|
||||
commands::sync_nextui_card,
|
||||
commands::download_rom_to_nextui,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running RomM Companion");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
romm_companion_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
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<i64>,
|
||||
pub matched_rom_name: Option<String>,
|
||||
pub matched_platform: Option<String>,
|
||||
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<String>,
|
||||
pub md5: Option<String>,
|
||||
pub sha1: Option<String>,
|
||||
pub matched_rom_id: Option<i64>,
|
||||
pub matched_rom_name: Option<String>,
|
||||
pub matched_platform: Option<String>,
|
||||
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::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn tokenize(norm: &str) -> HashSet<String> {
|
||||
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<String, ManualLink>,
|
||||
) -> Vec<DiscoveredSaveItem> {
|
||||
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::<Vec<_>>()
|
||||
.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<String, ManualLink>,
|
||||
) -> 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<Utc> = m
|
||||
.modified()
|
||||
.map(DateTime::<Utc>::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<std::time::SystemTime> = 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<Utc> = latest.map(DateTime::<Utc>::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<u8>, 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<Vec<u8>, String> {
|
||||
let mut files: Vec<PathBuf> = 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<String>, Option<String>, Option<String>), 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,881 @@
|
||||
use crate::config::{push_log, AppConfig, ManualLink};
|
||||
use crate::matcher::{match_name_to_roms, read_save_payload_and_hash};
|
||||
use crate::romm_api::{ClientSaveState, RommClient, SimpleRomSchema};
|
||||
use crate::sync_engine::{create_backup, write_downloaded_save, SyncConflictItem, SyncRunSummary};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DetectedNextUiVolume {
|
||||
pub path: String,
|
||||
pub label: String,
|
||||
pub detected_platform: String, // "tg5050" | "tg5040" | "nextui"
|
||||
pub device_label: String,
|
||||
pub system_tags: Vec<String>,
|
||||
pub has_saves: bool,
|
||||
pub has_roms: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NextUiSdSaveItem {
|
||||
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<i64>,
|
||||
pub matched_rom_name: Option<String>,
|
||||
pub matched_platform: Option<String>,
|
||||
pub match_confidence: f32,
|
||||
pub match_source: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NextUiCardInspection {
|
||||
pub sd_root: String,
|
||||
pub detected_platform: String,
|
||||
pub device_name: String,
|
||||
pub handheld_device_id: Option<String>,
|
||||
pub system_tags: Vec<String>,
|
||||
pub saves: Vec<NextUiSdSaveItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HandheldDeviceMeta {
|
||||
device_id: Option<String>,
|
||||
device_name: String,
|
||||
}
|
||||
|
||||
fn handheld_meta_path(sd_root: &Path) -> PathBuf {
|
||||
sd_root.join(".userdata/shared/romm-companion/handheld_device.json")
|
||||
}
|
||||
|
||||
pub fn load_handheld_meta(sd_root: &Path, default_name: &str) -> (Option<String>, String) {
|
||||
let p = handheld_meta_path(sd_root);
|
||||
if let Ok(raw) = fs::read_to_string(&p) {
|
||||
if let Ok(meta) = serde_json::from_str::<HandheldDeviceMeta>(&raw) {
|
||||
return (meta.device_id, meta.device_name);
|
||||
}
|
||||
}
|
||||
(None, default_name.to_string())
|
||||
}
|
||||
|
||||
pub fn save_handheld_meta(sd_root: &Path, device_id: Option<String>, device_name: &str) {
|
||||
let p = handheld_meta_path(sd_root);
|
||||
if let Some(parent) = p.parent() {
|
||||
let _ = fs::create_dir_all(parent);
|
||||
}
|
||||
let meta = HandheldDeviceMeta {
|
||||
device_id,
|
||||
device_name: device_name.to_string(),
|
||||
};
|
||||
if let Ok(json) = serde_json::to_string_pretty(&meta) {
|
||||
let _ = fs::write(&p, json);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tag_to_romm_slugs(tag: &str) -> Vec<String> {
|
||||
let list: &[&str] = match tag.trim().to_uppercase().as_str() {
|
||||
"GB" => &["gb"],
|
||||
"GBC" => &["gbc"],
|
||||
"GBA" | "MGBA" | "GPSP" => &["gba"],
|
||||
"FC" | "NES" => &["nes", "famicom"],
|
||||
"SFC" | "SNES" | "SUPA" => &["snes", "sfam"],
|
||||
"N64" => &["n64"],
|
||||
"NDS" | "DS" => &["nds", "ds"],
|
||||
"PS" | "PSX" | "PS1" => &["psx", "ps1", "ps"],
|
||||
"PSP" => &["psp"],
|
||||
"MD" | "GEN" => &["genesis", "md", "megadrive"],
|
||||
"SMS" => &["sms"],
|
||||
"GG" => &["gamegear", "gg"],
|
||||
"SEGACD" | "MCD" | "SCD" => &["segacd"],
|
||||
"32X" => &["sega32x", "32x"],
|
||||
"DC" | "DREAMCAST" => &["dc", "dreamcast"],
|
||||
"SATURN" | "SS" => &["saturn"],
|
||||
"PCE" | "TG16" => &["tg16", "turbografx16", "pce"],
|
||||
"PCECD" | "TGCD" => &["turbografx-cd", "pcecd"],
|
||||
"NGP" | "NGPC" => &["ngp", "ngpc"],
|
||||
"WS" | "WSC" => &["wonderswan", "wonderswan-color"],
|
||||
"PKM" | "POKEMINI" => &["pokemon-mini", "pokemini"],
|
||||
"VB" => &["virtualboy", "vb"],
|
||||
"A2600" | "2600" | "ATARI" => &["atari2600"],
|
||||
"A7800" | "7800" => &["atari7800"],
|
||||
"LYNX" => &["lynx"],
|
||||
"FBN" | "FBNEO" | "ARCADE" | "MAME" | "CPS1" | "CPS2" | "CPS3" => &["arcade", "fbneo"],
|
||||
"NEOGEO" | "NEO" => &["neogeo", "arcade"],
|
||||
"PICO" | "PICO8" => &["pico8"],
|
||||
_ => return vec![tag.to_lowercase()],
|
||||
};
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
pub fn romm_slug_to_default_tag(slug: &str) -> String {
|
||||
match slug.to_lowercase().as_str() {
|
||||
"gb" => "GB",
|
||||
"gbc" => "GBC",
|
||||
"gba" => "GBA",
|
||||
"nes" | "famicom" => "FC",
|
||||
"snes" | "sfam" => "SFC",
|
||||
"n64" => "N64",
|
||||
"nds" | "ds" => "NDS",
|
||||
"psx" | "ps1" | "ps" => "PS",
|
||||
"psp" => "PSP",
|
||||
"genesis" | "md" | "megadrive" => "MD",
|
||||
"sms" => "SMS",
|
||||
"gamegear" | "gg" => "GG",
|
||||
"segacd" => "SEGACD",
|
||||
"sega32x" | "32x" => "32X",
|
||||
"dc" | "dreamcast" => "DC",
|
||||
"saturn" => "SATURN",
|
||||
"tg16" | "turbografx16" | "pce" => "PCE",
|
||||
"ngp" | "ngpc" => "NGPC",
|
||||
"wonderswan" | "wonderswan-color" => "WSC",
|
||||
"virtualboy" | "vb" => "VB",
|
||||
"lynx" => "LYNX",
|
||||
"neogeo" => "NEOGEO",
|
||||
"arcade" | "fbneo" => "FBN",
|
||||
"pico8" => "PICO",
|
||||
other => return other.to_uppercase(),
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn extract_tag_from_rom_folder(name: &str) -> Option<String> {
|
||||
let open = name.rfind('(')?;
|
||||
let close = name.rfind(')')?;
|
||||
if close > open + 1 {
|
||||
let tag = name[open + 1..close].trim();
|
||||
if !tag.is_empty() {
|
||||
return Some(tag.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn detect_platform_on_root(root: &Path) -> (String, String) {
|
||||
if root.join("Tools/tg5050").exists()
|
||||
|| root.join("Emus/tg5050").exists()
|
||||
|| root.join(".userdata/tg5050").exists()
|
||||
{
|
||||
(
|
||||
"tg5050".to_string(),
|
||||
"TrimUI Smart Pro S (NextUI USB)".to_string(),
|
||||
)
|
||||
} else if root.join("Tools/tg5040").exists()
|
||||
|| root.join("Emus/tg5040").exists()
|
||||
|| root.join(".userdata/tg5040").exists()
|
||||
{
|
||||
(
|
||||
"tg5040".to_string(),
|
||||
"TrimUI Brick / Smart Pro (NextUI USB)".to_string(),
|
||||
)
|
||||
} else {
|
||||
("nextui".to_string(), "NextUI Handheld (USB)".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_system_tags(root: &Path) -> Vec<String> {
|
||||
let mut tags: Vec<String> = Vec::new();
|
||||
if let Ok(entries) = fs::read_dir(root.join("Saves")) {
|
||||
for e in entries.flatten() {
|
||||
if e.path().is_dir() {
|
||||
let n = e.file_name().to_string_lossy().to_string();
|
||||
if !n.starts_with('.') && !tags.iter().any(|t| t.eq_ignore_ascii_case(&n)) {
|
||||
tags.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(entries) = fs::read_dir(root.join("Roms")) {
|
||||
for e in entries.flatten() {
|
||||
if e.path().is_dir() {
|
||||
let n = e.file_name().to_string_lossy().to_string();
|
||||
if let Some(tag) = extract_tag_from_rom_folder(&n) {
|
||||
if !tags.iter().any(|t| t.eq_ignore_ascii_case(&tag)) {
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
tags.sort();
|
||||
tags
|
||||
}
|
||||
|
||||
fn is_likely_nextui_root(root: &Path) -> bool {
|
||||
let has_saves = root.join("Saves").is_dir();
|
||||
let has_roms = root.join("Roms").is_dir();
|
||||
if !has_saves && !has_roms {
|
||||
return false;
|
||||
}
|
||||
let has_markers = root.join(".userdata").is_dir()
|
||||
|| root.join("Tools/tg5040").is_dir()
|
||||
|| root.join("Tools/tg5050").is_dir()
|
||||
|| root.join("Emus/tg5040").is_dir()
|
||||
|| root.join("Emus/tg5050").is_dir()
|
||||
|| root.join("Bios").is_dir();
|
||||
if has_markers {
|
||||
return true;
|
||||
}
|
||||
// Check for NextUI-style `System (TAG)` folder inside Roms/
|
||||
if has_roms {
|
||||
if let Ok(entries) = fs::read_dir(root.join("Roms")) {
|
||||
for e in entries.flatten() {
|
||||
if e.path().is_dir()
|
||||
&& extract_tag_from_rom_folder(&e.file_name().to_string_lossy()).is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Scans mounted removable volumes on macOS, Linux, and Windows for NextUI SD cards.
|
||||
pub fn detect_nextui_volumes() -> Vec<DetectedNextUiVolume> {
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
if let Ok(entries) = fs::read_dir("/Volumes") {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
candidates.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let user = std::env::var("USER").unwrap_or_default();
|
||||
for base in [
|
||||
PathBuf::from("/mnt"),
|
||||
PathBuf::from(format!("/media/{}", user)),
|
||||
PathBuf::from(format!("/run/media/{}", user)),
|
||||
] {
|
||||
if let Ok(entries) = fs::read_dir(base) {
|
||||
for e in entries.flatten() {
|
||||
if e.path().is_dir() {
|
||||
candidates.push(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
for letter in b'D'..=b'Z' {
|
||||
let p = PathBuf::from(format!("{}:\\", letter as char));
|
||||
if p.exists() {
|
||||
candidates.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut found = Vec::new();
|
||||
for root in candidates {
|
||||
if !is_likely_nextui_root(&root) {
|
||||
continue;
|
||||
}
|
||||
let (platform, device_label) = detect_platform_on_root(&root);
|
||||
let label = root
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| root.to_string_lossy().to_string());
|
||||
found.push(DetectedNextUiVolume {
|
||||
path: root.to_string_lossy().to_string(),
|
||||
label,
|
||||
detected_platform: platform,
|
||||
device_label,
|
||||
system_tags: collect_system_tags(&root),
|
||||
has_saves: root.join("Saves").is_dir(),
|
||||
has_roms: root.join("Roms").is_dir(),
|
||||
});
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Classifies a file inside `<sd_root>/Saves/<TAG>/` as Save vs Save State and returns `(is_state, clean_stem)`.
|
||||
pub fn classify_nextui_save_file(path: &Path) -> Option<(bool, String)> {
|
||||
let file_name = path.file_name()?.to_str()?;
|
||||
if file_name.starts_with('.') || file_name.ends_with(".romm_part") {
|
||||
return None;
|
||||
}
|
||||
let lower = file_name.to_lowercase();
|
||||
if lower.ends_with(".png")
|
||||
|| lower.ends_with(".jpg")
|
||||
|| lower.ends_with(".txt")
|
||||
|| lower.ends_with(".json")
|
||||
|| lower.ends_with(".cfg")
|
||||
|| lower.ends_with(".auto")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let (is_state, without_save_ext) = if let Some(idx) = lower.rfind(".state") {
|
||||
(true, &file_name[..idx])
|
||||
} else if lower.ends_with(".ppst") {
|
||||
(true, &file_name[..file_name.len() - 5])
|
||||
} else if let Some(dot) = lower.rfind('.') {
|
||||
let ext = &lower[dot + 1..];
|
||||
if (ext.starts_with("st") || ext.starts_with("ss"))
|
||||
&& ext.len() <= 4
|
||||
&& ext.len() > 2
|
||||
&& ext[2..].chars().all(|c| c.is_ascii_digit())
|
||||
{
|
||||
(true, &file_name[..dot])
|
||||
} else if matches!(
|
||||
ext,
|
||||
"sav" | "srm" | "mcr" | "mcd" | "dsv" | "eep" | "fla" | "mpk" | "vmu" | "bin" | "rtc" | "brm"
|
||||
) {
|
||||
(false, &file_name[..dot])
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let rom_exts = [
|
||||
".gba", ".gbc", ".gb", ".nes", ".sfc", ".smc", ".n64", ".z64", ".v64", ".nds", ".iso",
|
||||
".chd", ".pbp", ".cue", ".bin", ".cso", ".md", ".gen", ".sms", ".gg", ".pce", ".ngp",
|
||||
".ngc", ".ws", ".wsc", ".zip", ".7z", ".min", ".vb", ".lnx", ".a26", ".a78",
|
||||
];
|
||||
let mut stem = without_save_ext.to_string();
|
||||
let stem_lower = stem.to_lowercase();
|
||||
for rext in rom_exts {
|
||||
if stem_lower.ends_with(rext) {
|
||||
stem.truncate(stem.len() - rext.len());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Some((is_state, stem))
|
||||
}
|
||||
|
||||
pub fn inspect_nextui_card(
|
||||
sd_root: &Path,
|
||||
roms: &[SimpleRomSchema],
|
||||
manual_links: &HashMap<String, ManualLink>,
|
||||
) -> NextUiCardInspection {
|
||||
let (platform, default_name) = detect_platform_on_root(sd_root);
|
||||
let (handheld_device_id, device_name) = load_handheld_meta(sd_root, &default_name);
|
||||
let system_tags = collect_system_tags(sd_root);
|
||||
let saves = discover_saves_on_card(sd_root, roms, manual_links);
|
||||
|
||||
NextUiCardInspection {
|
||||
sd_root: sd_root.to_string_lossy().to_string(),
|
||||
detected_platform: platform,
|
||||
device_name,
|
||||
handheld_device_id,
|
||||
system_tags,
|
||||
saves,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn discover_saves_on_card(
|
||||
sd_root: &Path,
|
||||
roms: &[SimpleRomSchema],
|
||||
manual_links: &HashMap<String, ManualLink>,
|
||||
) -> Vec<NextUiSdSaveItem> {
|
||||
let saves_root = sd_root.join("Saves");
|
||||
if !saves_root.is_dir() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
let Ok(tag_dirs) = fs::read_dir(&saves_root) else {
|
||||
return out;
|
||||
};
|
||||
|
||||
for tag_entry in tag_dirs.flatten() {
|
||||
let tag_path = tag_entry.path();
|
||||
if !tag_path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let tag = tag_entry.file_name().to_string_lossy().to_string();
|
||||
if tag.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let slugs = tag_to_romm_slugs(&tag);
|
||||
|
||||
// Handle PSP folder saves under /Saves/PSP/PSP/SAVEDATA/
|
||||
if tag.eq_ignore_ascii_case("PSP") {
|
||||
let psp_dir = tag_path.join("PSP/SAVEDATA");
|
||||
if psp_dir.is_dir() {
|
||||
if let Ok(entries) = fs::read_dir(&psp_dir) {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if !p.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let (size, updated) = dir_size_and_mtime(&p);
|
||||
if size == 0 {
|
||||
continue;
|
||||
}
|
||||
out.push(build_sd_item(
|
||||
&p,
|
||||
format!("{}.zip", name),
|
||||
&name,
|
||||
&tag,
|
||||
&slugs,
|
||||
true,
|
||||
false,
|
||||
size,
|
||||
updated,
|
||||
roms,
|
||||
manual_links,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for entry in WalkDir::new(&tag_path).max_depth(2).into_iter().flatten() {
|
||||
let p = entry.path();
|
||||
if !p.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Some((is_state, stem)) = classify_nextui_save_file(p) else {
|
||||
continue;
|
||||
};
|
||||
let file_name = p
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let (size, updated) = file_size_and_mtime(p);
|
||||
out.push(build_sd_item(
|
||||
p,
|
||||
file_name,
|
||||
&stem,
|
||||
&tag,
|
||||
&slugs,
|
||||
false,
|
||||
is_state,
|
||||
size,
|
||||
updated,
|
||||
roms,
|
||||
manual_links,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_sd_item(
|
||||
path: &Path,
|
||||
file_name: String,
|
||||
stem: &str,
|
||||
tag: &str,
|
||||
slugs: &[String],
|
||||
is_directory: bool,
|
||||
is_state: bool,
|
||||
size_bytes: u64,
|
||||
updated_at: String,
|
||||
roms: &[SimpleRomSchema],
|
||||
manual_links: &HashMap<String, ManualLink>,
|
||||
) -> NextUiSdSaveItem {
|
||||
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 NextUiSdSaveItem {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: 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_name_to_roms(stem, slugs, roms) {
|
||||
NextUiSdSaveItem {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: tag.to_string(),
|
||||
is_directory,
|
||||
is_state,
|
||||
size_bytes,
|
||||
updated_at,
|
||||
slot: "default".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 {
|
||||
NextUiSdSaveItem {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: tag.to_string(),
|
||||
is_directory,
|
||||
is_state,
|
||||
size_bytes,
|
||||
updated_at,
|
||||
slot: "default".to_string(),
|
||||
matched_rom_id: None,
|
||||
matched_rom_name: None,
|
||||
matched_platform: None,
|
||||
match_confidence: 0.0,
|
||||
match_source: "unmatched".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the target `/Roms/<System> (<TAG>)/` directory on the NextUI SD card for a RomM platform.
|
||||
pub fn resolve_nextui_rom_folder(
|
||||
sd_root: &Path,
|
||||
platform_slug: &str,
|
||||
platform_display_name: &str,
|
||||
) -> PathBuf {
|
||||
let roms_root = sd_root.join("Roms");
|
||||
if let Ok(entries) = fs::read_dir(&roms_root) {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
if !p.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if let Some(tag) = extract_tag_from_rom_folder(&name) {
|
||||
let slugs = tag_to_romm_slugs(&tag);
|
||||
if slugs.iter().any(|s| s.eq_ignore_ascii_case(platform_slug)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let tag = romm_slug_to_default_tag(platform_slug);
|
||||
let safe_name = platform_display_name.replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|'], "");
|
||||
roms_root.join(format!("{} ({})", safe_name.trim(), tag))
|
||||
}
|
||||
|
||||
/// Runs a full two-way RomM 5.1.0 save + state sync for a mounted NextUI SD card.
|
||||
pub async fn sync_nextui_card(
|
||||
client: &RommClient,
|
||||
cfg: &mut AppConfig,
|
||||
roms: &[SimpleRomSchema],
|
||||
sd_root: &Path,
|
||||
sync_states: bool,
|
||||
) -> Result<SyncRunSummary, String> {
|
||||
let (_, default_name) = detect_platform_on_root(sd_root);
|
||||
let (mut handheld_device_id, device_name) = load_handheld_meta(sd_root, &default_name);
|
||||
|
||||
// Register a dedicated RomM device for this handheld SD card if not registered yet
|
||||
if handheld_device_id.is_none() {
|
||||
if let Ok(dev) = client.register_device(&device_name).await {
|
||||
handheld_device_id = Some(dev.id.clone());
|
||||
save_handheld_meta(sd_root, Some(dev.id), &device_name);
|
||||
}
|
||||
}
|
||||
|
||||
let effective_device_id = handheld_device_id.or_else(|| cfg.connection.device_id.clone());
|
||||
let discovered = discover_saves_on_card(sd_root, roms, &cfg.manual_links);
|
||||
let rom_by_id: HashMap<i64, &SimpleRomSchema> = roms.iter().map(|r| (r.id, r)).collect();
|
||||
|
||||
let mut summary = SyncRunSummary {
|
||||
session_id: None,
|
||||
uploaded_saves: 0,
|
||||
downloaded_saves: 0,
|
||||
uploaded_states: 0,
|
||||
up_to_date: 0,
|
||||
conflicts: Vec::new(),
|
||||
errors: Vec::new(),
|
||||
};
|
||||
|
||||
let matched_saves: Vec<&NextUiSdSaveItem> = discovered
|
||||
.iter()
|
||||
.filter(|d| !d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
let matched_states: Vec<&NextUiSdSaveItem> = discovered
|
||||
.iter()
|
||||
.filter(|d| d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
|
||||
let mut local_map: HashMap<(i64, String), (&NextUiSdSaveItem, Vec<u8>)> = HashMap::new();
|
||||
let mut client_states: Vec<ClientSaveState> = Vec::new();
|
||||
|
||||
for item in matched_saves {
|
||||
let Some(rom_id) = item.matched_rom_id else {
|
||||
continue;
|
||||
};
|
||||
match read_save_payload_and_hash(Path::new(&item.local_path), item.is_directory) {
|
||||
Ok((bytes, hash)) => {
|
||||
let slot = if item.slot.trim().is_empty() {
|
||||
"default".to_string()
|
||||
} else {
|
||||
item.slot.clone()
|
||||
};
|
||||
client_states.push(ClientSaveState {
|
||||
rom_id,
|
||||
file_name: item.file_name.clone(),
|
||||
slot: Some(slot.clone()),
|
||||
emulator: Some(format!("nextui-{}", item.system_tag.to_lowercase())),
|
||||
content_hash: Some(hash),
|
||||
updated_at: item.updated_at.clone(),
|
||||
file_size_bytes: bytes.len() as i64,
|
||||
});
|
||||
local_map.insert((rom_id, slot), (item, bytes));
|
||||
}
|
||||
Err(e) => summary.errors.push(format!("{}: {}", item.file_name, e)),
|
||||
}
|
||||
}
|
||||
|
||||
if !client_states.is_empty() || effective_device_id.is_some() {
|
||||
let neg = client
|
||||
.negotiate_sync(effective_device_id.clone(), client_states)
|
||||
.await?;
|
||||
summary.session_id = Some(neg.session_id);
|
||||
let mut completed = 0i64;
|
||||
let mut failed = 0i64;
|
||||
|
||||
for op in neg.operations {
|
||||
let slot_key = op.slot.clone().unwrap_or_else(|| "default".to_string());
|
||||
match op.action.as_str() {
|
||||
"no_op" => summary.up_to_date += 1,
|
||||
"upload" => {
|
||||
if let Some((item, bytes)) = local_map.get(&(op.rom_id, slot_key.clone())) {
|
||||
let emu_id = format!("nextui-{}", item.system_tag.to_lowercase());
|
||||
match client
|
||||
.upload_save(
|
||||
op.rom_id,
|
||||
Some(&emu_id),
|
||||
Some(&slot_key),
|
||||
effective_device_id.as_deref(),
|
||||
Some(neg.session_id),
|
||||
true,
|
||||
&item.file_name,
|
||||
bytes.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
summary.uploaded_saves += 1;
|
||||
completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"nextui_upload",
|
||||
format!("[NextUI USB] Uploaded {} ({})", item.file_name, item.system_tag),
|
||||
Some(op.rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
summary.errors.push(format!("Upload {}: {}", item.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"download" => {
|
||||
let Some(save_id) = op.save_id else {
|
||||
continue;
|
||||
};
|
||||
let target = local_map
|
||||
.get(&(op.rom_id, slot_key.clone()))
|
||||
.map(|(item, _)| (PathBuf::from(&item.local_path), item.is_directory))
|
||||
.or_else(|| {
|
||||
rom_by_id.get(&op.rom_id).map(|rom| {
|
||||
let tag = romm_slug_to_default_tag(&rom.platform_slug);
|
||||
let is_dir = tag == "PSP" && op.file_name.ends_with(".zip");
|
||||
let name = if is_dir {
|
||||
op.file_name
|
||||
.strip_suffix(".zip")
|
||||
.unwrap_or(&op.file_name)
|
||||
.to_string()
|
||||
} else {
|
||||
op.file_name.clone()
|
||||
};
|
||||
(sd_root.join("Saves").join(tag).join(name), is_dir)
|
||||
})
|
||||
});
|
||||
|
||||
if let Some((dest_path, is_dir)) = target {
|
||||
match client
|
||||
.download_save_bytes(
|
||||
save_id,
|
||||
effective_device_id.as_deref(),
|
||||
Some(neg.session_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(bytes) => {
|
||||
let _ = create_backup(
|
||||
&dest_path,
|
||||
op.rom_id,
|
||||
is_dir,
|
||||
cfg.settings.max_backups_per_save,
|
||||
);
|
||||
match write_downloaded_save(&dest_path, &bytes, is_dir) {
|
||||
Ok(()) => {
|
||||
if let Some(ref did) = effective_device_id {
|
||||
let _ = client
|
||||
.confirm_save_downloaded(save_id, did)
|
||||
.await;
|
||||
}
|
||||
summary.downloaded_saves += 1;
|
||||
completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"nextui_download",
|
||||
format!("[NextUI USB] Downloaded {} to SD card (backup saved)", op.file_name),
|
||||
Some(op.rom_id),
|
||||
Some(dest_path.to_string_lossy().to_string()),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
summary.errors.push(format!("Write {}: {}", op.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
summary.errors.push(format!("Download {}: {}", op.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"conflict" => {
|
||||
if let Some((item, _)) = local_map.get(&(op.rom_id, slot_key.clone())) {
|
||||
summary.conflicts.push(SyncConflictItem {
|
||||
id: format!("nextui:{}:{}:{}", op.rom_id, slot_key, op.save_id.unwrap_or(0)),
|
||||
rom_id: op.rom_id,
|
||||
rom_name: item
|
||||
.matched_rom_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("ROM #{}", op.rom_id)),
|
||||
save_id: op.save_id,
|
||||
local_path: item.local_path.clone(),
|
||||
file_name: item.file_name.clone(),
|
||||
is_directory: item.is_directory,
|
||||
emulator_id: format!("nextui-{}", item.system_tag.to_lowercase()),
|
||||
slot: slot_key,
|
||||
local_updated_at: item.updated_at.clone(),
|
||||
server_updated_at: op.server_updated_at.clone(),
|
||||
reason: format!("[NextUI SD] {}", op.reason),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = client
|
||||
.complete_sync_session(neg.session_id, completed, failed)
|
||||
.await;
|
||||
}
|
||||
|
||||
if sync_states {
|
||||
for item in matched_states {
|
||||
let Some(rom_id) = item.matched_rom_id else {
|
||||
continue;
|
||||
};
|
||||
match read_save_payload_and_hash(Path::new(&item.local_path), false) {
|
||||
Ok((bytes, hash)) => {
|
||||
if cfg.synced_state_hashes.get(&item.local_path) == Some(&hash) {
|
||||
summary.up_to_date += 1;
|
||||
continue;
|
||||
}
|
||||
let existing = client
|
||||
.get_states(Some(rom_id), None)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
|
||||
let emu_id = format!("nextui-{}", item.system_tag.to_lowercase());
|
||||
let res = if let Some(remote) = existing {
|
||||
client.update_state(remote.id, &item.file_name, bytes).await
|
||||
} else {
|
||||
client
|
||||
.upload_state(rom_id, Some(&emu_id), &item.file_name, bytes)
|
||||
.await
|
||||
};
|
||||
match res {
|
||||
Ok(_) => {
|
||||
cfg.synced_state_hashes.insert(item.local_path.clone(), hash);
|
||||
summary.uploaded_states += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"nextui_state",
|
||||
format!("[NextUI USB] Synced state {} ({})", item.file_name, item.system_tag),
|
||||
Some(rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
}
|
||||
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
|
||||
}
|
||||
}
|
||||
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
fn file_size_and_mtime(path: &Path) -> (u64, String) {
|
||||
match fs::metadata(path) {
|
||||
Ok(m) => {
|
||||
let dt: DateTime<Utc> = m
|
||||
.modified()
|
||||
.map(DateTime::<Utc>::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<std::time::SystemTime> = 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<Utc> = latest.map(DateTime::<Utc>::from).unwrap_or_else(Utc::now);
|
||||
(total, dt.to_rfc3339())
|
||||
}
|
||||
@@ -0,0 +1,835 @@
|
||||
use futures_util::StreamExt;
|
||||
use reqwest::multipart::{Form, Part};
|
||||
use reqwest::{Client, Method, RequestBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RommClient {
|
||||
http: Client,
|
||||
base_url: String,
|
||||
token: Option<String>,
|
||||
}
|
||||
|
||||
// ---------- Auth Schemas (RomM 5.1.0) ----------
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeviceAuthInitPayload {
|
||||
pub client_device_identifier: String,
|
||||
pub name: String,
|
||||
pub client: String,
|
||||
pub platform: Option<String>,
|
||||
pub client_version: Option<String>,
|
||||
pub requested_scopes: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DeviceAuthInitResponse {
|
||||
pub device_code: String,
|
||||
pub user_code: String,
|
||||
pub verification_path: String,
|
||||
pub verification_path_complete: String,
|
||||
pub expires_in: i64,
|
||||
pub interval: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeviceAuthTokenPayload {
|
||||
pub device_code: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DeviceAuthTokenResponse {
|
||||
pub access_token: String,
|
||||
pub device_id: String,
|
||||
pub scopes: Vec<String>,
|
||||
pub expires_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TokenResponse {
|
||||
pub access_token: String,
|
||||
pub token_type: String,
|
||||
pub expires: Option<i64>,
|
||||
pub refresh_token: Option<String>,
|
||||
pub refresh_expires: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClientTokenCreateSchema {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub scopes: Vec<String>,
|
||||
pub expires_at: Option<String>,
|
||||
pub device_id: Option<String>,
|
||||
pub raw_token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UserSchema {
|
||||
pub id: i64,
|
||||
pub username: String,
|
||||
pub email: Option<String>,
|
||||
pub role: Option<serde_json::Value>,
|
||||
pub current_device_id: Option<String>,
|
||||
}
|
||||
|
||||
// ---------- Device Schemas ----------
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeviceCreatePayload {
|
||||
pub name: Option<String>,
|
||||
pub platform: Option<String>,
|
||||
pub client: Option<String>,
|
||||
pub client_version: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub sync_mode: Option<String>,
|
||||
pub allow_existing: bool,
|
||||
pub allow_duplicate: bool,
|
||||
pub reset_syncs: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DeviceSchema {
|
||||
pub id: String,
|
||||
pub user_id: i64,
|
||||
pub name: Option<String>,
|
||||
pub platform: Option<String>,
|
||||
pub client: Option<String>,
|
||||
pub client_version: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
pub sync_enabled: Option<bool>,
|
||||
pub sync_mode: Option<String>,
|
||||
}
|
||||
|
||||
// ---------- Platform & ROM Schemas ----------
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PlatformSchema {
|
||||
pub id: i64,
|
||||
pub slug: String,
|
||||
pub fs_slug: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
pub rom_count: i64,
|
||||
pub url_logo: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RomFileSchema {
|
||||
pub id: i64,
|
||||
pub rom_id: i64,
|
||||
pub file_name: String,
|
||||
pub file_path: String,
|
||||
pub file_size_bytes: i64,
|
||||
pub full_path: String,
|
||||
pub crc_hash: Option<String>,
|
||||
pub md5_hash: Option<String>,
|
||||
pub sha1_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SimpleRomSchema {
|
||||
pub id: i64,
|
||||
pub platform_id: i64,
|
||||
pub platform_slug: String,
|
||||
pub platform_fs_slug: String,
|
||||
pub platform_display_name: String,
|
||||
pub fs_name: String,
|
||||
pub fs_name_no_tags: String,
|
||||
pub fs_name_no_ext: String,
|
||||
pub fs_extension: String,
|
||||
pub fs_size_bytes: i64,
|
||||
pub name: Option<String>,
|
||||
pub slug: Option<String>,
|
||||
pub path_cover_small: Option<String>,
|
||||
pub url_cover: Option<String>,
|
||||
pub crc_hash: Option<String>,
|
||||
pub md5_hash: Option<String>,
|
||||
pub sha1_hash: Option<String>,
|
||||
pub ra_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub regions: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub files: Vec<RomFileSchema>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RomPageResponse {
|
||||
pub items: Vec<SimpleRomSchema>,
|
||||
pub total: i64,
|
||||
pub limit: i64,
|
||||
pub offset: i64,
|
||||
}
|
||||
|
||||
// ---------- Save, State & Sync Negotiation Schemas (RomM 5.1.0) ----------
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SaveSchema {
|
||||
pub id: i64,
|
||||
pub rom_id: i64,
|
||||
pub user_id: i64,
|
||||
pub file_name: String,
|
||||
pub file_name_no_tags: String,
|
||||
pub file_name_no_ext: String,
|
||||
pub file_extension: String,
|
||||
pub file_size_bytes: i64,
|
||||
pub download_path: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub emulator: Option<String>,
|
||||
pub slot: Option<String>,
|
||||
pub content_hash: Option<String>,
|
||||
pub origin_device_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StateSchema {
|
||||
pub id: i64,
|
||||
pub rom_id: i64,
|
||||
pub user_id: i64,
|
||||
pub file_name: String,
|
||||
pub file_name_no_tags: String,
|
||||
pub file_name_no_ext: String,
|
||||
pub file_extension: String,
|
||||
pub file_size_bytes: i64,
|
||||
pub download_path: String,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub emulator: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClientSaveState {
|
||||
pub rom_id: i64,
|
||||
pub file_name: String,
|
||||
pub slot: Option<String>,
|
||||
pub emulator: Option<String>,
|
||||
pub content_hash: Option<String>,
|
||||
pub updated_at: String,
|
||||
pub file_size_bytes: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SyncNegotiatePayload {
|
||||
pub device_id: Option<String>,
|
||||
pub saves: Vec<ClientSaveState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SyncOperationSchema {
|
||||
pub action: String, // "upload" | "download" | "conflict" | "no_op"
|
||||
pub rom_id: i64,
|
||||
pub save_id: Option<i64>,
|
||||
pub file_name: String,
|
||||
pub slot: Option<String>,
|
||||
pub emulator: Option<String>,
|
||||
pub reason: String,
|
||||
pub server_updated_at: Option<String>,
|
||||
pub server_content_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SyncNegotiateResponse {
|
||||
pub session_id: i64,
|
||||
pub operations: Vec<SyncOperationSchema>,
|
||||
pub total_upload: i64,
|
||||
pub total_download: i64,
|
||||
pub total_conflict: i64,
|
||||
pub total_no_op: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct SyncCompletePayload {
|
||||
pub operations_completed: i64,
|
||||
pub operations_failed: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct ConfirmDownloadPayload {
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PairExchangePayload {
|
||||
code: String,
|
||||
}
|
||||
|
||||
impl RommClient {
|
||||
pub fn new(base_url: &str, token: Option<String>) -> Result<Self, String> {
|
||||
let normalized = base_url.trim().trim_end_matches('/').to_string();
|
||||
if normalized.is_empty() {
|
||||
return Err("RomM server URL is required".into());
|
||||
}
|
||||
let http = Client::builder()
|
||||
.user_agent("RomM-Companion/0.1.0")
|
||||
.build()
|
||||
.map_err(|e| format!("Failed to create HTTP client: {e}"))?;
|
||||
Ok(Self {
|
||||
http,
|
||||
base_url: normalized,
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn base_url(&self) -> &str {
|
||||
&self.base_url
|
||||
}
|
||||
|
||||
fn request(&self, method: Method, path: &str) -> RequestBuilder {
|
||||
let url = format!("{}{}", self.base_url, path);
|
||||
let mut req = self.http.request(method, url);
|
||||
if let Some(ref token) = self.token {
|
||||
req = req.bearer_auth(token);
|
||||
}
|
||||
req
|
||||
}
|
||||
|
||||
async fn parse_json<T: for<'de> Deserialize<'de>>(
|
||||
resp: reqwest::Response,
|
||||
) -> Result<T, String> {
|
||||
let status = resp.status();
|
||||
let text = resp
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to read response body: {e}"))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("HTTP {}: {}", status.as_u16(), text));
|
||||
}
|
||||
serde_json::from_str(&text)
|
||||
.map_err(|e| format!("Failed to parse JSON ({}): {}", e, &text[..text.len().min(300)]))
|
||||
}
|
||||
|
||||
// ---------- Auth ----------
|
||||
|
||||
pub async fn heartbeat(&self) -> Result<serde_json::Value, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, "/api/heartbeat")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Could not reach RomM server: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn get_me(&self) -> Result<UserSchema, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, "/api/users/me")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Request failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn device_auth_init(
|
||||
&self,
|
||||
client_device_identifier: &str,
|
||||
device_name: &str,
|
||||
) -> Result<DeviceAuthInitResponse, String> {
|
||||
let payload = DeviceAuthInitPayload {
|
||||
client_device_identifier: client_device_identifier.to_string(),
|
||||
name: device_name.to_string(),
|
||||
client: "romm-companion".to_string(),
|
||||
platform: Some(std::env::consts::OS.to_string()),
|
||||
client_version: Some("0.1.0".to_string()),
|
||||
requested_scopes: vec![
|
||||
"me.read".into(),
|
||||
"roms.read".into(),
|
||||
"platforms.read".into(),
|
||||
"assets.read".into(),
|
||||
"assets.write".into(),
|
||||
"devices.read".into(),
|
||||
"devices.write".into(),
|
||||
"roms.user.read".into(),
|
||||
"roms.user.write".into(),
|
||||
],
|
||||
};
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/auth/device/init")
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Device auth init failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn device_auth_poll(
|
||||
&self,
|
||||
device_code: &str,
|
||||
) -> Result<Option<DeviceAuthTokenResponse>, String> {
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/auth/device/token")
|
||||
.json(&DeviceAuthTokenPayload {
|
||||
device_code: device_code.to_string(),
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Device auth poll failed: {e}"))?;
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.map_err(|e| e.to_string())?;
|
||||
if status.is_success() {
|
||||
let parsed: DeviceAuthTokenResponse =
|
||||
serde_json::from_str(&text).map_err(|e| format!("Parse error: {e}"))?;
|
||||
return Ok(Some(parsed));
|
||||
}
|
||||
// Pending approval typically returns 400/428/403 with authorization_pending
|
||||
if status.as_u16() == 400 || status.as_u16() == 428 || status.as_u16() == 202 {
|
||||
if text.contains("pending") || text.contains("slow_down") {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
Err(format!("HTTP {}: {}", status.as_u16(), text))
|
||||
}
|
||||
|
||||
pub async fn exchange_pair_code(&self, code: &str) -> Result<ClientTokenCreateSchema, String> {
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/client-tokens/exchange")
|
||||
.json(&PairExchangePayload {
|
||||
code: code.trim().to_string(),
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Pair code exchange failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn login_password(
|
||||
&self,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<TokenResponse, String> {
|
||||
let scopes = "me.read roms.read platforms.read assets.read assets.write devices.read devices.write roms.user.read roms.user.write";
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/token")
|
||||
.form(&[
|
||||
("grant_type", "password"),
|
||||
("username", username),
|
||||
("password", password),
|
||||
("scope", scopes),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Login request failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
// ---------- Devices ----------
|
||||
|
||||
pub async fn register_device(&self, name: &str) -> Result<DeviceSchema, String> {
|
||||
let host = hostname::get()
|
||||
.ok()
|
||||
.and_then(|h| h.into_string().ok());
|
||||
let payload = DeviceCreatePayload {
|
||||
name: Some(name.to_string()),
|
||||
platform: Some(std::env::consts::OS.to_string()),
|
||||
client: Some("romm-companion".to_string()),
|
||||
client_version: Some("0.1.0".to_string()),
|
||||
hostname: host,
|
||||
sync_mode: Some("api".to_string()),
|
||||
allow_existing: true,
|
||||
allow_duplicate: false,
|
||||
reset_syncs: false,
|
||||
};
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/devices")
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Register device failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
// ---------- Platforms & ROMs ----------
|
||||
|
||||
pub async fn get_platforms(&self) -> Result<Vec<PlatformSchema>, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, "/api/platforms")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Get platforms failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn get_roms(
|
||||
&self,
|
||||
platform_id: Option<i64>,
|
||||
search_term: Option<&str>,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<RomPageResponse, String> {
|
||||
let mut req = self.request(Method::GET, "/api/roms").query(&[
|
||||
("limit", limit.to_string()),
|
||||
("offset", offset.to_string()),
|
||||
("with_files", "true".to_string()),
|
||||
]);
|
||||
if let Some(pid) = platform_id {
|
||||
req = req.query(&[("platform_ids", pid.to_string())]);
|
||||
}
|
||||
if let Some(term) = search_term {
|
||||
if !term.trim().is_empty() {
|
||||
req = req.query(&[("search_term", term.trim().to_string())]);
|
||||
}
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Get ROMs failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn get_all_roms_for_platforms(
|
||||
&self,
|
||||
platform_ids: &[i64],
|
||||
) -> Result<Vec<SimpleRomSchema>, String> {
|
||||
let mut all = Vec::new();
|
||||
if platform_ids.is_empty() {
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self.get_roms(None, None, 200, offset).await?;
|
||||
let count = page.items.len() as i64;
|
||||
all.extend(page.items);
|
||||
offset += count;
|
||||
if count == 0 || offset >= page.total {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for &pid in platform_ids {
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self.get_roms(Some(pid), None, 200, offset).await?;
|
||||
let count = page.items.len() as i64;
|
||||
all.extend(page.items);
|
||||
offset += count;
|
||||
if count == 0 || offset >= page.total {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
pub async fn get_rom_by_hash(
|
||||
&self,
|
||||
crc_hash: Option<&str>,
|
||||
md5_hash: Option<&str>,
|
||||
sha1_hash: Option<&str>,
|
||||
) -> Result<Option<SimpleRomSchema>, String> {
|
||||
let mut req = self.request(Method::GET, "/api/roms/by-hash");
|
||||
if let Some(h) = crc_hash {
|
||||
req = req.query(&[("crc_hash", h)]);
|
||||
}
|
||||
if let Some(h) = md5_hash {
|
||||
req = req.query(&[("md5_hash", h)]);
|
||||
}
|
||||
if let Some(h) = sha1_hash {
|
||||
req = req.query(&[("sha1_hash", h)]);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Hash lookup failed: {e}"))?;
|
||||
if resp.status().as_u16() == 404 {
|
||||
return Ok(None);
|
||||
}
|
||||
let rom: SimpleRomSchema = Self::parse_json(resp).await?;
|
||||
Ok(Some(rom))
|
||||
}
|
||||
|
||||
pub async fn download_rom(
|
||||
&self,
|
||||
rom_id: i64,
|
||||
file_name: &str,
|
||||
dest_path: &Path,
|
||||
mut on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<(), String> {
|
||||
let encoded = urlencoding_path_segment(file_name);
|
||||
let path = format!("/api/roms/{}/content/{}", rom_id, encoded);
|
||||
let resp = self
|
||||
.request(Method::GET, &path)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("ROM download request failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("ROM download failed with HTTP {}", resp.status()));
|
||||
}
|
||||
let total = resp.content_length();
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create destination folder: {e}"))?;
|
||||
}
|
||||
let tmp_path = dest_path.with_extension("romm_part");
|
||||
let mut file = tokio::fs::File::create(&tmp_path)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create file: {e}"))?;
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut downloaded: u64 = 0;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let bytes = chunk.map_err(|e| format!("Download stream error: {e}"))?;
|
||||
file.write_all(&bytes)
|
||||
.await
|
||||
.map_err(|e| format!("Disk write error: {e}"))?;
|
||||
downloaded += bytes.len() as u64;
|
||||
on_progress(downloaded, total);
|
||||
}
|
||||
file.flush().await.map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
tokio::fs::rename(&tmp_path, dest_path)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to finalize downloaded ROM: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------- Saves & Sync Negotiation ----------
|
||||
|
||||
pub async fn get_saves(
|
||||
&self,
|
||||
rom_id: Option<i64>,
|
||||
platform_id: Option<i64>,
|
||||
device_id: Option<&str>,
|
||||
) -> Result<Vec<SaveSchema>, String> {
|
||||
let mut req = self.request(Method::GET, "/api/saves");
|
||||
if let Some(id) = rom_id {
|
||||
req = req.query(&[("rom_id", id.to_string())]);
|
||||
}
|
||||
if let Some(pid) = platform_id {
|
||||
req = req.query(&[("platform_id", pid.to_string())]);
|
||||
}
|
||||
if let Some(did) = device_id {
|
||||
req = req.query(&[("device_id", did.to_string())]);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Get saves failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn negotiate_sync(
|
||||
&self,
|
||||
device_id: Option<String>,
|
||||
saves: Vec<ClientSaveState>,
|
||||
) -> Result<SyncNegotiateResponse, String> {
|
||||
let resp = self
|
||||
.request(Method::POST, "/api/sync/negotiate")
|
||||
.json(&SyncNegotiatePayload { device_id, saves })
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Sync negotiate failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn upload_save(
|
||||
&self,
|
||||
rom_id: i64,
|
||||
emulator: Option<&str>,
|
||||
slot: Option<&str>,
|
||||
device_id: Option<&str>,
|
||||
session_id: Option<i64>,
|
||||
overwrite: bool,
|
||||
file_name: &str,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<SaveSchema, String> {
|
||||
let mut req = self.request(Method::POST, "/api/saves").query(&[
|
||||
("rom_id", rom_id.to_string()),
|
||||
("overwrite", overwrite.to_string()),
|
||||
]);
|
||||
if let Some(e) = emulator {
|
||||
req = req.query(&[("emulator", e)]);
|
||||
}
|
||||
if let Some(s) = slot {
|
||||
req = req.query(&[("slot", s)]);
|
||||
}
|
||||
if let Some(d) = device_id {
|
||||
req = req.query(&[("device_id", d)]);
|
||||
}
|
||||
if let Some(sid) = session_id {
|
||||
req = req.query(&[("session_id", sid.to_string())]);
|
||||
}
|
||||
|
||||
let part = Part::bytes(bytes)
|
||||
.file_name(file_name.to_string())
|
||||
.mime_str("application/octet-stream")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let form = Form::new().part("saveFile", part);
|
||||
|
||||
let resp = req
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Upload save failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn download_save_bytes(
|
||||
&self,
|
||||
save_id: i64,
|
||||
device_id: Option<&str>,
|
||||
session_id: Option<i64>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let mut req = self.request(Method::GET, &format!("/api/saves/{}/content", save_id));
|
||||
if let Some(d) = device_id {
|
||||
req = req.query(&[("device_id", d)]);
|
||||
}
|
||||
if let Some(sid) = session_id {
|
||||
req = req.query(&[("session_id", sid.to_string())]);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Download save failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Download save failed: HTTP {}", resp.status()));
|
||||
}
|
||||
resp.bytes()
|
||||
.await
|
||||
.map(|b| b.to_vec())
|
||||
.map_err(|e| format!("Failed reading save bytes: {e}"))
|
||||
}
|
||||
|
||||
pub async fn confirm_save_downloaded(
|
||||
&self,
|
||||
save_id: i64,
|
||||
device_id: &str,
|
||||
) -> Result<(), String> {
|
||||
let resp = self
|
||||
.request(Method::POST, &format!("/api/saves/{}/downloaded", save_id))
|
||||
.json(&ConfirmDownloadPayload {
|
||||
device_id: device_id.to_string(),
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Confirm download failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let txt = resp.text().await.unwrap_or_default();
|
||||
return Err(format!("Confirm download HTTP {}: {}", status, txt));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn complete_sync_session(
|
||||
&self,
|
||||
session_id: i64,
|
||||
completed: i64,
|
||||
failed: i64,
|
||||
) -> Result<(), String> {
|
||||
let resp = self
|
||||
.request(
|
||||
Method::POST,
|
||||
&format!("/api/sync/sessions/{}/complete", session_id),
|
||||
)
|
||||
.json(&SyncCompletePayload {
|
||||
operations_completed: completed,
|
||||
operations_failed: failed,
|
||||
})
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Complete sync session failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let txt = resp.text().await.unwrap_or_default();
|
||||
return Err(format!("Complete sync session HTTP {}: {}", status, txt));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------- Save States ----------
|
||||
|
||||
pub async fn get_states(
|
||||
&self,
|
||||
rom_id: Option<i64>,
|
||||
platform_id: Option<i64>,
|
||||
) -> Result<Vec<StateSchema>, String> {
|
||||
let mut req = self.request(Method::GET, "/api/states");
|
||||
if let Some(id) = rom_id {
|
||||
req = req.query(&[("rom_id", id.to_string())]);
|
||||
}
|
||||
if let Some(pid) = platform_id {
|
||||
req = req.query(&[("platform_id", pid.to_string())]);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Get states failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn upload_state(
|
||||
&self,
|
||||
rom_id: i64,
|
||||
emulator: Option<&str>,
|
||||
file_name: &str,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<StateSchema, String> {
|
||||
let mut req = self
|
||||
.request(Method::POST, "/api/states")
|
||||
.query(&[("rom_id", rom_id.to_string())]);
|
||||
if let Some(e) = emulator {
|
||||
req = req.query(&[("emulator", e)]);
|
||||
}
|
||||
let part = Part::bytes(bytes)
|
||||
.file_name(file_name.to_string())
|
||||
.mime_str("application/octet-stream")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let form = Form::new().part("stateFile", part);
|
||||
let resp = req
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Upload state failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn update_state(
|
||||
&self,
|
||||
state_id: i64,
|
||||
file_name: &str,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<StateSchema, String> {
|
||||
let part = Part::bytes(bytes)
|
||||
.file_name(file_name.to_string())
|
||||
.mime_str("application/octet-stream")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let form = Form::new().part("stateFile", part);
|
||||
let resp = self
|
||||
.request(Method::PUT, &format!("/api/states/{}", state_id))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Update state failed: {e}"))?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn download_state_bytes(&self, state_id: i64) -> Result<Vec<u8>, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, &format!("/api/states/{}/content", state_id))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Download state failed: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Download state failed: HTTP {}", resp.status()));
|
||||
}
|
||||
resp.bytes()
|
||||
.await
|
||||
.map(|b| b.to_vec())
|
||||
.map_err(|e| format!("Failed reading state bytes: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn urlencoding_path_segment(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(b as char);
|
||||
}
|
||||
_ => {
|
||||
out.push_str(&format!("%{:02X}", b));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
use crate::config::{backups_dir, push_log, AppConfig};
|
||||
use crate::matcher::{discover_saves_for_emulators, read_save_payload_and_hash, DiscoveredSaveItem};
|
||||
use crate::romm_api::{ClientSaveState, RommClient, SimpleRomSchema};
|
||||
use chrono::Utc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
use zip::ZipArchive;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncConflictItem {
|
||||
pub id: String,
|
||||
pub rom_id: i64,
|
||||
pub rom_name: String,
|
||||
pub save_id: Option<i64>,
|
||||
pub local_path: String,
|
||||
pub file_name: String,
|
||||
pub is_directory: bool,
|
||||
pub emulator_id: String,
|
||||
pub slot: String,
|
||||
pub local_updated_at: String,
|
||||
pub server_updated_at: Option<String>,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncRunSummary {
|
||||
pub session_id: Option<i64>,
|
||||
pub uploaded_saves: usize,
|
||||
pub downloaded_saves: usize,
|
||||
pub uploaded_states: usize,
|
||||
pub up_to_date: usize,
|
||||
pub conflicts: Vec<SyncConflictItem>,
|
||||
pub errors: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackupEntry {
|
||||
pub backup_path: String,
|
||||
pub rom_id: String,
|
||||
pub file_name: String,
|
||||
pub created_at: String,
|
||||
pub size_bytes: u64,
|
||||
}
|
||||
|
||||
pub fn create_backup(
|
||||
local_path: &Path,
|
||||
rom_id: i64,
|
||||
is_directory: bool,
|
||||
max_backups: usize,
|
||||
) -> Result<Option<PathBuf>, String> {
|
||||
if !local_path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let rom_backup_dir = backups_dir().join(rom_id.to_string());
|
||||
fs::create_dir_all(&rom_backup_dir).map_err(|e| format!("Failed creating backup dir: {e}"))?;
|
||||
|
||||
let stamp = Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
|
||||
let base_name = local_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "save".to_string());
|
||||
|
||||
let dest = if is_directory {
|
||||
let (zip_bytes, _) = read_save_payload_and_hash(local_path, true)?;
|
||||
let zip_path = rom_backup_dir.join(format!("{}_{}.zip", stamp, base_name));
|
||||
fs::write(&zip_path, zip_bytes).map_err(|e| format!("Backup write failed: {e}"))?;
|
||||
zip_path
|
||||
} else {
|
||||
let copy_path = rom_backup_dir.join(format!("{}_{}", stamp, base_name));
|
||||
fs::copy(local_path, ©_path).map_err(|e| format!("Backup copy failed: {e}"))?;
|
||||
copy_path
|
||||
};
|
||||
|
||||
// Prune oldest backups beyond max_backups
|
||||
if max_backups > 0 {
|
||||
if let Ok(entries) = fs::read_dir(&rom_backup_dir) {
|
||||
let mut files: Vec<PathBuf> = entries
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file())
|
||||
.collect();
|
||||
files.sort();
|
||||
if files.len() > max_backups {
|
||||
let to_remove = files.len() - max_backups;
|
||||
for old in files.into_iter().take(to_remove) {
|
||||
let _ = fs::remove_file(old);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(dest))
|
||||
}
|
||||
|
||||
pub fn write_downloaded_save(
|
||||
dest_path: &Path,
|
||||
bytes: &[u8],
|
||||
is_directory: bool,
|
||||
) -> Result<(), String> {
|
||||
if is_directory {
|
||||
fs::create_dir_all(dest_path).map_err(|e| format!("Failed creating save dir: {e}"))?;
|
||||
let cursor = Cursor::new(bytes);
|
||||
let mut archive =
|
||||
ZipArchive::new(cursor).map_err(|e| format!("Downloaded archive is not a valid zip: {e}"))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut file = archive.by_index(i).map_err(|e| e.to_string())?;
|
||||
let Some(enclosed) = file.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let out_path = dest_path.join(enclosed);
|
||||
if file.is_dir() {
|
||||
fs::create_dir_all(&out_path).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(parent) = out_path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut out_file = fs::File::create(&out_path).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut file, &mut out_file).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
fs::write(dest_path, bytes).map_err(|e| format!("Failed writing save file: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list_all_backups() -> Vec<BackupEntry> {
|
||||
let root = backups_dir();
|
||||
let mut out = Vec::new();
|
||||
if let Ok(rom_dirs) = fs::read_dir(&root) {
|
||||
for rom_dir in rom_dirs.flatten() {
|
||||
if !rom_dir.path().is_dir() {
|
||||
continue;
|
||||
}
|
||||
let rom_id = rom_dir.file_name().to_string_lossy().to_string();
|
||||
if let Ok(files) = fs::read_dir(rom_dir.path()) {
|
||||
for f in files.flatten() {
|
||||
let p = f.path();
|
||||
if !p.is_file() {
|
||||
continue;
|
||||
}
|
||||
let meta = fs::metadata(&p).ok();
|
||||
let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);
|
||||
let created = meta
|
||||
.and_then(|m| m.modified().ok())
|
||||
.map(|t| chrono::DateTime::<Utc>::from(t).to_rfc3339())
|
||||
.unwrap_or_default();
|
||||
out.push(BackupEntry {
|
||||
backup_path: p.to_string_lossy().to_string(),
|
||||
rom_id: rom_id.clone(),
|
||||
file_name: f.file_name().to_string_lossy().to_string(),
|
||||
created_at: created,
|
||||
size_bytes: size,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.created_at.cmp(&a.created_at));
|
||||
out
|
||||
}
|
||||
|
||||
pub fn restore_backup_to_path(
|
||||
backup_path: &Path,
|
||||
target_path: &Path,
|
||||
is_directory: bool,
|
||||
) -> Result<(), String> {
|
||||
let bytes = fs::read(backup_path).map_err(|e| format!("Failed reading backup: {e}"))?;
|
||||
write_downloaded_save(target_path, &bytes, is_directory)
|
||||
}
|
||||
|
||||
pub async fn run_sync(
|
||||
client: &RommClient,
|
||||
cfg: &mut AppConfig,
|
||||
roms: &[SimpleRomSchema],
|
||||
) -> Result<SyncRunSummary, String> {
|
||||
let discovered = discover_saves_for_emulators(&cfg.emulators, roms, &cfg.manual_links);
|
||||
let rom_by_id: HashMap<i64, &SimpleRomSchema> = roms.iter().map(|r| (r.id, r)).collect();
|
||||
|
||||
let mut summary = SyncRunSummary {
|
||||
session_id: None,
|
||||
uploaded_saves: 0,
|
||||
downloaded_saves: 0,
|
||||
uploaded_states: 0,
|
||||
up_to_date: 0,
|
||||
conflicts: Vec::new(),
|
||||
errors: Vec::new(),
|
||||
};
|
||||
|
||||
// Split matched saves vs matched states
|
||||
let matched_saves: Vec<&DiscoveredSaveItem> = discovered
|
||||
.iter()
|
||||
.filter(|d| !d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
let matched_states: Vec<&DiscoveredSaveItem> = discovered
|
||||
.iter()
|
||||
.filter(|d| d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
|
||||
// Map (rom_id, slot) -> (DiscoveredSaveItem, bytes, hash)
|
||||
let mut local_save_map: HashMap<(i64, String), (&DiscoveredSaveItem, Vec<u8>, String)> =
|
||||
HashMap::new();
|
||||
let mut client_states: Vec<ClientSaveState> = Vec::new();
|
||||
|
||||
for item in matched_saves {
|
||||
let Some(rom_id) = item.matched_rom_id else {
|
||||
continue;
|
||||
};
|
||||
let path = Path::new(&item.local_path);
|
||||
match read_save_payload_and_hash(path, item.is_directory) {
|
||||
Ok((bytes, hash)) => {
|
||||
let slot = if item.slot.trim().is_empty() {
|
||||
"default".to_string()
|
||||
} else {
|
||||
item.slot.clone()
|
||||
};
|
||||
client_states.push(ClientSaveState {
|
||||
rom_id,
|
||||
file_name: item.file_name.clone(),
|
||||
slot: Some(slot.clone()),
|
||||
emulator: Some(item.emulator_id.clone()),
|
||||
content_hash: Some(hash.clone()),
|
||||
updated_at: item.updated_at.clone(),
|
||||
file_size_bytes: bytes.len() as i64,
|
||||
});
|
||||
local_save_map.insert((rom_id, slot), (item, bytes, hash));
|
||||
}
|
||||
Err(e) => {
|
||||
summary.errors.push(format!("{}: {}", item.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Negotiate two-way save sync with RomM 5.1.0
|
||||
if !client_states.is_empty() || cfg.connection.device_id.is_some() {
|
||||
let neg = client
|
||||
.negotiate_sync(cfg.connection.device_id.clone(), client_states)
|
||||
.await?;
|
||||
summary.session_id = Some(neg.session_id);
|
||||
let mut ops_completed = 0i64;
|
||||
let mut ops_failed = 0i64;
|
||||
|
||||
for op in neg.operations {
|
||||
let slot_key = op.slot.clone().unwrap_or_else(|| "default".to_string());
|
||||
match op.action.as_str() {
|
||||
"no_op" => {
|
||||
summary.up_to_date += 1;
|
||||
}
|
||||
"upload" => {
|
||||
if let Some((item, bytes, _hash)) = local_save_map.get(&(op.rom_id, slot_key.clone())) {
|
||||
match client
|
||||
.upload_save(
|
||||
op.rom_id,
|
||||
Some(&item.emulator_id),
|
||||
Some(&slot_key),
|
||||
cfg.connection.device_id.as_deref(),
|
||||
Some(neg.session_id),
|
||||
true,
|
||||
&item.file_name,
|
||||
bytes.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
summary.uploaded_saves += 1;
|
||||
ops_completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"upload_save",
|
||||
format!(
|
||||
"Uploaded save '{}' for {}",
|
||||
item.file_name,
|
||||
item.matched_rom_name.as_deref().unwrap_or("ROM")
|
||||
),
|
||||
Some(op.rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
ops_failed += 1;
|
||||
summary.errors.push(format!("Upload {}: {}", item.file_name, e));
|
||||
push_log(
|
||||
cfg,
|
||||
"error",
|
||||
"upload_save",
|
||||
format!("Failed uploading {}: {}", item.file_name, e),
|
||||
Some(op.rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"download" => {
|
||||
let Some(save_id) = op.save_id else {
|
||||
continue;
|
||||
};
|
||||
// Determine local target path: either existing matched local file, or emulator save_dir
|
||||
let target_info = local_save_map
|
||||
.get(&(op.rom_id, slot_key.clone()))
|
||||
.map(|(item, _, _)| (PathBuf::from(&item.local_path), item.is_directory))
|
||||
.or_else(|| {
|
||||
// Find enabled emulator matching op.emulator, or inherit from the ROM's platform slug
|
||||
let matched_emu = op
|
||||
.emulator
|
||||
.as_ref()
|
||||
.and_then(|emu_id| {
|
||||
cfg.emulators
|
||||
.iter()
|
||||
.find(|e| e.enabled && e.id.eq_ignore_ascii_case(emu_id))
|
||||
})
|
||||
.or_else(|| {
|
||||
rom_by_id.get(&op.rom_id).and_then(|rom| {
|
||||
cfg.emulators.iter().find(|e| {
|
||||
e.enabled
|
||||
&& e.platform_slugs.iter().any(|s| {
|
||||
s.eq_ignore_ascii_case(&rom.platform_slug)
|
||||
|| s.eq_ignore_ascii_case(&rom.platform_fs_slug)
|
||||
})
|
||||
})
|
||||
})
|
||||
});
|
||||
|
||||
matched_emu.map(|e| {
|
||||
let is_dir =
|
||||
e.structure == crate::config::SaveStructure::FolderPerGame;
|
||||
let target_path = if is_dir {
|
||||
let trimmed = op
|
||||
.file_name
|
||||
.strip_suffix(".zip")
|
||||
.unwrap_or(&op.file_name);
|
||||
if e.folder_depth > 1 {
|
||||
let parts: Vec<&str> =
|
||||
trimmed.splitn(e.folder_depth, '_').collect();
|
||||
let mut p = PathBuf::from(&e.save_dir);
|
||||
for part in parts {
|
||||
p.push(part);
|
||||
}
|
||||
p
|
||||
} else {
|
||||
PathBuf::from(&e.save_dir).join(trimmed)
|
||||
}
|
||||
} else {
|
||||
PathBuf::from(&e.save_dir).join(&op.file_name)
|
||||
};
|
||||
(target_path, is_dir)
|
||||
})
|
||||
});
|
||||
|
||||
if let Some((target_path, is_dir)) = target_info {
|
||||
match client
|
||||
.download_save_bytes(
|
||||
save_id,
|
||||
cfg.connection.device_id.as_deref(),
|
||||
Some(neg.session_id),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(bytes) => {
|
||||
let _ = create_backup(
|
||||
&target_path,
|
||||
op.rom_id,
|
||||
is_dir,
|
||||
cfg.settings.max_backups_per_save,
|
||||
);
|
||||
match write_downloaded_save(&target_path, &bytes, is_dir) {
|
||||
Ok(()) => {
|
||||
if let Some(ref dev_id) = cfg.connection.device_id {
|
||||
let _ = client
|
||||
.confirm_save_downloaded(save_id, dev_id)
|
||||
.await;
|
||||
}
|
||||
summary.downloaded_saves += 1;
|
||||
ops_completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"download_save",
|
||||
format!("Downloaded '{}' (backup created)", op.file_name),
|
||||
Some(op.rom_id),
|
||||
Some(target_path.to_string_lossy().to_string()),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
ops_failed += 1;
|
||||
summary.errors.push(format!("Write {}: {}", op.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
ops_failed += 1;
|
||||
summary.errors.push(format!("Download {}: {}", op.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"conflict" => {
|
||||
if let Some((item, _, _)) = local_save_map.get(&(op.rom_id, slot_key.clone())) {
|
||||
let conflict = SyncConflictItem {
|
||||
id: format!("{}:{}:{}", op.rom_id, slot_key, op.save_id.unwrap_or(0)),
|
||||
rom_id: op.rom_id,
|
||||
rom_name: item
|
||||
.matched_rom_name
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("ROM #{}", op.rom_id)),
|
||||
save_id: op.save_id,
|
||||
local_path: item.local_path.clone(),
|
||||
file_name: item.file_name.clone(),
|
||||
is_directory: item.is_directory,
|
||||
emulator_id: item.emulator_id.clone(),
|
||||
slot: slot_key,
|
||||
local_updated_at: item.updated_at.clone(),
|
||||
server_updated_at: op.server_updated_at.clone(),
|
||||
reason: op.reason.clone(),
|
||||
};
|
||||
push_log(
|
||||
cfg,
|
||||
"warning",
|
||||
"conflict",
|
||||
format!("Conflict detected for '{}': {}", item.file_name, op.reason),
|
||||
Some(op.rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
summary.conflicts.push(conflict);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = client
|
||||
.complete_sync_session(neg.session_id, ops_completed, ops_failed)
|
||||
.await;
|
||||
}
|
||||
|
||||
// 2. Sync Save States (/api/states) for changed local state files
|
||||
for item in matched_states {
|
||||
let Some(rom_id) = item.matched_rom_id else {
|
||||
continue;
|
||||
};
|
||||
let path = Path::new(&item.local_path);
|
||||
match read_save_payload_and_hash(path, false) {
|
||||
Ok((bytes, hash)) => {
|
||||
if cfg.synced_state_hashes.get(&item.local_path) == Some(&hash) {
|
||||
summary.up_to_date += 1;
|
||||
continue;
|
||||
}
|
||||
// Check if a remote state with same file_name exists for this ROM
|
||||
let existing = client
|
||||
.get_states(Some(rom_id), None)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
|
||||
|
||||
let res = if let Some(remote_state) = existing {
|
||||
client
|
||||
.update_state(remote_state.id, &item.file_name, bytes)
|
||||
.await
|
||||
} else {
|
||||
client
|
||||
.upload_state(rom_id, Some(&item.emulator_id), &item.file_name, bytes)
|
||||
.await
|
||||
};
|
||||
|
||||
match res {
|
||||
Ok(_) => {
|
||||
cfg.synced_state_hashes.insert(item.local_path.clone(), hash);
|
||||
summary.uploaded_states += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"upload_state",
|
||||
format!("Synced save state '{}'", item.file_name),
|
||||
Some(rom_id),
|
||||
Some(item.local_path.clone()),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
summary
|
||||
.errors
|
||||
.push(format!("State {}: {}", item.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
summary.errors.push(format!("State {}: {}", item.file_name, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(summary)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use crate::config::EmulatorRule;
|
||||
use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode, DebounceEventResult, Debouncer};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
pub struct WatcherHandle {
|
||||
_debouncer: Debouncer<notify::RecommendedWatcher>,
|
||||
pub watched_paths: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn start_watcher(
|
||||
app: AppHandle,
|
||||
emulators: &[EmulatorRule],
|
||||
debounce_seconds: u64,
|
||||
) -> Result<WatcherHandle, String> {
|
||||
let debounce = Duration::from_secs(debounce_seconds.max(1));
|
||||
let app_clone = app.clone();
|
||||
|
||||
let mut debouncer = new_debouncer(debounce, move |res: DebounceEventResult| {
|
||||
if let Ok(events) = res {
|
||||
let paths: Vec<String> = events
|
||||
.into_iter()
|
||||
.map(|e| e.path.to_string_lossy().to_string())
|
||||
.filter(|p| !p.contains(".romm_part") && !p.contains(".DS_Store"))
|
||||
.collect();
|
||||
if !paths.is_empty() {
|
||||
let _ = app_clone.emit("watcher:change", paths);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("Failed to initialize file watcher: {e}"))?;
|
||||
|
||||
let mut watched_paths = Vec::new();
|
||||
for emu in emulators.iter().filter(|e| e.enabled) {
|
||||
let save_p = PathBuf::from(&emu.save_dir);
|
||||
if save_p.exists() {
|
||||
if debouncer
|
||||
.watcher()
|
||||
.watch(&save_p, RecursiveMode::Recursive)
|
||||
.is_ok()
|
||||
{
|
||||
watched_paths.push(emu.save_dir.clone());
|
||||
}
|
||||
}
|
||||
if emu.sync_states {
|
||||
if let Some(ref sdir) = emu.state_dir {
|
||||
let state_p = PathBuf::from(sdir);
|
||||
if state_p.exists() && sdir != &emu.save_dir {
|
||||
if debouncer
|
||||
.watcher()
|
||||
.watch(&state_p, RecursiveMode::Recursive)
|
||||
.is_ok()
|
||||
{
|
||||
watched_paths.push(sdir.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(WatcherHandle {
|
||||
_debouncer: debouncer,
|
||||
watched_paths,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "RomM Companion",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.romm.companion",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "npm run build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "RomM Companion",
|
||||
"width": 1240,
|
||||
"height": 820,
|
||||
"minWidth": 960,
|
||||
"minHeight": 640,
|
||||
"resizable": true
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.ico",
|
||||
"icons/icon.png"
|
||||
]
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user