diff --git a/crates/coa-core/src/client.rs b/crates/coa-core/src/client.rs index c2846c4..754a960 100644 --- a/crates/coa-core/src/client.rs +++ b/crates/coa-core/src/client.rs @@ -189,6 +189,32 @@ pub fn set_realmlist(client: &Path, meta: &Path, host: &str) -> Result Result> { + let compact = |t: &str| t.lines().map(|l| l.trim().to_ascii_lowercase()).filter(|l| !l.is_empty()).collect::>().join("\n"); + let mut files = realmlist_files(client); + if files.is_empty() { + files = installed_locales(client).into_iter().map(|loc| client.join("Data").join(loc).join("realmlist.wtf")).collect(); + } + let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string(); + let mut changed = Vec::new(); + for file in files { + let old = fs::read(&file).ok(); + if let Some(old) = &old { + if compact(&String::from_utf8_lossy(old)) == compact(content) { + continue; + } + let locale = file.parent().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + fsx::atomic_write(&backup_dir(meta).join(format!("realmlist-{locale}-{stamp}.wtf")), old)?; + } + fsx::atomic_write(&file, content.as_bytes())?; + changed.push(file.to_string_lossy().into_owned()); + } + Ok(changed) +} + /// Copy the addon into the client. If a different version is there, that one folder is backed up first; /// files in it that the package does not contain are left alone. pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> { diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index ab68b7e..59a022b 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -26,6 +26,8 @@ pub mod migrations; pub mod net; pub mod package; pub mod ra; +pub mod modules; +pub mod realmlist; pub mod registry; pub mod release; pub mod update; diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs new file mode 100644 index 0000000..2241684 --- /dev/null +++ b/crates/coa-core/src/modules.rs @@ -0,0 +1,239 @@ +//! Optional server modules. They are compiled into the server; what the owner decides is whether each one is on and how it is +//! configured, which lives in `Core/configs/modules/.conf` (the documented defaults are in the `.dist` beside it). +//! The list of known modules is a bundled catalog, so a module is added to the Manager by adding a few lines to it. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::config::parser::ConfFile; +use crate::error::{Error, Result}; +use crate::fsx; + +static CATALOG: &str = include_str!("../../../modules/catalog.json"); + +#[derive(Debug, Clone, Deserialize)] +pub struct Entry { + pub id: String, + pub name: String, + /// language code -> text; "en" is always there. + pub description: BTreeMap, + pub repo: String, + /// File in `Core/configs/modules` that holds this module's settings. + pub conf: String, + /// The setting that switches the whole module on or off (1 / 0). + pub enable_key: String, +} + +#[derive(Deserialize)] +struct Catalog { + modules: Vec, +} + +pub fn catalog() -> Vec { + serde_json::from_str::(CATALOG).map(|c| c.modules).unwrap_or_default() +} + +fn entry(id: &str) -> Result { + catalog().into_iter().find(|e| e.id == id).ok_or_else(|| Error::Invalid("That module is not known to the Manager.".into())) +} + +fn dir(root: &Path) -> PathBuf { + root.join("Core/configs/modules") +} + +fn read(path: &Path) -> Option { + fs::read(path).ok().and_then(|b| ConfFile::parse_bytes(&b).ok()) +} + +fn truthy(v: &str) -> bool { + matches!(v.trim().trim_matches('"').to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on") +} + +#[derive(Debug, Serialize)] +pub struct ModuleView { + pub id: String, + pub name: String, + pub description: BTreeMap, + pub repo: String, + /// The module's configuration is present on this server (otherwise it is not part of this server build). + pub installed: bool, + pub enabled: bool, +} + +pub fn list(root: &Path) -> Vec { + catalog() + .into_iter() + .map(|e| { + let conf = dir(root).join(&e.conf); + let dist = dir(root).join(format!("{}.dist", e.conf)); + let installed = conf.is_file() || dist.is_file(); + // the active file decides; without one the documented default is what the server will use + let enabled = read(&conf).or_else(|| read(&dist)).and_then(|c| c.get(&e.enable_key).map(truthy)).unwrap_or(false); + ModuleView { id: e.id, name: e.name, description: e.description, repo: e.repo, installed, enabled } + }) + .collect() +} + +/// The active file, created from its `.dist` when it does not exist yet. +fn active_file(root: &Path, e: &Entry) -> Result { + let conf = dir(root).join(&e.conf); + if !conf.is_file() { + let dist = dir(root).join(format!("{}.dist", e.conf)); + if !dist.is_file() { + return Err(Error::Invalid("This module is not part of this server.".into())); + } + fsx::atomic_write(&conf, &fs::read(&dist)?)?; + } + Ok(conf) +} + +fn backup(meta: &Path, conf: &Path) -> Result<()> { + let name = conf.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let to = meta.join("backups").join("modules").join(format!("{name}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S"))); + fsx::atomic_write(&to, &fs::read(conf)?) +} + +pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { + let e = entry(id)?; + let conf = active_file(root, &e)?; + let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; + if file.get(&e.enable_key).map(truthy) == Some(on) { + return Ok(()); + } + backup(meta, &conf)?; + file.set(&e.enable_key, if on { "1" } else { "0" }, &["Changed by CoA Server Manager"]); + fsx::atomic_write(&conf, file.to_text().as_bytes())?; + tracing::info!(module = id, on, "module switched"); + Ok(()) +} + +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct Setting { + pub key: String, + pub value: String, + pub default: Option, + /// The documentation the module ships above the setting. + pub doc: String, +} + +/// Every active setting of the module with its current value, its documented default and its description. +pub fn settings(root: &Path, id: &str) -> Result> { + let e = entry(id)?; + let conf = dir(root).join(&e.conf); + let dist = read(&dir(root).join(format!("{}.dist", e.conf))); + let active = read(&conf).or_else(|| dist.clone()).ok_or_else(|| Error::Invalid("This module is not part of this server.".into()))?; + Ok(active + .entries() + .map(|(k, v)| Setting { + key: k.to_string(), + value: v.to_string(), + default: dist.as_ref().and_then(|d| d.get(k)).map(str::to_string), + doc: dist.as_ref().map(|d| d.doc_for(k)).filter(|d| !d.is_empty()).unwrap_or_else(|| active.doc_for(k)).join(" "), + }) + .collect()) +} + +/// Change values of settings the module already has. A value is one line of at most 500 characters. +pub fn save_settings(root: &Path, meta: &Path, id: &str, changes: &BTreeMap) -> Result> { + let e = entry(id)?; + let conf = active_file(root, &e)?; + let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; + let mut changed = Vec::new(); + for (key, value) in changes { + let value = value.trim(); + if file.get(key).is_none() { + return Err(Error::Invalid(format!("{key} is not a setting of this module."))); + } + if value.is_empty() || value.len() > 500 || value.chars().any(char::is_control) { + return Err(Error::Invalid(format!("The value of {key} must be one line of text."))); + } + if file.get(key).map(str::trim) != Some(value) { + changed.push((key.clone(), value.to_string())); + } + } + if changed.is_empty() { + return Ok(Vec::new()); + } + backup(meta, &conf)?; + for (k, v) in &changed { + file.set(k, v, &[]); + } + fsx::atomic_write(&conf, file.to_text().as_bytes())?; + Ok(changed.into_iter().map(|(k, _)| k).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn server(d: &Path) -> (PathBuf, PathBuf) { + let (root, meta) = (d.join("srv"), d.join("meta")); + let m = dir(&root); + fs::create_dir_all(&m).unwrap(); + fs::create_dir_all(&meta).unwrap(); + fs::write(m.join("war_games.conf.dist"), "# Turns War Games on.\r\n# Second line.\r\nWarGames.Enable = 1\r\n\r\n# How long a challenge stays open.\r\nWarGames.ChallengeSeconds = 60\r\n").unwrap(); + (root, meta) + } + + #[test] + fn the_bundled_catalog_is_complete() { + let c = catalog(); + assert!(c.len() >= 5); + for e in &c { + assert!(e.description.contains_key("en") && e.description.len() == 5, "{} has all five descriptions", e.id); + assert!(e.repo.starts_with("https://github.com/Corfirean/") && e.conf.ends_with(".conf") && e.enable_key.ends_with(".Enable"), "{}", e.id); + } + let mut ids: Vec<_> = c.iter().map(|e| e.id.as_str()).collect(); + ids.sort(); + ids.dedup(); + assert_eq!(ids.len(), c.len(), "ids are unique"); + } + + #[test] + fn a_module_is_listed_as_installed_with_its_documented_default_until_a_file_exists() { + let d = tempfile::tempdir().unwrap(); + let (root, _) = server(d.path()); + let wg = list(&root).into_iter().find(|m| m.id == "war-games").unwrap(); + assert!(wg.installed && wg.enabled, "the .dist says 1"); + assert!(!list(&root).into_iter().find(|m| m.id == "spellbook").unwrap().installed, "no configuration of that module on this server"); + } + + #[test] + fn switching_a_module_creates_its_file_saves_the_old_one_and_changes_only_that_line() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + set_enabled(&root, &meta, "war-games", false).unwrap(); + let conf = fs::read_to_string(dir(&root).join("war_games.conf")).unwrap(); + assert!(conf.contains("WarGames.Enable = 0") && conf.contains("WarGames.ChallengeSeconds = 60"), "{conf}"); + assert!(!list(&root).into_iter().find(|m| m.id == "war-games").unwrap().enabled); + set_enabled(&root, &meta, "war-games", false).unwrap(); + assert_eq!(fs::read_dir(meta.join("backups/modules")).unwrap().count(), 1, "no change, no backup"); + set_enabled(&root, &meta, "war-games", true).unwrap(); + assert!(fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("WarGames.Enable = 1")); + assert!(set_enabled(&root, &meta, "spellbook", true).is_err(), "not part of this server"); + assert!(set_enabled(&root, &meta, "nonsense", true).is_err()); + } + + #[test] + fn settings_show_the_documentation_and_only_known_keys_with_one_line_values_can_be_saved() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + let s = settings(&root, "war-games").unwrap(); + assert_eq!(s.len(), 2); + assert_eq!(s[1], Setting { key: "WarGames.ChallengeSeconds".into(), value: "60".into(), default: Some("60".into()), doc: "How long a challenge stays open.".into() }); + assert_eq!(s[0].doc, "Turns War Games on. Second line."); + + let ok = BTreeMap::from([("WarGames.ChallengeSeconds".to_string(), "90".to_string())]); + assert_eq!(save_settings(&root, &meta, "war-games", &ok).unwrap(), ["WarGames.ChallengeSeconds"]); + assert!(settings(&root, "war-games").unwrap()[1].value == "90"); + assert!(save_settings(&root, &meta, "war-games", &ok).unwrap().is_empty(), "same value: nothing to do"); + for bad in [("Other.Key", "1"), ("WarGames.ChallengeSeconds", ""), ("WarGames.ChallengeSeconds", "1\nInjected = 1")] { + let c = BTreeMap::from([(bad.0.to_string(), bad.1.to_string())]); + assert!(save_settings(&root, &meta, "war-games", &c).is_err(), "{bad:?}"); + } + assert!(!fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("Injected")); + } +} diff --git a/crates/coa-core/src/realmlist.rs b/crates/coa-core/src/realmlist.rs new file mode 100644 index 0000000..34af612 --- /dev/null +++ b/crates/coa-core/src/realmlist.rs @@ -0,0 +1,235 @@ +//! Named realmlists for the game client ("Solo" for your own server, "PTR" for the shared one, ...). Choosing one writes its +//! text into the client's `Data//realmlist.wtf` files; the file that was there is saved first. The profiles live +//! in the Manager's folder for the server, never in the client. + +use std::fs; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::client; +use crate::error::{Error, Result}; +use crate::fsx; + +const FILE: &str = "realmlists.json"; +const MAX_PROFILES: usize = 24; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Profile { + pub id: String, + pub name: String, + /// The text of `realmlist.wtf` (normalised: `set ` lines). + pub data: String, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct Store { + profiles: Vec, +} + +#[derive(Debug, Serialize)] +pub struct View { + pub profiles: Vec, + /// The profile whose text every realmlist file of the client currently holds. + pub active: Option, +} + +fn compact(text: &str) -> String { + text.lines().map(|l| l.trim().to_ascii_lowercase()).filter(|l| !l.is_empty()).collect::>().join("\n") +} + +/// Accept either the whole file text or just an address ("play.example.com", "192.168.0.5:3724"), and make sure that +/// what is written into the client is nothing but `set ` lines. +pub fn normalize(data: &str) -> Result { + let bad = |m: &str| Err(Error::Invalid(m.into())); + let text = data.trim(); + if text.is_empty() { + return bad("Enter the realmlist text or an address."); + } + if text.len() > 2000 { + return bad("That text is too long for a realmlist."); + } + let lines: Vec = if !text.contains(char::is_whitespace) { + vec![format!("set realmlist {text}")] + } else { + text.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect() + }; + for line in &lines { + let mut parts = line.splitn(3, char::is_whitespace); + let (set, key, value) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or("").trim()); + if !set.eq_ignore_ascii_case("set") || key.is_empty() || value.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + return bad("Each line must look like: set realmlist 127.0.0.1"); + } + if !value.chars().all(|c| c.is_ascii_graphic() || c == ' ') { + return bad("The realmlist may only use plain letters, digits and punctuation."); + } + if key.eq_ignore_ascii_case("realmlist") && !value.trim_matches('"').chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '_')) { + return bad("That address is not valid."); + } + } + Ok(lines.join("\r\n") + "\r\n") +} + +fn slug(name: &str) -> String { + let s: String = name.to_ascii_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + let s = s.trim_matches('-').to_string(); + if s.is_empty() { "realm".into() } else { s } +} + +fn load(meta: &Path, client_dir: Option<&Path>) -> Store { + let mut store: Store = fsx::read_json(&meta.join(FILE)).unwrap_or_default(); + if store.profiles.is_empty() { + // First use: "Solo" for this computer, and what the client held before so that it can be switched back to. + store.profiles.push(Profile { id: "solo".into(), name: "Solo".into(), data: "set realmlist 127.0.0.1\r\n".into() }); + if let Some(files) = client_dir.map(client::realmlist_files) { + if let Some(text) = files.iter().find_map(|f| fs::read_to_string(f).ok()) { + if let Ok(data) = normalize(&text) { + if compact(&data) != compact(&store.profiles[0].data) { + store.profiles.push(Profile { id: "previous".into(), name: "Previous".into(), data }); + } + } + } + } + let _ = fsx::atomic_write_json(&meta.join(FILE), &store); + } + store +} + +fn save_store(meta: &Path, store: &Store) -> Result<()> { + fsx::atomic_write_json(&meta.join(FILE), store) +} + +pub fn view(meta: &Path, client_dir: Option<&Path>) -> View { + let store = load(meta, client_dir); + let active = client_dir.and_then(|c| { + let files = client::realmlist_files(c); + let texts: Vec = files.iter().filter_map(|f| fs::read_to_string(f).ok()).map(|t| compact(&t)).collect(); + let first = texts.first()?; + if texts.iter().any(|t| t != first) { + return None; + } + store.profiles.iter().find(|p| compact(&p.data) == *first).map(|p| p.id.clone()) + }); + View { profiles: store.profiles, active } +} + +/// Add a profile (`id` None) or change one. Names are 1-32 characters and unique regardless of capitals. +pub fn save_profile(meta: &Path, client_dir: Option<&Path>, id: Option<&str>, name: &str, data: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > 32 || name.chars().any(char::is_control) { + return Err(Error::Invalid("The name must be 1 to 32 characters.".into())); + } + let data = normalize(data)?; + let mut store = load(meta, client_dir); + if store.profiles.iter().any(|p| p.name.eq_ignore_ascii_case(name) && Some(p.id.as_str()) != id) { + return Err(Error::Invalid("A realmlist with that name already exists.".into())); + } + let profile = match id { + Some(id) => { + let p = store.profiles.iter_mut().find(|p| p.id == id).ok_or_else(|| Error::Invalid("That realmlist does not exist.".into()))?; + p.name = name.to_string(); + p.data = data; + p.clone() + } + None => { + if store.profiles.len() >= MAX_PROFILES { + return Err(Error::Invalid("There are too many realmlists; remove one first.".into())); + } + let mut new_id = slug(name); + while store.profiles.iter().any(|p| p.id == new_id) { + new_id.push('-'); + } + let p = Profile { id: new_id, name: name.to_string(), data }; + store.profiles.push(p.clone()); + p + } + }; + save_store(meta, &store)?; + Ok(profile) +} + +pub fn delete_profile(meta: &Path, client_dir: Option<&Path>, id: &str) -> Result<()> { + let mut store = load(meta, client_dir); + if store.profiles.len() <= 1 { + return Err(Error::Invalid("The last realmlist cannot be removed.".into())); + } + store.profiles.retain(|p| p.id != id); + save_store(meta, &store) +} + +/// Write the profile into the client; returns the files that changed (each was saved to the backup folder first). +pub fn activate(meta: &Path, client_dir: &Path, id: &str) -> Result> { + let store = load(meta, Some(client_dir)); + let profile = store.profiles.iter().find(|p| p.id == id).ok_or_else(|| Error::Invalid("That realmlist does not exist.".into()))?; + client::write_realmlist(client_dir, meta, &profile.data) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake_client(d: &Path, host: &str) -> std::path::PathBuf { + let c = d.join("wow"); + for loc in ["enUS", "ruRU"] { + fs::create_dir_all(c.join("Data").join(loc)).unwrap(); + fs::write(c.join("Data").join(loc).join("realmlist.wtf"), format!("set realmlist {host}\r\nset patchlist x.example\r\n")).unwrap(); + } + fs::write(c.join("Ascension.exe"), b"exe").unwrap(); + c + } + + #[test] + fn an_address_or_whole_lines_are_accepted_and_anything_else_is_not() { + assert_eq!(normalize("play.example.com").unwrap(), "set realmlist play.example.com\r\n"); + assert_eq!(normalize("SET realmlist 192.168.0.5:3724\nset patchlist x.example\n").unwrap(), "SET realmlist 192.168.0.5:3724\r\nset patchlist x.example\r\n"); + for bad in ["", " ", "rm -rf /", "set realmlist bad host;calc", "set realmlist", "x\ny", "set realmlist a\"b", &"a".repeat(2100)] { + assert!(normalize(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn the_first_use_offers_solo_and_what_the_client_had_and_the_active_one_is_recognised() { + let d = tempfile::tempdir().unwrap(); + let (c, meta) = (fake_client(d.path(), "ptr.example.org"), d.path().join("meta")); + fs::create_dir_all(&meta).unwrap(); + let v = view(&meta, Some(&c)); + assert_eq!(v.profiles.iter().map(|p| p.name.as_str()).collect::>(), ["Solo", "Previous"]); + assert_eq!(v.active.as_deref(), Some("previous"), "the files hold exactly what was captured"); + assert!(activate(&meta, &c, "previous").unwrap().is_empty(), "already what the files hold"); + assert_eq!(fs::read_to_string(c.join("Data/enUS/realmlist.wtf")).unwrap(), "set realmlist ptr.example.org\r\nset patchlist x.example\r\n"); + } + + #[test] + fn switching_writes_every_locale_saves_the_old_file_and_changes_nothing_else() { + let d = tempfile::tempdir().unwrap(); + let (c, meta) = (fake_client(d.path(), "ptr.example.org"), d.path().join("meta")); + fs::create_dir_all(&meta).unwrap(); + fs::write(c.join("WTF.txt"), b"mine").unwrap(); + let ptr = save_profile(&meta, Some(&c), None, "PTR", "ptr.example.org").unwrap(); + let changed = activate(&meta, &c, "solo").unwrap(); + assert_eq!(changed.len(), 2); + for loc in ["enUS", "ruRU"] { + assert_eq!(fs::read_to_string(c.join("Data").join(loc).join("realmlist.wtf")).unwrap(), "set realmlist 127.0.0.1\r\n"); + } + assert_eq!(view(&meta, Some(&c)).active.as_deref(), Some("solo")); + assert_eq!(fs::read_dir(meta.join("backups/client")).unwrap().count(), 2, "each replaced file was saved"); + activate(&meta, &c, &ptr.id).unwrap(); + assert_eq!(view(&meta, Some(&c)).active.as_deref(), Some(ptr.id.as_str())); + assert_eq!(fs::read(c.join("WTF.txt")).unwrap(), b"mine"); + } + + #[test] + fn names_are_unique_profiles_can_be_edited_and_the_last_one_stays() { + let d = tempfile::tempdir().unwrap(); + let meta = d.path().join("meta"); + fs::create_dir_all(&meta).unwrap(); + let a = save_profile(&meta, None, None, "PTR", "ptr.example.org").unwrap(); + assert!(save_profile(&meta, None, None, "ptr", "other.example.org").is_err(), "names are unique regardless of capitals"); + let edited = save_profile(&meta, None, Some(&a.id), "PTR 2", "ptr2.example.org").unwrap(); + assert_eq!((edited.id.as_str(), edited.data.as_str()), (a.id.as_str(), "set realmlist ptr2.example.org\r\n")); + assert!(save_profile(&meta, None, None, "", "x.example.org").is_err()); + delete_profile(&meta, None, &a.id).unwrap(); + assert!(delete_profile(&meta, None, "solo").is_err(), "one profile must remain"); + assert_eq!(view(&meta, None).profiles.len(), 1); + } +} diff --git a/modules/catalog.json b/modules/catalog.json new file mode 100644 index 0000000..cbfa516 --- /dev/null +++ b/modules/catalog.json @@ -0,0 +1,131 @@ +{ + "schema": 1, + "modules": [ + { + "id": "spellbook", + "name": "Spellbook", + "description": { + "en": "Restores the Books of Ascension as class trainers: right-click a book to see your class abilities by rank and train them for gold.", + "ru": "Возвращает Книги Вознесения как учителей класса: ПКМ по книге показывает умения вашего класса по рангам, их можно изучить за золото.", + "de": "Bringt die Bücher des Aufstiegs als Klassenlehrer zurück: Rechtsklick auf ein Buch zeigt die Fähigkeiten deiner Klasse nach Rang, die du für Gold erlernen kannst.", + "fr": "Rétablit les Livres de l’Ascension comme maîtres de classe : un clic droit sur un livre affiche les capacités de votre classe par rang, à apprendre contre de l’or.", + "es": "Restaura los Libros de Ascensión como instructores de clase: clic derecho en un libro muestra las habilidades de tu clase por rango para aprenderlas por oro." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-spellbook", + "conf": "spellbook.conf", + "enable_key": "Spellbook.Enable" + }, + { + "id": "war-games", + "name": "War Games", + "description": { + "en": "Private arena matches between two groups, arranged by Teri Glozilk in Orgrimmar and Stormwind.", + "ru": "Частные матчи на арене между двумя группами: их устраивает Тери Глозилк в Оргриммаре и Штормграде.", + "de": "Private Arenakämpfe zwischen zwei Gruppen, vermittelt von Teri Glozilk in Orgrimmar und Sturmwind.", + "fr": "Matchs d’arène privés entre deux groupes, organisés par Teri Glozilk à Orgrimmar et à Hurlevent.", + "es": "Combates de arena privados entre dos grupos, organizados por Teri Glozilk en Orgrimmar y Ventormenta." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-war-games", + "conf": "war_games.conf", + "enable_key": "WarGames.Enable" + }, + { + "id": "item-recovery", + "name": "Item Recovery", + "description": { + "en": "Answers the client's Item Recovery window from the vendor buyback slots: get back an item you just sold, for the price paid.", + "ru": "Отвечает окну «Восстановление предметов» клиента данными выкупа у торговца: можно вернуть недавно проданный предмет за ту же цену.", + "de": "Beantwortet das Fenster „Gegenstandswiederherstellung“ des Clients mit den Rückkauf-Plätzen des Händlers: kürzlich verkaufte Gegenstände zum gezahlten Preis zurückholen.", + "fr": "Répond à la fenêtre de récupération d’objets du client avec les emplacements de rachat du marchand : récupérez un objet vendu au prix payé.", + "es": "Responde a la ventana de recuperación de objetos del cliente con las ranuras de recompra del vendedor: recupera un objeto recién vendido por el precio pagado." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-item-recovery", + "conf": "item_recovery.conf", + "enable_key": "ItemRecovery.Enable" + }, + { + "id": "hero-call-board", + "name": "Hero's Call Board", + "description": { + "en": "The Hero's Call Board (Stormwind) and the Warchief's Command Board (Orgrimmar): 47 daily quests in PvE, Profession and PvP categories.", + "ru": "Доска призыва героев (Штормград) и Доска приказов вождя (Оргриммар): 47 ежедневных заданий в категориях PvE, профессии и PvP.", + "de": "Das Heldenruf-Brett (Sturmwind) und das Kriegshäuptlings-Befehlsbrett (Orgrimmar): 47 tägliche Quests in den Kategorien PvE, Beruf und PvP.", + "fr": "Le tableau d’appel des héros (Hurlevent) et le tableau de commandement du chef de guerre (Orgrimmar) : 47 quêtes quotidiennes JcE, métiers et JcJ.", + "es": "El Tablón de Llamada del Héroe (Ventormenta) y el Tablón de Mando del Jefe de Guerra (Orgrimmar): 47 misiones diarias de JcE, profesión y JcJ." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-hero-call-board", + "conf": "hero_call_board.conf", + "enable_key": "HeroCallBoard.Enable" + }, + { + "id": "path-to-ascension", + "name": "Path to Ascension", + "description": { + "en": "The tutorial book of the Ascension client: the server side of its tutorials, objectives and rewards.", + "ru": "Обучающая книга клиента Ascension: серверная часть её уроков, целей и наград.", + "de": "Das Tutorialbuch des Ascension-Clients: die Serverseite seiner Tutorials, Ziele und Belohnungen.", + "fr": "Le livre de tutoriels du client Ascension : la partie serveur de ses tutoriels, objectifs et récompenses.", + "es": "El libro de tutoriales del cliente Ascension: la parte del servidor de sus tutoriales, objetivos y recompensas." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-path-to-ascension", + "conf": "path_to_ascension.conf", + "enable_key": "PathToAscension.Enable" + }, + { + "id": "craftsmans-codex", + "name": "Craftsman's Codex", + "description": { + "en": "Restores the Craftsman's Codex: a character may learn one more primary profession than the standard two, once per codex used.", + "ru": "Возвращает Кодекс мастера: персонаж может выучить ещё одну основную профессию сверх обычных двух, по разу за использованный кодекс.", + "de": "Bringt den Kodex des Handwerkers zurück: Ein Charakter kann einen weiteren Hauptberuf zusätzlich zu den üblichen zwei erlernen, einmal pro benutztem Kodex.", + "fr": "Rétablit le Codex de l’artisan : un personnage peut apprendre un métier principal de plus que les deux habituels, une fois par codex utilisé.", + "es": "Restaura el Códice del Artesano: un personaje puede aprender una profesión principal más que las dos habituales, una vez por códice usado." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-craftsmans-codex", + "conf": "craftsmans_codex.conf", + "enable_key": "CraftsmansCodex.Enable" + }, + { + "id": "coa-prestige", + "name": "Prestige Mode", + "description": { + "en": "Chromie's Prestige Mode: at level 60 a character winds back to level 1 and levels again with an experience bonus and Prestige rewards.", + "ru": "Режим престижа Хроми: на 60 уровне персонаж откатывается на 1 уровень и снова растёт с бонусом к опыту и наградами за престиж.", + "de": "Chromies Prestigemodus: Auf Stufe 60 wird ein Charakter auf Stufe 1 zurückgesetzt und levelt erneut mit Erfahrungsbonus und Prestige-Belohnungen.", + "fr": "Le mode Prestige de Chromie : au niveau 60, un personnage revient au niveau 1 et remonte avec un bonus d’expérience et des récompenses de prestige.", + "es": "El modo Prestigio de Chromie: al nivel 60 un personaje vuelve al nivel 1 y sube de nuevo con bonificación de experiencia y recompensas de prestigio." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-coa-prestige", + "conf": "mod-coa-prestige.conf", + "enable_key": "CoAPrestige.Enable" + }, + { + "id": "coa-challenges", + "name": "Challenges", + "description": { + "en": "The Conquest of Azeroth challenges / trials: lives, rules, objectives, completions and rewards behind the client's Challenge window.", + "ru": "Испытания Conquest of Azeroth: жизни, правила, цели, завершения и награды для окна испытаний клиента.", + "de": "Die Herausforderungen / Prüfungen von Conquest of Azeroth: Leben, Regeln, Ziele, Abschlüsse und Belohnungen hinter dem Herausforderungsfenster des Clients.", + "fr": "Les défis / épreuves de Conquest of Azeroth : vies, règles, objectifs, réussites et récompenses derrière la fenêtre de défis du client.", + "es": "Los desafíos / pruebas de Conquest of Azeroth: vidas, reglas, objetivos, finalizaciones y recompensas de la ventana de desafíos del cliente." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-coa-challenges", + "conf": "mod-coa-challenges.conf", + "enable_key": "CoAChallenges.Enable" + }, + { + "id": "teleport-actionbar", + "name": "Teleport Action Bar", + "description": { + "en": "Makes CoA teleport tokens usable from the spellbook collection and from an action bar button, and keeps each stone on its own faction's side.", + "ru": "Делает телепорт-жетоны CoA доступными из коллекции книги заклинаний и с кнопки на панели действий и оставляет каждый камень на стороне своей фракции.", + "de": "Macht CoA-Teleportmarken aus der Zauberbuch-Sammlung und über eine Aktionsleisten-Schaltfläche nutzbar und hält jeden Stein auf der Seite seiner Fraktion.", + "fr": "Rend les jetons de téléportation CoA utilisables depuis la collection du grimoire et depuis un bouton de barre d’action, et garde chaque pierre du côté de sa faction.", + "es": "Hace que las fichas de teletransporte de CoA se puedan usar desde la colección del libro de hechizos y desde un botón de la barra de acción, y mantiene cada piedra del lado de su facción." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-teleport-actionbar", + "conf": "mod_teleport_actionbar.conf", + "enable_key": "TeleportActionBar.Enable" + } + ] +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 04ac106..7c5acb5 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -459,6 +459,82 @@ async fn create_account(state: State<'_, AppState>, id: String, username: String .await } +#[tauri::command] +async fn realmlist_profiles(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + Ok(coa_core::realmlist::view(&dir, linked_client(&root)?.as_deref())) + }) + .await +} + +#[tauri::command] +async fn realmlist_save(state: State<'_, AppState>, id: String, profile_id: Option, name: String, data: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + coa_core::realmlist::save_profile(&dir, linked_client(&root)?.as_deref(), profile_id.as_deref(), &name, &data) + }) + .await +} + +#[tauri::command] +async fn realmlist_delete(state: State<'_, AppState>, id: String, profile_id: String) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + coa_core::realmlist::delete_profile(&dir, linked_client(&root)?.as_deref(), &profile_id) + }) + .await +} + +/// Write the chosen realmlist into the linked game client. +#[tauri::command] +async fn realmlist_activate(state: State<'_, AppState>, id: String, profile_id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is set up for this server yet.".into()))?; + let changed = coa_core::realmlist::activate(&dir, &client, &profile_id)?; + tracing::info!(profile = %profile_id, files = changed.len(), "realmlist switched"); + Ok(changed) + }) + .await +} + +#[tauri::command] +async fn modules_list(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || Ok(coa_core::modules::list(&root))).await +} + +#[tauri::command] +async fn module_set_enabled(state: State<'_, AppState>, id: String, module: String, enabled: bool) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + coa_core::modules::set_enabled(&root, &dir, &module, enabled) + }) + .await +} + +#[tauri::command] +async fn module_settings(state: State<'_, AppState>, id: String, module: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || coa_core::modules::settings(&root, &module)).await +} + +#[tauri::command] +async fn module_save_settings(state: State<'_, AppState>, id: String, module: String, changes: BTreeMap) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + coa_core::modules::save_settings(&root, &dir, &module, &changes) + }) + .await +} + #[tauri::command] async fn list_accounts(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { let root = path_of(&state, &id)?; @@ -1007,7 +1083,7 @@ struct FriendsStatus { /// Manager to launch an arbitrary address. #[tauri::command] fn open_link(url: String) -> std::result::Result<(), UiError> { - const ALLOWED: &[&str] = &["https://tailscale.com/", "https://login.tailscale.com/", "https://portforward.com/"]; + const ALLOWED: &[&str] = &["https://tailscale.com/", "https://login.tailscale.com/", "https://portforward.com/", "https://github.com/Corfirean/"]; // A prefilled "new issue" page of this project: the address must be exactly that page, and its query may carry // `&` between the (percent-encoded) title and text. const NEW_ISSUE: &str = "https://github.com/Corfirean/coa-server-manager/issues/new"; @@ -1283,6 +1359,14 @@ pub fn run() { install_requirements, report_context, list_accounts, + realmlist_profiles, + realmlist_save, + realmlist_delete, + realmlist_activate, + modules_list, + module_set_enabled, + module_settings, + module_save_settings, account_set_password, account_set_access, account_rename, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 1c74d1e..fe7f49e 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -49,6 +49,14 @@ export {}; if(cmd==="client_download"){await run("scan",4,0);await run("download",40,41e6);w.__client="new";return {path:args.parent+"\\CoA Client",executable:"Ascension.exe",realmlists:[{path:"x",host:"127.0.0.1"}],addon:{installed:true,version:"1",up_to_date:true},other_addons:0};} if(cmd==="client_cancel"){w.__stop=true;return null;} } + if(cmd==="realmlist_profiles"){const w=window as any;w.__rl=w.__rl??{profiles:[{id:"solo",name:"Solo",data:"set realmlist 127.0.0.1\r\n"},{id:"ptr",name:"PTR",data:"set realmlist ptr.example.org\r\n"}],active:"solo"};return w.__rl;} + if(cmd==="realmlist_activate"){(window as any).__rl.active=args.profileId;return [];} + if(cmd==="realmlist_save"){const w=window as any;const rl=w.__rl;if(args.profileId){const p=rl.profiles.find((x: any)=>x.id===args.profileId);p.name=args.name;p.data=args.data;return p;}if(rl.profiles.some((x: any)=>x.name.toLowerCase()===String(args.name).toLowerCase()))throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"A realmlist with that name already exists."};const p={id:String(args.name).toLowerCase().replace(/[^a-z0-9]+/g,"-"),name:args.name,data:(/\s/.test(args.data.trim())?args.data.trim():"set realmlist "+args.data.trim())+"\r\n"};rl.profiles.push(p);return p;} + if(cmd==="realmlist_delete"){const rl=(window as any).__rl;rl.profiles=rl.profiles.filter((x: any)=>x.id!==args.profileId);return null;} + if(cmd==="modules_list"){const w=window as any;w.__mods=w.__mods??[{id:"spellbook",name:"Spellbook",description:{en:"Restores the Books of Ascension as class trainers: right-click a book to see your class abilities by rank and train them for gold."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-spellbook",installed:true,enabled:true},{id:"war-games",name:"War Games",description:{en:"Private arena matches between two groups, arranged by Teri Glozilk in Orgrimmar and Stormwind."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-war-games",installed:true,enabled:false},{id:"coa-prestige",name:"Prestige Mode",description:{en:"Chromie's Prestige Mode."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/mod-coa-prestige",installed:false,enabled:false}];return w.__mods;} + if(cmd==="module_set_enabled"){const m=(window as any).__mods.find((x: any)=>x.id===args.module);m.enabled=args.enabled;return null;} + if(cmd==="module_settings") return [{key:"WarGames.Enable",value:"1",default:"1",doc:"Turns War Games on."},{key:"WarGames.ChallengeSeconds",value:"60",default:"60",doc:"How long a challenge stays open."}]; + if(cmd==="module_save_settings") return Object.keys(args.changes); if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10"}; if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;} if(cmd==="export_diagnostics") return "C:\\Users\\you\\Desktop\\CoA-Diagnostics-20261001-140000.zip"; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index cad8b22..96a3244 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -695,6 +695,32 @@ const de: Partial> = { "rep.opened": "GitHub wurde im Browser geöffnet. Prüfe den Text, hänge Dateien an und klicke auf „Submit new issue“.", "rep.openedLong": "Der Bericht ist für einen Link zu lang und wurde deshalb in die Zwischenablage kopiert. GitHub ist geöffnet: Füge ihn (Strg+V) in die Beschreibung ein, hänge Dateien an und klicke auf „Submit new issue“.", "rep.copied": "In die Zwischenablage kopiert.", + + // Realmlist switcher and modules page + "realm.label": "Realm", + "realm.other": "Anderer", + "realm.add": "Realmlist hinzufügen …", + "realm.addTitle": "Neue Realmlist", + "realm.editTitle": "Realmlist ändern", + "realm.name": "Name", + "realm.nameHint": "Zum Beispiel Solo oder PTR", + "realm.data": "Realmlist-Text", + "realm.dataHint": "Was in die realmlist.wtf geschrieben wird, zum Beispiel: set realmlist play.example.com. Du kannst auch nur die Adresse eingeben. Beim Auswählen wird die Realmlist in deinen Spielclient geschrieben; die vorherige Datei wird zuvor gesichert.", + "realm.switched": "Das Spiel verwendet jetzt „{name}“.", + "realm.edit": "{name} ändern", + "realm.delete": "{name} entfernen", + "realm.confirmDelete": "Realmlist „{name}“ entfernen? Der Spielclient behält die aktuelle Datei.", + "nav.modules": "Module", + "q.modules": "Welche Zusatzfunktionen hat der Server?", + "mod.title": "Module", + "mod.intro": "Zusatzfunktionen, die bereits im Server eingebaut sind. Schalte die gewünschten ein oder aus, lies auf GitHub darüber oder ändere ihre Einstellungen.", + "mod.restart": "Änderungen werden nach einem Neustart des Weltservers wirksam.", + "mod.switch": "{name} ein- oder ausschalten", + "mod.notHere": "Nicht Teil dieses Servers", + "mod.github": "GitHub", + "mod.settings": "Einstellungen", + "mod.default": "Zurück zum Standard ({v})", + "mod.saved": "Gespeichert ({n} geändert).", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 9a7ecef..60da01e 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -695,6 +695,32 @@ const en = { "rep.opened": "GitHub was opened in your browser. Check the text, attach files and press Submit new issue.", "rep.openedLong": "The report is too long for a link, so it was copied to the clipboard. GitHub is open: paste it (Ctrl+V) into the description, attach files and press Submit new issue.", "rep.copied": "Copied to the clipboard.", + + // Realmlist switcher and modules page + "realm.label": "Realm", + "realm.other": "Other", + "realm.add": "Add a realmlist…", + "realm.addTitle": "New realmlist", + "realm.editTitle": "Change the realmlist", + "realm.name": "Name", + "realm.nameHint": "For example Solo or PTR", + "realm.data": "Realmlist text", + "realm.dataHint": "What goes into realmlist.wtf, for example: set realmlist play.example.com. You can also type just the address. Choosing a realmlist writes it into your game client; the previous file is saved first.", + "realm.switched": "The game now uses “{name}”.", + "realm.edit": "Change {name}", + "realm.delete": "Remove {name}", + "realm.confirmDelete": "Remove the realmlist “{name}”? The game client keeps whatever file it has now.", + "nav.modules": "Modules", + "q.modules": "What extra features does the server have?", + "mod.title": "Modules", + "mod.intro": "Extra features that are already built into the server. Switch the ones you want on or off, read about them on GitHub, or change their settings.", + "mod.restart": "Changes apply after the world server restarts.", + "mod.switch": "Turn {name} on or off", + "mod.notHere": "Not part of this server", + "mod.github": "GitHub", + "mod.settings": "Settings", + "mod.default": "Back to the default ({v})", + "mod.saved": "Saved ({n} changed).", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 3c59c12..a81f476 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -695,6 +695,32 @@ const es: Partial> = { "rep.opened": "GitHub se abrió en tu navegador. Revisa el texto, adjunta archivos y pulsa «Submit new issue».", "rep.openedLong": "El informe es demasiado largo para un enlace, así que se copió al portapapeles. GitHub está abierto: pégalo (Ctrl+V) en la descripción, adjunta archivos y pulsa «Submit new issue».", "rep.copied": "Copiado al portapapeles.", + + // Realmlist switcher and modules page + "realm.label": "Reino", + "realm.other": "Otro", + "realm.add": "Añadir una realmlist…", + "realm.addTitle": "Nueva realmlist", + "realm.editTitle": "Cambiar la realmlist", + "realm.name": "Nombre", + "realm.nameHint": "Por ejemplo Solo o PTR", + "realm.data": "Texto de la realmlist", + "realm.dataHint": "Lo que se escribe en realmlist.wtf, por ejemplo: set realmlist play.example.com. También puedes escribir solo la dirección. Al elegir una realmlist se escribe en tu cliente; el archivo anterior se guarda antes.", + "realm.switched": "El juego ahora usa «{name}».", + "realm.edit": "Cambiar {name}", + "realm.delete": "Eliminar {name}", + "realm.confirmDelete": "¿Eliminar la realmlist «{name}»? El cliente conserva el archivo actual.", + "nav.modules": "Módulos", + "q.modules": "¿Qué funciones adicionales tiene el servidor?", + "mod.title": "Módulos", + "mod.intro": "Funciones adicionales ya integradas en el servidor. Activa o desactiva las que quieras, léelas en GitHub o cambia sus ajustes.", + "mod.restart": "Los cambios se aplican al reiniciar el servidor del mundo.", + "mod.switch": "Activar o desactivar {name}", + "mod.notHere": "No forma parte de este servidor", + "mod.github": "GitHub", + "mod.settings": "Ajustes", + "mod.default": "Volver al valor por defecto ({v})", + "mod.saved": "Guardado ({n} cambiado(s)).", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 3560796..a88dc81 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -695,6 +695,32 @@ const fr: Partial> = { "rep.opened": "GitHub s’est ouvert dans votre navigateur. Vérifiez le texte, joignez les fichiers et appuyez sur « Submit new issue ».", "rep.openedLong": "Le rapport est trop long pour un lien : il a été copié dans le presse-papiers. GitHub est ouvert : collez-le (Ctrl+V) dans la description, joignez les fichiers et appuyez sur « Submit new issue ».", "rep.copied": "Copié dans le presse-papiers.", + + // Realmlist switcher and modules page + "realm.label": "Royaume", + "realm.other": "Autre", + "realm.add": "Ajouter une realmlist…", + "realm.addTitle": "Nouvelle realmlist", + "realm.editTitle": "Modifier la realmlist", + "realm.name": "Nom", + "realm.nameHint": "Par exemple Solo ou PTR", + "realm.data": "Texte de la realmlist", + "realm.dataHint": "Ce qui sera écrit dans realmlist.wtf, par exemple : set realmlist play.example.com. Vous pouvez aussi saisir seulement l’adresse. Choisir une realmlist l’écrit dans votre client ; l’ancien fichier est d’abord sauvegardé.", + "realm.switched": "Le jeu utilise maintenant « {name} ».", + "realm.edit": "Modifier {name}", + "realm.delete": "Supprimer {name}", + "realm.confirmDelete": "Supprimer la realmlist « {name} » ? Le client garde le fichier actuel.", + "nav.modules": "Modules", + "q.modules": "Quelles fonctions supplémentaires le serveur propose-t-il ?", + "mod.title": "Modules", + "mod.intro": "Fonctions supplémentaires déjà intégrées au serveur. Activez ou désactivez celles que vous voulez, lisez-en plus sur GitHub ou modifiez leurs réglages.", + "mod.restart": "Les changements s’appliquent après le redémarrage du serveur de monde.", + "mod.switch": "Activer ou désactiver {name}", + "mod.notHere": "Ne fait pas partie de ce serveur", + "mod.github": "GitHub", + "mod.settings": "Réglages", + "mod.default": "Revenir à la valeur par défaut ({v})", + "mod.saved": "Enregistré ({n} modifié(s)).", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 33f747c..82a9e14 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -695,6 +695,32 @@ const ru: Partial> = { "rep.opened": "GitHub открыт в браузере. Проверьте текст, прикрепите файлы и нажмите «Submit new issue».", "rep.openedLong": "Отчёт слишком длинный для ссылки, поэтому он скопирован в буфер обмена. GitHub открыт: вставьте текст (Ctrl+V) в описание, прикрепите файлы и нажмите «Submit new issue».", "rep.copied": "Скопировано в буфер обмена.", + + // Realmlist switcher and modules page + "realm.label": "Реалм", + "realm.other": "Другой", + "realm.add": "Добавить реалмлист…", + "realm.addTitle": "Новый реалмлист", + "realm.editTitle": "Изменить реалмлист", + "realm.name": "Название", + "realm.nameHint": "Например: Solo или PTR", + "realm.data": "Текст реалмлиста", + "realm.dataHint": "То, что попадёт в realmlist.wtf, например: set realmlist play.example.com. Можно ввести и просто адрес. Выбор реалмлиста записывает его в ваш игровой клиент; прежний файл сначала сохраняется.", + "realm.switched": "Игра теперь использует «{name}».", + "realm.edit": "Изменить {name}", + "realm.delete": "Удалить {name}", + "realm.confirmDelete": "Удалить реалмлист «{name}»? В игровом клиенте останется текущий файл.", + "nav.modules": "Модули", + "q.modules": "Какие дополнительные возможности есть у сервера?", + "mod.title": "Модули", + "mod.intro": "Дополнительные возможности, уже встроенные в сервер. Включайте и выключайте нужные, читайте о них на GitHub или меняйте их настройки.", + "mod.restart": "Изменения применятся после перезапуска игрового сервера.", + "mod.switch": "Включить или выключить {name}", + "mod.notHere": "Нет в этом сервере", + "mod.github": "GitHub", + "mod.settings": "Настройки", + "mod.default": "Вернуть по умолчанию ({v})", + "mod.saved": "Сохранено (изменено: {n}).", }; export default ru; diff --git a/src/lib/api.ts b/src/lib/api.ts index 8478dc0..a25cda5 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -167,6 +167,29 @@ export interface Preflight { free_bytes: number; } +export interface RealmProfile { + id: string; + name: string; + data: string; +} + +export interface ModuleView { + id: string; + name: string; + description: Record; + repo: string; + /** the module is part of this server build (its configuration exists) */ + installed: boolean; + enabled: boolean; +} + +export interface ModuleSetting { + key: string; + value: string; + default: string | null; + doc: string; +} + export interface ReportContext { manager_version: string; windows: string; @@ -336,6 +359,14 @@ export const api = { restoreDatabase: (id: string, backupId: string, database: string) => invoke("restore_backup_database", { id, backupId, database }), installPreflight: (dest: string, needed?: number) => invoke("install_preflight", { dest, needed: needed ?? null }), installRequirements: (pkg?: string) => invoke("install_requirements", { package: pkg ?? null }), + realmlistProfiles: (id: string) => invoke<{ profiles: RealmProfile[]; active: string | null }>("realmlist_profiles", { id }), + realmlistSave: (id: string, profileId: string | null, name: string, data: string) => invoke("realmlist_save", { id, profileId, name, data }), + realmlistDelete: (id: string, profileId: string) => invoke("realmlist_delete", { id, profileId }), + 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 }), + moduleSettings: (id: string, module: string) => invoke("module_settings", { id, module }), + moduleSaveSettings: (id: string, module: string, changes: Record) => invoke("module_save_settings", { id, module, changes }), reportContext: (id: string) => invoke("report_context", { id }), listAccounts: (id: string) => invoke("list_accounts", { id }), accountSetPassword: (id: string, name: string, password: string) => invoke("account_set_password", { id, name, password }), diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx new file mode 100644 index 0000000..9334419 --- /dev/null +++ b/src/screens/ModulesPage.tsx @@ -0,0 +1,157 @@ +import { useCallback, useEffect, useState } from "react"; +import { ExternalLink, Loader2 } from "lucide-react"; +import { api, asUiError, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { useHuman, useI18n } from "@/i18n"; + +/** The server's optional modules: switch each on or off, open its page on GitHub, change its settings. */ +export function ModulesPage({ serverId }: { serverId: string }) { + const { t, locale } = useI18n(); + const human = useHuman(); + const [modules, setModules] = useState(null); + const [open, setOpen] = useState(null); + const [error, setError] = useState(null); + const [changed, setChanged] = useState(false); + + const load = useCallback(async () => { + try { + setModules(await api.modulesList(serverId)); + } catch (e) { + setError(asUiError(e)); + } + }, [serverId]); + + useEffect(() => { + void load(); + }, [load]); + + async function toggle(m: ModuleView) { + setError(null); + try { + await api.moduleSetEnabled(serverId, m.id, !m.enabled); + setChanged(true); + await load(); + } catch (e) { + setError(asUiError(e)); + } + } + + return ( +
+

{t("mod.title")}

+

{t("q.modules")}

+

{t("mod.intro")}

+ {changed &&

{t("mod.restart")}

} + {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} + +
+ {modules === null &&

{t("overview.checking")}

} + {modules?.map((m) => ( + +
+
+

{m.name}

+

{m.description[locale] ?? m.description.en}

+
+ {m.installed ? ( + + ) : ( + {t("mod.notHere")} + )} +
+
+ + {m.installed && ( + + )} +
+ {open === m.id && setChanged(true)} />} +
+ ))} +
+
+ ); +} + +function ModuleSettings({ serverId, module, onSaved }: { serverId: string; module: ModuleView; onSaved: () => void }) { + const { t } = useI18n(); + const human = useHuman(); + const [items, setItems] = useState(null); + const [edits, setEdits] = useState>({}); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [note, setNote] = useState(null); + + useEffect(() => { + void api.moduleSettings(serverId, module.id).then((s) => setItems(s)).catch((e) => setError(asUiError(e))); + }, [serverId, module.id]); + + async function save() { + setBusy(true); + setError(null); + setNote(null); + try { + const done = await api.moduleSaveSettings(serverId, module.id, edits); + setEdits({}); + setItems(await api.moduleSettings(serverId, module.id)); + if (done.length) { + onSaved(); + setNote(t("mod.saved", { n: done.length })); + } + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(false); + } + } + + const dirty = Object.keys(edits).length > 0; + return ( +
+ {items === null && !error && } +
    + {items?.map((s) => ( +
  • +
    + + setEdits((x) => ({ ...x, [s.key]: e.target.value }))} + className="selectable w-56 rounded-md border border-line bg-bg px-2.5 py-1.5 text-sm outline-none focus:border-gold" + /> +
    + {s.doc &&

    {s.doc}

    } + {s.default !== null && (edits[s.key] ?? s.value) !== s.default && ( + + )} +
  • + ))} +
+
+ + {note && {note}} +
+ {error &&

{error.human.code === "unknown" ? error.technical : human(error.human).message}

} +
+ ); +} diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index e30684f..3d175df 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -6,6 +6,7 @@ import { useHuman, useT } from "@/i18n"; import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate"; import { checkClient, useClientStatus } from "@/lib/clientUpdate"; import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog"; +import { RealmlistMenu } from "@/screens/RealmlistMenu"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -276,12 +277,13 @@ export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSu {t("btn.stopSmall")} )} + {client && } {client && clientStatus?.update_available ? ( - ) : client ? ( - diff --git a/src/screens/RealmlistMenu.tsx b/src/screens/RealmlistMenu.tsx new file mode 100644 index 0000000..b230f94 --- /dev/null +++ b/src/screens/RealmlistMenu.tsx @@ -0,0 +1,154 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { Check, ChevronDown, Pencil, Plus, Trash2 } from "lucide-react"; +import { api, asUiError, type RealmProfile, type UiError } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { useHuman, useT } from "@/i18n"; + +/** The first `set realmlist` value of a realmlist text, for the small caption under a name. */ +function host(data: string): string { + const m = data.match(/^\s*set\s+realmlist\s+(\S+)/im); + return m ? m[1].replace(/"/g, "") : ""; +} + +/** Named realmlists for the game client, switched with one click: "Solo" for your own server, "PTR" for the shared one, and so on. */ +export function RealmlistMenu({ serverId, className }: { serverId: string; className?: string }) { + const t = useT(); + const human = useHuman(); + const [profiles, setProfiles] = useState([]); + const [active, setActive] = useState(null); + const [open, setOpen] = useState(false); + const [editing, setEditing] = useState<{ id: string | null; name: string; data: string } | null>(null); + const [error, setError] = useState(null); + const [note, setNote] = useState(null); + const box = useRef(null); + + const load = useCallback(async () => { + try { + const v = await api.realmlistProfiles(serverId); + setProfiles(v.profiles); + setActive(v.active); + } catch (e) { + setError(asUiError(e)); + } + }, [serverId]); + + useEffect(() => { + void load(); + }, [load]); + + useEffect(() => { + if (!open) return; + const away = (e: MouseEvent) => { + if (box.current && !box.current.contains(e.target as Node)) setOpen(false); + }; + document.addEventListener("mousedown", away); + return () => document.removeEventListener("mousedown", away); + }, [open]); + + async function choose(p: RealmProfile) { + setError(null); + setNote(null); + try { + await api.realmlistActivate(serverId, p.id); + setActive(p.id); + setNote(t("realm.switched", { name: p.name })); + } catch (e) { + setError(asUiError(e)); + } + } + + async function remove(p: RealmProfile) { + if (!window.confirm(t("realm.confirmDelete", { name: p.name }))) return; + setError(null); + try { + await api.realmlistDelete(serverId, p.id); + await load(); + } catch (e) { + setError(asUiError(e)); + } + } + + async function save() { + if (!editing) return; + setError(null); + try { + await api.realmlistSave(serverId, editing.id, editing.name, editing.data); + setEditing(null); + await load(); + } catch (e) { + setError(asUiError(e)); + } + } + + const current = profiles.find((p) => p.id === active); + const message = error ? (error.human.code === "unknown" ? error.technical : human(error.human).message) : null; + + return ( +
+ + + {open && ( +
+
    + {profiles.map((p) => ( +
  • + + + +
  • + ))} +
+
+ +
+ {note &&

{note}

} + {message && !editing &&

{message}

} +
+ )} + + {editing && ( +
+ +

{editing.id ? t("realm.editTitle") : t("realm.addTitle")}

+ + setEditing({ ...editing, name: e.target.value })} placeholder={t("realm.nameHint")} className="mt-1 block w-full rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold" /> + +