mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 11:25:56 +00:00
Tester suggestions: account management, install size and download volume, password show button, addon explanation
- Players page: list of the server's accounts with password change, access level (player/moderator/GM/administrator) and rename (a rename also sets a new password because the login verifier depends on the name; refused while logged in). Companion and console accounts are never listed. - Install screen: size of the server from the signed package list (unpacked, download, peak) and the drive check uses it. - Install progress shows downloaded / total volume and speed. - Own show/hide button on password fields (the browser's one disappeared after leaving the field). - Settings: one sentence on what the companion addon does. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2c0bb2bac3
commit
a4c1080575
17 files changed
+692
-14
No files matched your search
@@ -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<String>,
|
||||
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<AccountInfo> {
|
||||
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<Vec<AccountInfo>> {
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
Ok(parse_list(&db.query(LIST_SQL)?))
|
||||
}
|
||||
|
||||
fn upper(name: &str) -> Result<String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod accounts;
|
||||
pub mod backup;
|
||||
pub mod cleanbase;
|
||||
pub mod companions;
|
||||
|
||||
@@ -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<String>)) -> Result<PathBuf> {
|
||||
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::<u64>().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");
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+67
-3
@@ -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<u64>) -> 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<String>) -> std::result::Result<InstallRequirements, UiError> {
|
||||
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<Vec<coa_core::accounts::AccountInfo>, 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,
|
||||
|
||||
@@ -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<HTMLInputElement, Omit<React.InputHTMLAttributes<HTMLInputElement>, "type">>(
|
||||
({ className, ...props }, ref) => {
|
||||
const t = useT();
|
||||
const [shown, setShown] = React.useState(false);
|
||||
return (
|
||||
<div className="relative inline-block">
|
||||
<input ref={ref} type={shown ? "text" : "password"} className={cn(className, "pr-11 [&::-ms-reveal]:hidden")} {...props} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShown((v) => !v)}
|
||||
aria-label={shown ? t("pw.hide") : t("pw.show")}
|
||||
aria-pressed={shown}
|
||||
title={shown ? t("pw.hide") : t("pw.show")}
|
||||
className="absolute inset-y-0 right-0 flex w-10 cursor-pointer items-center justify-center text-muted hover:text-ink"
|
||||
>
|
||||
{shown ? <EyeOff className="h-4 w-4" aria-hidden /> : <Eye className="h-4 w-4" aria-hidden />}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
PasswordInput.displayName = "PasswordInput";
|
||||
@@ -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;}
|
||||
|
||||
@@ -627,6 +627,41 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"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;
|
||||
@@ -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;
|
||||
@@ -627,6 +627,41 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"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;
|
||||
@@ -627,6 +627,41 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"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;
|
||||
@@ -627,6 +627,41 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"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;
|
||||
+22
-1
@@ -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<void>("delete_backup", { id, backupId }),
|
||||
restoreConfigs: (id: string, backupId: string) => invoke<RecoveryPoint>("restore_backup_configs", { id, backupId }),
|
||||
restoreDatabase: (id: string, backupId: string, database: string) => invoke<DbRestore>("restore_backup_database", { id, backupId, database }),
|
||||
installPreflight: (dest: string) => invoke<Preflight>("install_preflight", { dest }),
|
||||
installPreflight: (dest: string, needed?: number) => invoke<Preflight>("install_preflight", { dest, needed: needed ?? null }),
|
||||
installRequirements: (pkg?: string) => invoke<InstallRequirements>("install_requirements", { package: pkg ?? null }),
|
||||
listAccounts: (id: string) => invoke<AccountInfo[]>("list_accounts", { id }),
|
||||
accountSetPassword: (id: string, name: string, password: string) => invoke<void>("account_set_password", { id, name, password }),
|
||||
accountSetAccess: (id: string, name: string, level: number) => invoke<void>("account_set_access", { id, name, level }),
|
||||
accountRename: (id: string, name: string, newName: string, password: string) => invoke<void>("account_rename", { id, name, newName, password }),
|
||||
installNew: (dest: string, pkg?: string) => invoke<ServerSummary>("install_new", { dest, package: pkg ?? null }),
|
||||
cancelInstall: () => invoke<void>("cancel_install"),
|
||||
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
||||
|
||||
@@ -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<AccountInfo[] | null>(null);
|
||||
const [listError, setListError] = useState(false);
|
||||
const [editor, setEditor] = useState<Editor | null>(null);
|
||||
const [newName, setNewName] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [note, setNote] = useState<string | null>(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<void>, 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 (
|
||||
<Card className="mt-6 p-6">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="font-semibold">{t("acc.title")}</h2>
|
||||
<p className="mt-1 text-sm text-muted">{t("acc.text")}</p>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={() => void load()} aria-label={t("acc.refresh")} title={t("acc.refresh")}>
|
||||
<RefreshCw className="h-4 w-4" aria-hidden />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{listError && <p className="mt-4 text-sm text-warn">{t("acc.unavailable")}</p>}
|
||||
{accounts && accounts.length === 0 && <p className="mt-4 text-sm text-muted">{t("acc.empty")}</p>}
|
||||
{accounts && accounts.length > 0 && (
|
||||
<div className="mt-4 overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="text-xs text-muted">
|
||||
<tr>
|
||||
<th className="py-2 pr-3 font-normal">{t("acc.col.name")}</th>
|
||||
<th className="py-2 pr-3 font-normal">{t("acc.col.chars")}</th>
|
||||
<th className="py-2 pr-3 font-normal">{t("acc.col.access")}</th>
|
||||
<th className="py-2 pr-3 font-normal">{t("acc.col.last")}</th>
|
||||
<th className="py-2 font-normal" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{accounts.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td className="py-2 pr-3 font-medium">
|
||||
{a.name}
|
||||
{a.online && <span className="ml-2 text-xs text-ok">{t("acc.online")}</span>}
|
||||
</td>
|
||||
<td className="py-2 pr-3">{a.characters}</td>
|
||||
<td className="py-2 pr-3">
|
||||
<select
|
||||
aria-label={t("acc.col.access")}
|
||||
className="rounded-md border border-line bg-bg px-2 py-1 text-sm"
|
||||
value={a.access}
|
||||
disabled={!online || busy !== null}
|
||||
onChange={(e) =>
|
||||
void run(
|
||||
`access:${a.name}`,
|
||||
() => api.accountSetAccess(serverId, a.name, Number(e.target.value)),
|
||||
t("acc.accessChanged", { name: a.name, level: t(`acc.level.${e.target.value}` as Key) }),
|
||||
)
|
||||
}
|
||||
>
|
||||
{LEVELS.map((l) => (
|
||||
<option key={l} value={l}>{t(`acc.level.${l}` as Key)}</option>
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
<td className="py-2 pr-3 text-muted">{a.last_login ?? t("acc.never")}</td>
|
||||
<td className="py-2 text-right whitespace-nowrap">
|
||||
<Button size="sm" variant="ghost" disabled={!online || busy !== null} onClick={() => { setEditor({ name: a.name, mode: "password" }); setError(null); setNote(null); }}>
|
||||
{t("acc.changePassword")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" disabled={!online || busy !== null || a.online} onClick={() => { setEditor({ name: a.name, mode: "rename" }); setError(null); setNote(null); }}>
|
||||
{t("acc.rename")}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{online === false && accounts && accounts.length > 0 && <p className="mt-3 text-xs text-muted">{t("acc.needsRunning")}</p>}
|
||||
|
||||
{editor && (
|
||||
<div className="mt-4 rounded-md border border-line bg-black/20 p-4">
|
||||
<p className="font-medium">{editor.mode === "password" ? t("acc.changeFor", { name: editor.name }) : t("acc.renameFor", { name: editor.name })}</p>
|
||||
{editor.mode === "rename" && (
|
||||
<div className="mt-3">
|
||||
<label htmlFor="acc-newname" className="text-sm text-muted">{t("acc.newName")}</label>
|
||||
<input id="acc-newname" className={inputClass + " mt-1 block"} value={newName} onChange={(e) => setNewName(e.target.value)} autoComplete="off" />
|
||||
<p className="mt-1 text-xs text-muted">{t("acc.nameRule")}</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3">
|
||||
<label htmlFor="acc-newpass" className="text-sm text-muted">{t("acc.newPassword")}</label>
|
||||
<PasswordInput id="acc-newpass" className={inputClass + " mt-1 block"} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" />
|
||||
<p className="mt-1 text-xs text-muted">{t("acc.passRule")}</p>
|
||||
</div>
|
||||
{editor.mode === "rename" && <p className="mt-3 text-xs text-muted">{t("acc.renameNote")}</p>}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
disabled={busy !== null || !passOk || (editor.mode === "rename" && !nameOk)}
|
||||
onClick={() =>
|
||||
editor.mode === "password"
|
||||
? void run("password", () => api.accountSetPassword(serverId, editor.name, password), t("acc.passwordChanged", { name: editor.name }))
|
||||
: void run("rename", () => api.accountRename(serverId, editor.name, newName, password), t("acc.renamed", { name: editor.name, new: newName.toUpperCase() }))
|
||||
}
|
||||
>
|
||||
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{t("acc.save")}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setEditor(null); setPassword(""); setNewName(""); }}>{t("common.cancel")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
|
||||
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -78,6 +78,7 @@ export function ClientCard({ serverId }: { serverId: string }) {
|
||||
<dd>
|
||||
{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 && <span className="ml-2 text-warn">{t("client.updateAvailable")}</span>}
|
||||
<span className="mt-1 block text-xs text-muted">{t("client.addonWhat")}</span>
|
||||
</dd>
|
||||
<dt className="text-muted">{t("client.otherAddons")}</dt>
|
||||
<dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
|
||||
|
||||
@@ -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<Preflight | null>(null);
|
||||
const [req, setReq] = useState<InstallRequirements | null>(null);
|
||||
const [phase, setPhase] = useState<Phase>("choose");
|
||||
const [step, setStep] = useState<InstallStep>({ step: "Preparing your server", percent: 0, detail: null });
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
@@ -32,10 +34,18 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
const [installed, setInstalled] = useState<ServerSummary | null>(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<InstallStep>("install-progress", (e) => setStep(e.payload));
|
||||
@@ -136,6 +146,11 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
||||
))}
|
||||
</Card>
|
||||
)}
|
||||
{req && (
|
||||
<p className="text-sm text-muted">
|
||||
{t("install.size", { size: formatBytes(req.unpacked_bytes), download: formatBytes(req.download_bytes), peak: formatBytes(req.unpacked_bytes + req.download_bytes) })}
|
||||
</p>
|
||||
)}
|
||||
{pre?.ok && <p className="text-sm text-ok">{t("install.ready", { gb: Math.round(pre.free_bytes / (1 << 30)) })}</p>}
|
||||
|
||||
{error && (
|
||||
|
||||
@@ -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<UiError | null>(null);
|
||||
const [done, setDone] = useState<string | null>(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 (
|
||||
<div className="max-w-xl">
|
||||
<div className="max-w-3xl">
|
||||
<h1 className="text-2xl font-semibold">{t("players.title")}</h1>
|
||||
<p className="mt-1 text-muted">{t("q.players")}</p>
|
||||
|
||||
@@ -59,7 +63,7 @@ export function PlayersPage({ serverId }: { serverId: string }) {
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="acc-pass" className="text-sm text-muted">{t("players.password")}</label>
|
||||
<input id="acc-pass" type="password" className={input + " mt-1 block"} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" />
|
||||
<PasswordInput id="acc-pass" className={input + " mt-1 block"} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" />
|
||||
</div>
|
||||
<label className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<input type="checkbox" checked={admin} onChange={(e) => setAdmin(e.target.checked)} className="mt-1" />
|
||||
@@ -79,6 +83,8 @@ export function PlayersPage({ serverId }: { serverId: string }) {
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<AccountsCard serverId={serverId} online={online} reloadKey={created} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user