Initial commit: RomM Companion NextUI Pak v0.1.0
This commit is contained in:
commit
049762e32a
16 files changed
+5495
No files matched your search
+193
@@ -0,0 +1,193 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
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 platform = env::var("PLATFORM").unwrap_or_else(|_| "tg5040".to_string());
|
||||
let label = match platform.as_str() {
|
||||
"tg5050" => "TrimUI Smart Pro S (NextUI)",
|
||||
"tg5040" => "TrimUI Handheld (NextUI)",
|
||||
other => other,
|
||||
};
|
||||
Self {
|
||||
server_url: String::new(),
|
||||
access_token: None,
|
||||
refresh_token: None,
|
||||
username: None,
|
||||
device_id: None,
|
||||
device_name: label.to_string(),
|
||||
client_device_identifier: Uuid::new_v4().to_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 system_tag: String,
|
||||
pub slot: String,
|
||||
pub is_state: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NextUiSettings {
|
||||
pub sync_states: bool,
|
||||
pub max_backups_per_save: usize,
|
||||
pub default_slot: String,
|
||||
pub web_port: u16,
|
||||
/// Optional custom NextUI tag -> RomM platform slug overrides (e.g. "PCE" -> "tg16")
|
||||
#[serde(default)]
|
||||
pub tag_overrides: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Default for NextUiSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
sync_states: true,
|
||||
max_backups_per_save: 5,
|
||||
default_slot: "default".to_string(),
|
||||
web_port: 8765,
|
||||
tag_overrides: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncLogEntry {
|
||||
pub timestamp: String,
|
||||
pub level: String,
|
||||
pub action: String,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NextUiConfig {
|
||||
pub connection: ConnectionConfig,
|
||||
pub settings: NextUiSettings,
|
||||
#[serde(default)]
|
||||
pub manual_links: HashMap<String, ManualLink>,
|
||||
#[serde(default)]
|
||||
pub synced_state_hashes: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub sync_logs: Vec<SyncLogEntry>,
|
||||
}
|
||||
|
||||
/// Resolves the NextUI SD card root directory (`$SDCARD_PATH` on TrimUI, or `/mnt/SDCARD`).
|
||||
pub fn sdcard_root() -> PathBuf {
|
||||
if let Ok(p) = env::var("SDCARD_PATH") {
|
||||
if !p.trim().is_empty() {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
}
|
||||
let default_trimui = PathBuf::from("/mnt/SDCARD");
|
||||
if default_trimui.exists() {
|
||||
return default_trimui;
|
||||
}
|
||||
env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
|
||||
}
|
||||
|
||||
/// Resolves NextUI's Saves root (`$SAVES_PATH` or `$SDCARD_PATH/Saves`).
|
||||
pub fn saves_root() -> PathBuf {
|
||||
if let Ok(p) = env::var("SAVES_PATH") {
|
||||
if !p.trim().is_empty() {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
}
|
||||
sdcard_root().join("Saves")
|
||||
}
|
||||
|
||||
/// Resolves NextUI's Roms root (`$ROMS_PATH` or `$SDCARD_PATH/Roms`).
|
||||
pub fn roms_root() -> PathBuf {
|
||||
if let Ok(p) = env::var("ROMS_PATH") {
|
||||
if !p.trim().is_empty() {
|
||||
return PathBuf::from(p);
|
||||
}
|
||||
}
|
||||
sdcard_root().join("Roms")
|
||||
}
|
||||
|
||||
/// Resolves persistent config/data dir (`$USERDATA_PATH/romm-companion` or `$SDCARD_PATH/.userdata/shared/romm-companion`).
|
||||
pub fn data_dir() -> PathBuf {
|
||||
let base = if let Ok(p) = env::var("USERDATA_PATH") {
|
||||
if !p.trim().is_empty() {
|
||||
PathBuf::from(p)
|
||||
} else {
|
||||
sdcard_root().join(".userdata/shared")
|
||||
}
|
||||
} else {
|
||||
sdcard_root().join(".userdata/shared")
|
||||
};
|
||||
let dir = base.join("romm-companion");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
pub fn backups_dir() -> PathBuf {
|
||||
let dir = data_dir().join("backups");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
pub fn config_path() -> PathBuf {
|
||||
data_dir().join("config.json")
|
||||
}
|
||||
|
||||
pub fn conflicts_path() -> PathBuf {
|
||||
data_dir().join("conflicts.json")
|
||||
}
|
||||
|
||||
pub fn load_config() -> NextUiConfig {
|
||||
let path = config_path();
|
||||
if let Ok(raw) = fs::read_to_string(&path) {
|
||||
if let Ok(cfg) = serde_json::from_str::<NextUiConfig>(&raw) {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
NextUiConfig::default()
|
||||
}
|
||||
|
||||
pub fn save_config(cfg: &NextUiConfig) -> Result<(), String> {
|
||||
let path = config_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 NextUiConfig, level: &str, action: &str, message: impl Into<String>) {
|
||||
cfg.sync_logs.insert(
|
||||
0,
|
||||
SyncLogEntry {
|
||||
timestamp: chrono::Utc::now().to_rfc3339(),
|
||||
level: level.to_string(),
|
||||
action: action.to_string(),
|
||||
message: message.into(),
|
||||
},
|
||||
);
|
||||
if cfg.sync_logs.len() > 150 {
|
||||
cfg.sync_logs.truncate(150);
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
mod config;
|
||||
mod matcher;
|
||||
mod nextui;
|
||||
mod romm_api;
|
||||
mod sync_engine;
|
||||
mod web_setup;
|
||||
|
||||
use config::{load_config, push_log, save_config};
|
||||
use matcher::discover_nextui_saves;
|
||||
use nextui::{discover_nextui_systems, resolve_rom_dest_folder};
|
||||
use romm_api::RommClient;
|
||||
use std::env;
|
||||
use sync_engine::{
|
||||
load_conflicts, pull_single_save, pull_single_state, push_single_item, resolve_conflict,
|
||||
run_sync,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let cmd = args.get(1).map(|s| s.as_str()).unwrap_or("status");
|
||||
|
||||
let res = match cmd {
|
||||
"status" => cmd_status(args.iter().any(|a| a == "--text")),
|
||||
"sync" => cmd_sync().await,
|
||||
"platforms-menu" => cmd_platforms_menu().await,
|
||||
"roms-menu" => {
|
||||
let pid = flag_value(&args, "--platform-id").and_then(|v| v.parse::<i64>().ok());
|
||||
cmd_roms_menu(pid).await
|
||||
}
|
||||
"download-rom" => {
|
||||
let rom_id = flag_value(&args, "--rom-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
cmd_download_rom(rom_id).await
|
||||
}
|
||||
"rom-saves-menu" => {
|
||||
let rom_id = flag_value(&args, "--rom-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
cmd_rom_saves_menu(rom_id).await
|
||||
}
|
||||
"pull-save" => {
|
||||
let save_id = flag_value(&args, "--save-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
let rom_id = flag_value(&args, "--rom-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
cmd_pull_save(save_id, rom_id).await
|
||||
}
|
||||
"pull-state" => {
|
||||
let state_id = flag_value(&args, "--state-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
let rom_id = flag_value(&args, "--rom-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
cmd_pull_state(state_id, rom_id).await
|
||||
}
|
||||
"push-rom-saves" => {
|
||||
let rom_id = flag_value(&args, "--rom-id")
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
cmd_push_rom_saves(rom_id).await
|
||||
}
|
||||
"conflicts-menu" => cmd_conflicts_menu(),
|
||||
"resolve-conflict" => {
|
||||
let id = flag_value(&args, "--id").unwrap_or_default();
|
||||
let resolution = flag_value(&args, "--resolution").unwrap_or_else(|| "keep_local".into());
|
||||
cmd_resolve_conflict(&id, &resolution).await
|
||||
}
|
||||
"web-setup" => {
|
||||
let port = flag_value(&args, "--port")
|
||||
.and_then(|v| v.parse::<u16>().ok())
|
||||
.unwrap_or_else(|| load_config().settings.web_port);
|
||||
web_setup::serve_web_setup(port).await
|
||||
}
|
||||
"ip" => {
|
||||
println!("{}", web_setup::local_lan_ip());
|
||||
Ok(())
|
||||
}
|
||||
_ => {
|
||||
eprintln!(
|
||||
"Usage: romm-nextui <status|sync|platforms-menu|roms-menu|download-rom|conflicts-menu|resolve-conflict|web-setup|ip>"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = res {
|
||||
eprintln!("ERROR: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn flag_value(args: &[String], flag: &str) -> Option<String> {
|
||||
args.iter()
|
||||
.position(|a| a == flag)
|
||||
.and_then(|i| args.get(i + 1))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn cmd_status(text_mode: bool) -> Result<(), String> {
|
||||
let cfg = load_config();
|
||||
let systems = discover_nextui_systems(&cfg);
|
||||
let conflicts = load_conflicts();
|
||||
let connected = cfg.connection.access_token.is_some() && !cfg.connection.server_url.is_empty();
|
||||
|
||||
if text_mode {
|
||||
if connected {
|
||||
println!(
|
||||
"Server: {}\nUser: {}\nDevice: {}\nNextUI Systems: {}\nPending Conflicts: {}",
|
||||
cfg.connection.server_url,
|
||||
cfg.connection.username.as_deref().unwrap_or("?"),
|
||||
cfg.connection.device_name,
|
||||
systems.len(),
|
||||
conflicts.len()
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"Not connected to RomM.\nOpen 'Web Setup (Phone / PC)' to pair this handheld.\nDetected NextUI Systems: {}",
|
||||
systems.len()
|
||||
);
|
||||
}
|
||||
} else {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"connected": connected,
|
||||
"serverUrl": cfg.connection.server_url,
|
||||
"username": cfg.connection.username,
|
||||
"deviceName": cfg.connection.device_name,
|
||||
"systems": systems.len(),
|
||||
"conflicts": conflicts.len()
|
||||
})
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_sync() -> Result<(), String> {
|
||||
let mut cfg = load_config();
|
||||
if cfg.connection.access_token.is_none() || cfg.connection.server_url.is_empty() {
|
||||
return Err("Not connected to RomM. Launch Web Setup first.".into());
|
||||
}
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let summary = run_sync(&client, &mut cfg, &roms).await?;
|
||||
save_config(&cfg)?;
|
||||
|
||||
println!(
|
||||
"Sync Complete!\nUploaded Saves: {}\nDownloaded Saves: {}\nSynced States: {}\nUp To Date: {}\nConflicts: {}\nErrors: {}",
|
||||
summary.uploaded_saves,
|
||||
summary.downloaded_saves,
|
||||
summary.uploaded_states,
|
||||
summary.up_to_date,
|
||||
summary.conflicts.len(),
|
||||
summary.errors.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Outputs a `minui-list`-compatible JSON object of RomM platforms.
|
||||
async fn cmd_platforms_menu() -> Result<(), String> {
|
||||
let cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let platforms = client.get_platforms().await?;
|
||||
let items: Vec<serde_json::Value> = platforms
|
||||
.into_iter()
|
||||
.filter(|p| p.rom_count > 0)
|
||||
.map(|p| {
|
||||
serde_json::json!({
|
||||
"name": format!("{} ({})", p.display_name, p.rom_count),
|
||||
"platform_id": p.id,
|
||||
"slug": p.slug
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", serde_json::json!({ "items": items }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Outputs a `minui-list`-compatible JSON object of ROMs for a platform.
|
||||
async fn cmd_roms_menu(platform_id: Option<i64>) -> Result<(), String> {
|
||||
let cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let page = client.get_roms(platform_id, None, 200, 0).await?;
|
||||
let items: Vec<serde_json::Value> = page
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let label = r.name.unwrap_or(r.fs_name_no_ext);
|
||||
serde_json::json!({
|
||||
"name": label,
|
||||
"rom_id": r.id,
|
||||
"file_name": r.fs_name
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", serde_json::json!({ "items": items }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_download_rom(rom_id: i64) -> Result<(), String> {
|
||||
if rom_id <= 0 {
|
||||
return Err("Invalid --rom-id".into());
|
||||
}
|
||||
let mut cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let rom = roms
|
||||
.into_iter()
|
||||
.find(|r| r.id == rom_id)
|
||||
.ok_or_else(|| format!("ROM #{} not found on server", rom_id))?;
|
||||
|
||||
let dest_dir = resolve_rom_dest_folder(&rom.platform_slug, &rom.platform_display_name, &cfg);
|
||||
let dest_file = dest_dir.join(&rom.fs_name);
|
||||
let bytes = client.download_rom(rom.id, &rom.fs_name, &dest_file).await?;
|
||||
push_log(
|
||||
&mut cfg,
|
||||
"success",
|
||||
"download_rom",
|
||||
format!("Downloaded {} ({} bytes)", rom.fs_name, bytes),
|
||||
);
|
||||
save_config(&cfg)?;
|
||||
println!("Downloaded to:\n{}", dest_file.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lists all server saves, server states, and local matched saves for a single ROM in `minui-list` format.
|
||||
async fn cmd_rom_saves_menu(rom_id: i64) -> Result<(), String> {
|
||||
if rom_id <= 0 {
|
||||
return Err("Invalid --rom-id".into());
|
||||
}
|
||||
let cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let saves = client
|
||||
.get_saves(Some(rom_id), cfg.connection.device_id.as_deref())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let states = client.get_states(Some(rom_id)).await.unwrap_or_default();
|
||||
|
||||
let mut items: Vec<serde_json::Value> = Vec::new();
|
||||
for s in saves {
|
||||
items.push(serde_json::json!({
|
||||
"name": format!("[Pull Save] {} ({})", s.file_name, s.slot.as_deref().unwrap_or("manual")),
|
||||
"kind": "pull_save",
|
||||
"id": s.id
|
||||
}));
|
||||
}
|
||||
for st in states {
|
||||
items.push(serde_json::json!({
|
||||
"name": format!("[Pull State] {}", st.file_name),
|
||||
"kind": "pull_state",
|
||||
"id": st.id
|
||||
}));
|
||||
}
|
||||
items.push(serde_json::json!({
|
||||
"name": "[Push] Upload Local Saves & States for This Game",
|
||||
"kind": "push_local",
|
||||
"id": rom_id
|
||||
}));
|
||||
println!("{}", serde_json::json!({ "items": items }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_pull_save(save_id: i64, rom_id: i64) -> Result<(), String> {
|
||||
let mut cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let rom = roms
|
||||
.into_iter()
|
||||
.find(|r| r.id == rom_id)
|
||||
.ok_or_else(|| format!("ROM #{} not found", rom_id))?;
|
||||
let saves = client
|
||||
.get_saves(Some(rom_id), cfg.connection.device_id.as_deref())
|
||||
.await?;
|
||||
let save = saves
|
||||
.into_iter()
|
||||
.find(|s| s.id == save_id)
|
||||
.ok_or_else(|| format!("Save #{} not found", save_id))?;
|
||||
|
||||
let dest = pull_single_save(
|
||||
&client,
|
||||
&mut cfg,
|
||||
save.id,
|
||||
rom.id,
|
||||
&rom.platform_slug,
|
||||
&save.file_name,
|
||||
)
|
||||
.await?;
|
||||
save_config(&cfg)?;
|
||||
println!("Save downloaded to:\n{}", dest);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_pull_state(state_id: i64, rom_id: i64) -> Result<(), String> {
|
||||
let mut cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let rom = roms
|
||||
.into_iter()
|
||||
.find(|r| r.id == rom_id)
|
||||
.ok_or_else(|| format!("ROM #{} not found", rom_id))?;
|
||||
let states = client.get_states(Some(rom_id)).await?;
|
||||
let st = states
|
||||
.into_iter()
|
||||
.find(|s| s.id == state_id)
|
||||
.ok_or_else(|| format!("State #{} not found", state_id))?;
|
||||
|
||||
let dest = pull_single_state(
|
||||
&client,
|
||||
&mut cfg,
|
||||
st.id,
|
||||
rom.id,
|
||||
&rom.platform_slug,
|
||||
&st.file_name,
|
||||
)
|
||||
.await?;
|
||||
save_config(&cfg)?;
|
||||
println!("State downloaded to:\n{}", dest);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_push_rom_saves(rom_id: i64) -> Result<(), String> {
|
||||
let mut cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let local = discover_nextui_saves(&cfg, &roms);
|
||||
let matched: Vec<_> = local
|
||||
.into_iter()
|
||||
.filter(|i| i.matched_rom_id == Some(rom_id))
|
||||
.collect();
|
||||
if matched.is_empty() {
|
||||
return Err("No local saves or states found on SD card for this game.".into());
|
||||
}
|
||||
let mut count = 0usize;
|
||||
for item in matched {
|
||||
push_single_item(&client, &mut cfg, &item, rom_id).await?;
|
||||
count += 1;
|
||||
}
|
||||
save_config(&cfg)?;
|
||||
println!("Uploaded {} local save/state file(s) to RomM!", count);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_conflicts_menu() -> Result<(), String> {
|
||||
let conflicts = load_conflicts();
|
||||
let items: Vec<serde_json::Value> = conflicts
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
serde_json::json!({
|
||||
"name": format!("{} ({})", c.rom_name, c.file_name),
|
||||
"conflict_id": c.id
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
println!("{}", serde_json::json!({ "items": items }));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cmd_resolve_conflict(conflict_id: &str, resolution: &str) -> Result<(), String> {
|
||||
let mut cfg = load_config();
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let msg = resolve_conflict(&client, &mut cfg, conflict_id, resolution).await?;
|
||||
save_config(&cfg)?;
|
||||
println!("{}", msg);
|
||||
Ok(())
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
use crate::config::{ManualLink, NextUiConfig};
|
||||
use crate::nextui::{classify_nextui_save_file, discover_nextui_systems};
|
||||
use crate::romm_api::SimpleRomSchema;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use walkdir::WalkDir;
|
||||
use zip::write::SimpleFileOptions;
|
||||
use zip::ZipWriter;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DiscoveredNextUiSave {
|
||||
pub local_path: String,
|
||||
pub file_name: String,
|
||||
pub system_tag: String,
|
||||
pub is_directory: bool,
|
||||
pub is_state: bool,
|
||||
pub size_bytes: u64,
|
||||
pub updated_at: String,
|
||||
pub slot: String,
|
||||
pub matched_rom_id: Option<i64>,
|
||||
pub matched_rom_name: Option<String>,
|
||||
pub matched_platform: Option<String>,
|
||||
pub match_confidence: f32,
|
||||
pub match_source: String, // "manual" | "exact" | "fuzzy" | "unmatched"
|
||||
}
|
||||
|
||||
pub fn normalize_title(input: &str) -> String {
|
||||
let mut cleaned = String::with_capacity(input.len());
|
||||
let mut paren = 0usize;
|
||||
let mut bracket = 0usize;
|
||||
for ch in input.chars() {
|
||||
match ch {
|
||||
'(' => paren += 1,
|
||||
')' => paren = paren.saturating_sub(1),
|
||||
'[' => bracket += 1,
|
||||
']' => bracket = bracket.saturating_sub(1),
|
||||
_ if paren == 0 && bracket == 0 => {
|
||||
if ch.is_alphanumeric() {
|
||||
for lc in ch.to_lowercase() {
|
||||
cleaned.push(lc);
|
||||
}
|
||||
} else {
|
||||
cleaned.push(' ');
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
cleaned.split_whitespace().collect::<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_stem_to_roms<'a>(
|
||||
stem: &str,
|
||||
platform_slugs: &[String],
|
||||
roms: &'a [SimpleRomSchema],
|
||||
) -> Option<(&'a SimpleRomSchema, f32, &'static str)> {
|
||||
let stem_lower = stem.trim().to_lowercase();
|
||||
let stem_norm = normalize_title(stem);
|
||||
if stem_lower.is_empty() && stem_norm.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut best: Option<(&SimpleRomSchema, f32, &'static str)> = None;
|
||||
for rom in roms {
|
||||
let platform_bonus: f32 = if platform_slugs.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
let p_slug = rom.platform_slug.to_lowercase();
|
||||
let p_fs = rom.platform_fs_slug.to_lowercase();
|
||||
if platform_slugs
|
||||
.iter()
|
||||
.any(|s| s.eq_ignore_ascii_case(&p_slug) || s.eq_ignore_ascii_case(&p_fs))
|
||||
{
|
||||
0.08
|
||||
} else {
|
||||
-0.15
|
||||
}
|
||||
};
|
||||
|
||||
if rom.fs_name_no_ext.to_lowercase() == stem_lower
|
||||
|| rom.fs_name_no_tags.to_lowercase() == stem_lower
|
||||
{
|
||||
let score = (1.0 + platform_bonus).min(1.0);
|
||||
if best.map_or(true, |(_, bs, _)| score > bs) {
|
||||
best = Some((rom, score, "exact"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut sim = similarity_score(stem, &rom.fs_name_no_tags);
|
||||
if let Some(ref name) = rom.name {
|
||||
sim = sim.max(similarity_score(stem, name));
|
||||
}
|
||||
let adjusted = (sim + platform_bonus).clamp(0.0, 1.0);
|
||||
if sim >= 0.55 && best.map_or(true, |(_, bs, _)| adjusted > bs) {
|
||||
let src = if sim >= 0.99 { "exact" } else { "fuzzy" };
|
||||
best = Some((rom, adjusted, src));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
pub fn discover_nextui_saves(
|
||||
cfg: &NextUiConfig,
|
||||
roms: &[SimpleRomSchema],
|
||||
) -> Vec<DiscoveredNextUiSave> {
|
||||
let systems = discover_nextui_systems(cfg);
|
||||
let mut results = Vec::new();
|
||||
|
||||
for sys in systems {
|
||||
let Some(ref save_folder) = sys.save_folder else {
|
||||
continue;
|
||||
};
|
||||
let save_root = Path::new(save_folder);
|
||||
if !save_root.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Special case: PPSSPP SAVEDATA folders under /Saves/PSP/
|
||||
if sys.tag.eq_ignore_ascii_case("PSP") {
|
||||
let psp_savedata = save_root.join("PSP/SAVEDATA");
|
||||
let scan_dir = if psp_savedata.exists() {
|
||||
psp_savedata
|
||||
} else {
|
||||
save_root.to_path_buf()
|
||||
};
|
||||
if let Ok(entries) = fs::read_dir(&scan_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let p = entry.path();
|
||||
if p.is_dir() {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') || name == "PSP" {
|
||||
continue;
|
||||
}
|
||||
let (size, updated) = dir_size_and_mtime(&p);
|
||||
if size == 0 {
|
||||
continue;
|
||||
}
|
||||
results.push(build_item(
|
||||
&p,
|
||||
format!("{}.zip", name),
|
||||
&name,
|
||||
&sys.tag,
|
||||
&sys.romm_slugs,
|
||||
true,
|
||||
false,
|
||||
size,
|
||||
updated,
|
||||
&cfg.settings.default_slot,
|
||||
roms,
|
||||
&cfg.manual_links,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for entry in WalkDir::new(save_root)
|
||||
.max_depth(2)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let path = entry.path();
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Some((is_state, stem)) = classify_nextui_save_file(path) else {
|
||||
continue;
|
||||
};
|
||||
if is_state && !cfg.settings.sync_states {
|
||||
continue;
|
||||
}
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let (size, updated) = file_size_and_mtime(path);
|
||||
results.push(build_item(
|
||||
path,
|
||||
file_name,
|
||||
&stem,
|
||||
&sys.tag,
|
||||
&sys.romm_slugs,
|
||||
false,
|
||||
is_state,
|
||||
size,
|
||||
updated,
|
||||
&cfg.settings.default_slot,
|
||||
roms,
|
||||
&cfg.manual_links,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_item(
|
||||
path: &Path,
|
||||
file_name: String,
|
||||
stem: &str,
|
||||
system_tag: &str,
|
||||
platform_slugs: &[String],
|
||||
is_directory: bool,
|
||||
is_state: bool,
|
||||
size_bytes: u64,
|
||||
updated_at: String,
|
||||
default_slot: &str,
|
||||
roms: &[SimpleRomSchema],
|
||||
manual_links: &HashMap<String, ManualLink>,
|
||||
) -> DiscoveredNextUiSave {
|
||||
let local_path = path.to_string_lossy().to_string();
|
||||
|
||||
if let Some(link) = manual_links.get(&local_path) {
|
||||
let plat = roms
|
||||
.iter()
|
||||
.find(|r| r.id == link.rom_id)
|
||||
.map(|r| r.platform_display_name.clone());
|
||||
return DiscoveredNextUiSave {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: system_tag.to_string(),
|
||||
is_directory,
|
||||
is_state,
|
||||
size_bytes,
|
||||
updated_at,
|
||||
slot: link.slot.clone(),
|
||||
matched_rom_id: Some(link.rom_id),
|
||||
matched_rom_name: Some(link.rom_name.clone()),
|
||||
matched_platform: plat,
|
||||
match_confidence: 1.0,
|
||||
match_source: "manual".to_string(),
|
||||
};
|
||||
}
|
||||
|
||||
if let Some((rom, conf, src)) = match_stem_to_roms(stem, platform_slugs, roms) {
|
||||
DiscoveredNextUiSave {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: system_tag.to_string(),
|
||||
is_directory,
|
||||
is_state,
|
||||
size_bytes,
|
||||
updated_at,
|
||||
slot: default_slot.to_string(),
|
||||
matched_rom_id: Some(rom.id),
|
||||
matched_rom_name: Some(rom.name.clone().unwrap_or_else(|| rom.fs_name_no_ext.clone())),
|
||||
matched_platform: Some(rom.platform_display_name.clone()),
|
||||
match_confidence: conf,
|
||||
match_source: src.to_string(),
|
||||
}
|
||||
} else {
|
||||
DiscoveredNextUiSave {
|
||||
local_path,
|
||||
file_name,
|
||||
system_tag: system_tag.to_string(),
|
||||
is_directory,
|
||||
is_state,
|
||||
size_bytes,
|
||||
updated_at,
|
||||
slot: default_slot.to_string(),
|
||||
matched_rom_id: None,
|
||||
matched_rom_name: None,
|
||||
matched_platform: None,
|
||||
match_confidence: 0.0,
|
||||
match_source: "unmatched".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn file_size_and_mtime(path: &Path) -> (u64, String) {
|
||||
match fs::metadata(path) {
|
||||
Ok(m) => {
|
||||
let dt: DateTime<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())
|
||||
}
|
||||
|
||||
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 reading {}: {}", path.display(), e))?
|
||||
};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(&bytes);
|
||||
Ok((bytes, hex::encode(hasher.finalize())))
|
||||
}
|
||||
|
||||
fn zip_directory_deterministic(dir: &Path) -> Result<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 f in files {
|
||||
let rel = f
|
||||
.strip_prefix(dir)
|
||||
.map_err(|e| e.to_string())?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
zip.start_file(rel, options).map_err(|e| e.to_string())?;
|
||||
zip.write_all(&fs::read(&f).map_err(|e| e.to_string())?)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
zip.finish().map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(cursor.into_inner())
|
||||
}
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
use crate::config::{roms_root, saves_root, NextUiConfig};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NextUiSystemFolder {
|
||||
pub tag: String,
|
||||
pub rom_folder: Option<String>,
|
||||
pub save_folder: Option<String>,
|
||||
pub romm_slugs: Vec<String>,
|
||||
}
|
||||
|
||||
/// Maps a NextUI tag (e.g. `GBA`, `FC`, `SFC`, `PS`, `MD`) to candidate RomM platform slugs.
|
||||
pub fn tag_to_romm_slugs(tag: &str, overrides: &HashMap<String, String>) -> Vec<String> {
|
||||
let upper = tag.trim().to_uppercase();
|
||||
if let Some(custom) = overrides.get(&upper).or_else(|| overrides.get(tag)) {
|
||||
return vec![custom.to_lowercase()];
|
||||
}
|
||||
let list: &[&str] = match upper.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"],
|
||||
"SCUMMVM" => &["scummvm"],
|
||||
"DOS" => &["dos"],
|
||||
_ => return vec![tag.to_lowercase()],
|
||||
};
|
||||
list.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Maps a RomM platform slug back to a default NextUI `(TAG)` when creating a ROM folder.
|
||||
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()
|
||||
}
|
||||
|
||||
/// Extracts the parenthesized NextUI tag from a folder like `Game Boy Advance (GBA)` -> `Some("GBA")`.
|
||||
pub fn extract_tag_from_rom_folder(folder_name: &str) -> Option<String> {
|
||||
let open = folder_name.rfind('(')?;
|
||||
let close = folder_name.rfind(')')?;
|
||||
if close > open + 1 {
|
||||
let tag = folder_name[open + 1..close].trim();
|
||||
if !tag.is_empty() {
|
||||
return Some(tag.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Discovers all NextUI system tags present in `/Roms` and `/Saves`.
|
||||
pub fn discover_nextui_systems(cfg: &NextUiConfig) -> Vec<NextUiSystemFolder> {
|
||||
let mut by_tag: HashMap<String, NextUiSystemFolder> = HashMap::new();
|
||||
|
||||
// 1. Scan /Roms/* (<TAG>)
|
||||
let r_root = roms_root();
|
||||
if let Ok(entries) = fs::read_dir(&r_root) {
|
||||
for entry in entries.flatten() {
|
||||
let p = entry.path();
|
||||
if !p.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
if let Some(tag) = extract_tag_from_rom_folder(&name) {
|
||||
let key = tag.to_uppercase();
|
||||
by_tag
|
||||
.entry(key.clone())
|
||||
.and_modify(|s| s.rom_folder = Some(p.to_string_lossy().to_string()))
|
||||
.or_insert_with(|| NextUiSystemFolder {
|
||||
tag: tag.clone(),
|
||||
rom_folder: Some(p.to_string_lossy().to_string()),
|
||||
save_folder: None,
|
||||
romm_slugs: tag_to_romm_slugs(&tag, &cfg.settings.tag_overrides),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Scan /Saves/<TAG>
|
||||
let s_root = saves_root();
|
||||
if let Ok(entries) = fs::read_dir(&s_root) {
|
||||
for entry in entries.flatten() {
|
||||
let p = entry.path();
|
||||
if !p.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let tag = entry.file_name().to_string_lossy().to_string();
|
||||
if tag.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let key = tag.to_uppercase();
|
||||
by_tag
|
||||
.entry(key)
|
||||
.and_modify(|s| s.save_folder = Some(p.to_string_lossy().to_string()))
|
||||
.or_insert_with(|| NextUiSystemFolder {
|
||||
tag: tag.clone(),
|
||||
rom_folder: None,
|
||||
save_folder: Some(p.to_string_lossy().to_string()),
|
||||
romm_slugs: tag_to_romm_slugs(&tag, &cfg.settings.tag_overrides),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let mut list: Vec<NextUiSystemFolder> = by_tag.into_values().collect();
|
||||
list.sort_by(|a, b| a.tag.cmp(&b.tag));
|
||||
list
|
||||
}
|
||||
|
||||
/// Finds (or computes) the right `/Roms/<Display> (<TAG>)/` path for a RomM platform.
|
||||
pub fn resolve_rom_dest_folder(
|
||||
platform_slug: &str,
|
||||
platform_display_name: &str,
|
||||
cfg: &NextUiConfig,
|
||||
) -> PathBuf {
|
||||
let systems = discover_nextui_systems(cfg);
|
||||
for sys in &systems {
|
||||
if sys
|
||||
.romm_slugs
|
||||
.iter()
|
||||
.any(|s| s.eq_ignore_ascii_case(platform_slug))
|
||||
{
|
||||
if let Some(ref rf) = sys.rom_folder {
|
||||
return PathBuf::from(rf);
|
||||
}
|
||||
}
|
||||
}
|
||||
let tag = romm_slug_to_default_tag(platform_slug);
|
||||
let safe_name = platform_display_name.replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|'], "");
|
||||
roms_root().join(format!("{} ({})", safe_name.trim(), tag))
|
||||
}
|
||||
|
||||
/// Finds (or computes) the right `/Saves/<TAG>/` folder for a RomM platform slug.
|
||||
pub fn resolve_save_dest_folder(platform_slug: &str, cfg: &NextUiConfig) -> (String, PathBuf) {
|
||||
let systems = discover_nextui_systems(cfg);
|
||||
for sys in &systems {
|
||||
if sys
|
||||
.romm_slugs
|
||||
.iter()
|
||||
.any(|s| s.eq_ignore_ascii_case(platform_slug))
|
||||
{
|
||||
if let Some(ref sf) = sys.save_folder {
|
||||
return (sys.tag.clone(), PathBuf::from(sf));
|
||||
}
|
||||
return (sys.tag.clone(), saves_root().join(&sys.tag));
|
||||
}
|
||||
}
|
||||
let tag = romm_slug_to_default_tag(platform_slug);
|
||||
let dir = saves_root().join(&tag);
|
||||
(tag, dir)
|
||||
}
|
||||
|
||||
/// Classifies a file inside `/Saves/<TAG>/` as Save vs Save State and extracts its clean ROM stem.
|
||||
/// Handles BOTH MinUI (`Game.gba.sav`, `Game.gba.state0`) and RetroArch (`Game.srm`, `Game.state.0`) naming!
|
||||
pub fn classify_nextui_save_file(path: &Path) -> Option<(bool /* is_state */, String /* clean_stem */)> {
|
||||
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();
|
||||
|
||||
// Ignore NextUI metadata/thumbnail files
|
||||
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;
|
||||
}
|
||||
|
||||
// Detect state files: `.state`, `.state0`..`.state99`, `.state.0`, `.st0`..`.st9`, `.ppst`, `.ss0`..`.ss9`
|
||||
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[2..].chars().all(|c| c.is_ascii_digit())
|
||||
&& ext.len() > 2
|
||||
{
|
||||
(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;
|
||||
};
|
||||
|
||||
// Strip MinUI's double extension (e.g. `Pokemon Emerald.gba` -> `Pokemon Emerald`)
|
||||
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))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_extract_tag() {
|
||||
assert_eq!(
|
||||
extract_tag_from_rom_folder("Game Boy Advance (GBA)"),
|
||||
Some("GBA".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tag_from_rom_folder("Sony PlayStation (PS)"),
|
||||
Some("PS".to_string())
|
||||
);
|
||||
assert_eq!(extract_tag_from_rom_folder("NoTagHere"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_minui_and_retroarch_saves() {
|
||||
assert_eq!(
|
||||
classify_nextui_save_file(Path::new("Pokemon Emerald (USA).gba.sav")),
|
||||
Some((false, "Pokemon Emerald (USA)".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_nextui_save_file(Path::new("Pokemon Emerald (USA).gba.state0")),
|
||||
Some((true, "Pokemon Emerald (USA)".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_nextui_save_file(Path::new("Chrono Trigger.srm")),
|
||||
Some((false, "Chrono Trigger".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_nextui_save_file(Path::new("Chrono Trigger.state.2")),
|
||||
Some((true, "Chrono Trigger".to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
classify_nextui_save_file(Path::new("preview.png")),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
+671
@@ -0,0 +1,671 @@
|
||||
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>,
|
||||
}
|
||||
|
||||
#[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 refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ClientTokenCreateSchema {
|
||||
pub id: i64,
|
||||
pub name: 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 current_device_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeviceCreatePayload {
|
||||
pub name: Option<String>,
|
||||
pub platform: Option<String>,
|
||||
pub client: Option<String>,
|
||||
pub client_version: 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 name: Option<String>,
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
#[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 crc_hash: Option<String>,
|
||||
pub md5_hash: Option<String>,
|
||||
pub sha1_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RomPageResponse {
|
||||
pub items: Vec<SimpleRomSchema>,
|
||||
pub total: i64,
|
||||
pub limit: i64,
|
||||
pub offset: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SaveSchema {
|
||||
pub id: i64,
|
||||
pub rom_id: i64,
|
||||
pub file_name: String,
|
||||
pub updated_at: String,
|
||||
pub emulator: Option<String>,
|
||||
pub slot: Option<String>,
|
||||
pub content_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StateSchema {
|
||||
pub id: i64,
|
||||
pub rom_id: i64,
|
||||
pub file_name: 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,
|
||||
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)]
|
||||
struct SyncCompletePayload {
|
||||
operations_completed: i64,
|
||||
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 not configured".into());
|
||||
}
|
||||
let http = Client::builder()
|
||||
.user_agent("RomM-NextUI-Companion/0.1.0")
|
||||
.build()
|
||||
.map_err(|e| format!("HTTP client error: {e}"))?;
|
||||
Ok(Self {
|
||||
http,
|
||||
base_url: normalized,
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
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| e.to_string())?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("HTTP {}: {}", status.as_u16(), text));
|
||||
}
|
||||
serde_json::from_str(&text)
|
||||
.map_err(|e| format!("JSON parse error ({}): {}", e, &text[..text.len().min(250)]))
|
||||
}
|
||||
|
||||
pub async fn heartbeat(&self) -> Result<serde_json::Value, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, "/api/heartbeat")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Cannot 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| e.to_string())?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn device_auth_init(
|
||||
&self,
|
||||
client_device_identifier: &str,
|
||||
device_name: &str,
|
||||
) -> Result<DeviceAuthInitResponse, String> {
|
||||
let platform = std::env::var("PLATFORM").unwrap_or_else(|_| "nextui".to_string());
|
||||
let payload = DeviceAuthInitPayload {
|
||||
client_device_identifier: client_device_identifier.to_string(),
|
||||
name: device_name.to_string(),
|
||||
client: "romm-nextui".to_string(),
|
||||
platform: Some(platform),
|
||||
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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
return Ok(Some(parsed));
|
||||
}
|
||||
if (status.as_u16() == 400 || status.as_u16() == 428 || status.as_u16() == 202)
|
||||
&& (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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn register_device(&self, name: &str) -> Result<DeviceSchema, String> {
|
||||
let platform = std::env::var("PLATFORM").unwrap_or_else(|_| "nextui".to_string());
|
||||
let payload = DeviceCreatePayload {
|
||||
name: Some(name.to_string()),
|
||||
platform: Some(platform),
|
||||
client: Some("romm-nextui".to_string()),
|
||||
client_version: Some("0.1.0".to_string()),
|
||||
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| e.to_string())?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn get_platforms(&self) -> Result<Vec<PlatformSchema>, String> {
|
||||
let resp = self
|
||||
.request(Method::GET, "/api/platforms")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
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()),
|
||||
]);
|
||||
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| e.to_string())?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
pub async fn get_all_roms(&self) -> Result<Vec<SimpleRomSchema>, String> {
|
||||
let mut all = Vec::new();
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
let page = self.get_roms(None, None, 250, 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 download_rom(
|
||||
&self,
|
||||
rom_id: i64,
|
||||
file_name: &str,
|
||||
dest_path: &Path,
|
||||
) -> Result<u64, String> {
|
||||
let encoded = encode_segment(file_name);
|
||||
let path = format!("/api/roms/{}/content/{}", rom_id, encoded);
|
||||
let resp = self
|
||||
.request(Method::GET, &path)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("ROM download failed: HTTP {}", resp.status()));
|
||||
}
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let tmp = dest_path.with_extension("romm_part");
|
||||
let mut f = tokio::fs::File::create(&tmp)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut total = 0u64;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let b = chunk.map_err(|e| e.to_string())?;
|
||||
f.write_all(&b).await.map_err(|e| e.to_string())?;
|
||||
total += b.len() as u64;
|
||||
}
|
||||
f.flush().await.map_err(|e| e.to_string())?;
|
||||
drop(f);
|
||||
tokio::fs::rename(&tmp, dest_path)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
pub async fn get_saves(
|
||||
&self,
|
||||
rom_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(d) = device_id {
|
||||
req = req.query(&[("device_id", d)]);
|
||||
}
|
||||
let resp = req.send().await.map_err(|e| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
Self::parse_json(resp).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Download save HTTP {}", resp.status()));
|
||||
}
|
||||
resp.bytes()
|
||||
.await
|
||||
.map(|b| b.to_vec())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
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| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Confirm download HTTP {}", resp.status()));
|
||||
}
|
||||
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| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Complete sync HTTP {}", resp.status()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_states(&self, rom_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())]);
|
||||
}
|
||||
let resp = req.send().await.map_err(|e| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
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| e.to_string())?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Download state HTTP {}", resp.status()));
|
||||
}
|
||||
resp.bytes()
|
||||
.await
|
||||
.map(|b| b.to_vec())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_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,579 @@
|
||||
use crate::config::{backups_dir, conflicts_path, push_log, NextUiConfig};
|
||||
use crate::matcher::{discover_nextui_saves, read_save_payload_and_hash, DiscoveredNextUiSave};
|
||||
use crate::nextui::resolve_save_dest_folder;
|
||||
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 system_tag: 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>,
|
||||
}
|
||||
|
||||
pub fn load_conflicts() -> Vec<SyncConflictItem> {
|
||||
if let Ok(raw) = fs::read_to_string(conflicts_path()) {
|
||||
if let Ok(list) = serde_json::from_str(&raw) {
|
||||
return list;
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn save_conflicts(list: &[SyncConflictItem]) {
|
||||
if let Ok(json) = serde_json::to_string_pretty(list) {
|
||||
let _ = fs::write(conflicts_path(), json);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_backup(
|
||||
local_path: &Path,
|
||||
rom_id: i64,
|
||||
is_directory: bool,
|
||||
max_backups: usize,
|
||||
) -> Result<(), String> {
|
||||
if !local_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
let rom_dir = backups_dir().join(rom_id.to_string());
|
||||
fs::create_dir_all(&rom_dir).map_err(|e| e.to_string())?;
|
||||
let stamp = Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
|
||||
let base = local_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "save".to_string());
|
||||
|
||||
if is_directory {
|
||||
let (zip_bytes, _) = read_save_payload_and_hash(local_path, true)?;
|
||||
fs::write(rom_dir.join(format!("{}_{}.zip", stamp, base)), zip_bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
fs::copy(local_path, rom_dir.join(format!("{}_{}", stamp, base)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
if max_backups > 0 {
|
||||
if let Ok(entries) = fs::read_dir(&rom_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(())
|
||||
}
|
||||
|
||||
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| e.to_string())?;
|
||||
let mut archive = ZipArchive::new(Cursor::new(bytes))
|
||||
.map_err(|e| format!("Invalid zip archive: {e}"))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut f = archive.by_index(i).map_err(|e| e.to_string())?;
|
||||
let Some(rel) = f.enclosed_name().map(|p| p.to_path_buf()) else {
|
||||
continue;
|
||||
};
|
||||
let out = dest_path.join(rel);
|
||||
if f.is_dir() {
|
||||
fs::create_dir_all(&out).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(p) = out.parent() {
|
||||
fs::create_dir_all(p).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut of = fs::File::create(&out).map_err(|e| e.to_string())?;
|
||||
std::io::copy(&mut f, &mut of).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
if let Some(p) = dest_path.parent() {
|
||||
fs::create_dir_all(p).map_err(|e| e.to_string())?;
|
||||
}
|
||||
fs::write(dest_path, bytes).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_sync(
|
||||
client: &RommClient,
|
||||
cfg: &mut NextUiConfig,
|
||||
roms: &[SimpleRomSchema],
|
||||
) -> Result<SyncRunSummary, String> {
|
||||
let discovered = discover_nextui_saves(cfg, roms);
|
||||
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 rom_by_id: HashMap<i64, &SimpleRomSchema> = roms.iter().map(|r| (r.id, r)).collect();
|
||||
|
||||
let matched_saves: Vec<&DiscoveredNextUiSave> = discovered
|
||||
.iter()
|
||||
.filter(|d| !d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
let matched_states: Vec<&DiscoveredNextUiSave> = discovered
|
||||
.iter()
|
||||
.filter(|d| d.is_state && d.matched_rom_id.is_some())
|
||||
.collect();
|
||||
|
||||
let mut local_map: HashMap<(i64, String), (&DiscoveredNextUiSave, 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() || 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 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_name = format!("nextui-{}", item.system_tag.to_lowercase());
|
||||
match client
|
||||
.upload_save(
|
||||
op.rom_id,
|
||||
Some(&emu_name),
|
||||
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;
|
||||
completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"upload_save",
|
||||
format!("Uploaded {} ({})", item.file_name, item.system_tag),
|
||||
);
|
||||
}
|
||||
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, save_dir) =
|
||||
resolve_save_dest_folder(&rom.platform_slug, cfg);
|
||||
let is_dir =
|
||||
tag.eq_ignore_ascii_case("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()
|
||||
};
|
||||
let dest = if is_dir {
|
||||
save_dir.join("PSP/SAVEDATA").join(name)
|
||||
} else {
|
||||
save_dir.join(name)
|
||||
};
|
||||
(dest, is_dir)
|
||||
})
|
||||
});
|
||||
|
||||
if let Some((dest_path, is_dir)) = target {
|
||||
match client
|
||||
.download_save_bytes(
|
||||
save_id,
|
||||
cfg.connection.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) = cfg.connection.device_id {
|
||||
let _ = client
|
||||
.confirm_save_downloaded(save_id, did)
|
||||
.await;
|
||||
}
|
||||
summary.downloaded_saves += 1;
|
||||
completed += 1;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"download_save",
|
||||
format!("Downloaded {} (backup saved)", op.file_name),
|
||||
);
|
||||
}
|
||||
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!("{}:{}:{}", 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,
|
||||
system_tag: item.system_tag.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 for {}: {}", item.file_name, op.reason),
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = client
|
||||
.complete_sync_session(neg.session_id, completed, failed)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Sync Save States (/api/states)
|
||||
if cfg.settings.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))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
|
||||
let emu_name = 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_name), &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 state {} ({})", item.file_name, item.system_tag),
|
||||
);
|
||||
}
|
||||
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
|
||||
}
|
||||
}
|
||||
Err(e) => summary.errors.push(format!("State {}: {}", item.file_name, e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
save_conflicts(&summary.conflicts);
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
pub async fn resolve_conflict(
|
||||
client: &RommClient,
|
||||
cfg: &mut NextUiConfig,
|
||||
conflict_id: &str,
|
||||
resolution: &str,
|
||||
) -> Result<String, String> {
|
||||
let mut conflicts = load_conflicts();
|
||||
let conflict = conflicts
|
||||
.iter()
|
||||
.find(|c| c.id == conflict_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| "Conflict not found".to_string())?;
|
||||
|
||||
let path = Path::new(&conflict.local_path);
|
||||
match resolution {
|
||||
"keep_local" => {
|
||||
let (bytes, _) = read_save_payload_and_hash(path, conflict.is_directory)?;
|
||||
let emu_name = format!("nextui-{}", conflict.system_tag.to_lowercase());
|
||||
client
|
||||
.upload_save(
|
||||
conflict.rom_id,
|
||||
Some(&emu_name),
|
||||
Some(&conflict.slot),
|
||||
cfg.connection.device_id.as_deref(),
|
||||
None,
|
||||
true,
|
||||
&conflict.file_name,
|
||||
bytes,
|
||||
)
|
||||
.await?;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"resolve_conflict",
|
||||
format!("Kept local save for {}", conflict.rom_name),
|
||||
);
|
||||
}
|
||||
"keep_server" => {
|
||||
let save_id = conflict
|
||||
.save_id
|
||||
.ok_or_else(|| "Missing server save ID".to_string())?;
|
||||
let bytes = client
|
||||
.download_save_bytes(save_id, cfg.connection.device_id.as_deref(), None)
|
||||
.await?;
|
||||
let _ = create_backup(
|
||||
path,
|
||||
conflict.rom_id,
|
||||
conflict.is_directory,
|
||||
cfg.settings.max_backups_per_save,
|
||||
);
|
||||
write_downloaded_save(path, &bytes, conflict.is_directory)?;
|
||||
if let Some(ref did) = cfg.connection.device_id {
|
||||
let _ = client.confirm_save_downloaded(save_id, did).await;
|
||||
}
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"resolve_conflict",
|
||||
format!("Downloaded server save for {} (backup kept)", conflict.rom_name),
|
||||
);
|
||||
}
|
||||
_ => return Err("Resolution must be keep_local or keep_server".into()),
|
||||
}
|
||||
|
||||
conflicts.retain(|c| c.id != conflict_id);
|
||||
save_conflicts(&conflicts);
|
||||
Ok(format!("Resolved conflict for {}", conflict.rom_name))
|
||||
}
|
||||
|
||||
/// Downloads a single server save and places it in the inherited NextUI `/Saves/<TAG>/` folder.
|
||||
pub async fn pull_single_save(
|
||||
client: &RommClient,
|
||||
cfg: &mut NextUiConfig,
|
||||
save_id: i64,
|
||||
rom_id: i64,
|
||||
platform_slug: &str,
|
||||
file_name: &str,
|
||||
) -> Result<String, String> {
|
||||
let (tag, save_dir) = resolve_save_dest_folder(platform_slug, cfg);
|
||||
let is_dir = tag.eq_ignore_ascii_case("PSP") && file_name.ends_with(".zip");
|
||||
let dest_path = if is_dir {
|
||||
let folder_name = file_name.strip_suffix(".zip").unwrap_or(file_name);
|
||||
save_dir.join("PSP/SAVEDATA").join(folder_name)
|
||||
} else {
|
||||
save_dir.join(file_name)
|
||||
};
|
||||
|
||||
let bytes = client
|
||||
.download_save_bytes(save_id, cfg.connection.device_id.as_deref(), None)
|
||||
.await?;
|
||||
let _ = create_backup(&dest_path, rom_id, is_dir, cfg.settings.max_backups_per_save);
|
||||
write_downloaded_save(&dest_path, &bytes, is_dir)?;
|
||||
if let Some(ref did) = cfg.connection.device_id {
|
||||
let _ = client.confirm_save_downloaded(save_id, did).await;
|
||||
}
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"pull_save",
|
||||
format!("Downloaded save '{}' to {}", file_name, dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Downloads a single server save state into the inherited NextUI `/Saves/<TAG>/` folder.
|
||||
pub async fn pull_single_state(
|
||||
client: &RommClient,
|
||||
cfg: &mut NextUiConfig,
|
||||
state_id: i64,
|
||||
rom_id: i64,
|
||||
platform_slug: &str,
|
||||
file_name: &str,
|
||||
) -> Result<String, String> {
|
||||
let (_tag, save_dir) = resolve_save_dest_folder(platform_slug, cfg);
|
||||
let dest_path = save_dir.join(file_name);
|
||||
|
||||
let bytes = client.download_state_bytes(state_id).await?;
|
||||
let _ = create_backup(&dest_path, rom_id, false, cfg.settings.max_backups_per_save);
|
||||
write_downloaded_save(&dest_path, &bytes, false)?;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"pull_state",
|
||||
format!("Downloaded state '{}' to {}", file_name, dest_path.display()),
|
||||
);
|
||||
Ok(dest_path.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Uploads a single local save or state file/folder straight to RomM.
|
||||
pub async fn push_single_item(
|
||||
client: &RommClient,
|
||||
cfg: &mut NextUiConfig,
|
||||
item: &DiscoveredNextUiSave,
|
||||
rom_id: i64,
|
||||
) -> Result<String, String> {
|
||||
let (bytes, hash) = read_save_payload_and_hash(Path::new(&item.local_path), item.is_directory)?;
|
||||
let emu_name = format!("nextui-{}", item.system_tag.to_lowercase());
|
||||
if item.is_state {
|
||||
let existing = client
|
||||
.get_states(Some(rom_id))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.find(|s| s.file_name.eq_ignore_ascii_case(&item.file_name));
|
||||
if let Some(remote) = existing {
|
||||
client
|
||||
.update_state(remote.id, &item.file_name, bytes)
|
||||
.await?;
|
||||
} else {
|
||||
client
|
||||
.upload_state(rom_id, Some(&emu_name), &item.file_name, bytes)
|
||||
.await?;
|
||||
}
|
||||
cfg.synced_state_hashes.insert(item.local_path.clone(), hash);
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"push_state",
|
||||
format!("Uploaded state '{}'", item.file_name),
|
||||
);
|
||||
} else {
|
||||
let slot = if item.slot.trim().is_empty() {
|
||||
"default"
|
||||
} else {
|
||||
&item.slot
|
||||
};
|
||||
client
|
||||
.upload_save(
|
||||
rom_id,
|
||||
Some(&emu_name),
|
||||
Some(slot),
|
||||
cfg.connection.device_id.as_deref(),
|
||||
None,
|
||||
true,
|
||||
&item.file_name,
|
||||
bytes,
|
||||
)
|
||||
.await?;
|
||||
push_log(
|
||||
cfg,
|
||||
"success",
|
||||
"push_save",
|
||||
format!("Uploaded save '{}' (slot: {})", item.file_name, slot),
|
||||
);
|
||||
}
|
||||
Ok(format!("Uploaded {}", item.file_name))
|
||||
}
|
||||
@@ -0,0 +1,725 @@
|
||||
use crate::config::{load_config, push_log, save_config, ManualLink};
|
||||
use crate::matcher::discover_nextui_saves;
|
||||
use crate::nextui::{discover_nextui_systems, resolve_rom_dest_folder};
|
||||
use crate::romm_api::RommClient;
|
||||
use crate::sync_engine::{
|
||||
load_conflicts, pull_single_save, pull_single_state, push_single_item, resolve_conflict,
|
||||
run_sync,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::net::UdpSocket;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
pub fn local_lan_ip() -> String {
|
||||
if let Ok(sock) = UdpSocket::bind("0.0.0.0:0") {
|
||||
if sock.connect("8.8.8.8:80").is_ok() {
|
||||
if let Ok(addr) = sock.local_addr() {
|
||||
return addr.ip().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
"127.0.0.1".to_string()
|
||||
}
|
||||
|
||||
pub async fn serve_web_setup(port: u16) -> Result<(), String> {
|
||||
let bind_addr = format!("0.0.0.0:{}", port);
|
||||
let listener = TcpListener::bind(&bind_addr)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to bind {}: {}", bind_addr, e))?;
|
||||
|
||||
let ip = local_lan_ip();
|
||||
println!("WEB_SETUP_URL=http://{}:{}", ip, port);
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {
|
||||
break;
|
||||
}
|
||||
accepted = listener.accept() => {
|
||||
if let Ok((stream, _)) = accepted {
|
||||
tokio::spawn(async move {
|
||||
let _ = handle_connection(stream).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_connection(mut stream: TcpStream) -> Result<(), String> {
|
||||
let mut buf = vec![0u8; 64 * 1024];
|
||||
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let req_str = String::from_utf8_lossy(&buf[..n]);
|
||||
let mut lines = req_str.lines();
|
||||
let request_line = lines.next().unwrap_or("");
|
||||
let mut parts = request_line.split_whitespace();
|
||||
let method = parts.next().unwrap_or("GET");
|
||||
let path = parts.next().unwrap_or("/");
|
||||
|
||||
let body = req_str
|
||||
.split("\r\n\r\n")
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.trim_end_matches('\0');
|
||||
|
||||
let (status, content_type, resp_body) = match (method, path) {
|
||||
("GET", "/") => ("200 OK", "text/html; charset=utf-8", INDEX_HTML.to_string()),
|
||||
("GET", "/api/state") => {
|
||||
let cfg = load_config();
|
||||
let systems = discover_nextui_systems(&cfg);
|
||||
let conflicts = load_conflicts();
|
||||
let payload = serde_json::json!({
|
||||
"connected": cfg.connection.access_token.is_some() && !cfg.connection.server_url.is_empty(),
|
||||
"serverUrl": cfg.connection.server_url,
|
||||
"username": cfg.connection.username,
|
||||
"deviceId": cfg.connection.device_id,
|
||||
"deviceName": cfg.connection.device_name,
|
||||
"settings": cfg.settings,
|
||||
"systems": systems,
|
||||
"conflicts": conflicts,
|
||||
"logs": cfg.sync_logs.iter().take(25).collect::<Vec<_>>(),
|
||||
});
|
||||
("200 OK", "application/json", payload.to_string())
|
||||
}
|
||||
("POST", "/api/connect") => handle_connect(body).await,
|
||||
("POST", "/api/test-server") => handle_test_server(body).await,
|
||||
("POST", "/api/device-auth/init") => handle_device_auth_init(body).await,
|
||||
("POST", "/api/device-auth/poll") => handle_device_auth_poll(body).await,
|
||||
("POST", "/api/sync") => handle_sync().await,
|
||||
("POST", "/api/resolve") => handle_resolve(body).await,
|
||||
("GET", "/api/saves") => handle_list_saves().await,
|
||||
("POST", "/api/link") => handle_manual_link(body).await,
|
||||
("POST", "/api/roms/search") => handle_search_roms(body).await,
|
||||
("POST", "/api/roms/download") => handle_download_rom(body).await,
|
||||
("POST", "/api/roms/assets") => handle_rom_assets(body).await,
|
||||
("POST", "/api/saves/pull") => handle_pull_save(body).await,
|
||||
("POST", "/api/states/pull") => handle_pull_state(body).await,
|
||||
("POST", "/api/saves/push") => handle_push_rom_saves(body).await,
|
||||
_ => ("404 Not Found", "application/json", r#"{"error":"Not found"}"#.into()),
|
||||
};
|
||||
|
||||
let response = format!(
|
||||
"HTTP/1.1 {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
status,
|
||||
content_type,
|
||||
resp_body.len(),
|
||||
resp_body
|
||||
);
|
||||
stream
|
||||
.write_all(response.as_bytes())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ConnectBody {
|
||||
server_url: String,
|
||||
device_name: Option<String>,
|
||||
mode: String, // "pair_code" | "token" | "password"
|
||||
pair_code: Option<String>,
|
||||
token: Option<String>,
|
||||
username: Option<String>,
|
||||
password: Option<String>,
|
||||
}
|
||||
|
||||
async fn handle_connect(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: ConnectBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
|
||||
let mut cfg = load_config();
|
||||
cfg.connection.server_url = parsed.server_url.trim().trim_end_matches('/').to_string();
|
||||
if let Some(dn) = parsed.device_name {
|
||||
if !dn.trim().is_empty() {
|
||||
cfg.connection.device_name = dn.trim().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
let result: Result<String, String> = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, None)?;
|
||||
let (access_token, device_id_opt) = match parsed.mode.as_str() {
|
||||
"pair_code" => {
|
||||
let code = parsed.pair_code.unwrap_or_default();
|
||||
let res = client.exchange_pair_code(&code).await?;
|
||||
(res.raw_token, res.device_id)
|
||||
}
|
||||
"token" => (parsed.token.unwrap_or_default().trim().to_string(), None),
|
||||
"password" => {
|
||||
let tok = client
|
||||
.login_password(
|
||||
&parsed.username.unwrap_or_default(),
|
||||
&parsed.password.unwrap_or_default(),
|
||||
)
|
||||
.await?;
|
||||
cfg.connection.refresh_token = tok.refresh_token;
|
||||
(tok.access_token, None)
|
||||
}
|
||||
_ => return Err("Unsupported auth mode".into()),
|
||||
};
|
||||
|
||||
let authed = RommClient::new(&cfg.connection.server_url, Some(access_token.clone()))?;
|
||||
let user = authed.get_me().await?;
|
||||
let device_id = match device_id_opt {
|
||||
Some(id) => Some(id),
|
||||
None => authed
|
||||
.register_device(&cfg.connection.device_name)
|
||||
.await
|
||||
.ok()
|
||||
.map(|d| d.id)
|
||||
.or(user.current_device_id),
|
||||
};
|
||||
|
||||
cfg.connection.access_token = Some(access_token);
|
||||
cfg.connection.device_id = device_id;
|
||||
cfg.connection.username = Some(user.username.clone());
|
||||
push_log(&mut cfg, "success", "auth", format!("Paired handheld as {}", user.username));
|
||||
save_config(&cfg)?;
|
||||
Ok(user.username)
|
||||
}
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(u) => ("200 OK", "application/json", serde_json::json!({"ok": true, "username": u}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ServerUrlBody {
|
||||
server_url: String,
|
||||
device_name: Option<String>,
|
||||
}
|
||||
|
||||
async fn handle_test_server(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: ServerUrlBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let res = async {
|
||||
let client = RommClient::new(&parsed.server_url, None)?;
|
||||
client.heartbeat().await
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(_) => ("200 OK", "application/json", r#"{"ok":true}"#.into()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_device_auth_init(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: ServerUrlBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
cfg.connection.server_url = parsed.server_url.trim().trim_end_matches('/').to_string();
|
||||
if let Some(dn) = parsed.device_name {
|
||||
if !dn.trim().is_empty() {
|
||||
cfg.connection.device_name = dn.trim().to_string();
|
||||
}
|
||||
}
|
||||
let _ = save_config(&cfg);
|
||||
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, None)?;
|
||||
client
|
||||
.device_auth_init(
|
||||
&cfg.connection.client_device_identifier,
|
||||
&cfg.connection.device_name,
|
||||
)
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(init) => ("200 OK", "application/json", serde_json::to_string(&init).unwrap_or_default()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DevicePollBody {
|
||||
server_url: String,
|
||||
device_code: String,
|
||||
}
|
||||
|
||||
async fn handle_device_auth_poll(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: DevicePollBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let res = async {
|
||||
let client = RommClient::new(&parsed.server_url, None)?;
|
||||
let Some(tok) = client.device_auth_poll(&parsed.device_code).await? else {
|
||||
return Ok::<_, String>(None);
|
||||
};
|
||||
let authed = RommClient::new(&parsed.server_url, Some(tok.access_token.clone()))?;
|
||||
let user = authed.get_me().await?;
|
||||
let mut cfg = load_config();
|
||||
cfg.connection.server_url = parsed.server_url.trim().trim_end_matches('/').to_string();
|
||||
cfg.connection.access_token = Some(tok.access_token);
|
||||
cfg.connection.device_id = Some(tok.device_id);
|
||||
cfg.connection.username = Some(user.username.clone());
|
||||
push_log(&mut cfg, "success", "auth", format!("Paired handheld as {}", user.username));
|
||||
save_config(&cfg)?;
|
||||
Ok(Some(user.username))
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(Some(u)) => ("200 OK", "application/json", serde_json::json!({"ok": true, "username": u}).to_string()),
|
||||
Ok(None) => ("200 OK", "application/json", r#"{"pending":true}"#.into()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_sync() -> (&'static str, &'static str, String) {
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let summary = run_sync(&client, &mut cfg, &roms).await?;
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(summary)
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(s) => ("200 OK", "application/json", serde_json::to_string(&s).unwrap_or_default()),
|
||||
Err(e) => ("500 Internal Server Error", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ResolveBody {
|
||||
conflict_id: String,
|
||||
resolution: String,
|
||||
}
|
||||
|
||||
async fn handle_resolve(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: ResolveBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let msg = resolve_conflict(&client, &mut cfg, &parsed.conflict_id, &parsed.resolution).await?;
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(msg)
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(msg) => ("200 OK", "application/json", serde_json::json!({"ok": true, "message": msg}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_list_saves() -> (&'static str, &'static str, String) {
|
||||
let cfg = load_config();
|
||||
let roms = match RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone()) {
|
||||
Ok(c) if cfg.connection.access_token.is_some() => c.get_all_roms().await.unwrap_or_default(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let saves = discover_nextui_saves(&cfg, &roms);
|
||||
(
|
||||
"200 OK",
|
||||
"application/json",
|
||||
serde_json::json!({"saves": saves, "romCount": roms.len()}).to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn handle_manual_link(body: &str) -> (&'static str, &'static str, String) {
|
||||
let link: ManualLink = match serde_json::from_str(body) {
|
||||
Ok(l) => l,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
cfg.manual_links.insert(link.local_path.clone(), link);
|
||||
match save_config(&cfg) {
|
||||
Ok(()) => ("200 OK", "application/json", r#"{"ok":true}"#.into()),
|
||||
Err(e) => ("500 Internal Server Error", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SearchRomsBody {
|
||||
query: Option<String>,
|
||||
}
|
||||
|
||||
async fn handle_search_roms(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: SearchRomsBody = serde_json::from_str(body).unwrap_or(SearchRomsBody { query: None });
|
||||
let cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
client.get_roms(None, parsed.query.as_deref(), 40, 0).await
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(page) => ("200 OK", "application/json", serde_json::to_string(&page).unwrap_or_default()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RomDownloadBody {
|
||||
rom_id: i64,
|
||||
file_name: String,
|
||||
platform_slug: String,
|
||||
platform_display_name: String,
|
||||
}
|
||||
|
||||
async fn handle_download_rom(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: RomDownloadBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let dest_dir = resolve_rom_dest_folder(&parsed.platform_slug, &parsed.platform_display_name, &cfg);
|
||||
let dest_file = dest_dir.join(&parsed.file_name);
|
||||
client.download_rom(parsed.rom_id, &parsed.file_name, &dest_file).await?;
|
||||
push_log(&mut cfg, "success", "download_rom", format!("Downloaded {} to {}", parsed.file_name, dest_file.display()));
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(dest_file.to_string_lossy().to_string())
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(path) => ("200 OK", "application/json", serde_json::json!({"ok": true, "path": path}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct RomIdBody {
|
||||
rom_id: i64,
|
||||
}
|
||||
|
||||
async fn handle_rom_assets(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: RomIdBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let saves = client.get_saves(Some(parsed.rom_id), cfg.connection.device_id.as_deref()).await?;
|
||||
let states = client.get_states(Some(parsed.rom_id)).await?;
|
||||
Ok::<_, String>(serde_json::json!({"saves": saves, "states": states}))
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(v) => ("200 OK", "application/json", v.to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct PullAssetBody {
|
||||
id: i64,
|
||||
rom_id: i64,
|
||||
platform_slug: String,
|
||||
file_name: String,
|
||||
}
|
||||
|
||||
async fn handle_pull_save(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: PullAssetBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let path = pull_single_save(&client, &mut cfg, parsed.id, parsed.rom_id, &parsed.platform_slug, &parsed.file_name).await?;
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(path)
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(path) => ("200 OK", "application/json", serde_json::json!({"ok": true, "path": path}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_pull_state(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: PullAssetBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let path = pull_single_state(&client, &mut cfg, parsed.id, parsed.rom_id, &parsed.platform_slug, &parsed.file_name).await?;
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(path)
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(path) => ("200 OK", "application/json", serde_json::json!({"ok": true, "path": path}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_push_rom_saves(body: &str) -> (&'static str, &'static str, String) {
|
||||
let parsed: RomIdBody = match serde_json::from_str(body) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return ("400 Bad Request", "application/json", serde_json::json!({"error": e.to_string()}).to_string()),
|
||||
};
|
||||
let mut cfg = load_config();
|
||||
let res = async {
|
||||
let client = RommClient::new(&cfg.connection.server_url, cfg.connection.access_token.clone())?;
|
||||
let roms = client.get_all_roms().await?;
|
||||
let local = discover_nextui_saves(&cfg, &roms);
|
||||
let matched: Vec<_> = local.into_iter().filter(|i| i.matched_rom_id == Some(parsed.rom_id)).collect();
|
||||
if matched.is_empty() {
|
||||
return Err("No local saves found on SD card for this game.".into());
|
||||
}
|
||||
let mut count = 0usize;
|
||||
for item in matched {
|
||||
push_single_item(&client, &mut cfg, &item, parsed.rom_id).await?;
|
||||
count += 1;
|
||||
}
|
||||
save_config(&cfg)?;
|
||||
Ok::<_, String>(count)
|
||||
}
|
||||
.await;
|
||||
match res {
|
||||
Ok(count) => ("200 OK", "application/json", serde_json::json!({"ok": true, "count": count}).to_string()),
|
||||
Err(e) => ("400 Bad Request", "application/json", serde_json::json!({"error": e}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
const INDEX_HTML: &str = r#"<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1"/>
|
||||
<title>RomM Companion — NextUI Setup</title>
|
||||
<style>
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,sans-serif;background:#020617;color:#f1f5f9;margin:0;padding:16px;line-height:1.5}
|
||||
.wrap{max-width:680px;margin:0 auto}
|
||||
.card{background:#0f172a;border:1px solid #1e293b;border-radius:14px;padding:18px;margin-bottom:14px}
|
||||
h1{font-size:20px;margin:0 0 4px} h2{font-size:15px;margin:0 0 10px;color:#cbd5e1}
|
||||
.muted{color:#94a3b8;font-size:13px}
|
||||
input,select,button{width:100%;box-sizing:border-box;padding:10px 12px;border-radius:9px;border:1px solid #334155;background:#020617;color:#f8fafc;font-size:14px;margin-bottom:10px}
|
||||
button{background:#4f46e5;border:none;font-weight:600;cursor:pointer}
|
||||
button.sec{background:#1e293b}
|
||||
button:disabled{opacity:.5}
|
||||
.row{display:flex;gap:8px}
|
||||
.badge{display:inline-block;padding:2px 8px;border-radius:99px;font-size:11px;background:#1e293b;color:#a5b4fc;margin-right:6px}
|
||||
.ok{color:#34d399} .err{color:#fb7185}
|
||||
.item{border-top:1px solid #1e293b;padding:10px 0;font-size:13px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="card">
|
||||
<h1>RomM Companion for NextUI</h1>
|
||||
<div id="status" class="muted">Loading handheld status...</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Connect to RomM 5.1.0</h2>
|
||||
<div class="row">
|
||||
<input id="url" placeholder="https://rom.example.com" />
|
||||
<button class="sec" style="width:auto;white-space:nowrap" onclick="testServer()">Test</button>
|
||||
</div>
|
||||
<input id="devName" placeholder="TrimUI Smart Pro S (NextUI)" />
|
||||
<select id="mode" onchange="toggleMode()">
|
||||
<option value="device">Passwordless Device Pairing (Recommended)</option>
|
||||
<option value="pair_code">One-Time Pair Code (RomM Client Tokens)</option>
|
||||
<option value="token">Raw API Token</option>
|
||||
<option value="password">Username & Password</option>
|
||||
</select>
|
||||
<div id="f_dev" class="muted" style="margin-bottom:10px">Starts RomM 5.1.0 device pairing and gives you a one-tap approval link.</div>
|
||||
<div id="f_pair" style="display:none"><input id="pairCode" placeholder="Pair code (e.g. ABCD-1234)" /></div>
|
||||
<div id="f_tok" style="display:none"><input id="token" type="password" placeholder="Paste API token" /></div>
|
||||
<div id="f_pw" style="display:none">
|
||||
<input id="user" placeholder="Username" />
|
||||
<input id="pass" type="password" placeholder="Password" />
|
||||
</div>
|
||||
<button onclick="connect()">Save & Connect</button>
|
||||
<div id="connMsg" class="muted"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Quick Actions</h2>
|
||||
<button id="syncBtn" onclick="runSync()">Sync Saves & States Now</button>
|
||||
<div id="syncMsg" class="muted"></div>
|
||||
</div>
|
||||
|
||||
<div id="conflictsCard" class="card" style="display:none">
|
||||
<h2>Conflicts</h2>
|
||||
<div id="conflictsList"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Games & Individual Saves</h2>
|
||||
<div class="row">
|
||||
<input id="romQ" placeholder="Search RomM games..." />
|
||||
<button style="width:auto;white-space:nowrap" onclick="searchRoms()">Search</button>
|
||||
</div>
|
||||
<div id="romMsg" class="muted"></div>
|
||||
<div id="romsList"></div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Detected NextUI Systems</h2>
|
||||
<div id="systemsList" class="muted">Scanning SD card...</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
function toggleMode(){
|
||||
const m=document.getElementById('mode').value;
|
||||
document.getElementById('f_dev').style.display=m==='device'?'block':'none';
|
||||
document.getElementById('f_pair').style.display=m==='pair_code'?'block':'none';
|
||||
document.getElementById('f_tok').style.display=m==='token'?'block':'none';
|
||||
document.getElementById('f_pw').style.display=m==='password'?'block':'none';
|
||||
}
|
||||
async function testServer(){
|
||||
const msg=document.getElementById('connMsg'); msg.textContent='Testing server...';
|
||||
const r=await fetch('/api/test-server',{method:'POST',body:JSON.stringify({serverUrl:document.getElementById('url').value})});
|
||||
const d=await r.json();
|
||||
msg.innerHTML=d.ok?'<span class="ok">RomM server reachable!</span>':`<span class="err">${d.error}</span>`;
|
||||
}
|
||||
async function loadState(){
|
||||
const r=await fetch('/api/state'); const s=await r.json();
|
||||
document.getElementById('url').value=s.serverUrl||'https://';
|
||||
document.getElementById('devName').value=s.deviceName||'TrimUI (NextUI)';
|
||||
document.getElementById('status').innerHTML=s.connected
|
||||
? `<span class="ok">Connected</span> to <b>${s.serverUrl}</b> as <b>${s.username}</b>`
|
||||
: 'Not connected yet — enter your RomM 5.1.0 server below.';
|
||||
const sysEl=document.getElementById('systemsList');
|
||||
sysEl.innerHTML=(s.systems||[]).length
|
||||
? s.systems.map(x=>`<span class="badge">${x.tag}</span>`).join('')
|
||||
: 'No /Saves or /Roms folders detected yet.';
|
||||
const cCard=document.getElementById('conflictsCard');
|
||||
if((s.conflicts||[]).length){
|
||||
cCard.style.display='block';
|
||||
document.getElementById('conflictsList').innerHTML=s.conflicts.map(c=>`
|
||||
<div class="item">
|
||||
<div><b>${c.romName}</b> (${c.fileName})</div>
|
||||
<div class="muted">${c.reason}</div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<button onclick="resolve('${c.id}','keep_local')">Keep Handheld</button>
|
||||
<button class="sec" onclick="resolve('${c.id}','keep_server')">Keep Server</button>
|
||||
</div>
|
||||
</div>`).join('');
|
||||
} else { cCard.style.display='none'; }
|
||||
}
|
||||
let pollTimer=null;
|
||||
async function connect(){
|
||||
const msg=document.getElementById('connMsg');
|
||||
const m=document.getElementById('mode').value;
|
||||
const serverUrl=document.getElementById('url').value.trim().replace(/\/+$/,'');
|
||||
const deviceName=document.getElementById('devName').value;
|
||||
if(m==='device'){
|
||||
msg.textContent='Starting device pairing...';
|
||||
const r=await fetch('/api/device-auth/init',{method:'POST',body:JSON.stringify({serverUrl,deviceName})});
|
||||
const d=await r.json();
|
||||
if(d.error){msg.innerHTML=`<span class="err">${d.error}</span>`;return;}
|
||||
const link=d.verification_path_complete.startsWith('http')?d.verification_path_complete:(serverUrl+d.verification_path_complete);
|
||||
msg.innerHTML=`Code: <b>${d.user_code}</b> — <a href="${link}" target="_blank" style="color:#818cf8">Approve in RomM</a> (waiting...)`;
|
||||
if(pollTimer)clearInterval(pollTimer);
|
||||
pollTimer=setInterval(async()=>{
|
||||
const pr=await fetch('/api/device-auth/poll',{method:'POST',body:JSON.stringify({serverUrl,deviceCode:d.device_code})});
|
||||
const pd=await pr.json();
|
||||
if(pd.ok){clearInterval(pollTimer);msg.innerHTML=`<span class="ok">Paired as ${pd.username}!</span>`;loadState();}
|
||||
else if(pd.error){clearInterval(pollTimer);msg.innerHTML=`<span class="err">${pd.error}</span>`;}
|
||||
},Math.max((d.interval||5)*1000,2500));
|
||||
return;
|
||||
}
|
||||
msg.textContent='Connecting...';
|
||||
const body={
|
||||
serverUrl,deviceName,mode:m,
|
||||
pairCode:document.getElementById('pairCode').value,
|
||||
token:document.getElementById('token').value,
|
||||
username:document.getElementById('user').value,
|
||||
password:document.getElementById('pass').value
|
||||
};
|
||||
const r=await fetch('/api/connect',{method:'POST',body:JSON.stringify(body)});
|
||||
const d=await r.json();
|
||||
msg.innerHTML=d.ok?`<span class="ok">Connected as ${d.username}!</span>`:`<span class="err">${d.error}</span>`;
|
||||
loadState();
|
||||
}
|
||||
async function runSync(){
|
||||
const b=document.getElementById('syncBtn'), m=document.getElementById('syncMsg');
|
||||
b.disabled=true; m.textContent='Syncing with RomM 5.1.0...';
|
||||
const r=await fetch('/api/sync',{method:'POST'}); const d=await r.json();
|
||||
b.disabled=false;
|
||||
m.innerHTML=d.error
|
||||
? `<span class="err">${d.error}</span>`
|
||||
: `<span class="ok">Done! Uploaded ${d.uploadedSaves} saves, downloaded ${d.downloadedSaves}, synced ${d.uploadedStates} states, ${d.upToDate} up-to-date.</span>`;
|
||||
loadState();
|
||||
}
|
||||
async function resolve(id,resolution){
|
||||
await fetch('/api/resolve',{method:'POST',body:JSON.stringify({conflictId:id,resolution})});
|
||||
loadState();
|
||||
}
|
||||
async function searchRoms(){
|
||||
const m=document.getElementById('romMsg'), el=document.getElementById('romsList');
|
||||
m.textContent='Searching RomM...'; el.innerHTML='';
|
||||
const r=await fetch('/api/roms/search',{method:'POST',body:JSON.stringify({query:document.getElementById('romQ').value})});
|
||||
const d=await r.json();
|
||||
if(d.error){m.innerHTML=`<span class="err">${d.error}</span>`;return;}
|
||||
m.textContent=`Showing ${(d.items||[]).length} of ${d.total||0} games`;
|
||||
el.innerHTML=(d.items||[]).map(g=>`
|
||||
<div class="item">
|
||||
<div><b>${g.name||g.fs_name_no_ext}</b> <span class="badge">${g.platform_display_name}</span></div>
|
||||
<div class="row" style="margin-top:8px">
|
||||
<button onclick='dlRom(${JSON.stringify({romId:g.id,fileName:g.fs_name,platformSlug:g.platform_slug,platformDisplayName:g.platform_display_name})})'>Download ROM</button>
|
||||
<button class="sec" onclick='showSaves(${g.id},${JSON.stringify(g.platform_slug)})'>Saves / States</button>
|
||||
</div>
|
||||
<div id="assets_${g.id}" style="margin-top:6px"></div>
|
||||
</div>`).join('');
|
||||
}
|
||||
async function dlRom(payload){
|
||||
const m=document.getElementById('romMsg'); m.textContent=`Downloading ${payload.fileName}...`;
|
||||
const r=await fetch('/api/roms/download',{method:'POST',body:JSON.stringify(payload)});
|
||||
const d=await r.json();
|
||||
m.innerHTML=d.ok?`<span class="ok">Saved ROM to ${d.path}</span>`:`<span class="err">${d.error}</span>`;
|
||||
}
|
||||
async function showSaves(romId,platformSlug){
|
||||
const box=document.getElementById('assets_'+romId); box.innerHTML='<span class="muted">Loading saves...</span>';
|
||||
const r=await fetch('/api/roms/assets',{method:'POST',body:JSON.stringify({romId})});
|
||||
const d=await r.json();
|
||||
if(d.error){box.innerHTML=`<span class="err">${d.error}</span>`;return;}
|
||||
let html='';
|
||||
for(const s of (d.saves||[])){
|
||||
html+=`<div class="row" style="margin-top:4px"><span class="muted" style="flex:1">${s.file_name} (${s.slot||'manual'})</span><button style="width:auto" onclick='pullAsset("save",${JSON.stringify({id:s.id,romId,platformSlug,fileName:s.file_name})})'>Pull Save</button></div>`;
|
||||
}
|
||||
for(const st of (d.states||[])){
|
||||
html+=`<div class="row" style="margin-top:4px"><span class="muted" style="flex:1">[State] ${st.file_name}</span><button class="sec" style="width:auto" onclick='pullAsset("state",${JSON.stringify({id:st.id,romId,platformSlug,fileName:st.file_name})})'>Pull State</button></div>`;
|
||||
}
|
||||
html+=`<button class="sec" style="margin-top:6px" onclick="pushRomSaves(${romId})">Push Local Saves for This Game</button>`;
|
||||
box.innerHTML=html;
|
||||
}
|
||||
async function pullAsset(kind,payload){
|
||||
const m=document.getElementById('romMsg'); m.textContent=`Downloading ${payload.fileName}...`;
|
||||
const r=await fetch(kind==='save'?'/api/saves/pull':'/api/states/pull',{method:'POST',body:JSON.stringify(payload)});
|
||||
const d=await r.json();
|
||||
m.innerHTML=d.ok?`<span class="ok">Placed at ${d.path}</span>`:`<span class="err">${d.error}</span>`;
|
||||
}
|
||||
async function pushRomSaves(romId){
|
||||
const m=document.getElementById('romMsg'); m.textContent='Uploading local saves...';
|
||||
const r=await fetch('/api/saves/push',{method:'POST',body:JSON.stringify({romId})});
|
||||
const d=await r.json();
|
||||
m.innerHTML=d.ok?`<span class="ok">Uploaded ${d.count} file(s) to RomM!</span>`:`<span class="err">${d.error}</span>`;
|
||||
}
|
||||
loadState();
|
||||
</script>
|
||||
</body>
|
||||
</html>"#;
|
||||
Reference in new issue
Block a user