mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 11:25:56 +00:00
Phase 8: game client integration (read-only detection, backed-up realmlist change, isolated addon install, START & PLAY)
Verified in the native UI with a stub client: realmlist pointed and backed up, addon installed without touching other addons, START & PLAY starts the server, waits for ready, then launches the client. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7b1942e6a1
commit
d85050ff95
8 files changed
+505
-2
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
fn main() {
|
||||||
|
let p = std::env::args().nth(1).expect("client folder");
|
||||||
|
println!("{}", serde_json::to_string_pretty(&coa_core::client::detect(std::path::Path::new(&p), None)).unwrap());
|
||||||
|
}
|
||||||
@@ -0,0 +1,301 @@
|
|||||||
|
//! The game client is a separate object: detected read-only, and touched only in two narrow ways -
|
||||||
|
//! `realmlist.wtf` (backed up first) and the `Interface/AddOns/CoABotUI` folder (backed up when it differs).
|
||||||
|
//! WTF, Cache, other addons and the executable are never modified.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::fsx;
|
||||||
|
|
||||||
|
pub const ADDON_NAME: &str = "CoABotUI";
|
||||||
|
const EXECUTABLES: [&str; 3] = ["Ascension.exe", "Wow.exe", "WoW.exe"];
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct Realmlist {
|
||||||
|
pub path: String,
|
||||||
|
pub host: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct AddonState {
|
||||||
|
pub installed: bool,
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// Some(true) when the installed files equal the package's; None when there is no package to compare with.
|
||||||
|
pub up_to_date: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ClientInfo {
|
||||||
|
pub path: String,
|
||||||
|
pub executable: String,
|
||||||
|
pub realmlists: Vec<Realmlist>,
|
||||||
|
pub addon: AddonState,
|
||||||
|
pub other_addons: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_exe(dir: &Path) -> Option<&'static str> {
|
||||||
|
EXECUTABLES.iter().copied().find(|e| dir.join(e).is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Data/<locale>/realmlist.wtf` files (a client may have several locales).
|
||||||
|
pub fn realmlist_files(client: &Path) -> Vec<PathBuf> {
|
||||||
|
let mut v: Vec<PathBuf> = fs::read_dir(client.join("Data"))
|
||||||
|
.map(|rd| rd.flatten().map(|e| e.path().join("realmlist.wtf")).filter(|p| p.is_file()).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
v.sort();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_host(text: &str) -> Option<String> {
|
||||||
|
text.lines().find_map(|l| {
|
||||||
|
let l = l.trim();
|
||||||
|
let rest = l.get(..3).filter(|p| p.eq_ignore_ascii_case("set")).and_then(|_| l[3..].trim_start().get(..9).filter(|w| w.eq_ignore_ascii_case("realmlist")).map(|_| l[3..].trim_start()[9..].trim()))?;
|
||||||
|
Some(rest.trim_matches('"').to_string())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn toc_version(toc: &Path) -> Option<String> {
|
||||||
|
fs::read_to_string(toc).ok()?.lines().find_map(|l| l.strip_prefix("## Version:").map(|v| v.trim().to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree_hashes(dir: &Path) -> BTreeMap<String, String> {
|
||||||
|
fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, String>) {
|
||||||
|
let Ok(rd) = fs::read_dir(dir) else { return };
|
||||||
|
for e in rd.flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(root, &p, out);
|
||||||
|
} else if let (Ok(rel), Ok(h)) = (p.strip_prefix(root), fsx::sha256_file(&p)) {
|
||||||
|
out.insert(rel.to_string_lossy().replace('\\', "/"), h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
walk(dir, dir, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a server package ships the addon, relative to the server folder.
|
||||||
|
pub fn addon_source(server_root: &Path) -> Option<PathBuf> {
|
||||||
|
let p = server_root.join("Extras").join(ADDON_NAME);
|
||||||
|
p.join(format!("{ADDON_NAME}.toc")).is_file().then_some(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn addon_state(client: &Path, source: Option<&Path>) -> AddonState {
|
||||||
|
let dir = client.join("Interface/AddOns").join(ADDON_NAME);
|
||||||
|
let toc = dir.join(format!("{ADDON_NAME}.toc"));
|
||||||
|
let installed = toc.is_file();
|
||||||
|
AddonState {
|
||||||
|
installed,
|
||||||
|
version: installed.then(|| toc_version(&toc)).flatten(),
|
||||||
|
up_to_date: source.filter(|_| installed).map(|s| {
|
||||||
|
let (want, have) = (tree_hashes(s), tree_hashes(&dir));
|
||||||
|
want.iter().all(|(k, v)| have.get(k) == Some(v))
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read-only look at a folder; None if it is not a game client.
|
||||||
|
pub fn detect(path: &Path, addon_package: Option<&Path>) -> Option<ClientInfo> {
|
||||||
|
if !path.join("Data").is_dir() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let exe = find_exe(path)?;
|
||||||
|
let realmlists = realmlist_files(path)
|
||||||
|
.into_iter()
|
||||||
|
.map(|p| Realmlist { host: fs::read_to_string(&p).ok().and_then(|t| parse_host(&t)), path: p.to_string_lossy().into_owned() })
|
||||||
|
.collect();
|
||||||
|
let other = fs::read_dir(path.join("Interface/AddOns")).map(|rd| rd.flatten().filter(|e| e.path().is_dir() && e.file_name() != ADDON_NAME).count()).unwrap_or(0);
|
||||||
|
Some(ClientInfo { path: path.to_string_lossy().into_owned(), executable: exe.into(), realmlists, addon: addon_state(path, addon_package), other_addons: other })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backup_dir(meta: &Path) -> PathBuf {
|
||||||
|
meta.join("backups").join("client")
|
||||||
|
}
|
||||||
|
|
||||||
|
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('-')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Point every locale's realmlist at `host`. Each changed file is copied to the backup folder first.
|
||||||
|
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();
|
||||||
|
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)?;
|
||||||
|
let text = String::from_utf8(old.clone()).map_err(|_| Error::Invalid("realmlist.wtf is not text".into()))?;
|
||||||
|
if parse_host(&text).as_deref() == Some(host) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||||
|
let mut replaced = false;
|
||||||
|
let mut lines: Vec<String> = text
|
||||||
|
.lines()
|
||||||
|
.map(|l| {
|
||||||
|
if !replaced && parse_host(l).is_some() {
|
||||||
|
replaced = true;
|
||||||
|
format!("set realmlist {host}")
|
||||||
|
} else {
|
||||||
|
l.to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if !replaced {
|
||||||
|
lines.push(format!("set realmlist {host}"));
|
||||||
|
}
|
||||||
|
let new = lines.join(eol) + eol;
|
||||||
|
let locale = file.parent().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||||
|
let saved = backup_dir(meta).join(format!("realmlist-{locale}-{stamp}.wtf"));
|
||||||
|
fsx::atomic_write(&saved, &old)?;
|
||||||
|
fsx::atomic_write(&file, new.as_bytes())?;
|
||||||
|
changed.push(file.to_string_lossy().into_owned());
|
||||||
|
}
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy the addon into the client. If a different version is there, that one folder is backed up first;
|
||||||
|
/// files in it that the package does not contain are left alone.
|
||||||
|
pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
|
||||||
|
if !source.join(format!("{ADDON_NAME}.toc")).is_file() {
|
||||||
|
return Err(Error::Invalid("The addon package is incomplete.".into()));
|
||||||
|
}
|
||||||
|
let dest = fsx::ensure_within(client, &client.join("Interface/AddOns").join(ADDON_NAME))?;
|
||||||
|
let want = tree_hashes(source);
|
||||||
|
if dest.is_dir() {
|
||||||
|
let have = tree_hashes(&dest);
|
||||||
|
if want.iter().all(|(k, v)| have.get(k) == Some(v)) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let keep = backup_dir(meta).join(format!("{ADDON_NAME}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S")));
|
||||||
|
for (rel, _) in &have {
|
||||||
|
let to = fsx::safe_join(&keep, rel)?;
|
||||||
|
fs::create_dir_all(to.parent().unwrap())?;
|
||||||
|
fs::copy(fsx::safe_join(&dest, rel)?, to)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for rel in want.keys() {
|
||||||
|
let target = fsx::safe_join(&dest, rel)?;
|
||||||
|
fsx::atomic_write(&target, &fs::read(fsx::safe_join(source, rel)?)?)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the game client. The caller is responsible for making sure the server is ready first.
|
||||||
|
pub fn launch(client: &Path) -> Result<u32> {
|
||||||
|
let exe = find_exe(client).ok_or_else(|| Error::Invalid("The game client was not found.".into()))?;
|
||||||
|
let child = Command::new(client.join(exe)).current_dir(client).spawn()?;
|
||||||
|
Ok(child.id())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn fake_client(d: &Path) -> PathBuf {
|
||||||
|
let c = d.join("wow");
|
||||||
|
fs::create_dir_all(c.join("Data/enUS")).unwrap();
|
||||||
|
fs::create_dir_all(c.join("Data/ruRU")).unwrap();
|
||||||
|
fs::create_dir_all(c.join("Interface/AddOns/ElvUI")).unwrap();
|
||||||
|
fs::create_dir_all(c.join("WTF")).unwrap();
|
||||||
|
fs::write(c.join("Ascension.exe"), b"exe").unwrap();
|
||||||
|
fs::write(c.join("Data/enUS/realmlist.wtf"), "set realmlist old.example.com\r\nset patchlist x\r\n").unwrap();
|
||||||
|
fs::write(c.join("Data/ruRU/realmlist.wtf"), "set realmlist 127.0.0.1\n").unwrap();
|
||||||
|
fs::write(c.join("WTF/Config.wtf"), "SET x 1").unwrap();
|
||||||
|
fs::write(c.join("Interface/AddOns/ElvUI/ElvUI.toc"), "## Title: Elv").unwrap();
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
fn package(d: &Path, version: &str) -> PathBuf {
|
||||||
|
let p = d.join("pkg").join(ADDON_NAME);
|
||||||
|
fs::create_dir_all(&p).unwrap();
|
||||||
|
fs::write(p.join("CoABotUI.toc"), format!("## Version: {version}\nCoABotUI.lua\n")).unwrap();
|
||||||
|
fs::write(p.join("CoABotUI.lua"), format!("-- v{version}")).unwrap();
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
fn snapshot(root: &Path) -> BTreeMap<String, String> {
|
||||||
|
tree_hashes(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_only_real_clients_and_reads_realmlists() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = fake_client(d.path());
|
||||||
|
let info = detect(&c, None).unwrap();
|
||||||
|
assert_eq!(info.executable, "Ascension.exe");
|
||||||
|
assert_eq!(info.realmlists.len(), 2);
|
||||||
|
assert_eq!(info.realmlists[0].host.as_deref(), Some("old.example.com"));
|
||||||
|
assert_eq!(info.other_addons, 1);
|
||||||
|
assert!(!info.addon.installed);
|
||||||
|
assert!(detect(d.path(), None).is_none(), "a plain folder is not a client");
|
||||||
|
fs::create_dir_all(d.path().join("srv/Data")).unwrap();
|
||||||
|
assert!(detect(&d.path().join("srv"), None).is_none(), "Data without an executable is not a client");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn realmlist_change_is_backed_up_minimal_and_idempotent() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = fake_client(d.path());
|
||||||
|
let meta = d.path().join("meta");
|
||||||
|
let before = snapshot(&c);
|
||||||
|
let changed = set_realmlist(&c, &meta, "192.168.0.5").unwrap();
|
||||||
|
assert_eq!(changed.len(), 2);
|
||||||
|
assert_eq!(fs::read_to_string(c.join("Data/enUS/realmlist.wtf")).unwrap(), "set realmlist 192.168.0.5\r\nset patchlist x\r\n", "other lines and line endings preserved");
|
||||||
|
assert_eq!(fs::read_to_string(c.join("Data/ruRU/realmlist.wtf")).unwrap(), "set realmlist 192.168.0.5\n");
|
||||||
|
let saved: Vec<_> = fs::read_dir(meta.join("backups/client")).unwrap().flatten().collect();
|
||||||
|
assert_eq!(saved.len(), 2, "each changed file was backed up");
|
||||||
|
assert_eq!(fs::read_to_string(saved.iter().find(|e| e.file_name().to_string_lossy().contains("enUS")).unwrap().path()).unwrap(), "set realmlist old.example.com\r\nset patchlist x\r\n");
|
||||||
|
// nothing else in the client changed
|
||||||
|
let after = snapshot(&c);
|
||||||
|
let diff: Vec<_> = after.iter().filter(|(k, v)| before.get(*k) != Some(*v)).map(|(k, _)| k.clone()).collect();
|
||||||
|
assert_eq!(diff, ["Data/ruRU/realmlist.wtf", "Data/enUS/realmlist.wtf"].iter().map(|s| s.to_string()).collect::<std::collections::BTreeSet<_>>().into_iter().collect::<Vec<_>>());
|
||||||
|
assert!(set_realmlist(&c, &meta, "192.168.0.5").unwrap().is_empty(), "already set: no write, no new backup");
|
||||||
|
assert!(set_realmlist(&c, &meta, "bad host; rm -rf").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn addon_install_touches_only_its_own_folder_and_backs_up_a_different_version() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = fake_client(d.path());
|
||||||
|
let meta = d.path().join("meta");
|
||||||
|
let v1 = package(d.path(), "1");
|
||||||
|
install_addon(&c, &meta, &v1).unwrap();
|
||||||
|
assert_eq!(addon_state(&c, Some(&v1)).up_to_date, Some(true));
|
||||||
|
assert!(!meta.join("backups/client").exists() || fs::read_dir(meta.join("backups/client")).unwrap().next().is_none(), "first install has nothing to back up");
|
||||||
|
|
||||||
|
let before = snapshot(&c);
|
||||||
|
install_addon(&c, &meta, &v1).unwrap();
|
||||||
|
assert_eq!(snapshot(&c), before, "same version: no change at all");
|
||||||
|
|
||||||
|
// user tweaks their copy, then a newer package arrives
|
||||||
|
fs::write(c.join("Interface/AddOns/CoABotUI/notes.txt"), "mine").unwrap();
|
||||||
|
let v2 = package(d.path(), "2");
|
||||||
|
let outside_before: BTreeMap<_, _> = snapshot(&c).into_iter().filter(|(k, _)| !k.starts_with("Interface/AddOns/CoABotUI")).collect();
|
||||||
|
install_addon(&c, &meta, &v2).unwrap();
|
||||||
|
assert_eq!(addon_state(&c, Some(&v2)).version.as_deref(), Some("2"));
|
||||||
|
assert_eq!(fs::read_to_string(c.join("Interface/AddOns/CoABotUI/notes.txt")).unwrap(), "mine", "the user's extra file survives");
|
||||||
|
let outside_after: BTreeMap<_, _> = snapshot(&c).into_iter().filter(|(k, _)| !k.starts_with("Interface/AddOns/CoABotUI")).collect();
|
||||||
|
assert_eq!(outside_before, outside_after, "other addons, WTF, Data untouched");
|
||||||
|
let kept = fs::read_dir(meta.join("backups/client")).unwrap().flatten().find(|e| e.file_name().to_string_lossy().starts_with(ADDON_NAME)).unwrap().path();
|
||||||
|
assert_eq!(fs::read_to_string(kept.join("CoABotUI.lua")).unwrap(), "-- v1", "the previous version and the user's copy are backed up");
|
||||||
|
assert!(kept.join("notes.txt").is_file());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incomplete_addon_package_and_missing_client_are_refused() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let c = fake_client(d.path());
|
||||||
|
let empty = d.path().join("emptypkg");
|
||||||
|
fs::create_dir_all(&empty).unwrap();
|
||||||
|
assert!(install_addon(&c, &d.path().join("meta"), &empty).is_err());
|
||||||
|
assert!(launch(d.path()).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
pub mod backup;
|
pub mod backup;
|
||||||
|
pub mod client;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod download;
|
pub mod download;
|
||||||
|
|||||||
+70
-1
@@ -521,6 +521,70 @@ async fn add_companions(state: State<'_, AppState>, id: String, count: u32) -> s
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn client_of(root: &std::path::Path) -> Result<(PathBuf, InstallMeta, Option<PathBuf>)> {
|
||||||
|
let (dir, meta) = install_meta(root)?;
|
||||||
|
let client = meta.client_path.clone().map(PathBuf::from).ok_or_else(|| Error::Invalid("No game client is set up for this server yet.".into()))?;
|
||||||
|
Ok((dir, meta, Some(client)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn client_info(state: State<'_, AppState>, id: String) -> std::result::Result<Option<coa_core::client::ClientInfo>, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let (_, meta) = install_meta(&root)?;
|
||||||
|
let source = coa_core::client::addon_source(&root);
|
||||||
|
Ok(meta.client_path.and_then(|p| coa_core::client::detect(std::path::Path::new(&p), source.as_deref())))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn set_client(state: State<'_, AppState>, id: String, path: String) -> std::result::Result<coa_core::client::ClientInfo, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let (dir, mut meta) = install_meta(&root)?;
|
||||||
|
let source = coa_core::client::addon_source(&root);
|
||||||
|
let info = coa_core::client::detect(std::path::Path::new(&path), source.as_deref())
|
||||||
|
.ok_or_else(|| Error::Invalid("This folder does not look like a game client (it needs Data and the game executable).".into()))?;
|
||||||
|
meta.client_path = Some(info.path.clone());
|
||||||
|
coa_core::fsx::atomic_write_json(&dir.join("install.json"), &meta).map_err(UiError::from)?;
|
||||||
|
Ok(info)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn client_realmlist(state: State<'_, AppState>, id: String, host: String) -> std::result::Result<Vec<String>, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let (dir, _, client) = client_of(&root)?;
|
||||||
|
Ok(coa_core::client::set_realmlist(&client.unwrap(), &dir, &host)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn client_install_addon(state: State<'_, AppState>, id: String) -> std::result::Result<(), UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let (dir, _, client) = client_of(&root)?;
|
||||||
|
let source = coa_core::client::addon_source(&root).ok_or_else(|| Error::Invalid("This server package does not include the companion addon.".into()))?;
|
||||||
|
Ok(coa_core::client::install_addon(&client.unwrap(), &dir, &source)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let (_, _, client) = client_of(&root)?;
|
||||||
|
let client = client.unwrap();
|
||||||
|
let ready = {
|
||||||
|
let o = coa_core::process::observe(&root, &layout::read_ports(&root));
|
||||||
|
[&o.mysql, &o.auth, &o.world].iter().all(|s| s.state == coa_core::process::ServiceState::Running)
|
||||||
|
};
|
||||||
|
if !ready {
|
||||||
|
let out = run_verb(&state, id, Verb::StartAll).await?;
|
||||||
|
if !out.ok {
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blocking(move || {
|
||||||
|
coa_core::client::launch(&client)?;
|
||||||
|
Ok(DriverOutcome { ok: true, exit_code: None, code: None, human: None, output: String::new() })
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
let dir = data_dir();
|
let dir = data_dir();
|
||||||
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
|
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
|
||||||
@@ -558,7 +622,12 @@ pub fn run() {
|
|||||||
rollback_update,
|
rollback_update,
|
||||||
get_population,
|
get_population,
|
||||||
companion_sizes,
|
companion_sizes,
|
||||||
add_companions
|
add_companions,
|
||||||
|
client_info,
|
||||||
|
set_client,
|
||||||
|
client_realmlist,
|
||||||
|
client_install_addon,
|
||||||
|
play
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while running CoA Server Manager");
|
.expect("error while running CoA Server Manager");
|
||||||
|
|||||||
@@ -209,6 +209,14 @@ export interface CompanionSizes {
|
|||||||
sizes: { id: string; title: string; bots: number; warning: string | null }[];
|
sizes: { id: string; title: string; bots: number; warning: string | null }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ClientInfo {
|
||||||
|
path: string;
|
||||||
|
executable: string;
|
||||||
|
realmlists: { path: string; host: string | null }[];
|
||||||
|
addon: { installed: boolean; version: string | null; up_to_date: boolean | null };
|
||||||
|
other_addons: number;
|
||||||
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
defaultInstallDir: () => invoke<string>("default_install_dir"),
|
defaultInstallDir: () => invoke<string>("default_install_dir"),
|
||||||
scan: (path: string) => invoke<ScanReport>("scan_server", { path }),
|
scan: (path: string) => invoke<ScanReport>("scan_server", { path }),
|
||||||
@@ -240,6 +248,11 @@ export const api = {
|
|||||||
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
||||||
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
||||||
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null }>("add_companions", { id, count }),
|
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null }>("add_companions", { id, count }),
|
||||||
|
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
|
||||||
|
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 }),
|
||||||
|
play: (id: string) => invoke<DriverOutcome>("play", { id }),
|
||||||
previewPreset: (id: string, scope: Scope, preset: string) => invoke<PresetPreview>("preview_preset", { id, scope, preset }),
|
previewPreset: (id: string, scope: Scope, preset: string) => invoke<PresetPreview>("preview_preset", { id, scope, preset }),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { open } from "@tauri-apps/plugin-dialog";
|
||||||
|
import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
|
||||||
|
export function ClientCard({ serverId }: { serverId: string }) {
|
||||||
|
const [info, setInfo] = useState<ClientInfo | null | undefined>(undefined);
|
||||||
|
const [error, setError] = useState<UiError | null>(null);
|
||||||
|
const [note, setNote] = useState<string | null>(null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const refresh = () => api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh();
|
||||||
|
}, [serverId]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
async function run(fn: () => Promise<string | void>) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNote(null);
|
||||||
|
try {
|
||||||
|
const msg = await fn();
|
||||||
|
if (msg) setNote(msg);
|
||||||
|
await refresh();
|
||||||
|
} catch (e) {
|
||||||
|
setError(asUiError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function choose() {
|
||||||
|
const picked = await open({ directory: true, multiple: false, title: "Choose your game client folder" });
|
||||||
|
if (typeof picked === "string") await run(async () => void (await api.setClient(serverId, picked)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const hosts = info?.realmlists.map((r) => r.host) ?? [];
|
||||||
|
const pointsLocal = hosts.length > 0 && hosts.every((h) => h === "127.0.0.1" || h === "localhost");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className="mt-6 p-6">
|
||||||
|
<h2 className="font-semibold">Game client</h2>
|
||||||
|
{info === undefined && <p className="mt-2 text-sm text-muted">Looking…</p>}
|
||||||
|
{info === null && (
|
||||||
|
<>
|
||||||
|
<p className="mt-1 text-sm text-muted">Tell Manager where your game is installed to get a PLAY button. Your game files are never changed except the server address and the companion addon.</p>
|
||||||
|
<Button className="mt-4" onClick={() => void choose()} disabled={busy}>Choose game folder…</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{info && (
|
||||||
|
<>
|
||||||
|
<p className="selectable mt-1 break-all text-sm text-muted">{info.path}</p>
|
||||||
|
<dl className="mt-4 grid grid-cols-[auto_1fr] gap-x-6 gap-y-2 text-sm">
|
||||||
|
<dt className="text-muted">Connects to</dt>
|
||||||
|
<dd>
|
||||||
|
{hosts.length ? hosts.filter(Boolean).join(", ") : "—"}
|
||||||
|
{pointsLocal ? <span className="ml-2 text-ok">✓ this computer</span> : <span className="ml-2 text-warn">not this server</span>}
|
||||||
|
</dd>
|
||||||
|
<dt className="text-muted">Companion addon</dt>
|
||||||
|
<dd>
|
||||||
|
{info.addon.installed ? `Installed${info.addon.version ? ` (version ${info.addon.version})` : ""}` : "Not installed"}
|
||||||
|
{info.addon.up_to_date === false && <span className="ml-2 text-warn">an update is available</span>}
|
||||||
|
</dd>
|
||||||
|
<dt className="text-muted">Other addons</dt>
|
||||||
|
<dd>{info.other_addons} — left exactly as they are</dd>
|
||||||
|
</dl>
|
||||||
|
<div className="mt-4 flex flex-wrap gap-2">
|
||||||
|
{!pointsLocal && (
|
||||||
|
<Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.setRealmlist(serverId, "127.0.0.1"); return "The game now connects to this computer. The previous address was saved."; })}>
|
||||||
|
Point the game at this server
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{(!info.addon.installed || info.addon.up_to_date === false) && (
|
||||||
|
<Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.installAddon(serverId); return "Companion addon installed. Other addons were not touched."; })}>
|
||||||
|
{info.addon.installed ? "Update companion addon" : "Install companion addon"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>Change folder…</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 : error.human.message}</p>}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { Loader2 } from "lucide-react";
|
import { Loader2 } from "lucide-react";
|
||||||
import { api, asUiError, type Human, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
|
import { api, asUiError, type ClientInfo, type Human, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
|
||||||
import { cn, formatUptime } from "@/lib/utils";
|
import { cn, formatUptime } from "@/lib/utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
@@ -37,6 +37,8 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
const [failure, setFailure] = useState<Failure | null>(null);
|
const [failure, setFailure] = useState<Failure | null>(null);
|
||||||
const [showDetails, setShowDetails] = useState(false);
|
const [showDetails, setShowDetails] = useState(false);
|
||||||
const [pop, setPop] = useState<Population | null>(null);
|
const [pop, setPop] = useState<Population | null>(null);
|
||||||
|
const [client, setClient] = useState<ClientInfo | null>(null);
|
||||||
|
const [playing, setPlaying] = useState(false);
|
||||||
const alive = useRef(true);
|
const alive = useRef(true);
|
||||||
|
|
||||||
const poll = useCallback(async () => {
|
const poll = useCallback(async () => {
|
||||||
@@ -54,6 +56,7 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
alive.current = true;
|
alive.current = true;
|
||||||
|
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
|
||||||
void poll();
|
void poll();
|
||||||
const t = setInterval(poll, 2000);
|
const t = setInterval(poll, 2000);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -85,6 +88,22 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function play() {
|
||||||
|
setFailure(null);
|
||||||
|
setShowDetails(false);
|
||||||
|
setPlaying(true);
|
||||||
|
try {
|
||||||
|
const out = await api.play(server.id);
|
||||||
|
if (!out.ok) throw { human: out.human, technical: out.output };
|
||||||
|
} catch (e) {
|
||||||
|
const ui = asUiError(e);
|
||||||
|
setFailure({ human: ui.human ?? asUiError(String(e)).human, technical: ui.technical });
|
||||||
|
} finally {
|
||||||
|
setPlaying(false);
|
||||||
|
void poll();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!status) return <p className="text-muted">Checking your server…</p>;
|
if (!status) return <p className="text-muted">Checking your server…</p>;
|
||||||
if (!status.path_exists) {
|
if (!status.path_exists) {
|
||||||
return (
|
return (
|
||||||
@@ -170,6 +189,12 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget
|
|||||||
Stop
|
Stop
|
||||||
</Button>
|
</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 ? "PLAY" : "START & PLAY"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{anyUp && !running && !transitioning && (
|
{anyUp && !running && !transitioning && (
|
||||||
<p className="mt-3 text-sm text-muted">Some parts are running. Press Start to bring up the rest, or Stop to shut everything down.</p>
|
<p className="mt-3 text-sm text-muted">Some parts are running. Press Start to bring up the rest, or Stop to shut everything down.</p>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
|
|||||||
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
|
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
|
import { ClientCard } from "@/screens/ClientCard";
|
||||||
|
|
||||||
const ACTION_TEXT: Record<string, string> = {
|
const ACTION_TEXT: Record<string, string> = {
|
||||||
create: "New file",
|
create: "New file",
|
||||||
@@ -110,6 +111,8 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
|||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<ClientCard serverId={serverId} />
|
||||||
|
|
||||||
<Card className="mt-6 p-6">
|
<Card className="mt-6 p-6">
|
||||||
<h2 className="font-semibold">Server updates</h2>
|
<h2 className="font-semibold">Server updates</h2>
|
||||||
<p className="mt-1 text-sm text-muted">Updates are checked for authenticity, backed up first, and can be undone.</p>
|
<p className="mt-1 text-sm text-muted">Updates are checked for authenticity, backed up first, and can be undone.</p>
|
||||||
|
|||||||
Reference in new issue
Block a user