From 726b089f423eb313145e32271b08fa1ac0403a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Fri, 2 Oct 2026 11:26:09 +0500 Subject: [PATCH] Modules page: square icon cards with status (early/beta/release), switch, GitHub and settings; companions, scaling, TBC and WotLK packs and client compatibility in the catalog; a module switched off hides its page. Accounts: delete an account with confirmation. Co-Authored-By: Claude Sonnet 5.5 --- crates/coa-core/src/accounts.rs | 36 +++++++++ crates/coa-core/src/modules.rs | 133 +++++++++++++++++++++++++++++--- crates/coa-core/src/ra.rs | 7 ++ modules/catalog.json | 85 +++++++++++++++++++- src-tauri/src/lib.rs | 11 +++ src/dev/mock.ts | 6 +- src/i18n/locales/de.ts | 17 +++- src/i18n/locales/en.ts | 17 +++- src/i18n/locales/es.ts | 17 +++- src/i18n/locales/fr.ts | 17 +++- src/i18n/locales/ru.ts | 17 +++- src/lib/api.ts | 8 ++ src/screens/AccountsCard.tsx | 33 +++++++- src/screens/ModulesPage.tsx | 132 +++++++++++++++++++++++++------ src/screens/Overview.tsx | 6 +- src/screens/Shell.tsx | 25 ++++-- 16 files changed, 514 insertions(+), 53 deletions(-) diff --git a/crates/coa-core/src/accounts.rs b/crates/coa-core/src/accounts.rs index 946a099..5aaa361 100644 --- a/crates/coa-core/src/accounts.rs +++ b/crates/coa-core/src/accounts.rs @@ -84,6 +84,32 @@ pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Ok(()) } +/// Accounts the Manager and the companions use themselves; they can never be deleted from here. +fn is_reserved(upper_name: &str) -> bool { + upper_name == "COAMANAGER" || upper_name.starts_with("COABOT") +} + +/// Delete an account and, with it, all of its characters. Needs the world console. Refuses the Manager's and the +/// companions' own accounts, an account that is not there and one that is logged in right now. +pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> { + let name = upper(name)?; + if is_reserved(&name) { + return Err(Error::Invalid("This account belongs to the Manager or the companions and cannot be deleted.".into())); + } + let db = Db::from_repack(root, Account::Admin)?; + match db.query(&format!("SELECT online FROM acore_auth.account WHERE username = '{name}';"))?.trim() { + "" => return Err(Error::Invalid("That account does not exist.".into())), + "0" => {} + _ => return Err(Error::Invalid("The account is logged in right now; log it out first.".into())), + } + ra.delete_account(&name)?; + if db.query(&format!("SELECT COUNT(*) FROM acore_auth.account WHERE username = '{name}';"))?.trim() != "0" { + return Err(Error::Invalid("The account was not deleted.".into())); + } + tracing::info!(%name, "account deleted"); + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -102,6 +128,16 @@ mod tests { assert!(LIST_SQL.contains("COABOTHOST%") && LIST_SQL.contains("COAMANAGER")); } + #[test] + fn the_managers_and_the_companions_accounts_are_never_deletable() { + for n in ["COAMANAGER", "COABOTHOST1", "COABOT12", "COABOTS"] { + assert!(is_reserved(n), "{n}"); + } + for n in ["ALICE", "MYCOABOT", "BOT1"] { + assert!(!is_reserved(n), "{n}"); + } + } + #[test] fn names_are_validated_and_stored_in_capitals() { assert_eq!(upper("Alice1").unwrap(), "ALICE1"); diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index b24b6ee..3db45f6 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -23,8 +23,36 @@ pub struct Entry { 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). + /// The name an older server build gave that file (used when `conf` is not there). + #[serde(default)] + pub alt_conf: Option, + /// The setting that switches the whole module on or off (1 / 0). Empty for a part that cannot be switched off. + #[serde(default)] pub enable_key: String, + /// Can be turned on and off here. A part the game client needs to talk to the server is only configured. + #[serde(default = "yes")] + pub switchable: bool, + /// What the module is when its setting is not in the file: a server from before the setting existed runs it. + #[serde(default = "yes")] + pub default_on: bool, + /// How far along it is: `early` (experimental, may change or break), `beta` (works, still being tested) or + /// `release` (stable). + #[serde(default = "release")] + pub status: String, + /// Which icon the page draws (a name the page knows). + #[serde(default)] + pub icon: String, + /// A page of the Manager that only makes sense while the module is on (it is hidden while it is off). + #[serde(default)] + pub page: Option, +} + +fn yes() -> bool { + true +} + +fn release() -> String { + "release".into() } #[derive(Deserialize)] @@ -61,31 +89,61 @@ pub struct ModuleView { /// 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 switchable: bool, + pub status: String, + pub icon: String, + pub page: Option, } pub fn list(root: &Path) -> Vec { list_in(&catalog(), root) } +/// The configuration file name this server uses for the module: the current one, or the name an older build gave it. +fn conf_name(root: &Path, e: &Entry) -> String { + let there = |n: &str| dir(root).join(n).is_file() || dir(root).join(format!("{n}.dist")).is_file(); + if there(&e.conf) { + return e.conf.clone(); + } + match &e.alt_conf { + Some(alt) if there(alt) => alt.clone(), + _ => e.conf.clone(), + } +} + fn list_in(cat: &[Entry], root: &Path) -> Vec { cat.iter() .cloned() .map(|e| { - let conf = dir(root).join(&e.conf); - let dist = dir(root).join(format!("{}.dist", e.conf)); + 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(); // 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 } + let enabled = !e.switchable + || read(&conf).or_else(|| read(&dist)).and_then(|c| c.get(&e.enable_key).map(truthy)).unwrap_or(e.default_on); + ModuleView { + id: e.id, + name: e.name, + description: e.description, + repo: e.repo, + installed, + enabled, + switchable: e.switchable, + status: e.status, + icon: e.icon, + page: e.page, + } }) .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); + let name = conf_name(root, e); + let conf = dir(root).join(&name); if !conf.is_file() { - let dist = dir(root).join(format!("{}.dist", e.conf)); + let dist = dir(root).join(format!("{name}.dist")); if !dist.is_file() { return Err(Error::Invalid("This module is not part of this server.".into())); } @@ -106,9 +164,12 @@ pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> { let e = entry_in(cat, id)?; + if !e.switchable || e.enable_key.is_empty() { + return Err(Error::Invalid("This part cannot be switched off.".into())); + } 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) { + if file.get(&e.enable_key).map(truthy).unwrap_or(e.default_on) == on && file.get(&e.enable_key).is_some() { return Ok(()); } backup(meta, &conf)?; @@ -134,8 +195,9 @@ pub fn settings(root: &Path, id: &str) -> Result> { fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result> { let e = entry_in(cat, id)?; - let conf = dir(root).join(&e.conf); - let dist = read(&dir(root).join(format!("{}.dist", e.conf))); + let name = conf_name(root, &e); + let conf = dir(root).join(&name); + let dist = read(&dir(root).join(format!("{name}.dist"))); 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() @@ -192,7 +254,13 @@ mod tests { description: ["en", "ru", "de", "fr", "es"].iter().map(|l| (l.to_string(), format!("{name} ({l})"))).collect(), repo: format!("https://github.com/Corfirean/example/{id}"), conf: conf.into(), + alt_conf: None, enable_key: key.into(), + switchable: true, + default_on: true, + status: "beta".into(), + icon: String::new(), + page: None, }; vec![one("war-games", "War Games", "war_games.conf", "WarGames.Enable"), one("spellbook", "Spellbook", "spellbook.conf", "Spellbook.Enable")] } @@ -212,7 +280,9 @@ mod tests { // it may be empty (modules are added to it one by one); whatever is in it must be complete 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); + assert!(e.repo.starts_with("https://github.com/Corfirean/") && e.conf.ends_with(".conf"), "{}", e.id); + assert!(!e.switchable || e.enable_key.ends_with(".Enable"), "{} needs the setting that switches it", e.id); + assert!(["early", "beta", "release"].contains(&e.status.as_str()), "{} has an unknown status", e.id); } let mut ids: Vec<_> = c.iter().map(|e| e.id.as_str()).collect(); ids.sort(); @@ -264,4 +334,45 @@ mod tests { } assert!(!fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("Injected")); } + + #[test] + fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + fs::write(dir(&root).join("old_name.conf"), "CoA.Enable = 0\r\nCoA.UnlockAllVanity = 1\r\n").unwrap(); + let compat = Entry { + id: "compat".into(), + name: "Compat".into(), + description: ["en", "ru", "de", "fr", "es"].iter().map(|l| (l.to_string(), "x".to_string())).collect(), + repo: "https://github.com/Corfirean/x".into(), + conf: "coa.conf".into(), + alt_conf: Some("old_name.conf".into()), + enable_key: String::new(), + switchable: false, + default_on: true, + status: "release".into(), + icon: String::new(), + page: None, + }; + let cat = vec![compat]; + let v = list_in(&cat, &root).remove(0); + assert!(v.installed && v.enabled && !v.switchable, "found under the old name, never reported as off"); + assert_eq!(settings_in(&cat, &root, "compat").unwrap().len(), 2); + let change = BTreeMap::from([("CoA.UnlockAllVanity".to_string(), "0".to_string())]); + assert_eq!(save_settings_in(&cat, &root, &meta, "compat", &change).unwrap(), ["CoA.UnlockAllVanity"]); + assert!(fs::read_to_string(dir(&root).join("old_name.conf")).unwrap().contains("CoA.UnlockAllVanity = 0")); + assert!(set_enabled_in(&cat, &root, &meta, "compat", false).is_err(), "cannot be switched off"); + } + + #[test] + fn a_module_whose_setting_is_not_in_the_file_counts_as_on_and_can_be_switched_off() { + let d = tempfile::tempdir().unwrap(); + let (root, meta) = server(d.path()); + fs::write(dir(&root).join("war_games.conf"), "WarGames.ChallengeSeconds = 60\r\n").unwrap(); + let cat = test_catalog(); + assert!(list_in(&cat, &root).into_iter().find(|m| m.id == "war-games").unwrap().enabled, "a missing key means the default (on)"); + set_enabled_in(&cat, &root, &meta, "war-games", false).unwrap(); + assert!(fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("WarGames.Enable = 0")); + assert!(!list_in(&cat, &root).into_iter().find(|m| m.id == "war-games").unwrap().enabled); + } } diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index 2b95287..b1fcb7c 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -155,6 +155,13 @@ impl Ra { account_reply(&out, "The access level was not changed") } + /// Delete an account together with its characters (the console's `account delete`). + pub fn delete_account(&mut self, name: &str) -> Result<()> { + validate_account(name, "placeholder")?; + let out = self.command(&format!("account delete {name}"))?; + account_reply(&out, "The account was not deleted") + } + /// Give `name` administrator rights on all realms (GM level 3). pub fn make_administrator(&mut self, name: &str) -> Result<()> { validate_account(name, "placeholder")?; diff --git a/modules/catalog.json b/modules/catalog.json index 65f1b1d..3cf59da 100644 --- a/modules/catalog.json +++ b/modules/catalog.json @@ -1,4 +1,87 @@ { "schema": 1, - "modules": [] + "modules": [ + { + "id": "companions", + "name": "CoA Companions", + "description": { + "en": "Companion bots for groups, dungeons and your guild.", + "ru": "Боты-компаньоны для групп, подземелий и гильдии.", + "de": "Begleiter-Bots für Gruppen, Dungeons und deine Gilde.", + "fr": "Des bots compagnons pour les groupes, les donjons et votre guilde.", + "es": "Bots acompañantes para grupos, mazmorras y tu hermandad." + }, + "repo": "https://github.com/Corfirean/mod-coa-playerbots", + "conf": "mod_coa_playerbots.conf", + "enable_key": "CoaBots.Enable", + "status": "beta", + "icon": "bot", + "page": "bots" + }, + { + "id": "content-scaling", + "name": "Content Scaling", + "description": { + "en": "Scales dungeons and raids to your group, with solo modes.", + "ru": "Подстраивает подземелья и рейды под вашу группу, есть соло-режимы.", + "de": "Passt Dungeons und Schlachtzüge an deine Gruppe an, mit Solo-Modi.", + "fr": "Adapte donjons et raids à votre groupe, avec des modes solo.", + "es": "Adapta mazmorras y bandas a tu grupo, con modos en solitario." + }, + "repo": "https://github.com/Corfirean/mod-coa-content-scaling", + "conf": "mod-coa-content-scaling.conf", + "enable_key": "CoAContentScaling.Enable", + "status": "early", + "icon": "scaling" + }, + { + "id": "tbc-content", + "name": "TBC Content", + "description": { + "en": "Outland dungeons and raids, scaled to your level range.", + "ru": "Подземелья и рейды Запределья, подогнанные под ваши уровни.", + "de": "Dungeons und Schlachtzüge der Scherbenwelt, an deine Stufen angepasst.", + "fr": "Donjons et raids de l'Outreterre, adaptés à vos niveaux.", + "es": "Mazmorras y bandas de Terrallende, adaptadas a tus niveles." + }, + "repo": "https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content", + "conf": "mod-coa-tbc-content.conf", + "enable_key": "CoATBC.Enable", + "status": "early", + "icon": "tbc" + }, + { + "id": "wotlk-content", + "name": "WotLK Content", + "description": { + "en": "Northrend dungeons and raids, scaled to your level range.", + "ru": "Подземелья и рейды Нордскола, подогнанные под ваши уровни.", + "de": "Dungeons und Schlachtzüge Nordends, an deine Stufen angepasst.", + "fr": "Donjons et raids du Norfendre, adaptés à vos niveaux.", + "es": "Mazmorras y bandas de Rasganorte, adaptadas a tus niveles." + }, + "repo": "https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content", + "conf": "mod-coa-wotlk-content.conf", + "enable_key": "CoAWotLK.Enable", + "status": "early", + "icon": "wotlk" + }, + { + "id": "client-compat", + "name": "Client compatibility", + "description": { + "en": "Client-server link and appearance unlocks.", + "ru": "Связь клиента с сервером и разблокировка внешних видов.", + "de": "Verbindung Client–Server und Aussehen-Freischaltungen.", + "fr": "Lien client-serveur et déblocage des apparences.", + "es": "Enlace cliente-servidor y desbloqueo de apariencias." + }, + "repo": "https://github.com/Corfirean/azerothcore-wotlk-coa", + "conf": "coa.conf", + "alt_conf": "mod_ascension_compat.conf", + "switchable": false, + "status": "release", + "icon": "plug" + } + ] } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ab0be19..1d225dd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -589,6 +589,16 @@ async fn account_rename(state: State<'_, AppState>, id: String, name: String, ne .await } +#[tauri::command] +async fn account_delete(state: State<'_, AppState>, id: String, name: String) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let mut ra = Ra::connect(&root)?; + coa_core::accounts::delete(&root, &mut ra, &name) + }) + .await +} + fn install_meta(root: &std::path::Path) -> Result<(PathBuf, InstallMeta)> { let dir = meta_dir(root)?; let (_, meta) = MetaDir::open(&dir)?; @@ -1388,6 +1398,7 @@ pub fn run() { account_set_password, account_set_access, account_rename, + account_delete, install_new, cancel_install, create_account, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index ae1dbae..f46ea6a 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -7,6 +7,7 @@ export {}; (() => { let added = false, running = false; + const modState: Record = { "companions": true, "content-scaling": true, "client-compat": true, "tbc-content": true, "wotlk-content": true }; const report = {path:"C:\games\CoA-Repack",classification:"healthy",items:[ {key:"worldserver",label:"World server",status:"found",detail:null}, {key:"authserver",label:"Auth server",status:"found",detail:null}, @@ -53,10 +54,11 @@ export {}; 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") return []; + if(cmd==="account_delete") return null; + if(cmd==="modules_list") return [{id:"companions",name:"CoA Companions",description:{en:"Companion bots for groups, dungeons and your guild.",ru:"Боты-компаньоны для групп, подземелий и гильдии."},repo:"https://github.com/Corfirean/mod-coa-playerbots",installed:true,enabled:modState["companions"],switchable:true,status:"beta",icon:"bot",page:"bots"},{id:"content-scaling",name:"Content Scaling",description:{en:"Scales dungeons and raids to your group, with solo modes.",ru:"Подстраивает подземелья и рейды под вашу группу, есть соло-режимы."},repo:"https://github.com/Corfirean/mod-coa-content-scaling",installed:true,enabled:modState["content-scaling"],switchable:true,status:"early",icon:"scaling",page:null},{id:"tbc-content",name:"TBC Content",description:{en:"Outland dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Запределья, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content",installed:true,enabled:modState["tbc-content"],switchable:true,status:"early",icon:"tbc",page:null},{id:"wotlk-content",name:"WotLK Content",description:{en:"Northrend dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Нордскола, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content",installed:true,enabled:modState["wotlk-content"],switchable:true,status:"early",icon:"wotlk",page:null},{id:"client-compat",name:"Client compatibility",description:{en:"Client-server link and appearance unlocks.",ru:"Связь клиента с сервером и разблокировка внешних видов."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["client-compat"],switchable:false,status:"release",icon:"plug",page:null}]; + if(cmd==="module_set_enabled"){ modState[args.module]=args.enabled; return null; } if(cmd==="all_settings") return [{key:"Rate.Drop.Item.Epic",value:"3",default:"1",doc:"Description: Drop rates for money and items based on quality. Default: 1",changed:true},{key:"Instance.ResetTimeHour",value:"4",default:"4",doc:"Description: Hour of the day when the global instance reset occurs. Range: 0-23 Default: 4 - (04:00 AM)",changed:false},{key:"PlayerLimit",value:"1000",default:"1000",doc:"Description: Maximum number of players in the world.",changed:false}]; if(cmd==="all_settings_save") return Object.keys(args&&args.changes||{}); - 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"}; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 6609a49..2ad513b 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -713,7 +713,7 @@ const de: Partial> = { "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.intro": "Zusatzfunktionen, die im Server eingebaut sind. Schalte die gewünschten ein oder aus, öffne ihre GitHub-Seite 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", @@ -739,6 +739,21 @@ const de: Partial> = { "import.suggest.text": "Der gewählte Ordner gehört zu einem Server. Der Hauptordner des Servers ist:", "import.suggest.use": "Diesen Ordner verwenden", "import.notRepack": "Das sieht nach einem eigenständigen AzerothCore-Server aus. Der Manager arbeitet mit dem Aufbau des CoA Repack (ein Ordner mit Core, mysql, Scripts und Settings). Nutze stattdessen „Neuen Server installieren“ oder binde ein CoA Repack ein.", + "acc.delete": "Löschen", + "acc.deleteFor": "Konto {name} löschen?", + "acc.deleteWarn": "Das Konto und alle seine Charaktere ({n}) werden endgültig gelöscht. Das lässt sich nicht rückgängig machen; erstelle zuerst eine Sicherung, falls du sie noch brauchst.", + "acc.deleteConfirm": "Zur Bestätigung {name} eingeben", + "acc.deleteButton": "Konto löschen", + "acc.deleted": "Das Konto {name} wurde gelöscht.", + "mod.status.early": "Früh", + "mod.status.beta": "Beta", + "mod.status.release": "Release", + "mod.hint.early": "Experimentell: kann sich ändern oder kaputtgehen.", + "mod.hint.beta": "Funktioniert, wird noch getestet.", + "mod.hint.release": "Stabil.", + "mod.legend": "Modulstatus", + "mod.alwaysOn": "Immer an", + "mod.settingsOf": "{name}: Einstellungen", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index b2bbcaa..3e6ebaf 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -713,7 +713,7 @@ const en = { "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.intro": "Extra features built into the server. Switch the ones you want on or off, open their GitHub page, 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", @@ -739,6 +739,21 @@ const en = { "import.suggest.text": "The folder you chose belongs to a server. The server's main folder is:", "import.suggest.use": "Use this folder", "import.notRepack": "This looks like a standalone AzerothCore server. The Manager works with the CoA Repack layout (a folder that contains Core, mysql, Scripts and Settings). Use \"Install a new server\" instead, or import a CoA Repack.", + "acc.delete": "Delete", + "acc.deleteFor": "Delete the account {name}?", + "acc.deleteWarn": "This permanently deletes the account and all of its characters ({n}). It cannot be undone; make a backup first if you might need them.", + "acc.deleteConfirm": "Type {name} to confirm", + "acc.deleteButton": "Delete the account", + "acc.deleted": "The account {name} was deleted.", + "mod.status.early": "Early", + "mod.status.beta": "Beta", + "mod.status.release": "Release", + "mod.hint.early": "Experimental: may change or break.", + "mod.hint.beta": "Works, still being tested.", + "mod.hint.release": "Stable.", + "mod.legend": "Module status", + "mod.alwaysOn": "Always on", + "mod.settingsOf": "{name}: settings", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 14d6b58..9ed2164 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -713,7 +713,7 @@ const es: Partial> = { "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.intro": "Funciones adicionales integradas en el servidor. Activa o desactiva las que quieras, abre su página de 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", @@ -739,6 +739,21 @@ const es: Partial> = { "import.suggest.text": "La carpeta elegida pertenece a un servidor. La carpeta principal del servidor es:", "import.suggest.use": "Usar esta carpeta", "import.notRepack": "Parece un servidor AzerothCore independiente. El Manager funciona con la estructura del CoA Repack (una carpeta que contiene Core, mysql, Scripts y Settings). Usa «Instalar un servidor nuevo» o importa un CoA Repack.", + "acc.delete": "Eliminar", + "acc.deleteFor": "¿Eliminar la cuenta {name}?", + "acc.deleteWarn": "La cuenta y todos sus personajes ({n}) se eliminarán de forma permanente. No se puede deshacer; haz antes una copia de seguridad si pudieras necesitarlos.", + "acc.deleteConfirm": "Escribe {name} para confirmar", + "acc.deleteButton": "Eliminar la cuenta", + "acc.deleted": "La cuenta {name} se eliminó.", + "mod.status.early": "Temprano", + "mod.status.beta": "Beta", + "mod.status.release": "Estable", + "mod.hint.early": "Experimental: puede cambiar o fallar.", + "mod.hint.beta": "Funciona, aún en pruebas.", + "mod.hint.release": "Estable.", + "mod.legend": "Estado del módulo", + "mod.alwaysOn": "Siempre activo", + "mod.settingsOf": "{name}: ajustes", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 7cb6642..d5383ee 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -713,7 +713,7 @@ const fr: Partial> = { "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.intro": "Fonctions supplémentaires intégrées au serveur. Activez ou désactivez celles que vous voulez, ouvrez leur page 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", @@ -739,6 +739,21 @@ const fr: Partial> = { "import.suggest.text": "Le dossier choisi fait partie d'un serveur. Le dossier principal du serveur est :", "import.suggest.use": "Utiliser ce dossier", "import.notRepack": "Cela ressemble à un serveur AzerothCore autonome. Le Manager fonctionne avec la structure du CoA Repack (un dossier contenant Core, mysql, Scripts et Settings). Utilisez plutôt « Installer un nouveau serveur » ou importez un CoA Repack.", + "acc.delete": "Supprimer", + "acc.deleteFor": "Supprimer le compte {name} ?", + "acc.deleteWarn": "Le compte et tous ses personnages ({n}) seront supprimés définitivement. C'est irréversible ; faites d'abord une sauvegarde si vous pouvez en avoir besoin.", + "acc.deleteConfirm": "Saisissez {name} pour confirmer", + "acc.deleteButton": "Supprimer le compte", + "acc.deleted": "Le compte {name} a été supprimé.", + "mod.status.early": "Précoce", + "mod.status.beta": "Bêta", + "mod.status.release": "Stable", + "mod.hint.early": "Expérimental : peut changer ou casser.", + "mod.hint.beta": "Fonctionne, encore en test.", + "mod.hint.release": "Stable.", + "mod.legend": "Statut du module", + "mod.alwaysOn": "Toujours actif", + "mod.settingsOf": "{name} : réglages", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 3280192..538ee4f 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -713,7 +713,7 @@ const ru: Partial> = { "nav.modules": "Модули", "q.modules": "Какие дополнительные возможности есть у сервера?", "mod.title": "Модули", - "mod.intro": "Дополнительные возможности, уже встроенные в сервер. Включайте и выключайте нужные, читайте о них на GitHub или меняйте их настройки.", + "mod.intro": "Дополнительные возможности, встроенные в сервер. Включайте и выключайте нужные, открывайте их страницу на GitHub или меняйте настройки.", "mod.restart": "Изменения применятся после перезапуска игрового сервера.", "mod.switch": "Включить или выключить {name}", "mod.notHere": "Нет в этом сервере", @@ -739,6 +739,21 @@ const ru: Partial> = { "import.suggest.text": "Выбранная папка является частью сервера. Главная папка сервера:", "import.suggest.use": "Использовать эту папку", "import.notRepack": "Похоже на отдельный сервер AzerothCore. Менеджер работает со структурой CoA Repack (папка, где лежат Core, mysql, Scripts и Settings). Выберите «Установить новый сервер» или подключите CoA Repack.", + "acc.delete": "Удалить", + "acc.deleteFor": "Удалить аккаунт {name}?", + "acc.deleteWarn": "Аккаунт и все его персонажи ({n}) будут удалены навсегда. Это нельзя отменить; если они могут понадобиться, сначала сделайте резервную копию.", + "acc.deleteConfirm": "Для подтверждения введите {name}", + "acc.deleteButton": "Удалить аккаунт", + "acc.deleted": "Аккаунт {name} удалён.", + "mod.status.early": "Ранний", + "mod.status.beta": "Бета", + "mod.status.release": "Релиз", + "mod.hint.early": "Экспериментально: может измениться или сломаться.", + "mod.hint.beta": "Работает, ещё тестируется.", + "mod.hint.release": "Стабильно.", + "mod.legend": "Статус модуля", + "mod.alwaysOn": "Всегда включён", + "mod.settingsOf": "{name}: настройки", }; export default ru; diff --git a/src/lib/api.ts b/src/lib/api.ts index 65f2888..68d25c0 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -184,6 +184,13 @@ export interface ModuleView { /** the module is part of this server build (its configuration exists) */ installed: boolean; enabled: boolean; + /** can be turned on and off (a part the game client needs is only configured) */ + switchable: boolean; + /** early (experimental), beta (still being tested) or release (stable) */ + status: "early" | "beta" | "release"; + icon: string; + /** a page of the Manager that is hidden while the module is off */ + page: string | null; } export interface ModuleSetting { @@ -386,6 +393,7 @@ export const api = { accountSetPassword: (id: string, name: string, password: string) => invoke("account_set_password", { id, name, password }), accountSetAccess: (id: string, name: string, level: number) => invoke("account_set_access", { id, name, level }), accountRename: (id: string, name: string, newName: string, password: string) => invoke("account_rename", { id, name, newName, password }), + accountDelete: (id: string, name: string) => invoke("account_delete", { id, name }), installNew: (dest: string, pkg?: string) => invoke("install_new", { dest, package: pkg ?? null }), cancelInstall: () => invoke("cancel_install"), createAccount: (id: string, username: string, password: string, administrator: boolean) => diff --git a/src/screens/AccountsCard.tsx b/src/screens/AccountsCard.tsx index 9236dc4..f83dc55 100644 --- a/src/screens/AccountsCard.tsx +++ b/src/screens/AccountsCard.tsx @@ -9,7 +9,7 @@ import { useHuman, useT, type Key } from "@/i18n"; const LEVELS = [0, 1, 2, 3] as const; const inputClass = "w-64 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"; -type Editor = { name: string; mode: "password" | "rename" }; +type Editor = { name: string; mode: "password" | "rename" | "delete"; characters?: number }; /** Everyone who can log in to the server, with the changes an owner usually needs: password, access level, name. */ export function AccountsCard({ serverId, online, reloadKey }: { serverId: string; online: boolean | null; reloadKey: number }) { @@ -19,6 +19,7 @@ export function AccountsCard({ serverId, online, reloadKey }: { serverId: string const [listError, setListError] = useState(false); const [editor, setEditor] = useState(null); const [newName, setNewName] = useState(""); + const [confirmName, setConfirmName] = useState(""); const [password, setPassword] = useState(""); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); @@ -48,6 +49,7 @@ export function AccountsCard({ serverId, online, reloadKey }: { serverId: string setEditor(null); setPassword(""); setNewName(""); + setConfirmName(""); await load(); } catch (e) { setError(asUiError(e)); @@ -120,6 +122,9 @@ export function AccountsCard({ serverId, online, reloadKey }: { serverId: string + ))} @@ -129,7 +134,31 @@ export function AccountsCard({ serverId, online, reloadKey }: { serverId: string )} {online === false && accounts && accounts.length > 0 &&

{t("acc.needsRunning")}

} - {editor && ( + {editor && editor.mode === "delete" && ( +
+

{t("acc.deleteFor", { name: editor.name })}

+

{t("acc.deleteWarn", { n: editor.characters ?? 0 })}

+
+ + setConfirmName(e.target.value)} autoComplete="off" /> +
+
+ + +
+
+ )} + + {editor && editor.mode !== "delete" && (

{editor.mode === "password" ? t("acc.changeFor", { name: editor.name }) : t("acc.renameFor", { name: editor.name })}

{editor.mode === "rename" && ( diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index fb13beb..9ed81da 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,13 +1,66 @@ -import { useCallback, useEffect, useState } from "react"; -import { ExternalLink, Loader2 } from "lucide-react"; +import { useCallback, useEffect, useState, type ComponentType } from "react"; +import { Bot, Flame, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, type LucideProps } 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"; +import { useHuman, useI18n, type Key } 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 }) { +/** The GitHub mark (lucide dropped its brand icons). */ +function GithubMark(props: { className?: string }) { + return ( + + + + ); +} + +/** Icon and colours of a module's square tile, by the name the catalog gives it. */ +const TILES: Record; from: string; to: string }> = { + bot: { icon: Bot, from: "from-emerald-500", to: "to-teal-700" }, + scaling: { icon: Scaling, from: "from-violet-500", to: "to-indigo-700" }, + plug: { icon: Plug, from: "from-amber-500", to: "to-orange-700" }, + tbc: { icon: Flame, from: "from-lime-500", to: "to-emerald-800" }, + wotlk: { icon: Snowflake, from: "from-sky-400", to: "to-blue-700" }, +}; +const DEFAULT_TILE = { icon: Puzzle, from: "from-slate-500", to: "to-slate-700" }; + +const STATUS: Record = { + early: { label: "mod.status.early", hint: "mod.hint.early", tone: "border-warn/50 bg-warn/10 text-warn" }, + beta: { label: "mod.status.beta", hint: "mod.hint.beta", tone: "border-sky-400/50 bg-sky-400/10 text-sky-300" }, + release: { label: "mod.status.release", hint: "mod.hint.release", tone: "border-ok/50 bg-ok/10 text-ok" }, +}; + +function StatusBadge({ status }: { status: string }) { + const { t } = useI18n(); + const s = STATUS[status] ?? STATUS.release; + return ( + + {t(s.label)} + + ); +} + +function Tile({ icon, off }: { icon: string; off: boolean }) { + const tile = TILES[icon] ?? DEFAULT_TILE; + const Icon = tile.icon; + return ( +
+ +
+ ); +} + +/** The server's optional modules: square cards with a switch, the module's status, a link to GitHub and its settings. */ +export function ModulesPage({ serverId, onChanged }: { serverId: string; onChanged?: () => void }) { const { t, locale } = useI18n(); const human = useHuman(); const [modules, setModules] = useState(null); @@ -33,30 +86,47 @@ export function ModulesPage({ serverId }: { serverId: string }) { await api.moduleSetEnabled(serverId, m.id, !m.enabled); setChanged(true); await load(); + onChanged?.(); } catch (e) { setError(asUiError(e)); } } + const selected = modules?.find((m) => m.id === open) ?? null; + return ( -
+

{t("mod.title")}

{t("q.modules")}

{t("mod.intro")}

- {changed &&

{t("mod.restart")}

} + +
+ {(["early", "beta", "release"] as const).map((s) => ( + + + {t(STATUS[s].hint)} + + ))} +
+ + {changed &&

{t("mod.restart")}

} {error &&

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

} -
+
{modules === null && !error &&

{t("overview.checking")}

} - {modules?.length === 0 && {t("mod.empty")}} + {modules?.length === 0 && {t("mod.empty")}} {modules?.map((m) => ( - -
-
-

{m.name}

-

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

+ +
+ +
+
+

{m.name}

+ +
+

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

- {m.installed ? ( + {m.installed && m.switchable && ( - ) : ( - {t("mod.notHere")} )} + {m.installed && !m.switchable && {t("mod.alwaysOn")}} + {!m.installed && {t("mod.notHere")}}
-
- +
+ {m.installed && ( )}
- {open === m.id && setChanged(true)} />} ))}
+ + {selected && ( + +

{t("mod.settingsOf", { name: selected.name })}

+ setChanged(true)} /> +
+ )}
); } @@ -98,6 +179,9 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul const [note, setNote] = useState(null); useEffect(() => { + setItems(null); + setEdits({}); + setNote(null); void api.moduleSettings(serverId, module.id).then((s) => setItems(s)).catch((e) => setError(asUiError(e))); }, [serverId, module.id]); @@ -122,7 +206,7 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul const dirty = Object.keys(edits).length > 0; return ( -
+
{items === null && !error && }
    {items?.map((s) => ( diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index e2ea768..9ce33dc 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -62,7 +62,7 @@ function Row({ label, s }: { label: string; s: ServiceStatus }) { ); } -export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSummary; onForget: () => Promise; onOpenUpdates: () => void }) { +export function Overview({ server, companions = true, onForget, onOpenUpdates }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise; onOpenUpdates: () => void }) { const t = useT(); const human = useHuman(); const [status, setStatus] = useState(null); @@ -230,10 +230,10 @@ export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSu
{t("overview.players")}
-
{pop ? `${pop.players_online}` : "—"}{pop && pop.bots_online > 0 ? {t("overview.companions", { n: pop.bots_online })} : null}
+
{pop ? `${pop.players_online}` : "—"}{companions && pop && pop.bots_online > 0 ? {t("overview.companions", { n: pop.bots_online })} : null}
- {startBots !== undefined && ( + {companions && startBots !== undefined && (

{startBots === null ? t("overview.startBotsOff") : t("overview.startBots", { n: startBots })}

)} {perf && } diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index 020c6b7..e308c2f 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -1,6 +1,6 @@ -import { useEffect, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { Archive, Bot, Bug, Gauge, Globe, Puzzle, Server, Settings, Terminal, Users, type LucideIcon } from "lucide-react"; -import { type ServerSummary } from "@/lib/api"; +import { api, type ServerSummary } from "@/lib/api"; import { useT, type Key } from "@/i18n"; import logo from "@/assets/logo.png"; import { cn } from "@/lib/utils"; @@ -46,6 +46,21 @@ export function Shell(props: { const current = NAV.find((n) => n.id === page)!; const update = useServerUpdate(props.activeId); + // A module that is switched off takes its page away (the companions' "Bots" page, for one). + const [hiddenPages, setHiddenPages] = useState([]); + const reloadModules = useCallback(() => { + void api + .modulesList(props.activeId) + .then((list) => setHiddenPages(list.filter((m) => m.page && m.installed && m.switchable && !m.enabled).map((m) => m.page as string))) + .catch(() => setHiddenPages([])); + }, [props.activeId]); + useEffect(() => { + reloadModules(); + }, [reloadModules]); + useEffect(() => { + if (hiddenPages.includes(page)) setPage("overview"); + }, [hiddenPages, page]); + // Look for a server and a game client update when the app starts and then every five minutes. useEffect(() => { const stopServer = startServerUpdatePolling(props.activeId); @@ -64,7 +79,7 @@ export function Shell(props: { {t("app.name")}
    - {NAV.map(({ id, label, icon: Icon }) => ( + {NAV.filter((n) => !hiddenPages.includes(n.id)).map(({ id, label, icon: Icon }) => (