Compare commits

...
6 Commits
Author SHA1 Message Date
ДмитрийandClaude Sonnet 5.5 c8f6d61b98 Release 0.3.0
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 07:59:59 +05:00
ДмитрийandClaude Sonnet 5.5 2317d46bda Client updates never overwrite renderer wrappers or config files; test that nothing outside the manifest changes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 07:56:40 +05:00
ДмитрийandClaude Sonnet 5.5 f1f2818525 Client setup dialog: drop the extra explanations, keep only the size
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 07:54:00 +05:00
ДмитрийandClaude Sonnet 5.5 615b3e938d Game client: download and update through the Manager
PLAY turns into UPDATE CLIENT when a tracked client is outdated; with no client linked
it offers choosing an existing folder or downloading from the community launcher servers
(resumable, hash-verified, free-space checked, progress and stop). Files the player changed
are kept on request or moved aside, never silently replaced. Existing clients can be adopted
from Settings. Fresh downloads get a realmlist for each installed locale.

Fixes zero-length files in the downloader (found by the live probe).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 07:52:58 +05:00
ДмитрийandClaude Sonnet 5.5 7d447b490f README: feature overview and screenshots
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 07:41:22 +05:00
ДмитрийandClaude Sonnet 5.5 0c376fdaf8 Main screen: server update check at start and every 5 minutes, UPDATE button instead of START when an update exists, progress, navigation dot; notes on client download
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 06:40:22 +05:00
32 changed files with 1919 additions and 40 deletions

No files matched your search

Generated
+3 -3
View File
@@ -347,7 +347,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.2.0"
version = "0.3.0"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -375,7 +375,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.2.0"
version = "0.3.0"
dependencies = [
"chrono",
"coa-core",
@@ -384,7 +384,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.2.0"
version = "0.3.0"
dependencies = [
"coa-core",
"serde",
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "2"
members = ["crates/coa-core", "crates/coa-release", "src-tauri"]
[workspace.package]
version = "0.2.0"
version = "0.3.0"
edition = "2021"
license = "AGPL-3.0-only"
+53 -18
View File
@@ -1,32 +1,67 @@
# CoA Server Manager
Windows desktop manager for local Conquest of Azeroth (AzerothCore) servers. Tauri 2 + Rust + React.
Design and audit: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
A Windows app that installs and runs your own **Conquest of Azeroth** server (AzerothCore) with a few clicks:
no console, no config files, no database tools. Tauri 2 + Rust + React.
![Overview](docs/screenshots/play.png)
## What it does
* **One-click install.** Downloads a signed, verified server package (resumable, checked file by file), sets up the
database and creates your first account. Or import a server you already have.
* **Start / Stop / PLAY.** One button for the whole server (database, auth, world) with live status, uptime and
players online. PLAY starts the game client with the right realmlist.
* **Game client.** Use the client you already have, or let the Manager download it (about 43 GB, resumable, every file
verified). A client the Manager looks after is checked for updates like the server: PLAY turns into **UPDATE CLIENT**,
and files you changed yourself are never replaced unless you say so.
* **Safe updates.** The Manager checks for a new server version on start and every five minutes; the main button turns
into **UPDATE**. Updates are authenticated (Ed25519), back up first, keep files you changed and can be rolled back.
* **Backups.** Characters, accounts and settings on demand, automatically before every update; verify and restore
from the app.
* **Companions (bots).** Fill the world with level-appropriate bots, see progress, stop spawning, take them offline,
despawn N to relieve the server, and choose how many log in at server start.
* **Settings without files.** Bots and Server pages with plain-language options and presets, a console to the world
server, player list with account tools.
* **Play with friends.** Checks whether your server is reachable, opens firewall rules, finds your router (UPnP),
supports LAN, direct and private-network (Tailscale) play, with step-by-step guides and a package to send to friends.
* **Updates to the Manager itself** download in the background and install when you close it. Your servers are never
stopped or changed by a Manager update.
* **Languages:** English, Russian, German, French, Spanish.
| Install | Ready |
|---------|-------|
| ![Installing](docs/screenshots/install.png) | ![Ready](docs/screenshots/ready.png) |
| Overview | Server updates |
|----------|----------------|
| ![Overview](docs/screenshots/overview.png) | ![Updates](docs/screenshots/updates.png) |
![Backups](docs/screenshots/backups.png)
## Install
Download the installer from the [Releases](https://github.com/Corfirean/coa-server-manager/releases) page
and run it. You need about 10 GB of free disk space for the server. The game client (about 43 GB) is separate: point the
Manager at the one you have, or let it download one for you.
## Status
| Phase | State |
|-------|-------|
| 0 Audit + architecture | done |
| 1 Foundation (fsx, registry, manifest, logging, error catalogue) | done |
| 2 Read-only import, process observation, Start/Stop via repack launcher, health diagnosis | done |
| 3 Config engine + Bots/Server settings UI + presets + snapshots | done |
| 4 Recovery points, DB dump/restore (staging + atomic swap), Backups UI | done |
| 5 Clean install: signed split packages, resumable verified download, staging + atomic commit, DB credential rotation, RA account creation | done |
| 6 Updates: tracked SQL migrations, update transaction (journal, conflicts, rollback), Settings > Server updates | done |
| 7 Companions: real population, hardware-aware sizes, RA spawn (install/update of the module rides on the update flow) | done |
| 8 Client: read-only detection, backed-up realmlist, isolated addon install, START & PLAY | done |
| Backlog: interface languages EN/RU/DE/FR/ES (see docs/ARCHITECTURE.md section 9) | planned |
| 9 Friends: exposure check, firewall rules, UPnP discovery, LAN/direct/private modes, friend package | done |
| 10 Polish: diagnostics, file verification, redacted diagnostic export | done; self-update installer, accessibility audit, i18n pending |
| `coa-server-build` repo: nightly build, edge/stable releases, fork sync | created; needs the COA_SIGNING_KEY / FORK_PUSH_TOKEN secrets |
Phases 0–10 of the plan in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) are done: foundation, import, start/stop,
config engine, backups, clean install from signed packages, updates, companions, client launch, friends, polish.
Remaining work (translation review by native speakers, optional extras) is listed in section 9 of that document. Translation notes: [docs/TRANSLATIONS.md](docs/TRANSLATIONS.md).
## Develop
```
npm install
cargo test --workspace # core logic (scan, fsx, manifest, process, driver, health)
cargo test --workspace # core logic (scan, fsx, manifest, process, driver, health, updates, ...)
npx tsc --noEmit # type check
node tools/check-i18n.mjs # translation keys and placeholders
npx vite # UI in a browser uses a mock IPC (src/dev/mock.ts)
cargo build -p coa-server-manager # native app (debug build loads http://localhost:1420)
```
Layout: `crates/coa-core` (logic), `crates/coa-release` (package tools: pack, sign, verify), `src-tauri`
(command layer), `src` (UI).
Live checks against a real repack: `cargo run -p coa-core --example scan -- <folder>` (read-only).
Start/stop testing must use a disposable copy: `tools/make-fixture.ps1` builds `C:\games\coa-fixture`
on offset ports from the pristine packaged database. Never run start/stop against a server in use.
+31
View File
@@ -0,0 +1,31 @@
//! Live check of the client download path against the community launcher's public server:
//! reads the manifest and downloads the few smallest files into a temp folder (never a real client).
//! Usage: cargo run -p coa-core --example client_probe (PROBE_SKIP=n skips the n smallest files)
use coa_core::clientdl::{self, Apply, Manifest};
use coa_core::download::{Cancel, HttpTransport};
fn main() {
let full = clientdl::fetch_latest().expect("manifest");
println!("version {} · {} files · {:.1} GB", full.version, full.files.len(), full.total_bytes() as f64 / 1e9);
let mut small = full.files.clone();
small.sort_by_key(|f| f.size);
let skip: usize = std::env::var("PROBE_SKIP").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
let small: Vec<_> = small.into_iter().skip(skip).take(6).collect();
let manifest = Manifest { version: full.version.clone(), published_at: None, files: small };
let dir = std::env::temp_dir().join(format!("coa-client-probe-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let cancel = Cancel::default();
let plan = clientdl::plan(&dir, &manifest, &Default::default(), &cancel, &|_| {}).unwrap();
println!("plan: {} files, {} bytes", plan.items.len(), plan.download_bytes);
let transport = HttpTransport::new().unwrap();
clientdl::apply(
&Apply { client: &dir, manifest: &manifest, plan: &plan, keep_modified: false, transport: &transport, objects_url: clientdl::OBJECTS_URL, cancel: &cancel },
&|s| println!("{} {}/{} {}", s.phase, s.done, s.total, s.file.unwrap_or_default()),
)
.expect("apply");
let again = clientdl::plan(&dir, &manifest, &clientdl::load_state(&dir).unwrap(), &cancel, &|_| {}).unwrap();
println!("second plan: {} to do, {} up to date, version {:?}", again.items.len(), again.up_to_date_files, clientdl::local(&dir).version);
std::fs::remove_dir_all(&dir).unwrap();
}
+44
View File
@@ -122,12 +122,40 @@ fn host_ok(h: &str) -> bool {
!h.is_empty() && h.len() <= 253 && h.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':')) && !h.starts_with('-')
}
/// Locales a client has game data for (`Data/<locale>/locale-<locale>.MPQ`), e.g. `enUS`.
fn installed_locales(client: &Path) -> Vec<String> {
let mut v: Vec<String> = fs::read_dir(client.join("Data"))
.map(|rd| {
rd.flatten()
.filter(|e| e.path().is_dir())
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| n.len() == 4 && n[..2].bytes().all(|b| b.is_ascii_lowercase()) && n[2..].bytes().all(|b| b.is_ascii_uppercase()))
.filter(|n| client.join("Data").join(n).join(format!("locale-{n}.MPQ")).is_file())
.collect()
})
.unwrap_or_default();
v.sort();
v
}
/// Point every locale's realmlist at `host`. Each changed file is copied to the backup folder first.
/// A freshly downloaded client has no realmlist yet; one is created for each installed locale.
pub fn set_realmlist(client: &Path, meta: &Path, host: &str) -> Result<Vec<String>> {
if !host_ok(host) {
return Err(Error::Invalid("That address is not valid.".into()));
}
let mut changed = Vec::new();
if realmlist_files(client).is_empty() {
for loc in installed_locales(client) {
let file = client.join("Data").join(&loc).join("realmlist.wtf");
fsx::atomic_write(&file, format!("set realmlist {host}
").as_bytes())?;
changed.push(file.to_string_lossy().into_owned());
}
if !changed.is_empty() {
return Ok(changed);
}
}
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string();
for file in realmlist_files(client) {
let old = fs::read(&file)?;
@@ -261,6 +289,22 @@ mod tests {
assert!(set_realmlist(&c, &meta, "bad host; rm -rf").is_err());
}
#[test]
fn a_fresh_client_gets_a_realmlist_for_each_installed_locale() {
let d = tempfile::tempdir().unwrap();
let c = d.path().join("fresh");
fs::create_dir_all(c.join("Data/enUS")).unwrap();
fs::create_dir_all(c.join("Data/Content")).unwrap();
fs::write(c.join("Data/enUS/locale-enUS.MPQ"), b"x").unwrap();
fs::write(c.join("Ascension.exe"), b"exe").unwrap();
let changed = set_realmlist(&c, &d.path().join("meta"), "127.0.0.1").unwrap();
assert_eq!(changed.len(), 1);
assert_eq!(fs::read_to_string(c.join("Data/enUS/realmlist.wtf")).unwrap(), "set realmlist 127.0.0.1
");
assert!(!c.join("Data/Content/realmlist.wtf").exists());
assert_eq!(detect(&c, None).unwrap().realmlists[0].host.as_deref(), Some("127.0.0.1"));
}
#[test]
fn addon_install_touches_only_its_own_folder_and_backs_up_a_different_version() {
let d = tempfile::tempdir().unwrap();
+630
View File
@@ -0,0 +1,630 @@
//! Download and update of the game client from the community launcher's public manifest.
//!
//! The manifest lists every file with its size and SHA-256; each file is fetched by hash and verified before it is
//! moved into place (`download::fetch_with`, resumable). The Manager keeps a small state file inside the client
//! folder (`.coa-manager/client-state.json`) so that later checks are cheap and so that files the player changed
//! are recognised: they are never overwritten without being asked, and a replaced file is moved aside, not deleted.
//! WTF, Cache, other addons, logs and `realmlist.wtf` are not part of what the Manager synchronises.
use std::collections::{BTreeMap, HashMap};
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::{Instant, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::download::{self, Cancel, HttpTransport, Job, Transport};
use crate::error::{Error, Result};
use crate::fsx;
pub const MANIFEST_URL: &str = "https://launcher-api.coa-development.org/downloads/client/latest.json";
pub const OBJECTS_URL: &str = "https://launcher-api.coa-development.org/downloads/client/objects";
const STATE_DIR: &str = ".coa-manager";
const MAX_MANIFEST_BYTES: u64 = 16 * 1024 * 1024;
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestFile {
pub path: String,
pub size: u64,
pub sha256: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Manifest {
pub version: String,
pub published_at: Option<String>,
pub files: Vec<ManifestFile>,
}
impl Manifest {
pub fn total_bytes(&self) -> u64 {
self.files.iter().map(|f| f.size).sum()
}
}
#[derive(Deserialize)]
struct RawManifest {
schema: u32,
version: String,
#[serde(rename = "publishedAt")]
published_at: Option<String>,
files: Vec<ManifestFile>,
}
/// Things the Manager never writes, even if a manifest lists them: logs, the realmlist, the player's own settings,
/// caches and the companion addon (those have their own safe paths).
fn is_excluded(path: &str) -> bool {
let p = path.replace('\\', "/").to_ascii_lowercase();
p.ends_with(".log")
|| p.rsplit('/').next() == Some("realmlist.wtf")
|| p.starts_with("wtf/")
|| p.starts_with("cache/")
|| p.starts_with("errors/")
|| p.starts_with("logs/")
|| p.starts_with(".coa-manager/")
|| p.starts_with("interface/addons/coabotui/")
}
/// Files players customise: graphics wrappers and their configuration. If one exists and differs from the published
/// file it is left exactly as it is, whatever the "keep my files" choice; it is only created when missing.
fn is_player_owned(path: &str) -> bool {
let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
matches!(name.as_str(), "d3d8.dll" | "d3d9.dll" | "d3d10core.dll" | "d3d11.dll" | "dxgi.dll" | "dxvk.conf")
|| matches!(name.rsplit('.').next(), Some("ini" | "conf" | "cfg" | "wtf"))
}
pub fn parse_manifest(text: &str) -> Result<Manifest> {
let raw: RawManifest = serde_json::from_str(text).map_err(|e| Error::Invalid(format!("The client list could not be read: {e}")))?;
if raw.schema != 1 {
return Err(Error::Invalid(format!("The client list uses a newer format ({}); update the Manager.", raw.schema)));
}
if raw.version.trim().is_empty() || raw.version.len() > 64 {
return Err(Error::Invalid("The client list has no version.".into()));
}
let root = Path::new("client-root");
let mut files = Vec::with_capacity(raw.files.len());
for f in raw.files {
fsx::safe_join(root, &f.path)?;
let hash_ok = f.sha256.len() == 64 && f.sha256.bytes().all(|b| b.is_ascii_hexdigit());
if !hash_ok || f.size > MAX_FILE_BYTES {
return Err(Error::Invalid(format!("The client list has a bad entry for {}.", f.path)));
}
if is_excluded(&f.path) {
continue;
}
files.push(ManifestFile { path: f.path.replace('\\', "/"), size: f.size, sha256: f.sha256.to_ascii_lowercase() });
}
if files.is_empty() {
return Err(Error::Invalid("The client list is empty.".into()));
}
Ok(Manifest { version: raw.version, published_at: raw.published_at, files })
}
pub fn fetch_manifest(transport: &dyn Transport, url: &str) -> Result<Manifest> {
let mut reply = transport.get(url, 0).map_err(|e| Error::Invalid(format!("Could not reach the client download server: {e}")))?;
if reply.status != 200 {
return Err(Error::Invalid(format!("The client download server answered {}.", reply.status)));
}
let mut text = String::new();
reply.body.by_ref().take(MAX_MANIFEST_BYTES).read_to_string(&mut text).map_err(|e| Error::Invalid(format!("Could not read the client list: {e}")))?;
parse_manifest(&text)
}
pub fn fetch_latest() -> Result<Manifest> {
download::check_url(MANIFEST_URL)?;
fetch_manifest(&HttpTransport::with_total_timeout(30)?, MANIFEST_URL)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
pub size: u64,
pub mtime: u64,
pub sha256: String,
/// The player chose to keep this file although the manifest has a different one (this is the manifest hash
/// they were asked about; a newer manifest asks again).
#[serde(default)]
pub kept_against: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct State {
/// The manifest version this folder was brought to; None while a download is unfinished.
pub version: Option<String>,
pub files: BTreeMap<String, Entry>,
}
fn state_path(client: &Path) -> PathBuf {
client.join(STATE_DIR).join("client-state.json")
}
pub fn load_state(client: &Path) -> Option<State> {
fsx::read_json(&state_path(client)).ok()
}
fn save_state(client: &Path, state: &State) -> Result<()> {
fsx::atomic_write_json(&state_path(client), state)
}
#[derive(Debug, Clone, Serialize)]
pub struct Local {
/// The Manager downloaded or adopted this folder (a state file exists).
pub managed: bool,
pub version: Option<String>,
}
pub fn local(client: &Path) -> Local {
let s = load_state(client);
Local { managed: s.is_some(), version: s.and_then(|s| s.version) }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
/// Not in the folder.
Missing,
/// Still as the Manager left it; the manifest has a newer file.
Changed,
/// Different from the manifest and not as the Manager left it (changed by the player or by something else).
Modified,
}
#[derive(Debug, Clone, Serialize)]
pub struct Item {
pub path: String,
pub size: u64,
pub kind: Kind,
#[serde(skip)]
sha256: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Plan {
pub version: String,
pub items: Vec<Item>,
pub download_bytes: u64,
pub total_files: usize,
pub up_to_date_files: usize,
pub kept_files: usize,
#[serde(skip)]
confirmed: BTreeMap<String, Entry>,
}
impl Plan {
pub fn modified(&self) -> Vec<&Item> {
self.items.iter().filter(|i| i.kind == Kind::Modified).collect()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Step {
/// "scan" while comparing files, "download" while fetching, "finish" at the end.
pub phase: &'static str,
pub done: u64,
pub total: u64,
pub bytes_per_sec: u64,
pub file: Option<String>,
}
fn cancelled() -> Error {
Error::Invalid("Download cancelled.".into())
}
fn mtime_secs(m: &fs::Metadata) -> u64 {
m.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0)
}
fn hash_file(path: &Path, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<String> {
let mut f = File::open(path)?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
loop {
if cancel.is_set() {
return Err(cancelled());
}
let n = f.read(&mut buf)?;
if n == 0 {
return Ok(hex::encode(hasher.finalize()));
}
hasher.update(&buf[..n]);
on_bytes(n as u64);
}
}
/// Compare the folder with the manifest. Files are hashed only when their size or modification time no longer
/// matches what the state file recorded, so a routine check of a managed folder is quick.
pub fn plan(client: &Path, m: &Manifest, state: &State, cancel: &Cancel, on_step: &dyn Fn(Step)) -> Result<Plan> {
let total = m.total_bytes();
let mut done = 0u64;
let mut items = Vec::new();
let mut confirmed = BTreeMap::new();
let (mut up_to_date, mut kept) = (0usize, 0usize);
for f in &m.files {
if cancel.is_set() {
return Err(cancelled());
}
on_step(Step { phase: "scan", done, total, bytes_per_sec: 0, file: Some(f.path.clone()) });
let path = fsx::safe_join(client, &f.path)?;
let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta,
_ => {
items.push(Item { path: f.path.clone(), size: f.size, kind: Kind::Missing, sha256: f.sha256.clone() });
done += f.size;
continue;
}
};
let (size, mtime) = (meta.len(), mtime_secs(&meta));
let entry = state.files.get(&f.path);
let trusted = entry.filter(|e| e.size == size && e.mtime == mtime);
let local: Option<String> = if let Some(e) = trusted {
Some(e.sha256.clone())
} else if size == f.size || entry.map(|e| e.size == size).unwrap_or(false) {
let base = done;
let mut seen = 0u64;
let h = hash_file(&path, cancel, &mut |n| {
seen += n;
on_step(Step { phase: "scan", done: base + seen.min(f.size), total, bytes_per_sec: 0, file: Some(f.path.clone()) });
})?;
Some(h)
} else {
None
};
done += f.size;
if is_player_owned(&f.path) && local.as_deref() != Some(f.sha256.as_str()) {
let sha = match local {
Some(h) => h,
None => hash_file(&path, cancel, &mut |_| {})?,
};
kept += 1;
confirmed.insert(f.path.clone(), Entry { size, mtime, sha256: sha, kept_against: Some(f.sha256.clone()) });
continue;
}
if local.as_deref() == Some(f.sha256.as_str()) {
up_to_date += 1;
confirmed.insert(f.path.clone(), Entry { size, mtime, sha256: f.sha256.clone(), kept_against: None });
continue;
}
let as_left = entry.filter(|e| local.as_deref() == Some(e.sha256.as_str()));
match as_left {
Some(e) if e.kept_against.as_deref() == Some(f.sha256.as_str()) => {
kept += 1;
confirmed.insert(f.path.clone(), Entry { size, mtime, sha256: e.sha256.clone(), kept_against: e.kept_against.clone() });
}
Some(e) if e.kept_against.is_none() => {
items.push(Item { path: f.path.clone(), size: f.size, kind: Kind::Changed, sha256: f.sha256.clone() });
}
_ => items.push(Item { path: f.path.clone(), size: f.size, kind: Kind::Modified, sha256: f.sha256.clone() }),
}
}
on_step(Step { phase: "scan", done: total, total, bytes_per_sec: 0, file: None });
let download_bytes = items.iter().map(|i| i.size).sum();
Ok(Plan { version: m.version.clone(), items, download_bytes, total_files: m.files.len(), up_to_date_files: up_to_date, kept_files: kept, confirmed })
}
pub struct Apply<'a> {
pub client: &'a Path,
pub manifest: &'a Manifest,
pub plan: &'a Plan,
/// Leave files the player changed alone (they are remembered, and asked about again only when the manifest changes).
pub keep_modified: bool,
pub transport: &'a dyn Transport,
pub objects_url: &'a str,
pub cancel: &'a Cancel,
}
fn blocked(path: &str, e: std::io::Error) -> Error {
Error::Invalid(format!("Could not replace {path}: {e}. Close the game and anything else using the client, then try again."))
}
/// Download what the plan lists. Progress is saved after every file, so an interrupted run resumes where it stopped.
pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
let mut state = State { version: None, files: a.plan.confirmed.clone() };
save_state(a.client, &state)?;
let mut todo = Vec::new();
for item in &a.plan.items {
if item.kind == Kind::Modified && a.keep_modified {
let path = fsx::safe_join(a.client, &item.path)?;
let meta = fs::metadata(&path)?;
let sha = hash_file(&path, a.cancel, &mut |_| {})?;
state.files.insert(item.path.clone(), Entry { size: meta.len(), mtime: mtime_secs(&meta), sha256: sha, kept_against: Some(item.sha256.clone()) });
} else {
todo.push(item);
}
}
let total: u64 = todo.iter().map(|i| i.size).sum();
fsx::require_space(a.client, total)?;
let staging = a.client.join(STATE_DIR).join("staging");
let replaced = a.client.join(STATE_DIR).join("replaced").join(chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string());
let mut done = 0u64;
let mut placed: HashMap<&str, PathBuf> = HashMap::new();
for item in todo {
if a.cancel.is_set() {
save_state(a.client, &state)?;
return Err(cancelled());
}
let target = fsx::safe_join(a.client, &item.path)?;
let started = Instant::now();
let staged = staging.join(&item.sha256);
let copy_from = placed.get(item.sha256.as_str()).cloned();
if copy_from.is_none() {
let job = Job { url: format!("{}/{}", a.objects_url, item.sha256), dest: staged.clone(), sha256: item.sha256.clone(), size: item.size };
let base = done;
let result = download::fetch_with(a.transport, &job, a.cancel, &|p| {
on_step(Step { phase: "download", done: base + p.downloaded, total, bytes_per_sec: p.bytes_per_sec, file: Some(item.path.clone()) });
});
if let Err(e) = result {
let _ = save_state(a.client, &state);
return Err(e);
}
}
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
if target.exists() {
if item.kind == Kind::Modified {
let keep = fsx::safe_join(&replaced, &item.path)?;
if let Some(parent) = keep.parent() {
fs::create_dir_all(parent)?;
}
fs::rename(&target, &keep).map_err(|e| blocked(&item.path, e))?;
} else {
fs::remove_file(&target).map_err(|e| blocked(&item.path, e))?;
}
}
match copy_from {
Some(src) => {
fs::copy(&src, &target).map_err(|e| blocked(&item.path, e))?;
}
None => fs::rename(&staged, &target).map_err(|e| blocked(&item.path, e))?,
}
placed.insert(&item.sha256, target.clone());
let meta = fs::metadata(&target)?;
state.files.insert(item.path.clone(), Entry { size: meta.len(), mtime: mtime_secs(&meta), sha256: item.sha256.clone(), kept_against: None });
save_state(a.client, &state)?;
done += item.size;
let secs = started.elapsed().as_secs_f64().max(0.001);
on_step(Step { phase: "download", done, total, bytes_per_sec: (item.size as f64 / secs) as u64, file: Some(item.path.clone()) });
}
state.version = Some(a.manifest.version.clone());
save_state(a.client, &state)?;
let _ = fs::remove_dir_all(&staging);
on_step(Step { phase: "finish", done: total, total, bytes_per_sec: 0, file: None });
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::download::Reply;
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
/// Serves objects by hash; remembers what was requested and can fail after N objects.
struct Server {
objects: Mutex<HashMap<String, Vec<u8>>>,
requested: Mutex<Vec<String>>,
cancel_after: Option<(AtomicUsize, Cancel)>,
}
impl Server {
fn new(files: &[(&str, &[u8])]) -> Self {
let s = Server { objects: Default::default(), requested: Default::default(), cancel_after: None };
for (_, body) in files {
s.objects.lock().unwrap().insert(fsx::sha256_bytes(body), body.to_vec());
}
s
}
}
impl Transport for Server {
fn get(&self, url: &str, from: u64) -> std::result::Result<Reply, String> {
let sha = url.rsplit('/').next().unwrap().to_string();
self.requested.lock().unwrap().push(sha.clone());
if let Some((left, cancel)) = &self.cancel_after {
if left.fetch_sub(1, Ordering::SeqCst) == 1 {
cancel.cancel();
}
}
let body = self.objects.lock().unwrap().get(&sha).cloned().ok_or("404")?;
let (status, start) = if from > 0 { (206, from as usize) } else { (200, 0) };
let cr = (from > 0).then(|| format!("bytes {from}-{}/{}", body.len() - 1, body.len()));
Ok(Reply { status, content_range: cr, body: Box::new(Cursor::new(body[start..].to_vec())) })
}
}
fn manifest(version: &str, files: &[(&str, &[u8])]) -> Manifest {
Manifest {
version: version.into(),
published_at: None,
files: files.iter().map(|(p, b)| ManifestFile { path: p.to_string(), size: b.len() as u64, sha256: fsx::sha256_bytes(b) }).collect(),
}
}
const V1: [(&str, &[u8]); 4] = [("Wow.exe", b"exe-1"), ("Data/common.MPQ", b"common-mpq-data"), ("Data/patch-A.MPQ", b"patch-a-1"), ("Data/enUS/locale.MPQ", b"locale")];
fn sync(dir: &Path, m: &Manifest, server: &Server, keep: bool) -> Result<Plan> {
let state = load_state(dir).unwrap_or_default();
let cancel = Cancel::default();
let p = plan(dir, m, &state, &cancel, &|_| {})?;
apply(&Apply { client: dir, manifest: m, plan: &p, keep_modified: keep, transport: server, objects_url: "https://x.invalid/objects", cancel: &cancel }, &|_| {})?;
Ok(p)
}
#[test]
fn manifest_rejects_traversal_and_bad_entries_and_skips_personal_files() {
let ok = r#"{"schema":1,"version":"v1","files":[
{"path":"Wow.exe","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"Data/enUS/realmlist.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"WTF/Config.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"Interface/AddOns/CoABotUI/x.lua","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
{"path":"MemoryBridge.log","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#;
let m = parse_manifest(ok).unwrap();
assert_eq!(m.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["Wow.exe"]);
for bad in [
r#"{"schema":1,"version":"v","files":[{"path":"../evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
r#"{"schema":1,"version":"v","files":[{"path":"C:/evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
r#"{"schema":1,"version":"v","files":[{"path":"a.dll","size":1,"sha256":"short"}]}"#,
r#"{"schema":2,"version":"v","files":[]}"#,
r#"{"schema":1,"version":"v","files":[]}"#,
] {
assert!(parse_manifest(bad).is_err(), "{bad}");
}
}
#[test]
fn fresh_download_installs_every_file_verified_and_leaves_nothing_behind() {
let d = tempfile::tempdir().unwrap();
let (m, s) = (manifest("v1", &V1), Server::new(&V1));
let p = sync(d.path(), &m, &s, false).unwrap();
assert_eq!(p.items.len(), 4);
for (path, body) in V1 {
assert_eq!(fs::read(d.path().join(path)).unwrap(), body);
}
let st = load_state(d.path()).unwrap();
assert_eq!(st.version.as_deref(), Some("v1"));
assert_eq!(st.files.len(), 4);
assert!(!d.path().join(".coa-manager/staging").exists());
assert!(local(d.path()).managed);
}
#[test]
fn an_update_downloads_only_what_changed_and_a_second_check_is_empty() {
let d = tempfile::tempdir().unwrap();
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
let mut v2 = V1.to_vec();
v2[2] = ("Data/patch-A.MPQ", b"patch-a-2-longer");
v2.push(("Data/new.MPQ", b"brand new"));
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
let p = sync(d.path(), &m2, &s2, false).unwrap();
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
assert_eq!(kinds, [("Data/patch-A.MPQ", Kind::Changed), ("Data/new.MPQ", Kind::Missing)]);
assert_eq!(s2.requested.lock().unwrap().len(), 2, "unchanged files were not downloaded again");
assert_eq!(fs::read(d.path().join("Data/patch-A.MPQ")).unwrap(), b"patch-a-2-longer");
assert!(!d.path().join(".coa-manager/replaced").exists(), "a file the Manager itself wrote needs no backup");
let again = sync(d.path(), &m2, &s2, false).unwrap();
assert!(again.items.is_empty() && again.up_to_date_files == 5);
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v2"));
}
#[test]
fn a_file_the_player_changed_is_asked_about_kept_when_told_to_and_saved_when_replaced() {
let d = tempfile::tempdir().unwrap();
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
fs::write(d.path().join("Wow.exe"), b"my patched exe").unwrap();
let mut v2 = V1.to_vec();
v2[0] = ("Wow.exe", b"exe-2");
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
let p = sync(d.path(), &m2, &s2, true).unwrap();
assert_eq!(p.modified().len(), 1);
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"my patched exe", "kept");
assert!(s2.requested.lock().unwrap().is_empty(), "nothing needed downloading");
let quiet = sync(d.path(), &m2, &s2, true).unwrap();
assert!(quiet.items.is_empty() && quiet.kept_files == 1, "the decision is remembered");
let mut v3 = V1.to_vec();
v3[0] = ("Wow.exe", b"exe-3");
let (m3, s3) = (manifest("v3", &v3), Server::new(&v3));
let again = sync(d.path(), &m3, &s3, false).unwrap();
assert_eq!(again.modified().len(), 1, "a newer client asks again");
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-3");
let saved = fs::read_dir(d.path().join(".coa-manager/replaced")).unwrap().next().unwrap().unwrap().path();
assert_eq!(fs::read(saved.join("Wow.exe")).unwrap(), b"my patched exe", "the player's version was moved aside, not lost");
}
#[test]
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
let d = tempfile::tempdir().unwrap();
let v1: Vec<(&str, &[u8])> = vec![("Wow.exe", b"exe-1"), ("d3d9.dll", b"official d3d9"), ("dxvk.conf", b"official conf"), ("Data/common.MPQ", b"common-1")];
sync(d.path(), &manifest("v1", &v1), &Server::new(&v1), false).unwrap();
// the player's own setup: custom renderer + configs, addons, WTF, realmlist, extra archives, backups
let mine: Vec<(&str, &[u8])> = vec![
("d3d9.dll", b"my renderer"),
("dxvk.conf", b"my conf"),
("ModernWoWRenderer.ini", b"cfg"),
("GraphicsEffects.ini.bak", b"bak"),
("Data/enUS/realmlist.wtf", b"set realmlist 127.0.0.1
"),
("Data/patch-5.MPQ", b"extra archive"),
("Interface/AddOns/ElvUI/ElvUI.toc", b"## Title: Elv"),
("WTF/Account/x/SavedVariables.lua", b"vars"),
("Cache/x.wdb", b"cache"),
];
for (p, b) in &mine {
let path = d.path().join(p);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b).unwrap();
}
let before: BTreeMap<String, String> = mine.iter().map(|(p, b)| (p.to_string(), fsx::sha256_bytes(b))).collect();
let v2: Vec<(&str, &[u8])> = vec![("Wow.exe", b"exe-2"), ("d3d9.dll", b"official d3d9 v2"), ("dxvk.conf", b"official conf v2"), ("Data/common.MPQ", b"common-2")];
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
for keep in [false, true] {
sync(d.path(), &m2, &s2, keep).unwrap();
for (p, h) in &before {
assert_eq!(&fsx::sha256_file(&d.path().join(p)).unwrap(), h, "{p} must not change (keep_modified={keep})");
}
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-2");
assert_eq!(fs::read(d.path().join("Data/common.MPQ")).unwrap(), b"common-2");
}
assert!(!d.path().join(".coa-manager/replaced").exists(), "nothing of the player's was displaced");
}
#[test]
fn an_existing_client_without_state_is_compared_by_content() {
let d = tempfile::tempdir().unwrap();
for (p, b) in V1 {
let path = d.path().join(p);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b).unwrap();
}
fs::write(d.path().join("Data/patch-A.MPQ"), b"patch-a-X").unwrap(); // same size, different content
fs::remove_file(d.path().join("Data/enUS/locale.MPQ")).unwrap();
fs::create_dir_all(d.path().join("WTF")).unwrap();
fs::write(d.path().join("WTF/Config.wtf"), b"mine").unwrap();
let m = manifest("v1", &V1);
let p = plan(d.path(), &m, &State::default(), &Cancel::default(), &|_| {}).unwrap();
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
assert_eq!(kinds, [("Data/patch-A.MPQ", Kind::Modified), ("Data/enUS/locale.MPQ", Kind::Missing)]);
assert_eq!(p.up_to_date_files, 2);
assert_eq!(fs::read(d.path().join("WTF/Config.wtf")).unwrap(), b"mine");
}
#[test]
fn cancel_keeps_finished_files_and_the_next_run_only_fetches_the_rest() {
let d = tempfile::tempdir().unwrap();
let m = manifest("v1", &V1);
let mut s = Server::new(&V1);
let cancel = Cancel::default();
s.cancel_after = Some((AtomicUsize::new(3), cancel.clone()));
let state = State::default();
let p = plan(d.path(), &m, &state, &cancel, &|_| {}).unwrap();
let r = apply(&Apply { client: d.path(), manifest: &m, plan: &p, keep_modified: false, transport: &s, objects_url: "https://x.invalid/o", cancel: &cancel }, &|_| {});
assert!(r.is_err());
let st = load_state(d.path()).unwrap();
assert!(st.version.is_none() && !st.files.is_empty() && st.files.len() < 4, "unfinished but remembered: {}", st.files.len());
assert!(local(d.path()).managed && local(d.path()).version.is_none());
let s2 = Server::new(&V1);
sync(d.path(), &m, &s2, false).unwrap();
assert_eq!(s2.requested.lock().unwrap().len(), 4 - st.files.len(), "only the missing files were requested");
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v1"));
}
#[test]
fn a_wrong_object_never_reaches_the_client_folder() {
let d = tempfile::tempdir().unwrap();
let m = manifest("v1", &V1);
let s = Server::new(&V1);
// the server returns different bytes under the right hash
let sha = fsx::sha256_bytes(b"exe-1");
s.objects.lock().unwrap().insert(sha, b"EVIL!".to_vec());
assert!(sync(d.path(), &m, &s, false).is_err());
assert!(!d.path().join("Wow.exe").exists());
assert!(load_state(d.path()).unwrap().version.is_none());
}
}
+26 -1
View File
@@ -35,7 +35,7 @@ impl Cancel {
pub fn cancel(&self) {
self.0.store(true, Ordering::SeqCst);
}
fn is_set(&self) -> bool {
pub fn is_set(&self) -> bool {
self.0.load(Ordering::SeqCst)
}
}
@@ -70,6 +70,17 @@ pub trait Transport {
pub struct HttpTransport(reqwest::blocking::Client);
impl HttpTransport {
/// For small documents (manifests): gives up when the server stalls instead of waiting forever.
pub fn with_total_timeout(secs: u64) -> Result<Self> {
reqwest::blocking::Client::builder()
.connect_timeout(Duration::from_secs(15))
.timeout(Duration::from_secs(secs))
.redirect(reqwest::redirect::Policy::limited(5))
.build()
.map(HttpTransport)
.map_err(|e| Error::Invalid(e.to_string()))
}
pub fn new() -> Result<Self> {
reqwest::blocking::Client::builder()
.connect_timeout(Duration::from_secs(15))
@@ -130,6 +141,10 @@ fn attempt(client: &dyn Transport, job: &Job, part: &Path, cancel: &Cancel, on_p
have = 0;
}
if have == job.size {
if !part.exists() {
// an empty file: nothing to request
File::create(part)?;
}
return finish(job, part, hasher);
}
@@ -378,6 +393,16 @@ mod tests {
assert!(part_path(&j.dest).exists(), "partial data is kept for the next try");
}
#[test]
fn an_empty_file_needs_no_request_and_is_still_created() {
let dir = tempfile::tempdir().unwrap();
let j = job(dir.path(), b"");
let m = Mock::new(Vec::new(), 0, true);
fetch_with(&m, &j, &Cancel::default(), &|_| {}).unwrap();
assert_eq!(fs::read(&j.dest).unwrap(), Vec::<u8>::new());
assert_eq!(m.calls.load(Ordering::SeqCst), 0);
}
#[test]
fn only_https_or_loopback_http_is_allowed() {
assert!(check_url("https://github.com/x").is_ok());
+1
View File
@@ -2,6 +2,7 @@ pub mod backup;
pub mod cleanbase;
pub mod companions;
pub mod client;
pub mod clientdl;
pub mod config;
pub mod console;
pub mod db;
+24 -3
View File
@@ -277,9 +277,10 @@ Advanced override, snapshot first.
### D9. Client integration
The client is a separate object. Manager only: detect (`Wow.exe`/`Ascension.exe` + `Data\`), read/write
`realmlist.wtf` after backing it up, and copy `Interface\AddOns\CoABotUI` (backing that one directory up only if
its files differ from the manifest). No touching of `WTF`, `Cache`, other AddOns, or the exe.
The client is a separate object. By default the Manager only detects it (`Wow.exe`/`Ascension.exe` + `Data\`), reads/writes
`realmlist.wtf` after backing it up, and copies `Interface\AddOns\CoABotUI` (backing that one directory up only if
its files differ from the manifest). No touching of `WTF`, `Cache`, other AddOns, or the exe. Downloading or updating
a client is opt-in and described in section 9 (game client download); an existing client is never changed without asking.
*Reference machine note:* `C:\games\Ascension` is a heavily modified Ascension client (custom `d3d9.dll`,
renderer files, many `.bak`s) — client detection must be strictly read-only + additive.
@@ -517,3 +518,23 @@ The reference install classifies as **Healthy (customised)**: repack shape, bina
hour, world thread stalled); (2) no active `coa.conf` (`CoA.Enable = 1`) because packages contain only `*.conf.dist`.
Fixed: `clean-base` restores quiet templates, `assemble-tree` ships `coa.conf.dist`, and the Manager creates missing
module `.conf` files from their `.dist` on install and before each start of a Manager-installed server.
* **Game client download and update through the Manager** (built 2026-10-01, `coa-core::clientdl`). The community PTR launcher
("Conquest of AzerothCore" Electron app) reads its client from
`https://launcher-api.coa-development.org/downloads/client/latest.json` (`{schema, version, publishedAt, files:[{path,size,sha256}]}`;
~200 files, 43 GiB: `Ascension.exe`, DLLs and ~40 big `Data/*.MPQ`) and fetches each file as the content-addressed object
`.../downloads/client/objects/<sha256>`. The Manager uses the same endpoints with its own resumable, hash-verified downloader:
* **State** lives in the client folder (`.coa-manager/client-state.json`: manifest version, per file size/mtime/sha256). A
routine check (every 5 minutes, like the server) is one small manifest request compared with the recorded version; no game file is read.
* **Plan, then apply** (like server updates): files are compared by size and mtime against the state, and hashed only when those
no longer match. Each file is `Missing`, `Changed` (still as the Manager left it) or `Modified` (the player changed it, e.g. a
custom `d3d9.dll` or a patched exe). Modified files are kept on request (and remembered: asked again only when the published file
changes) or replaced after being moved to `.coa-manager/replaced/<time>/`. Objects are staged in `.coa-manager/staging/<sha>` and
moved into place only after the hash matches; state is saved after every file, so cancel, crash or reboot resume where they stopped.
* **Never touched:** `WTF`, `Cache`, `Errors`, `Logs`, `*.log`, `realmlist.wtf`, `Interface/AddOns/CoABotUI` (those have their own paths).
* **UI:** PLAY becomes **UPDATE CLIENT** when a tracked client is outdated (with "Play without updating"); with no client linked it
becomes **Set up game client** (choose an existing folder, or download into `<chosen folder>/CoA Client` with a free-space check).
An existing client that is not tracked can be adopted from Settings > Game client ("Keep this client up to date").
A fresh download gets `realmlist.wtf` for each installed locale (the manifest has none) and the companion addon.
* **Open points:** ask the launcher maintainers before putting heavy load on their API; DBCs live inside the MPQ patch archives
(extracting them would need an MPQ reader), so the server's `Data\dbc` still comes from our `base` package for now.
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.2.0",
"version": "0.3.0",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+185 -1
View File
@@ -28,6 +28,8 @@ struct AppState {
busy: Mutex<HashSet<String>>,
/// Cancel handle of the installation currently running, if any.
install_cancel: Mutex<Option<Cancel>>,
/// Cancel handle of the game-client check or download currently running, if any.
client_cancel: Mutex<Option<Cancel>>,
}
/// Where official server packages are published (created by the release pipeline, Phase 6).
@@ -726,6 +728,182 @@ fn client_install_addon(state: State<'_, AppState>, id: String) -> std::result::
Ok(coa_core::client::install_addon(&client.unwrap(), &dir, &source)?)
}
#[derive(Serialize)]
struct ClientStatus {
/// A usable client folder is linked to this server.
linked: bool,
/// The Manager keeps this folder up to date (it downloaded it or was asked to adopt it).
managed: bool,
installed_version: Option<String>,
latest_version: Option<String>,
latest_bytes: Option<u64>,
/// A managed client is older than the published one (or its download never finished).
update_available: bool,
}
fn linked_client(root: &std::path::Path) -> Result<Option<PathBuf>> {
let (_, meta) = install_meta(root)?;
Ok(meta.client_path.map(PathBuf::from).filter(|p| coa_core::client::detect(p, None).is_some()))
}
/// Cheap: one small manifest request and the local state file; no game file is read.
#[tauri::command]
async fn client_status(state: State<'_, AppState>, id: String) -> std::result::Result<ClientStatus, UiError> {
let root = path_of(&state, &id)?;
blocking(move || {
let client = linked_client(&root)?;
let latest = coa_core::clientdl::fetch_latest().ok();
let local = client.as_deref().map(coa_core::clientdl::local);
let managed = local.as_ref().map(|l| l.managed).unwrap_or(false);
let installed = local.and_then(|l| l.version);
let update_available = managed && latest.as_ref().map(|l| installed.as_deref() != Some(l.version.as_str())).unwrap_or(false);
Ok(ClientStatus {
linked: client.is_some(),
managed,
installed_version: installed,
latest_bytes: latest.as_ref().map(|l| l.total_bytes()),
latest_version: latest.map(|l| l.version),
update_available,
})
})
.await
}
#[derive(Serialize)]
struct ClientDownloadCheck {
needed_bytes: u64,
free_bytes: u64,
version: String,
/// Where the client would go.
dest: String,
}
const CLIENT_FOLDER: &str = "CoA Client";
#[tauri::command]
async fn client_download_check(parent: String) -> std::result::Result<ClientDownloadCheck, UiError> {
blocking(move || {
let latest = coa_core::clientdl::fetch_latest()?;
let dest = PathBuf::from(&parent).join(CLIENT_FOLDER);
Ok(ClientDownloadCheck {
needed_bytes: latest.total_bytes(),
free_bytes: coa_core::fsx::free_space(std::path::Path::new(&parent))?,
version: latest.version,
dest: dest.to_string_lossy().into_owned(),
})
})
.await
}
/// Compare the linked client with the published one. Hashes files only where the recorded state cannot vouch for them.
#[tauri::command]
async fn client_plan(app: AppHandle, state: State<'_, AppState>, id: String) -> std::result::Result<coa_core::clientdl::Plan, UiError> {
let root = path_of(&state, &id)?;
let cancel = begin_client_job(&state)?;
let result = blocking(move || {
let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is set up for this server yet.".into()))?;
let manifest = coa_core::clientdl::fetch_latest()?;
let current = coa_core::clientdl::load_state(&client).unwrap_or_default();
coa_core::clientdl::plan(&client, &manifest, &current, &cancel, &|s| {
let _ = app.emit("client-progress", s);
})
})
.await;
end_client_job(&state);
result
}
/// Bring the linked client to the published version. `keep_modified` leaves files the player changed alone.
#[tauri::command]
async fn client_sync(app: AppHandle, state: State<'_, AppState>, id: String, keep_modified: bool) -> std::result::Result<(), UiError> {
let root = path_of(&state, &id)?;
let cancel = begin_client_job(&state)?;
let result = blocking(move || {
let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is set up for this server yet.".into()))?;
run_client_sync(&app, &client, keep_modified, &cancel)
})
.await;
end_client_job(&state);
result
}
fn run_client_sync(app: &AppHandle, client: &std::path::Path, keep_modified: bool, cancel: &Cancel) -> Result<()> {
let emit = |s: coa_core::clientdl::Step| {
let _ = app.emit("client-progress", s);
};
let manifest = coa_core::clientdl::fetch_latest()?;
let current = coa_core::clientdl::load_state(client).unwrap_or_default();
let plan = coa_core::clientdl::plan(client, &manifest, &current, cancel, &emit)?;
coa_core::download::check_url(coa_core::clientdl::OBJECTS_URL)?;
let transport = coa_core::download::HttpTransport::new()?;
coa_core::clientdl::apply(
&coa_core::clientdl::Apply { client, manifest: &manifest, plan: &plan, keep_modified, transport: &transport, objects_url: coa_core::clientdl::OBJECTS_URL, cancel },
&emit,
)?;
tracing::info!(version = %manifest.version, downloaded = plan.items.len(), "client brought up to date");
Ok(())
}
/// Download the whole client into `<parent>/CoA Client`, then link it to this server.
#[tauri::command]
async fn client_download(app: AppHandle, state: State<'_, AppState>, id: String, parent: String) -> std::result::Result<coa_core::client::ClientInfo, UiError> {
let root = path_of(&state, &id)?;
let cancel = begin_client_job(&state)?;
let result = blocking(move || {
let (dir, mut meta) = install_meta(&root)?;
let parent = PathBuf::from(&parent);
if !parent.is_dir() {
return Err(Error::Invalid("Choose an existing folder to put the game client in.".into()));
}
let dest = parent.join(CLIENT_FOLDER);
let resuming = coa_core::clientdl::load_state(&dest).is_some();
let non_empty = std::fs::read_dir(&dest).map(|mut r| r.next().is_some()).unwrap_or(false);
if non_empty && !resuming {
return Err(Error::Invalid(format!("{} already exists and is not an unfinished download. Choose another folder.", dest.display())));
}
std::fs::create_dir_all(&dest)?;
run_client_sync(&app, &dest, false, &cancel)?;
let source = coa_core::client::addon_source(&root);
let info = coa_core::client::detect(&dest, source.as_deref()).ok_or_else(|| Error::Invalid("The downloaded client looks incomplete.".into()))?;
meta.client_path = Some(info.path.clone());
coa_core::fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
// a fresh client has no realmlist; this server is on this computer
coa_core::client::set_realmlist(&dest, &dir, "127.0.0.1")?;
if let Some(src) = source {
coa_core::client::install_addon(&dest, &dir, &src)?;
}
Ok(coa_core::client::detect(&dest, coa_core::client::addon_source(&root).as_deref()).unwrap_or(info))
})
.await;
end_client_job(&state);
result
}
#[tauri::command]
fn client_cancel(state: State<'_, AppState>) {
if let Ok(c) = state.client_cancel.lock() {
if let Some(c) = c.as_ref() {
c.cancel();
}
}
}
fn begin_client_job(state: &AppState) -> std::result::Result<Cancel, UiError> {
let mut slot = state.client_cancel.lock().map_err(|_| Error::Invalid("state poisoned".into()))?;
if slot.is_some() {
return Err(Error::Invalid("The game client is already being checked or downloaded.".into()).into());
}
let cancel = Cancel::default();
*slot = Some(cancel.clone());
Ok(cancel)
}
fn end_client_job(state: &AppState) {
if let Ok(mut c) = state.client_cancel.lock() {
*c = None;
}
}
/// Start the server if needed, wait until it is ready, then launch the game client.
#[tauri::command]
async fn play(state: State<'_, AppState>, id: String) -> std::result::Result<DriverOutcome, UiError> {
@@ -969,7 +1147,7 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.manage(AppState { registry: Registry::at(dir.join("installs.json")), busy: Mutex::new(HashSet::new()), install_cancel: Mutex::new(None) })
.manage(AppState { registry: Registry::at(dir.join("installs.json")), busy: Mutex::new(HashSet::new()), install_cancel: Mutex::new(None), client_cancel: Mutex::new(None) })
.invoke_handler(tauri::generate_handler![
default_install_dir,
scan_server,
@@ -1012,6 +1190,12 @@ pub fn run() {
set_client,
client_realmlist,
client_install_addon,
client_status,
client_download_check,
client_plan,
client_sync,
client_download,
client_cancel,
play,
friends_status,
friends_check_internet,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.2.0",
"version": "0.3.0",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+18 -1
View File
@@ -31,10 +31,27 @@ export {};
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,download_bytes:6000000};
if(cmd==="apply_update"){await new Promise((r: any)=>setTimeout(r,1500));(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};}
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
if(cmd==="plugin:event|listen") return 1;
if(cmd.startsWith("client_")){
const w=window as any;
const emit=(payload: any)=>(w.__handlers?.["client-progress"]??[]).forEach((h: any)=>h({event:"client-progress",id:1,payload}));
const sleep=(ms: number)=>new Promise((r: any)=>setTimeout(r,ms));
const total=46404000000;
const run=async(phase: string,n: number,speed: number)=>{for(let i=1;i<=n;i++){if(w.__stop){w.__stop=false;throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"Download cancelled."};}emit({phase,done:Math.round(total*i/n),total,bytes_per_sec:speed,file:phase==="scan"?"Data/patch-"+i+".MPQ":"Data/patch-O.MPQ"});await sleep(120);}};
if(cmd==="client_status"){const c=w.__client??"none";return {linked:c!=="none",managed:c==="old"||c==="new",installed_version:c==="old"?"2026-09-20-01":c==="new"?"2026-09-29-01":null,latest_version:"2026-09-29-01",latest_bytes:total,update_available:c==="old"};}
if(cmd==="client_download_check") return {needed_bytes:total,free_bytes:args.parent.startsWith("C")?210e9:20e9,version:"2026-09-29-01",dest:args.parent+"\\CoA Client"};
if(cmd==="client_plan"){await run("scan",12,0);return {version:"2026-09-29-01",items:[{path:"Data/patch-O.MPQ",size:2814983707,kind:"changed"},{path:"Data/patch-WB1.MPQ",size:2001890268,kind:"missing"},...(w.__modified?[{path:"d3d9.dll",size:4284430,kind:"modified"},{path:"Ascension.exe",size:7694848,kind:"modified"}]:[])],download_bytes:4829000000,total_files:200,up_to_date_files:196,kept_files:0};}
if(cmd==="client_sync"){await run("download",25,41e6);w.__client="new";return null;}
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==="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;}
if(cmd==="plugin:event|unlisten") return null;
throw new Error("unmocked "+cmd);
}
+59
View File
@@ -568,6 +568,65 @@ const de: Partial<Record<keyof typeof en, string>> = {
"comp.despawnCount": "Wie viele abmelden",
"comp.despawnHint": "Entlastet sofort: Jeder Bot online kostet Serverzeit. Sie bleiben gespeichert und kommen beim nächsten Start zurück, wenn die automatische Anmeldung an ist.",
"comp.despawnSomeDone": "{n} Begleiter abgemeldet. Sie bleiben gespeichert.",
// Server update button
"btn.update": "AKTUALISIEREN",
"btn.updating": "WIRD AKTUALISIERT …",
"btn.updateTo": "Auf {v} aktualisieren",
"overview.updateAvail": "Ein Server-Update ist verfügbar: {to} (du hast {from}).",
"overview.updateConflicts": "Einige Dateien wurden von dir geändert. Entscheide in den Einstellungen, was damit geschehen soll.",
"overview.openUpdates": "Updates öffnen",
"overview.updatingNote": "Update läuft: Der Server wird gestoppt, gesichert, aktualisiert und zur Prüfung erneut gestartet.",
"nav.updateDot": "Update verfügbar",
// Game client download and update
"btn.close": "Schließen",
"btn.setupClient": "Spielclient einrichten",
"btn.updateClient": "CLIENT AKTUALISIEREN",
"client.setup.title": "Spielclient einrichten",
"client.setup.intro": "Zum Spielen brauchst du den Spielclient. Nutze einen vorhandenen oder lass ihn vom Manager herunterladen.",
"client.setup.have": "Ich habe bereits einen Client",
"client.setup.download": "Client herunterladen",
"client.setup.downloadHint": "Etwa 43 GB",
"client.dl.pickParent": "Wähle, wohin der Spielclient soll",
"client.dl.confirmText": "Version {v}, {size}. Er wird in diesem Ordner gespeichert:",
"client.dl.free": "Freier Platz auf diesem Laufwerk: {free}.",
"client.dl.notEnough": "Nicht genug freier Platz: {need} nötig, {free} verfügbar. Wähle ein anderes Laufwerk.",
"client.dl.otherFolder": "Anderer Ordner …",
"client.dl.start": "Herunterladen",
"client.dl.back": "Zurück",
"client.dl.retry": "Erneut versuchen",
"client.dl.resume": "Fortsetzen",
"client.dl.cancel": "Anhalten",
"client.dl.cancelled": "Angehalten. Alles bereits Heruntergeladene bleibt erhalten; du kannst jederzeit fortsetzen.",
"client.dl.scanning": "Dateien werden verglichen …",
"client.dl.downloading": "Wird heruntergeladen",
"client.dl.progress": "{done} von {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "Der Spielclient ist bereit",
"client.dl.doneText": "Er ist mit diesem Server verknüpft. Du kannst auf PLAY drücken.",
"client.upd.title": "Client-Update",
"client.upd.available": "Ein neuerer Spielclient ist verfügbar: {v}.",
"client.upd.summary": "{n} Datei(en) zum Herunterladen, insgesamt {size}.",
"client.upd.upToDate": "Dein Client entspricht bereits Version {v}.",
"client.upd.modifiedTitle": "{n} Datei(en) hast du geändert",
"client.upd.modifiedText": "Zum Beispiel eine gepatchte Programmdatei. Behalte sie oder ersetze sie durch die offiziellen Versionen; deine werden dann im Ordner .coa-manager des Clients gesichert. Grafik-Wrapper (d3d9.dll und ähnliche) und Konfigurationsdateien bleiben immer unverändert.",
"client.upd.keep": "Von mir geänderte Dateien behalten",
"client.upd.more": "… und {n} weitere",
"client.upd.start": "Client aktualisieren",
"client.upd.later": "Jetzt nicht",
"client.upd.playAnyway": "Ohne Update spielen",
"client.upd.done": "Der Spielclient ist aktuell",
"client.upd.doneText": "Der Manager sagt dir Bescheid, wenn eine neuere Version erscheint.",
"client.track.title": "Client aktuell halten",
"client.track.text": "Der Manager vergleicht deinen Client einmal mit dem offiziellen und prüft danach auf neue Versionen, wie beim Server. Von dir geänderte Dateien werden nur ersetzt, wenn du es willst.",
"client.track.start": "Aktuell halten",
"client.track.startUpdate": "Aktualisieren und aktuell halten",
"client.track.button": "Diesen Client aktuell halten …",
"client.version": "Client-Version",
"client.versionUntracked": "vom Manager nicht verfolgt",
"client.versionUnfinished": "Download nicht abgeschlossen",
"client.downloadInstead": "Client herunterladen …",
};
export default de;
+59
View File
@@ -568,6 +568,65 @@ const en = {
"comp.despawnCount": "How many to log out",
"comp.despawnHint": "Eases the load right away: every online bot costs server time. They stay saved and return at the next start if automatic login is on.",
"comp.despawnSomeDone": "{n} companions logged out. They stay saved.",
// Server update button
"btn.update": "UPDATE",
"btn.updating": "UPDATING…",
"btn.updateTo": "Update to {v}",
"overview.updateAvail": "A server update is available: {to} (you have {from}).",
"overview.updateConflicts": "Some files were changed by you. Choose what to do with them in Settings.",
"overview.openUpdates": "Open updates",
"overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.",
"nav.updateDot": "Update available",
// Game client download and update
"btn.close": "Close",
"btn.setupClient": "Set up game client",
"btn.updateClient": "UPDATE CLIENT",
"client.setup.title": "Set up the game client",
"client.setup.intro": "To play you need the game client. Use one you already have, or let the Manager download it.",
"client.setup.have": "I already have a client",
"client.setup.download": "Download the client",
"client.setup.downloadHint": "About 43 GB",
"client.dl.pickParent": "Choose where to put the game client",
"client.dl.confirmText": "Version {v}, {size}. It will be saved in this folder:",
"client.dl.free": "Free space on that drive: {free}.",
"client.dl.notEnough": "Not enough free space: {need} needed, {free} available. Choose another drive.",
"client.dl.otherFolder": "Other folder…",
"client.dl.start": "Download",
"client.dl.back": "Back",
"client.dl.retry": "Try again",
"client.dl.resume": "Continue",
"client.dl.cancel": "Stop",
"client.dl.cancelled": "Stopped. Everything already downloaded is kept; continue whenever you like.",
"client.dl.scanning": "Comparing files…",
"client.dl.downloading": "Downloading",
"client.dl.progress": "{done} of {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "The game client is ready",
"client.dl.doneText": "It is linked to this server. You can press PLAY.",
"client.upd.title": "Client update",
"client.upd.available": "A newer game client is available: {v}.",
"client.upd.summary": "{n} file(s) to download, {size} in total.",
"client.upd.upToDate": "Your client already matches version {v}.",
"client.upd.modifiedTitle": "{n} file(s) were changed by you",
"client.upd.modifiedText": "For example a patched executable. Keep them, or replace them with the official versions; yours are then saved in the client’s .coa-manager folder. Graphics wrappers (d3d9.dll and the like) and config files are always left as they are.",
"client.upd.keep": "Keep the files I changed",
"client.upd.more": "… and {n} more",
"client.upd.start": "Update client",
"client.upd.later": "Not now",
"client.upd.playAnyway": "Play without updating",
"client.upd.done": "The game client is up to date",
"client.upd.doneText": "The Manager will tell you when a newer one is published.",
"client.track.title": "Keep the client up to date",
"client.track.text": "The Manager compares your client with the official one once, then checks for new versions like it does for the server. Files you changed are never replaced unless you say so.",
"client.track.start": "Keep up to date",
"client.track.startUpdate": "Update and keep up to date",
"client.track.button": "Keep this client up to date…",
"client.version": "Client version",
"client.versionUntracked": "not tracked by the Manager",
"client.versionUnfinished": "download not finished",
"client.downloadInstead": "Download a client…",
} as const;
export default en;
+59
View File
@@ -568,6 +568,65 @@ const es: Partial<Record<keyof typeof en, string>> = {
"comp.despawnCount": "Cuántos desconectar",
"comp.despawnHint": "Alivia la carga al instante: cada bot conectado cuesta tiempo de servidor. Quedan guardados y vuelven en el próximo inicio si el inicio de sesión automático está activado.",
"comp.despawnSomeDone": "{n} compañeros desconectados. Quedan guardados.",
// Server update button
"btn.update": "ACTUALIZAR",
"btn.updating": "ACTUALIZANDO…",
"btn.updateTo": "Actualizar a {v}",
"overview.updateAvail": "Hay una actualización del servidor: {to} (tienes {from}).",
"overview.updateConflicts": "Algunos archivos los cambiaste tú. Decide en Ajustes qué hacer con ellos.",
"overview.openUpdates": "Abrir actualizaciones",
"overview.updatingNote": "Actualizando: el servidor se detiene, se respalda, se actualiza y se inicia de nuevo para comprobar que funciona.",
"nav.updateDot": "Actualización disponible",
// Game client download and update
"btn.close": "Cerrar",
"btn.setupClient": "Configurar el cliente del juego",
"btn.updateClient": "ACTUALIZAR CLIENTE",
"client.setup.title": "Configurar el cliente del juego",
"client.setup.intro": "Para jugar necesitas el cliente del juego. Usa uno que ya tengas o deja que el Manager lo descargue.",
"client.setup.have": "Ya tengo un cliente",
"client.setup.download": "Descargar el cliente",
"client.setup.downloadHint": "Unos 43 GB",
"client.dl.pickParent": "Elige dónde guardar el cliente del juego",
"client.dl.confirmText": "Versión {v}, {size}. Se guardará en esta carpeta:",
"client.dl.free": "Espacio libre en esa unidad: {free}.",
"client.dl.notEnough": "No hay espacio suficiente: se necesitan {need} y hay {free}. Elige otra unidad.",
"client.dl.otherFolder": "Otra carpeta…",
"client.dl.start": "Descargar",
"client.dl.back": "Atrás",
"client.dl.retry": "Reintentar",
"client.dl.resume": "Continuar",
"client.dl.cancel": "Detener",
"client.dl.cancelled": "Detenido. Todo lo ya descargado se conserva; puedes continuar cuando quieras.",
"client.dl.scanning": "Comparando archivos…",
"client.dl.downloading": "Descargando",
"client.dl.progress": "{done} de {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "El cliente del juego está listo",
"client.dl.doneText": "Está vinculado a este servidor. Puedes pulsar PLAY.",
"client.upd.title": "Actualización del cliente",
"client.upd.available": "Hay un cliente del juego más reciente: {v}.",
"client.upd.summary": "{n} archivo(s) por descargar, {size} en total.",
"client.upd.upToDate": "Tu cliente ya coincide con la versión {v}.",
"client.upd.modifiedTitle": "{n} archivo(s) cambiado(s) por ti",
"client.upd.modifiedText": "Por ejemplo un ejecutable modificado. Consérvalos o reemplázalos por las versiones oficiales; los tuyos se guardan entonces en la carpeta .coa-manager del cliente. Los wrappers gráficos (d3d9.dll y similares) y los archivos de configuración se dejan siempre como están.",
"client.upd.keep": "Conservar los archivos que cambié",
"client.upd.more": "… y {n} más",
"client.upd.start": "Actualizar cliente",
"client.upd.later": "Ahora no",
"client.upd.playAnyway": "Jugar sin actualizar",
"client.upd.done": "El cliente del juego está actualizado",
"client.upd.doneText": "El Manager te avisará cuando se publique una más reciente.",
"client.track.title": "Mantener el cliente actualizado",
"client.track.text": "El Manager compara una vez tu cliente con el oficial y luego busca versiones nuevas como hace con el servidor. Los archivos que cambiaste solo se reemplazan si tú lo decides.",
"client.track.start": "Mantener actualizado",
"client.track.startUpdate": "Actualizar y mantener actualizado",
"client.track.button": "Mantener este cliente actualizado…",
"client.version": "Versión del cliente",
"client.versionUntracked": "el Manager no la sigue",
"client.versionUnfinished": "descarga sin terminar",
"client.downloadInstead": "Descargar un cliente…",
};
export default es;
+59
View File
@@ -568,6 +568,65 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"comp.despawnCount": "Combien déconnecter",
"comp.despawnHint": "Allège aussitôt la charge : chaque bot en ligne coûte du temps serveur. Ils restent enregistrés et reviennent au prochain démarrage si la connexion automatique est activée.",
"comp.despawnSomeDone": "{n} compagnons déconnectés. Ils restent enregistrés.",
// Server update button
"btn.update": "METTRE À JOUR",
"btn.updating": "MISE À JOUR…",
"btn.updateTo": "Mettre à jour vers {v}",
"overview.updateAvail": "Une mise à jour du serveur est disponible : {to} (vous avez {from}).",
"overview.updateConflicts": "Certains fichiers ont été modifiés par vous. Choisissez dans les Paramètres ce qu’il faut en faire.",
"overview.openUpdates": "Ouvrir les mises à jour",
"overview.updatingNote": "Mise à jour : le serveur est arrêté, sauvegardé, mis à jour puis relancé pour vérifier qu’il fonctionne.",
"nav.updateDot": "Mise à jour disponible",
// Game client download and update
"btn.close": "Fermer",
"btn.setupClient": "Configurer le client du jeu",
"btn.updateClient": "METTRE À JOUR LE CLIENT",
"client.setup.title": "Configurer le client du jeu",
"client.setup.intro": "Pour jouer, il faut le client du jeu. Utilisez-en un existant ou laissez le Manager le télécharger.",
"client.setup.have": "J’ai déjà un client",
"client.setup.download": "Télécharger le client",
"client.setup.downloadHint": "Environ 43 Go",
"client.dl.pickParent": "Choisissez où placer le client du jeu",
"client.dl.confirmText": "Version {v}, {size}. Il sera enregistré dans ce dossier :",
"client.dl.free": "Espace libre sur ce disque : {free}.",
"client.dl.notEnough": "Espace libre insuffisant : {need} nécessaires, {free} disponibles. Choisissez un autre disque.",
"client.dl.otherFolder": "Autre dossier…",
"client.dl.start": "Télécharger",
"client.dl.back": "Retour",
"client.dl.retry": "Réessayer",
"client.dl.resume": "Continuer",
"client.dl.cancel": "Arrêter",
"client.dl.cancelled": "Arrêté. Tout ce qui est déjà téléchargé est conservé ; vous pouvez reprendre à tout moment.",
"client.dl.scanning": "Comparaison des fichiers…",
"client.dl.downloading": "Téléchargement",
"client.dl.progress": "{done} sur {total}",
"client.dl.speed": "{speed}/s",
"client.dl.done": "Le client du jeu est prêt",
"client.dl.doneText": "Il est lié à ce serveur. Vous pouvez appuyer sur PLAY.",
"client.upd.title": "Mise à jour du client",
"client.upd.available": "Un client de jeu plus récent est disponible : {v}.",
"client.upd.summary": "{n} fichier(s) à télécharger, {size} au total.",
"client.upd.upToDate": "Votre client correspond déjà à la version {v}.",
"client.upd.modifiedTitle": "{n} fichier(s) modifié(s) par vous",
"client.upd.modifiedText": "Par exemple un exécutable modifié. Conservez-les ou remplacez-les par les versions officielles ; les vôtres sont alors sauvegardées dans le dossier .coa-manager du client. Les wrappers graphiques (d3d9.dll et similaires) et les fichiers de configuration restent toujours tels quels.",
"client.upd.keep": "Conserver les fichiers que j’ai modifiés",
"client.upd.more": "… et {n} de plus",
"client.upd.start": "Mettre à jour le client",
"client.upd.later": "Pas maintenant",
"client.upd.playAnyway": "Jouer sans mettre à jour",
"client.upd.done": "Le client du jeu est à jour",
"client.upd.doneText": "Le Manager vous préviendra quand une version plus récente sera publiée.",
"client.track.title": "Garder le client à jour",
"client.track.text": "Le Manager compare une fois votre client avec l’officiel, puis cherche les nouvelles versions comme pour le serveur. Les fichiers que vous avez modifiés ne sont remplacés que si vous le décidez.",
"client.track.start": "Garder à jour",
"client.track.startUpdate": "Mettre à jour et garder à jour",
"client.track.button": "Garder ce client à jour…",
"client.version": "Version du client",
"client.versionUntracked": "non suivi par le Manager",
"client.versionUnfinished": "téléchargement inachevé",
"client.downloadInstead": "Télécharger un client…",
};
export default fr;
+59
View File
@@ -568,6 +568,65 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"comp.despawnCount": "Сколько убрать",
"comp.despawnHint": "Сразу снижает нагрузку: каждый бот в сети отнимает время сервера. Они остаются сохранёнными и вернутся при следующем запуске, если включён автоматический вход.",
"comp.despawnSomeDone": "Убрано из игры компаньонов: {n}. Они остаются сохранёнными.",
// Server update button
"btn.update": "ОБНОВИТЬ",
"btn.updating": "ОБНОВЛЯЮ…",
"btn.updateTo": "Обновить до {v}",
"overview.updateAvail": "Доступно обновление сервера: {to} (сейчас {from}).",
"overview.updateConflicts": "Часть файлов изменена вами. Решите, что с ними делать, в Настройках.",
"overview.openUpdates": "Открыть обновления",
"overview.updatingNote": "Идёт обновление: сервер останавливается, сохраняется резервная копия, затем он обновляется и запускается снова для проверки.",
"nav.updateDot": "Есть обновление",
// Game client download and update
"btn.close": "Закрыть",
"btn.setupClient": "Настроить клиент игры",
"btn.updateClient": "ОБНОВИТЬ КЛИЕНТ",
"client.setup.title": "Настройка клиента игры",
"client.setup.intro": "Чтобы играть, нужен клиент игры. Выберите уже имеющийся или позвольте менеджеру скачать его.",
"client.setup.have": "У меня уже есть клиент",
"client.setup.download": "Скачать клиент",
"client.setup.downloadHint": "Примерно 43 ГБ",
"client.dl.pickParent": "Выберите, куда поместить клиент игры",
"client.dl.confirmText": "Версия {v}, {size}. Клиент будет сохранён в эту папку:",
"client.dl.free": "Свободно на этом диске: {free}.",
"client.dl.notEnough": "Недостаточно места: нужно {need}, доступно {free}. Выберите другой диск.",
"client.dl.otherFolder": "Другая папка…",
"client.dl.start": "Скачать",
"client.dl.back": "Назад",
"client.dl.retry": "Повторить",
"client.dl.resume": "Продолжить",
"client.dl.cancel": "Остановить",
"client.dl.cancelled": "Остановлено. Всё уже скачанное сохранено, можно продолжить в любой момент.",
"client.dl.scanning": "Сравниваю файлы…",
"client.dl.downloading": "Загрузка",
"client.dl.progress": "{done} из {total}",
"client.dl.speed": "{speed}/с",
"client.dl.done": "Клиент игры готов",
"client.dl.doneText": "Он привязан к этому серверу. Можно нажимать PLAY.",
"client.upd.title": "Обновление клиента",
"client.upd.available": "Доступна новая версия клиента игры: {v}.",
"client.upd.summary": "Файлов к загрузке: {n}, всего {size}.",
"client.upd.upToDate": "Ваш клиент уже соответствует версии {v}.",
"client.upd.modifiedTitle": "Файлов, изменённых вами: {n}",
"client.upd.modifiedText": "Например, изменённый exe. Оставьте их или замените официальными версиями; ваши тогда сохранятся в папке .coa-manager внутри клиента. Графические обёртки (d3d9.dll и подобные) и конфиги всегда остаются как есть.",
"client.upd.keep": "Оставить файлы, которые я менял",
"client.upd.more": "… и ещё {n}",
"client.upd.start": "Обновить клиент",
"client.upd.later": "Не сейчас",
"client.upd.playAnyway": "Играть без обновления",
"client.upd.done": "Клиент игры обновлён",
"client.upd.doneText": "Менеджер сообщит, когда выйдет новая версия.",
"client.track.title": "Обновление клиента через менеджер",
"client.track.text": "Менеджер один раз сравнит ваш клиент с официальным, а потом будет проверять новые версии, как для сервера. Файлы, которые вы меняли, не заменяются без вашего согласия.",
"client.track.start": "Следить за обновлениями",
"client.track.startUpdate": "Обновить и следить за обновлениями",
"client.track.button": "Обновлять этот клиент через менеджер…",
"client.version": "Версия клиента",
"client.versionUntracked": "менеджер не отслеживает",
"client.versionUnfinished": "загрузка не завершена",
"client.downloadInstead": "Скачать клиент…",
};
export default ru;
+39
View File
@@ -226,6 +226,39 @@ export interface ClientInfo {
other_addons: number;
}
export interface ClientStatus {
linked: boolean;
managed: boolean;
installed_version: string | null;
latest_version: string | null;
latest_bytes: number | null;
update_available: boolean;
}
export interface ClientPlan {
version: string;
items: { path: string; size: number; kind: "missing" | "changed" | "modified" }[];
download_bytes: number;
total_files: number;
up_to_date_files: number;
kept_files: number;
}
export interface ClientStep {
phase: "scan" | "download" | "finish";
done: number;
total: number;
bytes_per_sec: number;
file: string | null;
}
export interface ClientDownloadCheck {
needed_bytes: number;
free_bytes: number;
version: string;
dest: string;
}
export type FriendsMode = "local" | "lan" | "direct" | "private";
export interface FriendsStatus {
@@ -301,6 +334,12 @@ export const api = {
setClient: (id: string, path: string) => invoke<ClientInfo>("set_client", { id, path }),
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
installAddon: (id: string) => invoke<void>("client_install_addon", { id }),
clientStatus: (id: string) => invoke<ClientStatus>("client_status", { id }),
clientDownloadCheck: (parent: string) => invoke<ClientDownloadCheck>("client_download_check", { parent }),
clientPlan: (id: string) => invoke<ClientPlan>("client_plan", { id }),
clientSync: (id: string, keepModified: boolean) => invoke<void>("client_sync", { id, keepModified }),
clientDownload: (id: string, parent: string) => invoke<ClientInfo>("client_download", { id, parent }),
clientCancel: () => invoke<void>("client_cancel"),
play: (id: string) => invoke<DriverOutcome>("play", { id }),
friendsStatus: (id: string) => invoke<FriendsStatus>("friends_status", { id }),
friendsCheckInternet: () => invoke<InternetCheck>("friends_check_internet"),
+51
View File
@@ -0,0 +1,51 @@
import { useSyncExternalStore } from "react";
import { api, type ClientStatus } from "@/lib/api";
/**
* Game client status for the main screen: which client is linked and, for a client the Manager keeps up to date,
* whether a newer one has been published. Checked at start and every five minutes (one small request; no game file is read).
*/
interface State {
status: ClientStatus | null;
checking: boolean;
}
const EMPTY: State = { status: null, checking: false };
const states = new Map<string, State>();
const listeners = new Set<() => void>();
const CHECK_EVERY_MS = 5 * 60 * 1000;
const get = (id: string) => states.get(id) ?? EMPTY;
function set(id: string, next: Partial<State>) {
states.set(id, { ...get(id), ...next });
listeners.forEach((l) => l());
}
export async function checkClient(id: string): Promise<void> {
if (get(id).checking) return;
set(id, { checking: true });
try {
set(id, { status: await api.clientStatus(id) });
} catch {
// offline: keep what we knew
} finally {
set(id, { checking: false });
}
}
/** Check now and then every five minutes. Returns the function that stops it. */
export function startClientPolling(id: string): () => void {
void checkClient(id);
const t = setInterval(() => void checkClient(id), CHECK_EVERY_MS);
return () => clearInterval(t);
}
export function useClientStatus(id: string): State {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => listeners.delete(l);
},
() => get(id),
);
}
+84
View File
@@ -0,0 +1,84 @@
import { useSyncExternalStore } from "react";
import { listen } from "@tauri-apps/api/event";
import { api, asUiError, type UpdatePreview } from "@/lib/api";
/**
* Server update status for the main screen and the navigation: checked when the app starts and every five minutes,
* and applied from the main button when nothing needs a decision (files the owner changed are decided in Settings).
*/
export interface ServerUpdateState {
preview: UpdatePreview | null;
available: boolean;
checking: boolean;
applying: boolean;
step: string | null;
percent: number;
error: string | null;
}
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null };
const states = new Map<string, ServerUpdateState>();
const listeners = new Set<() => void>();
export const CHECK_EVERY_MS = 5 * 60 * 1000;
const get = (id: string) => states.get(id) ?? EMPTY;
function set(id: string, next: Partial<ServerUpdateState>) {
states.set(id, { ...get(id), ...next });
listeners.forEach((l) => l());
}
export async function checkServerUpdate(id: string): Promise<void> {
const cur = get(id);
if (cur.applying || cur.checking) return;
set(id, { checking: true });
try {
const p = await api.checkUpdate(id);
set(id, { preview: p, available: p.to_version !== (p.from_version ?? ""), error: null });
} catch (e) {
// offline or no package published: keep what we knew and stay quiet
set(id, { error: asUiError(e).human.code });
} finally {
set(id, { checking: false });
}
}
/** Check now and then every five minutes. Returns the function that stops it. */
export function startServerUpdatePolling(id: string): () => void {
void checkServerUpdate(id);
const t = setInterval(() => void checkServerUpdate(id), CHECK_EVERY_MS);
return () => clearInterval(t);
}
/** Apply the pending update when no file needs a decision. Resolves true on success. */
export async function applyServerUpdate(id: string): Promise<boolean> {
const p = get(id).preview;
if (!p || p.conflicts.length > 0 || get(id).applying) return false;
set(id, { applying: true, step: null, percent: 0, error: null });
let un: (() => void) | undefined;
try {
un = await listen<{ step: string; percent: number }>("update-progress", (e) => set(id, { step: e.payload.step, percent: e.payload.percent }));
} catch {
/* progress is optional */
}
try {
await api.applyUpdate(id, {});
return true;
} catch (e) {
set(id, { error: asUiError(e).human.code });
return false;
} finally {
un?.();
set(id, { applying: false });
void checkServerUpdate(id);
}
}
export function useServerUpdate(id: string): ServerUpdateState {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => listeners.delete(l);
},
() => get(id),
);
}
+12
View File
@@ -5,6 +5,18 @@ export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
/** 1536 -> "1.5 KB"; 43.2e9 -> "40.2 GB" (binary units, as drive sizes are shown). */
export function formatBytes(n: number): string {
const units = ["B", "KB", "MB", "GB", "TB"];
let v = Math.max(0, n);
let i = 0;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${i === 0 || v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
}
export function formatUptime(secs: number | null | undefined): string {
if (secs == null) return "—";
const d = Math.floor(secs / 86400);
+35 -3
View File
@@ -1,6 +1,8 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api";
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
import { checkClient } from "@/lib/clientUpdate";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { useHuman, useT } from "@/i18n";
@@ -12,8 +14,13 @@ export function ClientCard({ serverId }: { serverId: string }) {
const [error, setError] = useState<UiError | null>(null);
const [note, setNote] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<ClientStatus | null>(null);
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
const refresh = () => api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
const refresh = () => {
void api.clientStatus(serverId).then(setStatus).catch(() => setStatus(null));
return api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
};
useEffect(() => {
void refresh();
}, [serverId]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -48,7 +55,7 @@ export function ClientCard({ serverId }: { serverId: string }) {
{info === null && (
<>
<p className="mt-1 text-sm text-muted">{t("client.intro")}</p>
<Button className="mt-4" onClick={() => void choose()} disabled={busy}>{t("client.chooseFolder")}</Button>
<Button className="mt-4" onClick={() => setDialog("setup")} disabled={busy}>{t("btn.setupClient")}</Button>
</>
)}
{info && (
@@ -60,6 +67,13 @@ export function ClientCard({ serverId }: { serverId: string }) {
{hosts.length ? hosts.filter(Boolean).join(", ") : "—"}
{pointsLocal ? <span className="ml-2 text-ok">{t("client.thisComputer")}</span> : <span className="ml-2 text-warn">{t("client.notThisServer")}</span>}
</dd>
<dt className="text-muted">{t("client.version")}</dt>
<dd>
{status?.managed
? status.installed_version ?? t("client.versionUnfinished")
: t("client.versionUntracked")}
{status?.update_available && <span className="ml-2 text-warn">{t("client.updateAvailable")}</span>}
</dd>
<dt className="text-muted">{t("client.addon")}</dt>
<dd>
{info.addon.installed ? (info.addon.version ? t("client.installedVersion", { v: info.addon.version }) : t("client.installed")) : t("client.addonNotInstalled")}
@@ -79,12 +93,30 @@ export function ClientCard({ serverId }: { serverId: string }) {
{info.addon.installed ? t("client.updateAddon") : t("client.installAddon")}
</Button>
)}
{status?.update_available && (
<Button size="sm" variant="primary" disabled={busy} onClick={() => setDialog("update")}>{t("client.upd.start")}</Button>
)}
{status && !status.managed && (
<Button size="sm" disabled={busy} onClick={() => setDialog("track")}>{t("client.track.button")}</Button>
)}
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>{t("client.changeFolder")}</Button>
<Button size="sm" variant="ghost" disabled={busy} onClick={() => setDialog("setup")}>{t("client.downloadInstead")}</Button>
</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>}
{dialog && (
<ClientDialog
serverId={serverId}
mode={dialog}
onClose={() => setDialog(null)}
onChanged={() => {
void refresh();
void checkClient(serverId);
}}
/>
)}
</Card>
);
}
+299
View File
@@ -0,0 +1,299 @@
import { useEffect, useRef, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { listen } from "@tauri-apps/api/event";
import { Check, Loader2 } from "lucide-react";
import { api, asUiError, type ClientDownloadCheck, type ClientPlan, type ClientStep, 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 } from "@/i18n";
/**
* - setup: no client linked yet: pick an existing folder or download the client.
* - update: a client the Manager keeps up to date has a newer version.
* - track: an existing client the Manager has not looked at yet: compare it once, then keep it up to date.
*/
export type ClientDialogMode = "setup" | "update" | "track";
type Phase = "choose" | "confirm" | "scanning" | "preview" | "working" | "done" | "stopped" | "failed";
export function ClientDialog(props: {
serverId: string;
mode: ClientDialogMode;
onClose: () => void;
/** The linked client or its version changed; the caller refreshes what it shows. */
onChanged: () => void;
/** Update mode only: start the game without updating. */
onPlayAnyway?: () => void;
}) {
const t = useT();
const human = useHuman();
const { serverId, mode } = props;
const [phase, setPhase] = useState<Phase>(mode === "setup" ? "choose" : "scanning");
const [step, setStep] = useState<ClientStep | null>(null);
const [parent, setParent] = useState<string | null>(null);
const [check, setCheck] = useState<ClientDownloadCheck | null>(null);
const [plan, setPlan] = useState<ClientPlan | null>(null);
const [keep, setKeep] = useState(true);
const [error, setError] = useState<UiError | null>(null);
const cancelled = useRef(false);
const working = phase === "scanning" || phase === "working";
useEffect(() => {
let un: (() => void) | undefined;
let gone = false;
listen<ClientStep>("client-progress", (e) => setStep(e.payload))
.then((u) => (gone ? u() : (un = u)))
.catch(() => undefined);
return () => {
gone = true;
un?.();
};
}, []);
useEffect(() => {
if (mode !== "setup") void startPlan();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" && !working) close();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
});
function close() {
props.onChanged();
props.onClose();
}
function fail(e: unknown) {
if (cancelled.current) {
setPhase("stopped");
} else {
setError(asUiError(e));
setPhase("failed");
}
}
async function useExisting() {
const picked = await open({ directory: true, multiple: false, title: t("client.dialogTitle") });
if (typeof picked !== "string") return;
setError(null);
try {
await api.setClient(serverId, picked);
setPhase("done");
} catch (e) {
setError(asUiError(e));
setPhase("failed");
}
}
async function pickParent() {
const picked = await open({ directory: true, multiple: false, title: t("client.dl.pickParent") });
if (typeof picked !== "string") return;
setError(null);
try {
setCheck(await api.clientDownloadCheck(picked));
setParent(picked);
setPhase("confirm");
} catch (e) {
setError(asUiError(e));
setPhase("failed");
}
}
async function startDownload() {
if (!parent) return;
cancelled.current = false;
setStep(null);
setPhase("working");
try {
await api.clientDownload(serverId, parent);
setPhase("done");
} catch (e) {
fail(e);
}
}
async function startPlan() {
cancelled.current = false;
setStep(null);
setError(null);
setPhase("scanning");
try {
const p = await api.clientPlan(serverId);
setPlan(p);
setKeep(p.items.some((i) => i.kind === "modified"));
setPhase("preview");
} catch (e) {
fail(e);
}
}
async function startSync() {
cancelled.current = false;
setStep(null);
setPhase("working");
try {
await api.clientSync(serverId, keep);
setPhase("done");
} catch (e) {
fail(e);
}
}
function stop() {
cancelled.current = true;
void api.clientCancel();
}
const modified = plan?.items.filter((i) => i.kind === "modified") ?? [];
const pct = step && step.total > 0 ? Math.min(100, Math.floor((step.done / step.total) * 100)) : 0;
const title = mode === "setup" ? t("client.setup.title") : mode === "update" ? t("client.upd.title") : t("client.track.title");
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6" role="presentation">
<Card className="max-h-full w-full max-w-lg overflow-y-auto p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={title}>
<h2 className="text-lg font-semibold">{title}</h2>
{phase === "choose" && (
<>
<p className="mt-1 text-sm text-muted">{t("client.setup.intro")}</p>
<div className="mt-4 grid gap-3">
<button type="button" onClick={() => void useExisting()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
<span className="block font-medium">{t("client.setup.have")}</span>
</button>
<button type="button" onClick={() => void pickParent()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
<span className="block font-medium">{t("client.setup.download")}</span>
<span className="mt-1 block text-sm text-muted">{t("client.setup.downloadHint")}</span>
</button>
</div>
<div className="mt-5 flex justify-end">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
</div>
</>
)}
{phase === "confirm" && check && (
<>
<p className="mt-1 text-sm text-muted">{t("client.dl.confirmText", { v: check.version, size: formatBytes(check.needed_bytes) })}</p>
<p className="selectable mt-3 break-all rounded-md bg-black/30 px-3 py-2 text-sm">{check.dest}</p>
<p className={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024 ? "mt-3 text-sm text-bad" : "mt-3 text-sm text-muted"}>
{check.free_bytes < check.needed_bytes + 512 * 1024 * 1024
? t("client.dl.notEnough", { need: formatBytes(check.needed_bytes), free: formatBytes(check.free_bytes) })
: t("client.dl.free", { free: formatBytes(check.free_bytes) })}
</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={() => void pickParent()}>{t("client.dl.otherFolder")}</Button>
<Button variant="primary" disabled={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024} onClick={() => void startDownload()}>
{t("client.dl.start")}
</Button>
</div>
</>
)}
{(phase === "scanning" || phase === "working") && (
<div className="mt-4" role="status">
<div className="flex items-center gap-2 text-sm">
<Loader2 className="h-4 w-4 animate-spin text-gold" aria-hidden />
<span>{phase === "scanning" || step?.phase === "scan" ? t("client.dl.scanning") : t("client.dl.downloading")}</span>
<span className="ml-auto text-muted">{pct}%</span>
</div>
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${pct}%` }} />
</div>
<div className="mt-2 flex justify-between gap-4 text-xs text-muted">
<span className="min-w-0 truncate">{step?.file ?? ""}</span>
<span className="shrink-0">
{step ? t("client.dl.progress", { done: formatBytes(step.done), total: formatBytes(step.total) }) : ""}
{step && step.phase === "download" && step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(step.bytes_per_sec) })}` : ""}
</span>
</div>
<div className="mt-5 flex justify-end">
<Button variant="ghost" onClick={stop}>{t("client.dl.cancel")}</Button>
</div>
</div>
)}
{phase === "preview" && plan && (
<>
{plan.items.length === 0 ? (
<p className="mt-2 text-sm">{t("client.upd.upToDate", { v: plan.version })}</p>
) : (
<>
{mode === "update" && <p className="mt-2 text-sm">{t("client.upd.available", { v: plan.version })}</p>}
<p className="mt-1 text-sm text-muted">{t("client.upd.summary", { n: plan.items.length, size: formatBytes(plan.download_bytes) })}</p>
</>
)}
{mode === "track" && <p className="mt-3 text-sm text-muted">{t("client.track.text")}</p>}
{modified.length > 0 && (
<div className="mt-4 rounded-md border border-warn/40 bg-warn/5 p-3 text-sm">
<p className="font-medium">{t("client.upd.modifiedTitle", { n: modified.length })}</p>
<p className="mt-1 text-muted">{t("client.upd.modifiedText")}</p>
<ul className="selectable mt-2 space-y-0.5 text-xs text-muted">
{modified.slice(0, 8).map((i) => (
<li key={i.path} className="truncate">{i.path}</li>
))}
{modified.length > 8 && <li>{t("client.upd.more", { n: modified.length - 8 })}</li>}
</ul>
<label className="mt-3 flex cursor-pointer items-center gap-2">
<input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
<span>{t("client.upd.keep")}</span>
</label>
</div>
)}
<div className="mt-5 flex flex-wrap justify-end gap-2">
{mode === "update" && props.onPlayAnyway && (
<Button variant="ghost" onClick={() => { close(); props.onPlayAnyway?.(); }}>{t("client.upd.playAnyway")}</Button>
)}
<Button variant="ghost" onClick={close}>{t("client.upd.later")}</Button>
<Button variant="primary" onClick={() => void startSync()}>
{mode === "track" ? (plan.items.length === 0 ? t("client.track.start") : t("client.track.startUpdate")) : t("client.upd.start")}
</Button>
</div>
</>
)}
{phase === "done" && (
<>
<div className="mt-4 flex items-center gap-3">
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-ok/15 text-ok"><Check className="h-5 w-5" aria-hidden /></span>
<div>
<p className="font-medium">{mode === "setup" ? t("client.dl.done") : t("client.upd.done")}</p>
<p className="text-sm text-muted">{mode === "setup" ? t("client.dl.doneText") : t("client.upd.doneText")}</p>
</div>
</div>
<div className="mt-5 flex justify-end">
<Button variant="primary" onClick={close}>{t("btn.close")}</Button>
</div>
</>
)}
{phase === "stopped" && (
<>
<p className="mt-3 text-sm text-muted">{t("client.dl.cancelled")}</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
{mode === "setup" ? (
parent && <Button variant="primary" onClick={() => void startDownload()}>{t("client.dl.resume")}</Button>
) : (
<Button variant="primary" onClick={() => void startPlan()}>{t("client.dl.resume")}</Button>
)}
</div>
</>
)}
{phase === "failed" && error && (
<>
<p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>
<div className="mt-5 flex justify-end gap-2">
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
{mode === "setup" ? <Button onClick={() => { setError(null); setPhase("choose"); }}>{t("client.dl.back")}</Button> : <Button onClick={() => void startPlan()}>{t("client.dl.retry")}</Button>}
</div>
</>
)}
</Card>
</div>
);
}
+68 -5
View File
@@ -3,6 +3,9 @@ import { Loader2 } from "lucide-react";
import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
import { cn, formatUptime } from "@/lib/utils";
import { useHuman, useT } from "@/i18n";
import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate";
import { checkClient, useClientStatus } from "@/lib/clientUpdate";
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -58,7 +61,7 @@ function Row({ label, s }: { label: string; s: ServiceStatus }) {
);
}
export function Overview({ server, onForget }: { server: ServerSummary; onForget: () => Promise<void> }) {
export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSummary; onForget: () => Promise<void>; onOpenUpdates: () => void }) {
const t = useT();
const human = useHuman();
const [status, setStatus] = useState<StatusView | null>(null);
@@ -66,9 +69,13 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
const [failure, setFailure] = useState<Failure | null>(null);
const [showDetails, setShowDetails] = useState(false);
const [pop, setPop] = useState<Population | null>(null);
const [client, setClient] = useState<ClientInfo | null>(null);
const [client, setClient] = useState<ClientInfo | null | undefined>(undefined);
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
const clientStatus = useClientStatus(server.id).status;
const [playing, setPlaying] = useState(false);
const [perf, setPerf] = useState<Performance | null>(null);
const upd = useServerUpdate(server.id);
const needsDecision = (upd.preview?.conflicts.length ?? 0) > 0;
const [startBots, setStartBots] = useState<number | null | undefined>(undefined);
useEffect(() => {
@@ -236,6 +243,17 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{t("btn.stop")}
</Button>
) : upd.available ? (
<Button
variant="primary"
size="xl"
disabled={transitioning || upd.applying}
onClick={() => (needsDecision ? onOpenUpdates() : void applyServerUpdate(server.id))}
className="min-w-56"
>
{upd.applying && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{upd.applying ? t("btn.updating") : needsDecision ? t("overview.openUpdates") : t("btn.update")}
</Button>
) : (
<Button variant="primary" size="xl" disabled={transitioning} onClick={() => run("starting")} className="min-w-56">
{transitioning && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
@@ -243,25 +261,57 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
</Button>
)}
{running && (
<Button variant="ghost" size="sm" disabled={transitioning} onClick={() => run("restarting")}>
<Button variant="ghost" size="sm" disabled={transitioning || upd.applying} onClick={() => run("restarting")}>
{t("btn.restart")}
</Button>
)}
{running && upd.available && (
<Button variant="secondary" size="sm" disabled={transitioning || upd.applying} onClick={() => (needsDecision ? onOpenUpdates() : void applyServerUpdate(server.id))}>
{upd.applying && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{needsDecision ? t("overview.openUpdates") : t("btn.updateTo", { v: upd.preview?.to_version ?? "" })}
</Button>
)}
{anyUp && !running && (
<Button variant="ghost" size="sm" disabled={transitioning} onClick={() => run("stopping")}>
{t("btn.stopSmall")}
</Button>
)}
{client && (
{client && clientStatus?.update_available ? (
<Button variant="primary" size="xl" disabled={playing} onClick={() => setDialog("update")} className="ml-auto min-w-40">
{t("btn.updateClient")}
</Button>
) : client ? (
<Button variant={running ? "primary" : "secondary"} size="xl" disabled={transitioning || playing} onClick={() => void play()} className="ml-auto min-w-40">
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
{running ? t("btn.play") : t("btn.startPlay")}
</Button>
)}
) : client === null ? (
<Button variant="secondary" size="xl" onClick={() => setDialog("setup")} className="ml-auto min-w-40">
{t("btn.setupClient")}
</Button>
) : null}
</div>
{anyUp && !running && !transitioning && (
<p className="mt-3 text-sm text-muted">{t("overview.partial")}</p>
)}
{upd.available && upd.preview && (
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
{needsDecision && <p className="mt-1 text-muted">{t("overview.updateConflicts")}</p>}
{upd.applying && (
<div className="mt-2">
<p className="text-muted" role="status">{t("overview.updatingNote")}</p>
<div className="mt-2 flex justify-between text-xs">
<span>{upd.step ?? ""}</span>
<span className="text-muted">{upd.percent}%</span>
</div>
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={upd.percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${upd.percent}%` }} />
</div>
</div>
)}
</div>
)}
</Card>
{conflict && !anyUp && (
@@ -292,6 +342,19 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
)}
</Card>
)}
{dialog && (
<ClientDialog
serverId={server.id}
mode={dialog}
onClose={() => setDialog(null)}
onChanged={() => {
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
void checkClient(server.id);
}}
onPlayAnyway={() => void play()}
/>
)}
</div>
);
}
+18 -2
View File
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { Archive, Bot, Gauge, Globe, Server, Settings, Terminal, Users, type LucideIcon } from "lucide-react";
import { type ServerSummary } from "@/lib/api";
import { useT, type Key } from "@/i18n";
@@ -13,6 +13,8 @@ import { SettingsHome } from "@/screens/SettingsHome";
import { FriendsPage } from "@/screens/FriendsPage";
import { ConsolePage } from "@/screens/ConsolePage";
import { Button } from "@/components/ui/button";
import { startServerUpdatePolling, useServerUpdate } from "@/lib/serverUpdate";
import { startClientPolling } from "@/lib/clientUpdate";
type Page = "overview" | "bots" | "server" | "players" | "friends" | "backups" | "console" | "settings";
@@ -38,6 +40,17 @@ export function Shell(props: {
const [page, setPage] = useState<Page>("overview");
const server = props.servers.find((s) => s.id === props.activeId)!;
const current = NAV.find((n) => n.id === page)!;
const update = useServerUpdate(props.activeId);
// Look for a server and a game client update when the app starts and then every five minutes.
useEffect(() => {
const stopServer = startServerUpdatePolling(props.activeId);
const stopClient = startClientPolling(props.activeId);
return () => {
stopServer();
stopClient();
};
}, [props.activeId]);
return (
<div className="flex h-full">
@@ -59,6 +72,9 @@ export function Shell(props: {
>
<Icon className={cn("h-[18px] w-[18px]", page === id && "text-gold")} aria-hidden />
{t(label)}
{id === "settings" && update.available && (
<span className="ml-auto h-2 w-2 rounded-full bg-gold" role="img" aria-label={t("nav.updateDot")} title={t("nav.updateDot")} />
)}
</button>
</li>
))}
@@ -87,7 +103,7 @@ export function Shell(props: {
<main className="h-full flex-1 overflow-y-auto px-10 py-8">
{page === "overview" ? (
<Overview key={server.id} server={server} onForget={() => props.onForget(server.id)} />
<Overview key={server.id} server={server} onForget={() => props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} />
) : page === "bots" || page === "server" ? (
<SettingsPage key={`${server.id}-${page}`} serverId={server.id} scope={page} title={t(current.label)} question={t(current.question)} />
) : page === "console" ? (