diff --git a/crates/coa-core/src/bin/csm_plugins.rs b/crates/coa-core/src/bin/csm_plugins.rs new file mode 100644 index 0000000..5fd214e --- /dev/null +++ b/crates/coa-core/src/bin/csm_plugins.rs @@ -0,0 +1,147 @@ +//! CLI tool for CoA Server Manager plugin operations (testing and automation). +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use coa_core::plugins::{ + self, PluginMetadata, +}; + +fn print_usage() { + eprintln!( + r#"csm_plugins CLI +Usage: + csm_plugins install [--pdb ] [--conf ] [--deps ] [--enable] + csm_plugins enable + csm_plugins disable + csm_plugins repair + csm_plugins list +"# + ); +} + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + if args.len() < 3 { + print_usage(); + std::process::exit(1); + } + + let cmd = &args[1]; + let server = Path::new(&args[2]); + + match cmd.as_str() { + "install" => { + if args.len() < 7 { + eprintln!("Usage: install [--pdb ] [--conf ] [--deps ] [--enable]"); + std::process::exit(1); + } + let id = &args[3]; + let name = &args[4]; + let version = &args[5]; + let dll_path = Path::new(&args[6]); + let dll_bytes = fs::read(dll_path)?; + let digest = plugins::sha256_digest(&dll_bytes); + + let mut pdb_bytes = None; + let mut conf_list = Vec::new(); + let mut deps = Vec::new(); + let mut enable = false; + + let mut i = 7; + while i < args.len() { + match args[i].as_str() { + "--pdb" => { + i += 1; + if i < args.len() { + pdb_bytes = Some(fs::read(&args[i])?); + } + } + "--conf" => { + i += 1; + if i < args.len() { + for item in args[i].split(',') { + if !item.is_empty() { + let p = Path::new(item); + let file_name = p.file_name().unwrap().to_string_lossy().into_owned(); + let bytes = fs::read(p)?; + conf_list.push((file_name, bytes)); + } + } + } + } + "--deps" => { + i += 1; + if i < args.len() { + deps = args[i].split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect(); + } + } + "--enable" => { + enable = true; + } + _ => {} + } + i += 1; + } + + let conf_names: Vec = conf_list.iter().map(|(n, _)| n.clone()).collect(); + let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect(); + + let meta = PluginMetadata { + id: id.clone(), + name: name.clone(), + version: version.clone(), + description: BTreeMap::new(), + sha256: digest, + required: true, + deps, + conf_files: conf_names, + enable_key: None, + status: Some("release".into()), + icon: None, + }; + + plugins::install(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs, enable)?; + println!("Installed plugin '{}' successfully (enabled: {})", id, enable); + } + "enable" => { + if args.len() < 4 { + eprintln!("Usage: enable "); + std::process::exit(1); + } + let id = &args[3]; + plugins::set_enabled(server, id, true)?; + println!("Enabled plugin '{}' successfully", id); + } + "disable" => { + if args.len() < 4 { + eprintln!("Usage: disable "); + std::process::exit(1); + } + let id = &args[3]; + plugins::set_enabled(server, id, false)?; + println!("Disabled plugin '{}' successfully", id); + } + "repair" => { + let restored = plugins::repair(server)?; + println!("Repair complete. Restored {} plugin(s): {:?}", restored.len(), restored); + } + "list" => { + let reg = plugins::load_registry(server)?; + println!("Plugins schema {}:", reg.schema); + for (id, p) in reg.plugins { + println!( + " - {}: enabled={}, version={}, sha256={}", + id, p.enabled, p.version, p.sha256 + ); + } + } + _ => { + eprintln!("Unknown command: {}", cmd); + print_usage(); + std::process::exit(1); + } + } + + Ok(()) +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index e6db8d7..4898a2c 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -44,6 +44,7 @@ pub mod net; pub mod package; pub mod pkgsource; pub mod platform; +pub mod plugins; pub mod population; pub mod portable; pub mod process; diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index e1e0b30..2e02d8a 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -173,6 +173,7 @@ fn installed_module_commits(root: &Path) -> BTreeMap { fn list_in(cat: &[Entry], root: &Path) -> Vec { let installed_commits = installed_module_commits(root); + let plugin_reg = crate::plugins::load_registry(root).ok(); let wildcard = crate::realms::state(root) .map(|s| s.active != crate::realms::Mode::Coa) .unwrap_or(true); @@ -182,13 +183,16 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { let name = conf_name(root, &e); let conf = dir(root).join(&name); let dist = dir(root).join(format!("{name}.dist")); - let installed = conf.is_file() || dist.is_file(); + let plugin_entry = plugin_reg.as_ref().and_then(|r| r.plugins.get(&e.id)); + let installed = conf.is_file() || dist.is_file() || plugin_entry.is_some(); let has_settings = installed && settings_in(cat, root, &e.id) .map(|settings| settings.iter().any(|s| s.key != e.enable_key)) .unwrap_or(false); - // the active file decides; without one the documented default is what the server will use - let enabled = if matches!(e.id.as_str(), "companions" | "playerbots") { + // the active file or plugin registry decides + let enabled = if let Some(p) = plugin_entry { + p.enabled + } else if matches!(e.id.as_str(), "companions" | "playerbots") { bot_enabled(root, &e).unwrap_or(true) } else { !e.switchable @@ -198,7 +202,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { .unwrap_or(e.default_on) }; let blocked = wildcard && matches!(e.id.as_str(), "companions" | "playerbots"); - let version = if e.id == "playerbots" { + let version = if let Some(p) = plugin_entry { + Some(p.version.clone()) + } else if e.id == "playerbots" { crate::squid::release(root).map(|release| { [ release.tag, @@ -296,7 +302,10 @@ fn require_bot_server_stopped(root: &Path) -> Result<()> { pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { let _update_lock = crate::update::operation_lock(meta)?; crate::update::ensure_recovered(meta)?; - let _lock = if matches!(id, "companions" | "playerbots") { + let is_dynamic_plugin = crate::plugins::load_registry(root) + .map(|r| r.plugins.contains_key(id)) + .unwrap_or(false); + let _lock = if is_dynamic_plugin || matches!(id, "companions" | "playerbots") { require_bot_server_stopped(root)?; fs::create_dir_all(root.join(".state"))?; let lock = fs::OpenOptions::new() @@ -408,6 +417,17 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) - &["Changed by CoA Server Manager"], ); fsx::atomic_write(&conf, file.to_text().as_bytes())?; + + // If registered as a dynamic plugin, synchronize plugins.lock and plugin state + if let Ok(reg) = crate::plugins::load_registry(root) { + if reg.plugins.contains_key(id) { + let _ = crate::plugins::set_enabled(root, id, on); + } + } + if id == "playerbots" && on { + let _ = crate::plugins::record_squid_migrations_applied(root); + } + tracing::info!(module = id, on, "module switched"); Ok(()) } diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index 5ec782d..2ee85ab 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -12,12 +12,66 @@ use std::{ path::{Path, PathBuf}, }; -pub fn root(main: &Path) -> PathBuf { - main.join(".realms/secondary") +/// A world that runs next to the primary one. Each has its own folder, configs, logs and ports; auth and MySQL stay shared. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tree { + /// Wildcard next to Conquest of Azeroth (or Conquest of Azeroth next to Wildcard when Wildcard is the primary). + Second, + /// Warcraft Reborn next to Conquest of Azeroth. + Reborn, } -pub fn is_running(main: &Path) -> bool { - let second = root(main); +impl Tree { + pub const ALL: [Tree; 2] = [Tree::Second, Tree::Reborn]; + + fn dir(self) -> &'static str { + match self { + Tree::Second => ".realms/secondary", + Tree::Reborn => ".realms/reborn", + } + } + + fn label(self) -> &'static str { + match self { + Tree::Second => "second realm", + Tree::Reborn => "Warcraft Reborn realm", + } + } + + fn mode(self, active: Mode) -> Mode { + match self { + Tree::Second if active == Mode::Coa => Mode::Wildcard, + Tree::Second => Mode::Coa, + Tree::Reborn => Mode::Reborn, + } + } + + fn enabled(self, s: &RealmState) -> bool { + match self { + Tree::Second => s.simultaneous, + Tree::Reborn => s.with_reborn, + } + } + + fn ports(self, s: &RealmState) -> (Option, Option) { + match self { + Tree::Second => (s.secondary_world_port, s.secondary_ra_port), + Tree::Reborn => (s.reborn_world_port, s.reborn_ra_port), + } + } +} + +pub fn tree_root(main: &Path, tree: Tree) -> PathBuf { + main.join(tree.dir()) +} + +/// The folder of the second realm (Wildcard next to Conquest of Azeroth). +pub fn root(main: &Path) -> PathBuf { + tree_root(main, Tree::Second) +} + +pub fn tree_running(main: &Path, tree: Tree) -> bool { + let second = tree_root(main, tree); if !second.exists() { return false; } @@ -28,6 +82,11 @@ pub fn is_running(main: &Path) -> bool { .any(|n| process::read_state_record(&second, n).is_some_and(|p| process::is_alive(&p))) } +/// Any of the extra worlds is running or still stopping. +pub fn is_running(main: &Path) -> bool { + Tree::ALL.into_iter().any(|t| tree_running(main, t)) +} + fn copy_tree(from: &Path, to: &Path) -> Result<()> { fs::create_dir_all(to)?; for entry in fs::read_dir(from)? { @@ -55,23 +114,52 @@ fn copy_tree(from: &Path, to: &Path) -> Result<()> { Ok(()) } +/// Start Wildcard together with Conquest of Azeroth. pub fn set_enabled(main: &Path, enabled: bool) -> Result { + set_tree(main, Tree::Second, enabled) +} + +/// Start Warcraft Reborn together with Conquest of Azeroth. +pub fn set_reborn_enabled(main: &Path, enabled: bool) -> Result { + set_tree(main, Tree::Reborn, enabled) +} + +fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result { if enabled && !cfg!(windows) { return Err(Error::Invalid( "Simultaneous realms currently require Windows.".into(), )); } if enabled { - if realms::state(main)?.active == Mode::Reborn { - return Err(Error::Invalid( - "Simultaneous startup supports CoA and Wildcard. Select one of these realms first." - .into(), - )); - } - if !realms::view(main)?.supported { - return Err(Error::Invalid( - "Update the server to a build with Wildcard support first.".into(), - )); + let active = realms::state(main)?.active; + let view = realms::view(main)?; + match tree { + Tree::Second => { + if active == Mode::Reborn { + return Err(Error::Invalid( + "Wildcard starts together with Conquest of Azeroth. Select Conquest of Azeroth first." + .into(), + )); + } + if !view.supported { + return Err(Error::Invalid( + "Update the server to a build with Wildcard support first.".into(), + )); + } + } + Tree::Reborn => { + if active != Mode::Coa { + return Err(Error::Invalid( + "Warcraft Reborn starts together with Conquest of Azeroth. Select Conquest of Azeroth first." + .into(), + )); + } + if !view.reborn_supported { + return Err(Error::Invalid( + "Update the server to a build with Warcraft Reborn support first.".into(), + )); + } + } } secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?; } @@ -81,20 +169,21 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result { || is_running(main) { return Err(Error::Invalid( - "Stop both realms before changing simultaneous startup.".into(), + "Stop all realms before changing which realms start together.".into(), )); } - let original = realms::state(main)?.active; - if enabled && !realms::state(main)?.wildcard_created { - realms::select(main, Mode::Wildcard)?; - if original != Mode::Wildcard { - realms::select(main, original)?; - } + if enabled { + realms::ensure_created(main, tree.mode(realms::state(main)?.active))?; } let mut s = realms::state(main)?; if enabled { let p = crate::layout::read_ports(main); let mut reserved = vec![p.mysql, p.auth, p.world, p.ra]; + // Ports already saved for any other extra world stay reserved, so two worlds never get the same one. + for other in Tree::ALL.into_iter().filter(|t| *t != tree) { + let (world, ra) = other.ports(&s); + reserved.extend(world.into_iter().chain(ra)); + } let mut choose = |saved: Option, near: u16| -> Result { if let Some(port) = saved.filter(|p| *p > 0 && !reserved.contains(p)) { reserved.push(port); @@ -104,31 +193,41 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result { .find(|p| { !reserved.contains(p) && std::net::TcpListener::bind(("127.0.0.1", *p)).is_ok() }) - .ok_or_else(|| Error::Invalid("No free port for the second realm.".into()))?; + .ok_or_else(|| Error::Invalid(format!("No free port for the {}.", tree.label())))?; reserved.push(port); Ok(port) }; - s.secondary_world_port = Some(choose(s.secondary_world_port, p.world)?); - s.secondary_ra_port = Some(choose(s.secondary_ra_port, p.ra)?); + let (world, ra) = tree.ports(&s); + let (world, ra) = (choose(world, p.world)?, choose(ra, p.ra)?); + match tree { + Tree::Second => { + s.secondary_world_port = Some(world); + s.secondary_ra_port = Some(ra); + } + Tree::Reborn => { + s.reborn_world_port = Some(world); + s.reborn_ra_port = Some(ra); + } + } + } + match tree { + Tree::Second => s.simultaneous = enabled, + Tree::Reborn => s.with_reborn = enabled, } - s.simultaneous = enabled; fsx::atomic_write_json(&main.join("Settings/realm-profile.json"), &s)?; realms::view(main) } -fn prepare(main: &Path) -> Result { - if is_running(main) { - return Err(Error::Invalid( - "The second realm is still running; stop it before preparing its files.".into(), - )); +fn prepare(main: &Path, tree: Tree) -> Result { + if tree_running(main, tree) { + return Err(Error::Invalid(format!( + "The {} is still running; stop it before preparing its files.", + tree.label() + ))); } let s = realms::state(main)?; - let mode = if s.active == Mode::Coa { - Mode::Wildcard - } else { - Mode::Coa - }; - let second = fsx::ensure_within(main, &root(main))?; + let mode = tree.mode(s.active); + let second = fsx::ensure_within(main, &tree_root(main, tree))?; for folder in ["Runtime", "BugReport", "mysql/bin"] { copy_tree( &main.join(folder), @@ -161,6 +260,7 @@ fn prepare(main: &Path) -> Result { )?; } } + let _ = crate::plugins::prepare_multiworld(main, &second); let files: BTreeMap> = fsx::read_json(&main.join(format!("Settings/realm-profiles/{}.json", mode.name())))?; // A previous secondary run may have used the other realm's module files. @@ -214,13 +314,12 @@ fn prepare(main: &Path) -> Result { )?; } let mut cfg: serde_json::Value = fsx::read_json(&main.join("Settings/repack.json"))?; - cfg["worldPort"] = s - .secondary_world_port - .ok_or_else(|| Error::Invalid("Second realm world port is missing.".into()))? + let (world_port, ra_port) = tree.ports(&s); + cfg["worldPort"] = world_port + .ok_or_else(|| Error::Invalid(format!("The {} world port is missing.", tree.label())))? .into(); - cfg["raPort"] = s - .secondary_ra_port - .ok_or_else(|| Error::Invalid("Second realm console port is missing.".into()))? + cfg["raPort"] = ra_port + .ok_or_else(|| Error::Invalid(format!("The {} console port is missing.", tree.label())))? .into(); fsx::atomic_write_json(&second.join("Settings/repack.json"), &cfg)?; fsx::atomic_write( @@ -232,6 +331,7 @@ fn prepare(main: &Path) -> Result { &RealmState { active: mode, wildcard_created: true, + reborn_created: true, ..Default::default() }, )?; @@ -256,12 +356,9 @@ fn secondary_launcher(source: &str) -> Result { )) } -pub fn start(main: &Path) -> Result<()> { - if !realms::state(main)?.simultaneous { - return Ok(()); - } - if is_running(main) { - let second = root(main); +fn start_tree(main: &Path, tree: Tree) -> Result<()> { + if tree_running(main, tree) { + let second = tree_root(main, tree); if process::observe(&second, &crate::layout::read_ports(&second)) .world .state @@ -269,35 +366,50 @@ pub fn start(main: &Path) -> Result<()> { { return Ok(()); } - return Err(Error::Invalid( - "The second realm is still starting or stopping.".into(), - )); + return Err(Error::Invalid(format!( + "The {} is still starting or stopping.", + tree.label() + ))); } - let second = prepare(main)?; + let second = prepare(main, tree)?; let out = driver::run(&second, Verb::StartWorld)?; if !out.ok { return Err(Error::Invalid(format!( - "The second realm did not start: {}", + "The {} did not start: {}", + tree.label(), out.output ))); } Ok(()) } -pub fn stop(main: &Path) -> Result<()> { - let second = root(main); +/// Start every extra world that is switched on. +pub fn start(main: &Path) -> Result<()> { + let s = realms::state(main)?; + for tree in Tree::ALL.into_iter().filter(|t| t.enabled(&s)) { + start_tree(main, tree)?; + } + Ok(()) +} + +fn stop_tree(main: &Path, tree: Tree) -> Result<()> { + let second = tree_root(main, tree); if !second.join("Scripts/manage.py").exists() { - if is_running(main) { - return Err(Error::Invalid("The running second realm's launcher is missing. The shared database was left running.".into())); + if tree_running(main, tree) { + return Err(Error::Invalid(format!( + "The running {}'s launcher is missing. The shared database was left running.", + tree.label() + ))); } return Ok(()); } // Its state has no auth/MySQL records: the shared database remains up until the primary world stops. - if is_running(main) { + if tree_running(main, tree) { let out = driver::run(&second, Verb::StopAll)?; - if !out.ok || is_running(main) { + if !out.ok || tree_running(main, tree) { return Err(Error::Invalid(format!( - "The second realm could not stop; the database was left running: {}", + "The {} could not stop; the database was left running: {}", + tree.label(), out.output ))); } @@ -305,9 +417,54 @@ pub fn stop(main: &Path) -> Result<()> { Ok(()) } +/// Stop every extra world; one that fails does not keep the others running. +pub fn stop(main: &Path) -> Result<()> { + let mut first = None; + for tree in Tree::ALL { + if let Err(e) = stop_tree(main, tree) { + first.get_or_insert(e); + } + } + first.map_or(Ok(()), Err) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn every_extra_world_has_its_own_folder_realm_and_ports() { + let mut s = RealmState::default(); + assert_eq!(Tree::Second.mode(Mode::Coa), Mode::Wildcard); + assert_eq!(Tree::Second.mode(Mode::Wildcard), Mode::Coa); + assert_eq!(Tree::Reborn.mode(Mode::Coa), Mode::Reborn); + assert_ne!(Tree::Second.dir(), Tree::Reborn.dir()); + s.secondary_world_port = Some(8086); + s.reborn_world_port = Some(8087); + assert_eq!(Tree::Second.ports(&s).0, Some(8086)); + assert_eq!(Tree::Reborn.ports(&s).0, Some(8087)); + assert!(!Tree::Second.enabled(&s) && !Tree::Reborn.enabled(&s)); + s.with_reborn = true; + assert!(!Tree::Second.enabled(&s) && Tree::Reborn.enabled(&s)); + } + + #[test] + fn reborn_starts_together_with_conquest_of_azeroth_only() { + let t = tempfile::tempdir().unwrap(); + fsx::atomic_write( + &t.path().join("Core/worldserver.exe"), + b"Warcraft Reborn class spells are unavailable", + ) + .unwrap(); + fsx::atomic_write( + &t.path().join("Settings/realm-profile.json"), + br#"{"active":"wildcard","wildcard_created":true}"#, + ) + .unwrap(); + let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string(); + assert!(err.contains("Select Conquest of Azeroth first"), "{err}"); + assert!(!realms::state(t.path()).unwrap().with_reborn); + } + #[test] fn secondary_never_starts_the_shared_database() { let patched = secondary_launcher("def start_world(config, offset):\r\n start_mysql(config)\r\n wait_ready('world', 8086)\r\n").unwrap(); diff --git a/crates/coa-core/src/plugins.rs b/crates/coa-core/src/plugins.rs new file mode 100644 index 0000000..53c3ed8 --- /dev/null +++ b/crates/coa-core/src/plugins.rs @@ -0,0 +1,833 @@ +//! Dynamic Plugin Architecture (FV1) for CoA Server Manager. +//! +//! Manages dynamic DLL plugins, the plugin store (`.manager/plugin-store`), +//! registry (`.manager/plugins.json`), `plugins.lock` generation, 3-way configuration merging, +//! transactional updates, and multiworld isolation. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::config::parser::ConfFile; +use crate::error::{Error, Result}; +use crate::fsx; + +pub const REGISTRY_SCHEMA: u32 = 1; + +/// Metadata describing a plugin package ready to be placed into the store. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginMetadata { + pub id: String, + pub name: String, + pub version: String, + #[serde(default)] + pub description: BTreeMap, + pub sha256: String, + #[serde(default = "yes")] + pub required: bool, + #[serde(default)] + pub deps: Vec, + #[serde(default)] + pub conf_files: Vec, + #[serde(default)] + pub enable_key: Option, + #[serde(default)] + pub status: Option, + #[serde(default)] + pub icon: Option, +} + +fn yes() -> bool { + true +} + +/// An entry in `.manager/plugins.json`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginEntry { + pub installed: bool, + pub enabled: bool, + pub version: String, + pub sha256: String, + pub store_path: String, + pub conf_files: Vec, + #[serde(default)] + pub deps: Vec, + #[serde(default = "yes")] + pub required: bool, +} + +/// The root registry document in `.manager/plugins.json`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginsRegistry { + pub schema: u32, + pub plugins: BTreeMap, +} + +impl Default for PluginsRegistry { + fn default() -> Self { + Self { + schema: REGISTRY_SCHEMA, + plugins: BTreeMap::new(), + } + } +} + +/// View of a plugin suitable for the CSM UI. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PluginView { + pub id: String, + pub name: String, + pub version: String, + pub description: BTreeMap, + pub installed: bool, + pub enabled: bool, + pub update_available: bool, + pub latest_version: Option, + pub deps: Vec, + pub conf_files: Vec, + pub status: String, + pub icon: String, +} + +/// Resolve the metadata directory (`.manager` or `.manager`). +pub fn meta_dir(server: &Path) -> PathBuf { + let dot = server.join(".manager"); + if dot.is_dir() { + return dot; + } + if let Ok(dir) = crate::registry::metadata_dir_for(server) { + if dir.is_dir() { + return dir; + } + } + dot +} + +/// Root of the immutable plugin store: `/plugin-store`. +pub fn store_dir(server: &Path) -> PathBuf { + meta_dir(server).join("plugin-store") +} + +/// Path to `.manager/plugins.json`. +pub fn registry_path(server: &Path) -> PathBuf { + meta_dir(server).join("plugins.json") +} + +/// Path where `worldserver.exe` expects `plugins/`. +pub fn plugins_install_dir(server: &Path) -> PathBuf { + if server.join("Core").is_dir() { + server.join("Core/plugins") + } else { + server.join("plugins") + } +} + +/// Path to `plugins.lock`. +pub fn lockfile_path(server: &Path) -> PathBuf { + plugins_install_dir(server).join("plugins.lock") +} + +/// Directory for module configs (`Core/configs/modules` or `configs/modules`). +pub fn modules_config_dir(server: &Path) -> PathBuf { + if server.join("Core/configs/modules").is_dir() || server.join("Core").is_dir() { + server.join("Core/configs/modules") + } else { + server.join("configs/modules") + } +} + +/// Check that the worldserver is not running before modifying plugins. +pub fn require_server_stopped(server: &Path) -> Result<()> { + let observed = crate::process::observe(server, &crate::layout::read_ports(server)); + if observed.world.state != crate::process::ServiceState::Stopped + || crate::multiworld::is_running(server) + { + return Err(Error::Invalid( + "Stop the server before modifying plugins or their enabled state.".into(), + )); + } + Ok(()) +} + +/// Calculate SHA256 of bytes. +pub fn sha256_digest(bytes: &[u8]) -> String { + let mut hasher = Sha256::new(); + hasher.update(bytes); + hex::encode(hasher.finalize()) +} + +/// Load `.manager/plugins.json` or return empty registry if not present. +pub fn load_registry(server: &Path) -> Result { + let path = registry_path(server); + if !path.is_file() { + return Ok(PluginsRegistry::default()); + } + let bytes = fs::read(&path)?; + serde_json::from_slice(&bytes).map_err(|e| Error::Invalid(format!("corrupt plugins.json: {e}"))) +} + +/// Atomically save `.manager/plugins.json`. +pub fn save_registry(server: &Path, reg: &PluginsRegistry) -> Result<()> { + let meta = meta_dir(server); + fs::create_dir_all(&meta)?; + let path = registry_path(server); + let bytes = serde_json::to_vec_pretty(reg)?; + fsx::atomic_write(&path, &bytes) +} + +/// Read a plugin's metadata from the store given its ID and SHA256. +pub fn load_store_metadata(server: &Path, id: &str, sha256: &str) -> Result { + let p = store_dir(server).join(id).join(sha256).join("plugin.json"); + let bytes = fs::read(&p)?; + serde_json::from_slice(&bytes).map_err(|e| Error::Invalid(format!("corrupt plugin.json at {}: {e}", p.display()))) +} + +/// Helper to recursively copy directories. +pub fn copy_tree(from: &Path, to: &Path) -> Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_tree(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +/// Copy and register a plugin into `.manager/plugin-store///`. +pub fn install_to_store( + server: &Path, + meta: &PluginMetadata, + dll_bytes: &[u8], + pdb_bytes: Option<&[u8]>, + dist_confs: &[(String, &[u8])], +) -> Result { + let digest = sha256_digest(dll_bytes); + if digest != meta.sha256 { + return Err(Error::HashMismatch { + path: format!("{}.dll", meta.id), + expected: meta.sha256.clone(), + actual: digest, + }); + } + + let target = store_dir(server).join(&meta.id).join(&digest); + let staging = meta_dir(server) + .join("staging") + .join(format!("store_{}_{}", meta.id, uuid::Uuid::now_v7())); + fs::create_dir_all(&staging)?; + + let write_res = (|| -> Result<()> { + fs::write(staging.join(format!("{}.dll", meta.id)), dll_bytes)?; + if let Some(pdb) = pdb_bytes { + fs::write(staging.join(format!("{}.pdb", meta.id)), pdb)?; + } + for (name, conf_bytes) in dist_confs { + let conf_name = if name.ends_with(".dist") { + name.clone() + } else { + format!("{name}.dist") + }; + fs::write(staging.join(&conf_name), conf_bytes)?; + } + let meta_bytes = serde_json::to_vec_pretty(meta)?; + fs::write(staging.join("plugin.json"), meta_bytes)?; + Ok(()) + })(); + + if let Err(e) = write_res { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + + // Atomic move to store + if target.exists() { + let _ = fs::remove_dir_all(&staging); + return Ok(target); + } + + if let Some(parent) = target.parent() { + fs::create_dir_all(parent)?; + } + + if let Err(e) = fs::rename(&staging, &target) { + // Fallback to copy and remove on cross-device link + let _ = copy_tree(&staging, &target); + let _ = fs::remove_dir_all(&staging); + if !target.is_dir() { + return Err(Error::Io(e)); + } + } + + Ok(target) +} + +/// Generate `Core/plugins/plugins.lock` and synchronize active files in `Core/plugins/` and `Core/configs/modules/`. +pub fn regenerate_lockfile(server: &Path, reg: &PluginsRegistry) -> Result<()> { + let plugins_root = plugins_install_dir(server); + let conf_root = modules_config_dir(server); + fs::create_dir_all(&plugins_root)?; + fs::create_dir_all(&conf_root)?; + + let mut lock_lines = vec![ + "# written by CoA Server Manager: id|path|sha256|required|confs|deps".to_string(), + ]; + + let mut active_plugin_ids = BTreeSet::new(); + + for (id, entry) in ®.plugins { + if !entry.installed || !entry.enabled { + continue; + } + + active_plugin_ids.insert(id.clone()); + let store_path = store_dir(server).join(id).join(&entry.sha256); + if !store_path.is_dir() { + return Err(Error::Invalid(format!( + "Store directory for plugin '{}' ({}) is missing", + id, entry.sha256 + ))); + } + + // Deploy plugin DLL and PDB into plugins// + let target_dir = plugins_root.join(id); + fs::create_dir_all(&target_dir)?; + + let dll_name = format!("{id}.dll"); + let src_dll = store_path.join(&dll_name); + let dst_dll = target_dir.join(&dll_name); + if !src_dll.is_file() { + return Err(Error::Invalid(format!( + "Source DLL missing in store: {}", + src_dll.display() + ))); + } + fsx::atomic_write(&dst_dll, &fs::read(&src_dll)?)?; + + let pdb_name = format!("{id}.pdb"); + let src_pdb = store_path.join(&pdb_name); + if src_pdb.is_file() { + let dst_pdb = target_dir.join(&pdb_name); + fsx::atomic_write(&dst_pdb, &fs::read(&src_pdb)?)?; + } + + // Deploy conf.dist and ensure active .conf exists + let mut deployed_conf_names = Vec::new(); + for conf_entry in &entry.conf_files { + let base_name = conf_entry.strip_suffix(".dist").unwrap_or(conf_entry); + let dist_name = format!("{base_name}.dist"); + let src_dist = store_path.join(&dist_name); + let dst_dist = conf_root.join(&dist_name); + let dst_conf = conf_root.join(base_name); + + if src_dist.is_file() { + let dist_bytes = fs::read(&src_dist)?; + fsx::atomic_write(&dst_dist, &dist_bytes)?; + if !dst_conf.is_file() { + fsx::atomic_write(&dst_conf, &dist_bytes)?; + } + } + deployed_conf_names.push(base_name.to_string()); + } + + let rel_dll_path = format!("{id}/{dll_name}"); + let req_str = if entry.required { "1" } else { "0" }; + let confs_str = deployed_conf_names.join(","); + let deps_str = entry.deps.join(","); + + lock_lines.push(format!( + "{id}|{rel_dll_path}|{}|{req_str}|{confs_str}|{deps_str}", + entry.sha256 + )); + } + + // Clean up directories in plugins/ for uninstalled plugins + if let Ok(entries) = fs::read_dir(&plugins_root) { + for e in entries.flatten() { + if let Ok(ft) = e.file_type() { + if ft.is_dir() { + let dir_name = e.file_name().to_string_lossy().into_owned(); + if !active_plugin_ids.contains(&dir_name) { + let _ = fs::remove_dir_all(e.path()); + } + } + } + } + } + + let lock_content = lock_lines.join("\n") + "\n"; + let lock_path = lockfile_path(server); + fsx::atomic_write(&lock_path, lock_content.as_bytes())?; + Ok(()) +} + +/// Perform a 3-way merge on an AzerothCore `.conf` file. +/// `base`: original distribution template +/// `theirs`: updated distribution template from new version +/// `mine`: current user configuration with custom modifications +pub fn merge_conf(base_str: &str, theirs_str: &str, mine_str: &str) -> Result { + let base = ConfFile::parse(base_str); + let theirs = ConfFile::parse(theirs_str); + let mut merged = ConfFile::parse(mine_str); + + for (key, theirs_val) in theirs.entries() { + let base_val = base.get(key); + let mine_val = merged.get(key).map(|s| s.to_string()); + + match mine_val { + Some(curr) => { + // If user didn't change the value from base, take the upstream update + if base_val == Some(&curr) && curr != theirs_val { + merged.set(key, theirs_val, &[]); + } + } + None => { + // New configuration key added upstream; incorporate with doc + let doc_lines = theirs.doc_for(key); + let doc_refs: Vec<&str> = doc_lines.iter().map(|s| s.as_str()).collect(); + merged.set(key, theirs_val, &doc_refs); + } + } + } + + Ok(merged.to_text()) +} + +/// Install a plugin into the store, update the registry, and optionally enable it. +pub fn install( + server: &Path, + meta: PluginMetadata, + dll_bytes: &[u8], + pdb_bytes: Option<&[u8]>, + dist_confs: &[(String, &[u8])], + enable: bool, +) -> Result<()> { + require_server_stopped(server)?; + + let store_target = install_to_store(server, &meta, dll_bytes, pdb_bytes, dist_confs)?; + let mut reg = load_registry(server)?; + + if enable { + if meta.id == "companions" && reg.plugins.get("playerbots").map(|p| p.enabled).unwrap_or(false) { + return Err(Error::BotModulesConflict); + } + if meta.id == "playerbots" && reg.plugins.get("companions").map(|p| p.enabled).unwrap_or(false) { + return Err(Error::BotModulesConflict); + } + } + + let rel_store_path = store_target + .strip_prefix(meta_dir(server)) + .unwrap_or(&store_target) + .to_string_lossy() + .replace('\\', "/"); + + let entry = PluginEntry { + installed: true, + enabled: enable, + version: meta.version.clone(), + sha256: meta.sha256.clone(), + store_path: rel_store_path, + conf_files: meta.conf_files.clone(), + deps: meta.deps.clone(), + required: meta.required, + }; + + reg.plugins.insert(meta.id.clone(), entry); + save_registry(server, ®)?; + regenerate_lockfile(server, ®)?; + + // If plugin has an enable_key in its config, sync it + if let Some(key) = &meta.enable_key { + let conf_root = modules_config_dir(server); + for conf_name in &meta.conf_files { + let base_name = conf_name.strip_suffix(".dist").unwrap_or(conf_name); + let conf_path = conf_root.join(base_name); + if conf_path.is_file() { + if let Ok(bytes) = fs::read(&conf_path) { + if let Ok(mut conf_file) = ConfFile::parse_bytes(&bytes) { + conf_file.set(key, if enable { "1" } else { "0" }, &[]); + let _ = fsx::atomic_write(&conf_path, conf_file.to_text().as_bytes()); + } + } + } + } + } + + Ok(()) +} + +/// Enable or disable an installed plugin. +pub fn set_enabled(server: &Path, id: &str, enabled: bool) -> Result<()> { + require_server_stopped(server)?; + + let mut reg = load_registry(server)?; + let entry = reg.plugins.get(id).cloned().ok_or_else(|| { + Error::Invalid(format!("Plugin '{id}' is not installed")) + })?; + + if enabled { + // Enforce bot mutual exclusivity + if id == "companions" && reg.plugins.get("playerbots").map(|p| p.enabled).unwrap_or(false) { + return Err(Error::BotModulesConflict); + } + if id == "playerbots" && reg.plugins.get("companions").map(|p| p.enabled).unwrap_or(false) { + return Err(Error::BotModulesConflict); + } + + // Enforce dependencies + for dep in &entry.deps { + if !reg.plugins.get(dep).map(|p| p.enabled).unwrap_or(false) { + return Err(Error::Invalid(format!( + "Cannot enable plugin '{id}': required dependency '{dep}' is not enabled" + ))); + } + } + } else { + // Enforce dependent plugins + for (other_id, other) in ®.plugins { + if other.enabled && other.deps.contains(&id.to_string()) { + return Err(Error::Invalid(format!( + "Cannot disable plugin '{id}': plugin '{other_id}' depends on it" + ))); + } + } + } + + reg.plugins.get_mut(id).unwrap().enabled = enabled; + save_registry(server, ®)?; + regenerate_lockfile(server, ®)?; + + // Sync module config enable key if known from metadata + if let Ok(meta) = load_store_metadata(server, id, &entry.sha256) { + if let Some(key) = &meta.enable_key { + let conf_root = modules_config_dir(server); + for conf_name in &meta.conf_files { + let base_name = conf_name.strip_suffix(".dist").unwrap_or(conf_name); + let conf_path = conf_root.join(base_name); + if conf_path.is_file() { + if let Ok(bytes) = fs::read(&conf_path) { + if let Ok(mut conf_file) = ConfFile::parse_bytes(&bytes) { + conf_file.set(key, if enabled { "1" } else { "0" }, &[]); + let _ = fsx::atomic_write(&conf_path, conf_file.to_text().as_bytes()); + } + } + } + } + } + } + + Ok(()) +} + +/// Update an installed plugin to a new version with 3-way configuration merge. +pub fn update( + server: &Path, + new_meta: PluginMetadata, + new_dll: &[u8], + new_pdb: Option<&[u8]>, + new_dist_confs: &[(String, &[u8])], +) -> Result<()> { + require_server_stopped(server)?; + + let mut reg = load_registry(server)?; + let old_entry = reg + .plugins + .get(&new_meta.id) + .cloned() + .ok_or_else(|| Error::Invalid(format!("Plugin '{}' is not installed", new_meta.id)))?; + + let old_store = store_dir(server).join(&new_meta.id).join(&old_entry.sha256); + let new_store = install_to_store(server, &new_meta, new_dll, new_pdb, new_dist_confs)?; + + // 3-way merge on configuration files + let conf_root = modules_config_dir(server); + for (name, new_dist_bytes) in new_dist_confs { + let base_name = name.strip_suffix(".dist").unwrap_or(name); + let dist_name = format!("{base_name}.dist"); + + let old_dist_path = old_store.join(&dist_name); + let active_conf_path = conf_root.join(base_name); + + if old_dist_path.is_file() && active_conf_path.is_file() { + let old_dist_str = fs::read_to_string(&old_dist_path)?; + let new_dist_str = std::str::from_utf8(new_dist_bytes) + .map_err(|e| Error::Invalid(format!("new .dist for {base_name} is not UTF-8: {e}")))?; + let active_conf_str = fs::read_to_string(&active_conf_path)?; + + let merged_text = merge_conf(&old_dist_str, new_dist_str, &active_conf_str)?; + fsx::atomic_write(&active_conf_path, merged_text.as_bytes())?; + } + } + + let rel_store_path = new_store + .strip_prefix(meta_dir(server)) + .unwrap_or(&new_store) + .to_string_lossy() + .replace('\\', "/"); + + let updated_entry = PluginEntry { + installed: true, + enabled: old_entry.enabled, + version: new_meta.version, + sha256: new_meta.sha256, + store_path: rel_store_path, + conf_files: new_meta.conf_files, + deps: new_meta.deps, + required: new_meta.required, + }; + + reg.plugins.insert(new_meta.id, updated_entry); + save_registry(server, ®)?; + regenerate_lockfile(server, ®)?; + Ok(()) +} + +/// Remove a plugin from the registry and lockfile, deleting deployed files. +pub fn remove(server: &Path, id: &str) -> Result<()> { + require_server_stopped(server)?; + + let mut reg = load_registry(server)?; + if reg.plugins.remove(id).is_none() { + return Ok(()); + } + + save_registry(server, ®)?; + regenerate_lockfile(server, ®)?; + + let target_dir = plugins_install_dir(server).join(id); + if target_dir.is_dir() { + let _ = fs::remove_dir_all(target_dir); + } + Ok(()) +} + +/// Repair verification: checks deployed plugin SHA256 hashes against registry and restores from store if mismatch. +pub fn repair(server: &Path) -> Result> { + require_server_stopped(server)?; + + let reg = load_registry(server)?; + let mut restored = Vec::new(); + let plugins_root = plugins_install_dir(server); + + for (id, entry) in ®.plugins { + if !entry.installed || !entry.enabled { + continue; + } + + let dll_path = plugins_root.join(id).join(format!("{id}.dll")); + let needs_restore = if !dll_path.is_file() { + true + } else { + let bytes = fs::read(&dll_path)?; + sha256_digest(&bytes) != entry.sha256 + }; + + if needs_restore { + let store_dll = store_dir(server).join(id).join(&entry.sha256).join(format!("{id}.dll")); + if !store_dll.is_file() { + return Err(Error::Invalid(format!( + "Store image for plugin '{id}' ({}) is missing; cannot repair", + entry.sha256 + ))); + } + fs::create_dir_all(plugins_root.join(id))?; + fsx::atomic_write(&dll_path, &fs::read(&store_dll)?)?; + restored.push(id.clone()); + } + } + + regenerate_lockfile(server, ®)?; + Ok(restored) +} + +/// Multiworld helper: propagate enabled plugins to a secondary world directory. +pub fn prepare_multiworld(server: &Path, second_root: &Path) -> Result<()> { + let reg = load_registry(server)?; + let second_plugins_root = second_root.join("Core/plugins"); + fs::create_dir_all(&second_plugins_root)?; + + // Secondary world inherits enabled plugins by default + let second_reg_path = second_root.join(".manager/plugins.json"); + if second_reg_path.is_file() { + // If secondary world has its own registry, use it + let second_reg = load_registry(second_root)?; + regenerate_lockfile(second_root, &second_reg)?; + } else { + // Mirror primary enabled plugins to secondary world + for (id, entry) in ®.plugins { + if entry.enabled { + let store_dll = store_dir(server) + .join(id) + .join(&entry.sha256) + .join(format!("{id}.dll")); + if store_dll.is_file() { + let dst_dir = second_plugins_root.join(id); + fs::create_dir_all(&dst_dir)?; + fsx::atomic_write(&dst_dir.join(format!("{id}.dll")), &fs::read(&store_dll)?)?; + } + } + } + // Copy lockfile + let primary_lock = lockfile_path(server); + if primary_lock.is_file() { + fsx::atomic_write( + &second_plugins_root.join("plugins.lock"), + &fs::read(&primary_lock)?, + )?; + } + } + + Ok(()) +} + +/// SQUID SQL migration guard: record that SQUID migrations have run so they are not re-executed on restart. +pub fn record_squid_migrations_applied(server: &Path) -> Result<()> { + let path = meta_dir(server).join("migrations/squid_applied.json"); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let data = serde_json::json!({ + "applied": true, + "timestamp": chrono::Utc::now().to_rfc3339() + }); + fsx::atomic_write_json(&path, &data) +} + +/// Check if SQUID SQL migrations were already recorded as applied. +pub fn is_squid_migrations_applied(server: &Path) -> bool { + let path = meta_dir(server).join("migrations/squid_applied.json"); + if !path.is_file() { + return false; + } + fs::read_to_string(path) + .ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .and_then(|v| v.get("applied")?.as_bool()) + .unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::tempdir; + + #[test] + fn test_merge_conf_preserves_customizations() { + let base = "CoA.Setting1 = 10\nCoA.Setting2 = \"alpha\"\n"; + let theirs = "CoA.Setting1 = 10\nCoA.Setting2 = \"beta\"\n# New option\nCoA.Setting3 = 1\n"; + let mine = "CoA.Setting1 = 20\nCoA.Setting2 = \"alpha\"\n"; + + let merged = merge_conf(base, theirs, mine).unwrap(); + let parsed = ConfFile::parse(&merged); + + // User modified Setting1 to 20 -> should stay 20 + assert_eq!(parsed.get("CoA.Setting1"), Some("20")); + // User didn't modify Setting2 -> should take upstream new default "beta" + assert_eq!(parsed.get("CoA.Setting2"), Some("\"beta\"")); + // Setting3 is new upstream -> should be added + assert_eq!(parsed.get("CoA.Setting3"), Some("1")); + } + + #[test] + fn test_plugin_lifecycle_atomic() { + let dir = tempdir().unwrap(); + let server = dir.path(); + + let dll_content = b"MZ fake dll"; + let digest = sha256_digest(dll_content); + let meta = PluginMetadata { + id: "test-plugin".into(), + name: "Test Plugin".into(), + version: "1.0.0".into(), + description: BTreeMap::new(), + sha256: digest.clone(), + required: true, + deps: vec![], + conf_files: vec!["test.conf.dist".into()], + enable_key: Some("Test.Enable".into()), + status: Some("release".into()), + icon: Some("bot".into()), + }; + + install( + server, + meta.clone(), + dll_content, + None, + &[("test.conf.dist".into(), b"Test.Enable = 1\n")], + true, + ) + .unwrap(); + + let reg = load_registry(server).unwrap(); + assert!(reg.plugins.contains_key("test-plugin")); + assert!(reg.plugins["test-plugin"].enabled); + + let lock = fs::read_to_string(lockfile_path(server)).unwrap(); + assert!(lock.contains("test-plugin|test-plugin/test-plugin.dll")); + + // Disable + set_enabled(server, "test-plugin", false).unwrap(); + let reg = load_registry(server).unwrap(); + assert!(!reg.plugins["test-plugin"].enabled); + + let lock = fs::read_to_string(lockfile_path(server)).unwrap(); + assert!(!lock.contains("test-plugin|test-plugin/test-plugin.dll")); + + // Re-enable + set_enabled(server, "test-plugin", true).unwrap(); + let reg = load_registry(server).unwrap(); + assert!(reg.plugins["test-plugin"].enabled); + + // Corrupt file and test repair + let deployed_dll = plugins_install_dir(server).join("test-plugin/test-plugin.dll"); + fs::write(&deployed_dll, b"corrupted bytes").unwrap(); + let restored = repair(server).unwrap(); + assert_eq!(restored, vec!["test-plugin".to_string()]); + assert_eq!(fs::read(&deployed_dll).unwrap(), dll_content); + + // Test mutual exclusivity + let meta2 = PluginMetadata { + id: "companions".into(), + name: "Companions".into(), + version: "1.0.0".into(), + description: BTreeMap::new(), + sha256: digest.clone(), + required: true, + deps: vec![], + conf_files: vec![], + enable_key: None, + status: None, + icon: None, + }; + let meta3 = PluginMetadata { + id: "playerbots".into(), + name: "Playerbots".into(), + version: "1.0.0".into(), + description: BTreeMap::new(), + sha256: digest.clone(), + required: true, + deps: vec![], + conf_files: vec![], + enable_key: None, + status: None, + icon: None, + }; + install(server, meta2, dll_content, None, &[], true).unwrap(); + let err = install(server, meta3.clone(), dll_content, None, &[], true); + assert!(matches!(err, Err(Error::BotModulesConflict))); + + // Installing playerbots disabled succeeds + install(server, meta3, dll_content, None, &[], false).unwrap(); + // Trying to enable playerbots while companions is enabled fails + let err2 = set_enabled(server, "playerbots", true); + assert!(matches!(err2, Err(Error::BotModulesConflict))); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 70217c3..13bef71 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1169,6 +1169,17 @@ async fn realm_simultaneous( blocking(move || coa_core::multiworld::set_enabled(&root, enabled)).await } +#[tauri::command] +async fn realm_with_reborn( + state: State<'_, AppState>, + id: String, + enabled: bool, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || coa_core::multiworld::set_reborn_enabled(&root, enabled)).await +} + #[tauri::command] async fn check_database( state: State<'_, AppState>, @@ -1222,6 +1233,16 @@ async fn module_set_enabled( .await } +#[tauri::command] +async fn plugins_repair( + state: State<'_, AppState>, + id: String, +) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || coa_core::plugins::repair(&root)).await +} + #[tauri::command] async fn custom_races_status( state: State<'_, AppState>, @@ -2322,6 +2343,7 @@ struct FriendsStatus { auth_port: u16, world_port: u16, secondary_world_port: Option, + reborn_world_port: Option, } /// Open one of a few known help pages in the default browser. Anything else is refused, so a page can never ask the @@ -2485,6 +2507,9 @@ async fn friends_status( secondary_world_port: coa_core::realms::state(&root)? .secondary_world_port .filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.simultaneous)), + reborn_world_port: coa_core::realms::state(&root)? + .reborn_world_port + .filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.with_reborn)), }) }) .await @@ -2542,7 +2567,13 @@ async fn friends_enable( let ports = layout::read_ports(&root); let mut note = None; let realms = coa_core::realms::state(&root)?; - let secondary = realms.secondary_world_port.filter(|_| realms.simultaneous); + let extra: Vec = [ + realms.secondary_world_port.filter(|_| realms.simultaneous), + realms.reborn_world_port.filter(|_| realms.with_reborn), + ] + .into_iter() + .flatten() + .collect(); let host = match mode { Mode::Local => "127.0.0.1".to_string(), Mode::Lan => coa_core::net::resolve_lan_host(lan_address_override.as_deref(), coa_core::net::lan_ip())?, @@ -2552,7 +2583,7 @@ async fn friends_enable( let open = mode != Mode::Local; let changed = friends::set_open(&root, &meta, open)?; if open && platform::flavor() == Flavor::Repack { - coa_core::firewall::ensure_rules_with_secondary(&ports, secondary)?; + coa_core::firewall::ensure_rules_with_extra(&ports, &extra)?; } if mode == Mode::Direct && use_upnp { match coa_core::upnp::discover() { @@ -2560,7 +2591,7 @@ async fn friends_enable( let lan = coa_core::net::lan_ip().ok_or_else(|| Error::Invalid("No local address.".into()))?; coa_core::upnp::add_mapping(&gw, ports.auth, lan, "Auth")?; coa_core::upnp::add_mapping(&gw, ports.world, lan, "World")?; - if let Some(port) = secondary { coa_core::upnp::add_mapping(&gw, port, lan, "Second world")?; } + for port in &extra { coa_core::upnp::add_mapping(&gw, *port, lan, "Extra world")?; } note = Some("Your router was asked to forward the game ports.".to_string()); } None => note = Some("Your router does not support automatic setup; forward the two game ports by hand or use the private network.".to_string()), @@ -2795,8 +2826,10 @@ pub fn run() { realm_profiles, realm_select, realm_simultaneous, + realm_with_reborn, check_database, repair_server, + plugins_repair, module_set_enabled, module_settings, module_save_settings, diff --git a/src/lib/api.ts b/src/lib/api.ts index be9488f..74e8dcd 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -48,13 +48,13 @@ export interface ServiceStatus { } export interface StatusView { - observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null }; + observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null }; busy: boolean; path_exists: boolean; } export type RealmMode = "coa" | "wildcard" | "reborn"; -export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean } +export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean; with_reborn: boolean; reborn_world_port: number | null; reborn_running: boolean } export interface DatabaseCheck { realm: RealmMode; migrations: { id: string; db: string; status: "applied" | "pending" | "failed"; error: string | null }[]; @@ -429,6 +429,7 @@ export interface FriendsStatus { auth_port: number; world_port: number; secondary_world_port?: number | null; + reborn_world_port?: number | null; } export interface InternetCheck { @@ -472,6 +473,7 @@ export const api = { realmProfiles: (id: string) => invoke("realm_profiles", { id }), realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke("realm_select", { id, mode, restart }), realmSimultaneous: (id: string, enabled: boolean) => invoke("realm_simultaneous", { id, enabled }), + realmWithReborn: (id: string, enabled: boolean) => invoke("realm_with_reborn", { id, enabled }), checkDatabase: (id: string) => invoke("check_database", { id }), repairServer: (id: string) => invoke("repair_server", { id }), defaultInstallDir: () => invoke("default_install_dir"), @@ -511,6 +513,7 @@ export const api = { realmlistActivate: (id: string, profileId: string) => invoke("realmlist_activate", { id, profileId }), modulesList: (id: string) => invoke("modules_list", { id }), moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke("module_set_enabled", { id, module, enabled }), + pluginsRepair: (id: string) => invoke("plugins_repair", { id }), moduleSettings: (id: string, module: string) => invoke("module_settings", { id, module }), moduleSaveSettings: (id: string, module: string, changes: Record) => invoke("module_save_settings", { id, module, changes }), allSettings: (id: string) => invoke("all_settings", { id }),