diff --git a/crates/coa-core/src/accounts.rs b/crates/coa-core/src/accounts.rs new file mode 100644 index 0000000..946a099 --- /dev/null +++ b/crates/coa-core/src/accounts.rs @@ -0,0 +1,110 @@ +//! The accounts of the people who play on this server: listed from the login database, changed through the world +//! console (password, access level) or - for a rename - by changing the stored name and then letting the console set +//! a new password, because the login verifier is computed from the name and would no longer match. +//! The accounts the Manager and the companions use themselves are never listed. + +use std::path::Path; + +use serde::Serialize; + +use crate::db::{Account, Db}; +use crate::error::{Error, Result}; +use crate::ra::{validate_account, Ra}; + +#[derive(Debug, Clone, Serialize, PartialEq, Eq)] +pub struct AccountInfo { + pub id: u32, + pub name: String, + /// 0 player, 1 moderator, 2 game master, 3 administrator. + pub access: u8, + pub online: bool, + pub last_login: Option, + pub characters: u32, +} + +const LIST_SQL: &str = "SELECT a.id, a.username, \ + IFNULL((SELECT MAX(aa.gmlevel) FROM acore_auth.account_access aa WHERE aa.id = a.id), 0), \ + a.online, IFNULL(a.last_login, ''), \ + (SELECT COUNT(*) FROM acore_characters.characters c WHERE c.account = a.id) \ + FROM acore_auth.account a \ + WHERE a.username NOT LIKE 'COABOTHOST%' AND a.username <> 'COAMANAGER' ORDER BY a.id;"; + +/// Rows of tab-separated columns as the `mysql` client prints them. +pub fn parse_list(out: &str) -> Vec { + out.lines() + .filter_map(|line| { + let c: Vec<&str> = line.split('\t').collect(); + if c.len() < 6 { + return None; + } + Some(AccountInfo { + id: c[0].trim().parse().ok()?, + name: c[1].trim().to_string(), + access: c[2].trim().parse().unwrap_or(0), + online: c[3].trim() != "0", + last_login: Some(c[4].trim().to_string()).filter(|s| !s.is_empty() && s != "NULL"), + characters: c[5].trim().parse().unwrap_or(0), + }) + }) + .collect() +} + +pub fn list(root: &Path) -> Result> { + let db = Db::from_repack(root, Account::Admin)?; + Ok(parse_list(&db.query(LIST_SQL)?)) +} + +fn upper(name: &str) -> Result { + validate_account(name, "placeholder")?; + Ok(name.to_ascii_uppercase()) +} + +/// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an +/// account that is not logged in. The old name is put back if anything goes wrong. +pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> { + let (old, new) = (upper(old)?, upper(new)?); + validate_account(&new, password)?; + if old == new { + return Err(Error::Invalid("That is already the name of this account.".into())); + } + let db = Db::from_repack(root, Account::Admin)?; + let taken = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account WHERE username = '{new}';"))?; + if taken.trim() != "0" { + return Err(Error::Invalid("That account name is already taken.".into())); + } + let changed = db.query(&format!("UPDATE acore_auth.account SET username = '{new}' WHERE username = '{old}' AND online = 0; SELECT ROW_COUNT();"))?; + if changed.trim() != "1" { + return Err(Error::Invalid("The account was not renamed: it does not exist or is logged in right now.".into())); + } + if let Err(e) = ra.set_account_password(&new, password) { + let _ = db.query(&format!("UPDATE acore_auth.account SET username = '{old}' WHERE username = '{new}';")); + return Err(e); + } + tracing::info!(%old, %new, "account renamed"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_from_the_client_become_accounts() { + let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n"; + let a = parse_list(out); + assert_eq!(a.len(), 2, "a short row is skipped"); + assert_eq!(a[0], AccountInfo { id: 2, name: "ALICE".into(), access: 3, online: false, last_login: Some("2026-09-30 21:04:11".into()), characters: 4 }); + assert!(a[1].online && a[1].last_login.is_none() && a[1].access == 0); + } + + #[test] + fn the_internal_accounts_are_filtered_out_by_the_query() { + assert!(LIST_SQL.contains("COABOTHOST%") && LIST_SQL.contains("COAMANAGER")); + } + + #[test] + fn names_are_validated_and_stored_in_capitals() { + assert_eq!(upper("Alice1").unwrap(), "ALICE1"); + assert!(upper("a").is_err() && upper("x; DROP TABLE account").is_err() && upper("bad name").is_err()); + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 30ac248..ab68b7e 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -1,3 +1,4 @@ +pub mod accounts; pub mod backup; pub mod cleanbase; pub mod companions; diff --git a/crates/coa-core/src/pkgsource.rs b/crates/coa-core/src/pkgsource.rs index 4e61471..85fac7a 100644 --- a/crates/coa-core/src/pkgsource.rs +++ b/crates/coa-core/src/pkgsource.rs @@ -53,20 +53,48 @@ pub fn fetch_manifest(source: &Source, trusted_key: &str) -> Result<(Manifest, V /// Make every archive part available in a verified folder: a local source is used in place, a remote one is /// downloaded (resumable) into `download_dir`. `report(fraction 0..1, speed_text)`. +/// 1536 -> "1.5 KB", 6.3e9 -> "5.9 GB" (binary units, as drive sizes are shown). +pub fn human_bytes(n: u64) -> String { + let units = ["B", "KB", "MB", "GB", "TB"]; + let mut v = n as f64; + let mut i = 0; + while v >= 1024.0 && i < units.len() - 1 { + v /= 1024.0; + i += 1; + } + if i == 0 || v >= 100.0 { format!("{} {}", v.round() as u64, units[i]) } else { format!("{v:.1} {}", units[i]) } +} + pub fn fetch_parts(source: &Source, manifest: &Manifest, download_dir: &Path, cancel: &Cancel, report: &dyn Fn(f64, Option)) -> Result { let archive = manifest.archive.as_ref().ok_or_else(|| Error::InvalidManifest("manifest has no archive".into()))?; match source { Source::Dir(d) => Ok(d.clone()), Source::Url(base) => { - let total = archive.parts.len(); - for (i, part) in archive.parts.iter().enumerate() { + let all: u64 = archive.parts.iter().map(|p| p.size).sum::().max(1); + let mut before = 0u64; + for part in archive.parts.iter() { let job = Job { url: format!("{}/{}", base.trim_end_matches('/'), part.name), dest: download_dir.join(&part.name), sha256: part.sha256.clone(), size: part.size }; download::fetch(&job, cancel, &|p: Progress| { - let frac = (i as f64 + p.downloaded as f64 / p.total.max(1) as f64) / total as f64; - report(frac, Some(format!("{:.1} MB/s", p.bytes_per_sec as f64 / 1e6))); + let done = before + p.downloaded.min(part.size); + // language-neutral so the screen can show it as it is: "3.1 GB / 5.9 GB · 40.6 MB/s" + report(done as f64 / all as f64, Some(format!("{} / {} \u{b7} {:.1} MB/s", human_bytes(done), human_bytes(all), p.bytes_per_sec as f64 / 1e6))); })?; + before += part.size; } Ok(download_dir.to_path_buf()) } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sizes_are_shown_in_binary_units() { + assert_eq!(human_bytes(0), "0 B"); + assert_eq!(human_bytes(1536), "1.5 KB"); + assert_eq!(human_bytes(6 * (1 << 30)), "6.0 GB"); + assert_eq!(human_bytes(150 * (1 << 20)), "150 MB"); + } +} diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index d54db4a..c0630fe 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -138,6 +138,23 @@ impl Ra { Ok(out.lines().last().unwrap_or("").to_string()) } + /// Set a new password for an existing account. + pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> { + validate_account(name, password)?; + let out = self.command(&format!("account set password {name} {password} {password}"))?; + account_reply(&out, "The password was not changed") + } + + /// Access level of an account on all realms: 0 player, 1 moderator, 2 game master, 3 administrator. + pub fn set_account_access(&mut self, name: &str, level: u8) -> Result<()> { + validate_account(name, "placeholder")?; + if level > 3 { + return Err(Error::Invalid("The access level must be 0 to 3.".into())); + } + let out = self.command(&format!("account set gmlevel {name} {level} -1"))?; + account_reply(&out, "The access level was not changed") + } + /// Give `name` administrator rights on all realms (GM level 3). pub fn make_administrator(&mut self, name: &str) -> Result<()> { validate_account(name, "placeholder")?; @@ -150,6 +167,16 @@ impl Ra { } } +/// The console reports a failed account command in words; anything else (including silence) counts as done. +fn account_reply(out: &str, what: &str) -> Result<()> { + let l = out.to_lowercase(); + let failed = ["does not exist", "not exist", "not found", "do not match", "don't match", "usage", "unknown", "incorrect", "error"]; + if failed.iter().any(|m| l.contains(m)) { + return Err(Error::Invalid(format!("{what}: {}", out.lines().last().unwrap_or("").trim()))); + } + Ok(()) +} + /// The console answers an unknown sub-command with the list of the ones it knows. fn is_unsupported_command(out: &str) -> bool { let l = out.to_lowercase(); @@ -287,6 +314,28 @@ AC>"; assert_eq!(h.join().unwrap(), ["local", "secretra", "account create Player1 hunter22"]); } + #[test] + fn changes_a_password_and_an_access_level_with_the_expected_commands() { + let _lock = serial(); + let (port, h) = fake_ra("The password was changed"); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + ra.set_account_password("Player1", "newpass9").unwrap(); + drop(ra); + assert_eq!(h.join().unwrap()[2], "account set password Player1 newpass9 newpass9"); + + let (port, h) = fake_ra("You have changed security level of Player1 to 2."); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + ra.set_account_access("Player1", 2).unwrap(); + assert!(ra.set_account_access("Player1", 4).is_err(), "only 0 to 3"); + drop(ra); + assert_eq!(h.join().unwrap()[2], "account set gmlevel Player1 2 -1"); + + let (port, _h) = fake_ra("Account not found."); + let mut ra = Ra::connect_to(port, "u", "p").unwrap(); + assert!(ra.set_account_password("Nobody", "newpass9").unwrap_err().to_string().contains("not found")); + assert!(ra.set_account_password("x", "newpass9").is_err(), "the name is validated before anything is sent"); + } + #[test] fn spawn_bots_sends_only_a_bounded_number() { let _lock = serial(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 69af757..10b58f1 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -385,9 +385,30 @@ async fn restore_backup_database(state: State<'_, AppState>, id: String, backup_ } #[tauri::command] -fn install_preflight(state: State<'_, AppState>, dest: String) -> Preflight { - // The real size is checked again once the signed manifest is known; assume a typical install here. - install::preflight(std::path::Path::new(&dest), 6 * 1024 * 1024 * 1024, &state.registry) +fn install_preflight(state: State<'_, AppState>, dest: String, needed: Option) -> Preflight { + // `needed` is the real size from the signed package list when the screen already has it; the real size is checked + // again at install time either way. + install::preflight(std::path::Path::new(&dest), needed.unwrap_or(6 * 1024 * 1024 * 1024), &state.registry) +} + +#[derive(Serialize)] +struct InstallRequirements { + /// What is downloaded. + download_bytes: u64, + /// What the unpacked server takes on the drive (the downloaded parts are removed afterwards). + unpacked_bytes: u64, + version: String, +} + +/// How big the server is, read from the package's signed list before anything is downloaded. +#[tauri::command] +async fn install_requirements(package: Option) -> std::result::Result { + blocking(move || { + let (m, _) = coa_core::pkgsource::fetch_manifest(&package_source(package), coa_core::signing::EMBEDDED_PUBLIC_KEY)?; + let archive = m.archive.ok_or_else(|| Error::InvalidManifest("no archive".into()))?; + Ok(InstallRequirements { download_bytes: archive.parts.iter().map(|p| p.size).sum(), unpacked_bytes: archive.unpacked_size, version: m.version }) + }) + .await } #[tauri::command] @@ -438,6 +459,44 @@ async fn create_account(state: State<'_, AppState>, id: String, username: String .await } +#[tauri::command] +async fn list_accounts(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || coa_core::accounts::list(&root)).await +} + +#[tauri::command] +async fn account_set_password(state: State<'_, AppState>, id: String, name: String, password: String) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + Ra::connect(&root)?.set_account_password(&name, &password)?; + tracing::info!(%name, "account password changed"); + Ok(()) + }) + .await +} + +#[tauri::command] +async fn account_set_access(state: State<'_, AppState>, id: String, name: String, level: u8) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + Ra::connect(&root)?.set_account_access(&name, level)?; + tracing::info!(%name, level, "account access level changed"); + Ok(()) + }) + .await +} + +#[tauri::command] +async fn account_rename(state: State<'_, AppState>, id: String, name: String, new_name: String, password: String) -> std::result::Result<(), UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let mut ra = Ra::connect(&root)?; + coa_core::accounts::rename(&root, &mut ra, &name, &new_name, &password) + }) + .await +} + fn install_meta(root: &std::path::Path) -> Result<(PathBuf, InstallMeta)> { let dir = meta_dir(root)?; let (_, meta) = MetaDir::open(&dir)?; @@ -1173,6 +1232,11 @@ pub fn run() { restore_backup_configs, restore_backup_database, install_preflight, + install_requirements, + list_accounts, + account_set_password, + account_set_access, + account_rename, install_new, cancel_install, create_account, diff --git a/src/components/ui/password-input.tsx b/src/components/ui/password-input.tsx new file mode 100644 index 0000000..04790aa --- /dev/null +++ b/src/components/ui/password-input.tsx @@ -0,0 +1,31 @@ +import * as React from "react"; +import { Eye, EyeOff } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { useT } from "@/i18n"; + +/** + * A password field with its own show/hide button. The browser's built-in one only exists while the field is focused and + * comes back only after the field is emptied, so people could not look at a password they had already typed. + */ +export const PasswordInput = React.forwardRef, "type">>( + ({ className, ...props }, ref) => { + const t = useT(); + const [shown, setShown] = React.useState(false); + return ( +
+ + +
+ ); + }, +); +PasswordInput.displayName = "PasswordInput"; diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 8cead1c..4317e92 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -49,6 +49,12 @@ 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==="install_preflight") return {ok:true,problems:[],free_bytes:210*2**30}; + if(cmd==="install_requirements") return {download_bytes:Math.round(5.9*2**30),unpacked_bytes:Math.round(11.4*2**30),version:"0.2.0"}; + if(cmd==="list_accounts"){const w=window as any;w.__acc=w.__acc??[{id:2,name:"ALICE",access:3,online:true,last_login:"2026-10-01 12:04:11",characters:4},{id:5,name:"BOB",access:0,online:false,last_login:null,characters:0},{id:6,name:"CAROL",access:2,online:false,last_login:"2026-09-30 21:40:02",characters:2}];return w.__acc;} + if(cmd==="account_set_access"){const a=(window as any).__acc.find((x: any)=>x.name===args.name);if(a)a.access=args.level;return null;} + if(cmd==="account_set_password") return null; + if(cmd==="account_rename"){const a=(window as any).__acc.find((x: any)=>x.name===args.name);if(a)a.name=String(args.newName).toUpperCase();return null;} if(cmd==="client_info"){const c=(window as any).__client??"none";return c==="none"?null:{path:"C:\\games\\CoA Client",executable:"Ascension.exe",realmlists:[{path:"x",host:"127.0.0.1"}],addon:{installed:true,version:"1",up_to_date:true},other_addons:2};} if(cmd==="set_client"){(window as any).__client="foreign";return {path:args.path,executable:"Ascension.exe",realmlists:[],addon:{installed:false,version:null,up_to_date:null},other_addons:0};} if(cmd==="plugin:event|listen"){const w=window as any;(w.__handlers??={})[args.event]=[...(w.__handlers[args.event]??[]),args.handler];return 1;} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index a692e71..d10369e 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -627,6 +627,41 @@ const de: Partial> = { "client.versionUntracked": "vom Manager nicht verfolgt", "client.versionUnfinished": "Download nicht abgeschlossen", "client.downloadInstead": "Client herunterladen …", + + // Accounts panel, password toggle, install size, addon explanation + "pw.show": "Passwort anzeigen", + "pw.hide": "Passwort verbergen", + "install.size": "Der Server belegt etwa {size} auf dem Laufwerk. Der Download ist {download} groß; während der Installation werden etwa {peak} benötigt.", + "client.addonWhat": "Ein Panel im Spiel (über eine Minimap-Schaltfläche) zur Steuerung deiner Begleiter: Gruppe auffüllen, Rollen und Formationen festlegen, Befehle wie Angriff, Pull oder Position halten geben und ihre Ausrüstung und Aufgaben ansehen. Ohne ihn funktioniert das Spiel; die Begleiter folgen dann nur ihrer eigenen KI.", + "acc.title": "Konten", + "acc.text": "Alle, die sich auf diesem Server anmelden können. Für Änderungen an Passwort und Zugriff muss der Server laufen.", + "acc.refresh": "Liste aktualisieren", + "acc.unavailable": "Die Liste ist gerade nicht verfügbar. Starte den Server und versuche es erneut.", + "acc.empty": "Noch keine Konten. Erstelle oben das erste.", + "acc.col.name": "Konto", + "acc.col.chars": "Charaktere", + "acc.col.access": "Zugriff", + "acc.col.last": "Letzte Anmeldung", + "acc.online": "online", + "acc.never": "nie", + "acc.level.0": "Spieler", + "acc.level.1": "Moderator", + "acc.level.2": "Spielleiter", + "acc.level.3": "Administrator", + "acc.changePassword": "Passwort ändern", + "acc.rename": "Umbenennen", + "acc.needsRunning": "Starte den Server, um Konten zu ändern.", + "acc.changeFor": "Neues Passwort für {name}", + "acc.renameFor": "{name} umbenennen", + "acc.newName": "Neuer Kontoname", + "acc.newPassword": "Neues Passwort", + "acc.nameRule": "3–17 Buchstaben oder Ziffern.", + "acc.passRule": "6–16 Zeichen, keine Leerzeichen oder Anführungszeichen.", + "acc.renameNote": "Ein neues Passwort ist nötig, weil das Anmeldepasswort vom Kontonamen abhängt. Der Spieler meldet sich mit dem neuen Namen und diesem Passwort an. Das Konto darf nicht angemeldet sein.", + "acc.save": "Speichern", + "acc.passwordChanged": "Das Passwort von {name} wurde geändert.", + "acc.renamed": "{name} heißt jetzt {new}.", + "acc.accessChanged": "{name} ist jetzt: {level}.", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 9b619ea..37fef66 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -627,6 +627,41 @@ const en = { "client.versionUntracked": "not tracked by the Manager", "client.versionUnfinished": "download not finished", "client.downloadInstead": "Download a client…", + + // Accounts panel, password toggle, install size, addon explanation + "pw.show": "Show password", + "pw.hide": "Hide password", + "install.size": "The server will take about {size} on the drive. The download is {download}; while it installs about {peak} is needed.", + "client.addonWhat": "A panel inside the game (opened from a minimap button) for commanding your companions: fill your group, set roles and formations, give orders such as attack, pull or hold, and see their gear and tasks. The game works without it; companions then simply follow their own AI.", + "acc.title": "Accounts", + "acc.text": "Everyone who can log in to this server. Password and access changes need the server to be running.", + "acc.refresh": "Refresh the list", + "acc.unavailable": "The list is not available right now. Start the server and try again.", + "acc.empty": "No accounts yet. Create the first one above.", + "acc.col.name": "Account", + "acc.col.chars": "Characters", + "acc.col.access": "Access", + "acc.col.last": "Last login", + "acc.online": "online", + "acc.never": "never", + "acc.level.0": "Player", + "acc.level.1": "Moderator", + "acc.level.2": "Game master", + "acc.level.3": "Administrator", + "acc.changePassword": "Change password", + "acc.rename": "Rename", + "acc.needsRunning": "Start the server to change accounts.", + "acc.changeFor": "New password for {name}", + "acc.renameFor": "Rename {name}", + "acc.newName": "New account name", + "acc.newPassword": "New password", + "acc.nameRule": "3–17 letters or digits.", + "acc.passRule": "6–16 characters, no spaces or quotes.", + "acc.renameNote": "A new password is needed because the login password depends on the account name. The player logs in with the new name and this password. The account must not be logged in.", + "acc.save": "Save", + "acc.passwordChanged": "The password of {name} was changed.", + "acc.renamed": "{name} is now called {new}.", + "acc.accessChanged": "{name} is now: {level}.", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index e22b3ce..4cc2856 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -627,6 +627,41 @@ const es: Partial> = { "client.versionUntracked": "el Manager no la sigue", "client.versionUnfinished": "descarga sin terminar", "client.downloadInstead": "Descargar un cliente…", + + // Accounts panel, password toggle, install size, addon explanation + "pw.show": "Mostrar contraseña", + "pw.hide": "Ocultar contraseña", + "install.size": "El servidor ocupará unos {size} en la unidad. La descarga es de {download}; durante la instalación se necesitan unos {peak}.", + "client.addonWhat": "Un panel dentro del juego (se abre desde un botón del minimapa) para dirigir a tus compañeros: completar el grupo, definir roles y formaciones, dar órdenes como atacar, iniciar combate o mantener posición, y ver su equipo y tareas. El juego funciona sin él; los compañeros simplemente siguen su propia IA.", + "acc.title": "Cuentas", + "acc.text": "Todas las personas que pueden entrar en este servidor. Para cambiar contraseñas y accesos el servidor debe estar en marcha.", + "acc.refresh": "Actualizar la lista", + "acc.unavailable": "La lista no está disponible ahora. Inicia el servidor e inténtalo de nuevo.", + "acc.empty": "Aún no hay cuentas. Crea la primera arriba.", + "acc.col.name": "Cuenta", + "acc.col.chars": "Personajes", + "acc.col.access": "Acceso", + "acc.col.last": "Último acceso", + "acc.online": "en línea", + "acc.never": "nunca", + "acc.level.0": "Jugador", + "acc.level.1": "Moderador", + "acc.level.2": "Maestro del juego", + "acc.level.3": "Administrador", + "acc.changePassword": "Cambiar contraseña", + "acc.rename": "Renombrar", + "acc.needsRunning": "Inicia el servidor para cambiar las cuentas.", + "acc.changeFor": "Nueva contraseña para {name}", + "acc.renameFor": "Renombrar {name}", + "acc.newName": "Nuevo nombre de cuenta", + "acc.newPassword": "Nueva contraseña", + "acc.nameRule": "De 3 a 17 letras o dígitos.", + "acc.passRule": "De 6 a 16 caracteres, sin espacios ni comillas.", + "acc.renameNote": "Hace falta una contraseña nueva porque la contraseña de acceso depende del nombre de la cuenta. El jugador entra con el nuevo nombre y esta contraseña. La cuenta no debe estar conectada.", + "acc.save": "Guardar", + "acc.passwordChanged": "Se cambió la contraseña de {name}.", + "acc.renamed": "{name} ahora se llama {new}.", + "acc.accessChanged": "{name} ahora es: {level}.", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 3b4205b..c6bb11b 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -627,6 +627,41 @@ const fr: Partial> = { "client.versionUntracked": "non suivi par le Manager", "client.versionUnfinished": "téléchargement inachevé", "client.downloadInstead": "Télécharger un client…", + + // Accounts panel, password toggle, install size, addon explanation + "pw.show": "Afficher le mot de passe", + "pw.hide": "Masquer le mot de passe", + "install.size": "Le serveur occupera environ {size} sur le disque. Le téléchargement fait {download} ; pendant l’installation, environ {peak} sont nécessaires.", + "client.addonWhat": "Un panneau dans le jeu (ouvert depuis un bouton de la minicarte) pour commander vos compagnons : compléter le groupe, définir rôles et formations, donner des ordres (attaquer, engager, tenir la position) et voir leur équipement et leurs tâches. Le jeu fonctionne sans lui ; les compagnons suivent alors simplement leur propre IA.", + "acc.title": "Comptes", + "acc.text": "Toutes les personnes qui peuvent se connecter à ce serveur. Changer un mot de passe ou un accès nécessite que le serveur soit lancé.", + "acc.refresh": "Actualiser la liste", + "acc.unavailable": "La liste n’est pas disponible pour le moment. Lancez le serveur et réessayez.", + "acc.empty": "Aucun compte pour l’instant. Créez le premier ci-dessus.", + "acc.col.name": "Compte", + "acc.col.chars": "Personnages", + "acc.col.access": "Accès", + "acc.col.last": "Dernière connexion", + "acc.online": "en ligne", + "acc.never": "jamais", + "acc.level.0": "Joueur", + "acc.level.1": "Modérateur", + "acc.level.2": "Maître de jeu", + "acc.level.3": "Administrateur", + "acc.changePassword": "Changer le mot de passe", + "acc.rename": "Renommer", + "acc.needsRunning": "Lancez le serveur pour modifier les comptes.", + "acc.changeFor": "Nouveau mot de passe pour {name}", + "acc.renameFor": "Renommer {name}", + "acc.newName": "Nouveau nom de compte", + "acc.newPassword": "Nouveau mot de passe", + "acc.nameRule": "3 à 17 lettres ou chiffres.", + "acc.passRule": "6 à 16 caractères, sans espaces ni guillemets.", + "acc.renameNote": "Un nouveau mot de passe est nécessaire car le mot de passe de connexion dépend du nom du compte. Le joueur se connecte avec le nouveau nom et ce mot de passe. Le compte ne doit pas être connecté.", + "acc.save": "Enregistrer", + "acc.passwordChanged": "Le mot de passe de {name} a été modifié.", + "acc.renamed": "{name} s’appelle maintenant {new}.", + "acc.accessChanged": "{name} est maintenant : {level}.", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 98a25c8..975e34c 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -627,6 +627,41 @@ const ru: Partial> = { "client.versionUntracked": "менеджер не отслеживает", "client.versionUnfinished": "загрузка не завершена", "client.downloadInstead": "Скачать клиент…", + + // Accounts panel, password toggle, install size, addon explanation + "pw.show": "Показать пароль", + "pw.hide": "Скрыть пароль", + "install.size": "Сервер займёт на диске около {size}. Загрузка — {download}; на время установки нужно около {peak}.", + "client.addonWhat": "Панель внутри игры (открывается кнопкой у миникарты) для управления компаньонами: набрать группу, назначить роли и построения, отдавать приказы (атаковать, начать бой, держать позицию), смотреть их снаряжение и задания. Без аддона игра работает: компаньоны просто действуют по своему ИИ.", + "acc.title": "Аккаунты", + "acc.text": "Все, кто может войти на этот сервер. Для смены пароля и прав сервер должен быть запущен.", + "acc.refresh": "Обновить список", + "acc.unavailable": "Список сейчас недоступен. Запустите сервер и попробуйте снова.", + "acc.empty": "Аккаунтов пока нет. Создайте первый выше.", + "acc.col.name": "Аккаунт", + "acc.col.chars": "Персонажи", + "acc.col.access": "Права", + "acc.col.last": "Последний вход", + "acc.online": "в игре", + "acc.never": "никогда", + "acc.level.0": "Игрок", + "acc.level.1": "Модератор", + "acc.level.2": "Гейм-мастер", + "acc.level.3": "Администратор", + "acc.changePassword": "Сменить пароль", + "acc.rename": "Переименовать", + "acc.needsRunning": "Чтобы менять аккаунты, запустите сервер.", + "acc.changeFor": "Новый пароль для {name}", + "acc.renameFor": "Переименовать {name}", + "acc.newName": "Новое имя аккаунта", + "acc.newPassword": "Новый пароль", + "acc.nameRule": "От 3 до 17 букв или цифр.", + "acc.passRule": "От 6 до 16 символов, без пробелов и кавычек.", + "acc.renameNote": "Нужен новый пароль: пароль для входа зависит от имени аккаунта. Игрок входит под новым именем и этим паролем. Аккаунт не должен быть в игре.", + "acc.save": "Сохранить", + "acc.passwordChanged": "Пароль {name} изменён.", + "acc.renamed": "{name} теперь называется {new}.", + "acc.accessChanged": "{name}: теперь {level}.", }; export default ru; diff --git a/src/lib/api.ts b/src/lib/api.ts index 3a7d70a..3d1c91a 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -167,6 +167,22 @@ export interface Preflight { free_bytes: number; } +export interface InstallRequirements { + download_bytes: number; + unpacked_bytes: number; + version: string; +} + +export interface AccountInfo { + id: number; + name: string; + /** 0 player, 1 moderator, 2 game master, 3 administrator */ + access: number; + online: boolean; + last_login: string | null; + characters: number; +} + export interface InstallStep { step: string; percent: number; @@ -311,7 +327,12 @@ export const api = { deleteBackup: (id: string, backupId: string) => invoke("delete_backup", { id, backupId }), restoreConfigs: (id: string, backupId: string) => invoke("restore_backup_configs", { id, backupId }), restoreDatabase: (id: string, backupId: string, database: string) => invoke("restore_backup_database", { id, backupId, database }), - installPreflight: (dest: string) => invoke("install_preflight", { dest }), + installPreflight: (dest: string, needed?: number) => invoke("install_preflight", { dest, needed: needed ?? null }), + installRequirements: (pkg?: string) => invoke("install_requirements", { package: pkg ?? null }), + listAccounts: (id: string) => invoke("list_accounts", { id }), + 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 }), 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 new file mode 100644 index 0000000..9236dc4 --- /dev/null +++ b/src/screens/AccountsCard.tsx @@ -0,0 +1,171 @@ +import { useCallback, useEffect, useState } from "react"; +import { Loader2, RefreshCw } from "lucide-react"; +import { api, asUiError, type AccountInfo, type UiError } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { PasswordInput } from "@/components/ui/password-input"; +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" }; + +/** 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 }) { + const t = useT(); + const human = useHuman(); + const [accounts, setAccounts] = useState(null); + const [listError, setListError] = useState(false); + const [editor, setEditor] = useState(null); + const [newName, setNewName] = useState(""); + const [password, setPassword] = useState(""); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(null); + const [note, setNote] = useState(null); + + const load = useCallback(async () => { + try { + setAccounts(await api.listAccounts(serverId)); + setListError(false); + } catch { + setAccounts(null); + setListError(true); + } + }, [serverId]); + + useEffect(() => { + void load(); + }, [load, reloadKey, online]); + + async function run(label: string, fn: () => Promise, ok: string) { + setBusy(label); + setError(null); + setNote(null); + try { + await fn(); + setNote(ok); + setEditor(null); + setPassword(""); + setNewName(""); + await load(); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + } + } + + const passOk = password.length >= 6 && password.length <= 16 && /^[\x21-\x7e]+$/.test(password) && !/["']/.test(password); + const nameOk = /^[A-Za-z0-9]{3,17}$/.test(newName); + + return ( + +
+
+

{t("acc.title")}

+

{t("acc.text")}

+
+ +
+ + {listError &&

{t("acc.unavailable")}

} + {accounts && accounts.length === 0 &&

{t("acc.empty")}

} + {accounts && accounts.length > 0 && ( +
+ + + + + + + + + + + {accounts.map((a) => ( + + + + + + + + ))} + +
{t("acc.col.name")}{t("acc.col.chars")}{t("acc.col.access")}{t("acc.col.last")} +
+ {a.name} + {a.online && {t("acc.online")}} + {a.characters} + + {a.last_login ?? t("acc.never")} + + +
+
+ )} + {online === false && accounts && accounts.length > 0 &&

{t("acc.needsRunning")}

} + + {editor && ( +
+

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

+ {editor.mode === "rename" && ( +
+ + setNewName(e.target.value)} autoComplete="off" /> +

{t("acc.nameRule")}

+
+ )} +
+ + setPassword(e.target.value)} autoComplete="new-password" /> +

{t("acc.passRule")}

+
+ {editor.mode === "rename" &&

{t("acc.renameNote")}

} +
+ + +
+
+ )} + + {note &&

{note}

} + {error &&

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

} +
+ ); +} diff --git a/src/screens/ClientCard.tsx b/src/screens/ClientCard.tsx index e829213..040010e 100644 --- a/src/screens/ClientCard.tsx +++ b/src/screens/ClientCard.tsx @@ -78,6 +78,7 @@ export function ClientCard({ serverId }: { serverId: string }) {
{info.addon.installed ? (info.addon.version ? t("client.installedVersion", { v: info.addon.version }) : t("client.installed")) : t("client.addonNotInstalled")} {info.addon.up_to_date === false && {t("client.updateAvailable")}} + {t("client.addonWhat")}
{t("client.otherAddons")}
{t("client.leftAsIs", { n: info.other_addons })}
diff --git a/src/screens/InstallServer.tsx b/src/screens/InstallServer.tsx index ce11cd9..32a9c42 100644 --- a/src/screens/InstallServer.tsx +++ b/src/screens/InstallServer.tsx @@ -2,7 +2,8 @@ import { useEffect, useState } from "react"; import { listen } from "@tauri-apps/api/event"; import { open } from "@tauri-apps/plugin-dialog"; import { Check, ChevronDown, ChevronRight, Loader2 } from "lucide-react"; -import { api, asUiError, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api"; +import { api, asUiError, type InstallRequirements, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api"; +import { formatBytes } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { useHuman, useT, type Key } from "@/i18n"; @@ -24,6 +25,7 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void; const human = useHuman(); const [dest, setDest] = useState("C:\\Games\\CoA Server"); const [pre, setPre] = useState(null); + const [req, setReq] = useState(null); const [phase, setPhase] = useState("choose"); const [step, setStep] = useState({ step: "Preparing your server", percent: 0, detail: null }); const [error, setError] = useState(null); @@ -32,10 +34,18 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void; const [installed, setInstalled] = useState(null); const [showDetails, setShowDetails] = useState(false); + // how big the server is, from the package's signed list (re-read when another package source is entered) useEffect(() => { - const t = setTimeout(() => void api.installPreflight(dest).then(setPre).catch(() => setPre(null)), 250); - return () => clearTimeout(t); - }, [dest]); + const timer = setTimeout(() => void api.installRequirements(pkg.trim() || undefined).then(setReq).catch(() => setReq(null)), 400); + return () => clearTimeout(timer); + }, [pkg]); + + // room for the unpacked server plus the download that is removed afterwards + const needed = req ? req.unpacked_bytes + req.download_bytes : undefined; + useEffect(() => { + const timer = setTimeout(() => void api.installPreflight(dest, needed).then(setPre).catch(() => setPre(null)), 250); + return () => clearTimeout(timer); + }, [dest, needed]); useEffect(() => { const un = listen("install-progress", (e) => setStep(e.payload)); @@ -136,6 +146,11 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void; ))} )} + {req && ( +

+ {t("install.size", { size: formatBytes(req.unpacked_bytes), download: formatBytes(req.download_bytes), peak: formatBytes(req.unpacked_bytes + req.download_bytes) })} +

+ )} {pre?.ok &&

{t("install.ready", { gb: Math.round(pre.free_bytes / (1 << 30)) })}

} {error && ( diff --git a/src/screens/PlayersPage.tsx b/src/screens/PlayersPage.tsx index d721469..a710a93 100644 --- a/src/screens/PlayersPage.tsx +++ b/src/screens/PlayersPage.tsx @@ -2,6 +2,8 @@ import { useEffect, useState } from "react"; import { api, asUiError, type UiError } from "@/lib/api"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; +import { PasswordInput } from "@/components/ui/password-input"; +import { AccountsCard } from "@/screens/AccountsCard"; import { useHuman, useT } from "@/i18n"; export function PlayersPage({ serverId }: { serverId: string }) { @@ -14,6 +16,7 @@ export function PlayersPage({ serverId }: { serverId: string }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [done, setDone] = useState(null); + const [created, setCreated] = useState(0); useEffect(() => { let alive = true; @@ -33,6 +36,7 @@ export function PlayersPage({ serverId }: { serverId: string }) { try { await api.createAccount(serverId, username, password, admin); setDone(username); + setCreated((n) => n + 1); setUsername(""); setPassword(""); } catch (e) { @@ -44,7 +48,7 @@ export function PlayersPage({ serverId }: { serverId: string }) { const input = "w-72 rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold"; return ( -
+

{t("players.title")}

{t("q.players")}

@@ -59,7 +63,7 @@ export function PlayersPage({ serverId }: { serverId: string }) {
- setPassword(e.target.value)} autoComplete="new-password" /> + setPassword(e.target.value)} autoComplete="new-password" />
); }