Compare commits

..
4 Commits
15 changed files with 735 additions and 14 deletions

No files matched your search

Generated
+3 -3
View File
@@ -491,7 +491,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.6.8"
version = "0.6.9"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -520,7 +520,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.6.8"
version = "0.6.9"
dependencies = [
"chrono",
"coa-core",
@@ -529,7 +529,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.6.8"
version = "0.6.9"
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.6.8"
version = "0.6.9"
edition = "2021"
license = "AGPL-3.0-only"
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Custom races can be enabled and their client patches installed from Modules
---
Install the custom race client assets from the module card, then enable the module and restart the server.
+501
View File
@@ -0,0 +1,501 @@
//! Management of client-side patches and assets for Custom Races.
//!
//! Handles detecting, enabling/disabling (via `.disabled` extension renaming),
//! and downloading/extracting client patches (Esteria and additional races)
//! into the player's WoW client directory.
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::download::Cancel;
use crate::error::{Error, Result};
use crate::fsx;
pub const MANIFEST_FILENAME: &str = "custom_races_patch_manifest.txt";
pub const ARCHIVES: &[(&str, &str)] = &[
(
"CoA-Custom-1.4-main-20261007-b46a130e.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.4/CoA-Custom-1.4-main-20261007-b46a130e.zip",
),
(
"CoA-Custom-1.4-client-part1.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.4/CoA-Custom-1.4-client-part1.zip",
),
(
"CoA-Custom-1.4-client-part2.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.4/CoA-Custom-1.4-client-part2.zip",
),
];
pub const RACE_MPQS: &[&str] = &[
"patch-T.MPQ",
"patch-ZE1.MPQ",
"patch-ZE2.MPQ",
"patch-ZE3.MPQ",
"patch-ZE5.MPQ",
"patch-ZE6.MPQ",
"patch-ZE7.MPQ",
"patch-ZE8.MPQ",
"patch-ZE9.MPQ",
"patch-ZEA.MPQ",
"patch-ZG.MPQ",
"patch-ZH.MPQ",
"patch-ZHA.MPQ",
"patch-ZHM.MPQ",
"patch-ZM.MPQ",
"patch-ZVU.MPQ",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ClientPatchState {
NotInstalled,
Enabled,
Disabled,
PartiallyInstalled,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientPatchStatus {
pub state: ClientPatchState,
pub installed_mpqs: usize,
pub total_mpqs: usize,
pub has_root_files: bool,
pub client_path: Option<String>,
}
/// Inspect the client folder and determine the state of custom races patches.
pub fn client_patch_status(client_path: &Path) -> ClientPatchStatus {
let data_dir = client_path.join("Data");
let mut enabled_count = 0;
let mut disabled_count = 0;
for mpq in RACE_MPQS {
if data_dir.join(format!("{mpq}.disabled")).is_file() {
disabled_count += 1;
} else if data_dir.join(mpq).is_file() {
enabled_count += 1;
}
}
let has_root = client_path.join("EsteriaAppearance.dll").is_file()
|| client_path.join("dinput8.dll").is_file()
|| client_path.join("dinput8.dll.disabled").is_file();
let total = RACE_MPQS.len();
let state = if enabled_count == total && client_path.join("dinput8.dll").is_file() {
ClientPatchState::Enabled
} else if disabled_count == total && client_path.join("dinput8.dll.disabled").is_file() {
ClientPatchState::Disabled
} else if (enabled_count + disabled_count) > 0 {
ClientPatchState::PartiallyInstalled
} else {
ClientPatchState::NotInstalled
};
ClientPatchStatus {
state,
installed_mpqs: enabled_count + disabled_count,
total_mpqs: total,
has_root_files: has_root,
client_path: Some(client_path.to_string_lossy().into_owned()),
}
}
/// Enable or disable client patches by renaming MPQs and `dinput8.dll` with `.disabled`.
pub fn set_client_patch_enabled(client_path: &Path, enabled: bool) -> Result<()> {
if !client_path.is_dir() {
return Err(Error::Invalid("Game client directory not found.".into()));
}
if crate::client::is_running(client_path) {
return Err(Error::Invalid("Close the game before changing custom races patches.".into()));
}
if !client_path.join(MANIFEST_FILENAME).is_file()
&& !RACE_MPQS.iter().skip(1).any(|name| client_path.join("Data").join(name).is_file()
|| client_path.join("Data").join(format!("{name}.disabled")).is_file()) {
return Ok(());
}
let mut paths: Vec<PathBuf> = RACE_MPQS.iter().map(|name| client_path.join("Data").join(name)).collect();
paths.push(client_path.join("dinput8.dll"));
paths.push(client_path.join("Ascension.exe"));
for active in paths {
let disabled = active.with_extension(format!("{}.disabled", active.extension().unwrap_or_default().to_string_lossy()));
let original = active.with_extension(format!("{}.original", active.extension().unwrap_or_default().to_string_lossy()));
if enabled && disabled.is_file() {
if active.is_file() {
if !original.is_file() {
return Err(Error::Invalid(format!("Cannot replace existing {} without an original backup.", active.display())));
}
fs::remove_file(&active)?;
}
fs::rename(&disabled, &active)?;
} else if !enabled && active.is_file() && !disabled.is_file() {
if active.file_name().is_some_and(|name| name == "Ascension.exe") && !original.is_file() {
continue;
}
fs::rename(&active, &disabled)?;
if original.is_file() {
fs::copy(&original, &active)?;
}
}
}
tracing::info!(enabled, "custom races client patches toggled");
Ok(())
}
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
let expected = match filename {
"CoA-Custom-1.4-main-20261007-b46a130e.zip" => "eaf934b5283476aa7b5d6eca7200ceae016e866ddbdab726bd47f39739c9c802",
"CoA-Custom-1.4-client-part1.zip" => "669f8396e82f396125e0be2070b2bad782f0104c695939a88924ec97f4fc4d21",
"CoA-Custom-1.4-client-part2.zip" => "088b3ddcf292abccbc84453c0ccf4cd74ff6b20c848d5902dc83854553aecc8b",
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
};
if fsx::sha256_file(path)? != expected {
return Err(Error::Invalid(format!("Custom races archive {filename} failed verification. Remove it and try again.")));
}
Ok(())
}
/// Locate an archive locally in Downloads or cache, or download it from GitHub.
fn resolve_or_download_archive(
filename: &str,
url: &str,
client: &reqwest::blocking::Client,
cancel: &Cancel,
report: &dyn Fn(&str, f32),
base_percent: f32,
percent_slice: f32,
) -> Result<PathBuf> {
// 1. Check user Downloads folder
if let Some(userprofile) = std::env::var_os("USERPROFILE") {
let downloads = PathBuf::from(userprofile).join("Downloads");
let candidate = downloads.join(filename);
if candidate.is_file() {
if let Ok(meta) = candidate.metadata() {
if meta.len() > 1000 {
tracing::info!(path = %candidate.display(), "using existing archive in Downloads");
verify_archive(&candidate, filename)?;
return Ok(candidate);
}
}
}
}
// 2. Check temp / cache directory
let cache_dir = std::env::temp_dir().join("coa-client-races");
fs::create_dir_all(&cache_dir)?;
let target = cache_dir.join(filename);
if target.is_file() {
if let Ok(meta) = target.metadata() {
if meta.len() > 1000 {
verify_archive(&target, filename)?;
return Ok(target);
}
}
}
// 3. Download from GitHub Releases
report(&format!("Downloading {filename}..."), base_percent);
let part_path = cache_dir.join(format!("{filename}.part"));
let resp = client
.get(url)
.send()
.map_err(|e| Error::NetworkUnreachable(format!("Could not reach download server: {e}")))?;
if !resp.status().is_success() {
return Err(Error::NetworkUnreachable(format!(
"Download failed with status {} for {url}",
resp.status()
)));
}
let total_bytes = resp.content_length().unwrap_or(0);
let mut downloaded = 0u64;
let mut src = resp;
let mut dst = File::create(&part_path)?;
let mut buf = [0u8; 64 * 1024];
let mut last_report = std::time::Instant::now();
loop {
if cancel.is_set() {
let _ = fs::remove_file(&part_path);
return Err(Error::Invalid("Operation cancelled.".into()));
}
let n = src
.read(&mut buf)
.map_err(|e| Error::NetworkUnreachable(format!("Download interrupted: {e}")))?;
if n == 0 {
break;
}
dst.write_all(&buf[..n])?;
downloaded += n as u64;
if last_report.elapsed() > std::time::Duration::from_millis(200) {
let ratio = if total_bytes > 0 {
(downloaded as f32 / total_bytes as f32).clamp(0.0, 1.0)
} else {
0.5
};
report(
&format!(
"Downloading {filename} ({:.1} MB)...",
downloaded as f64 / 1_048_576.0
),
base_percent + ratio * percent_slice,
);
last_report = std::time::Instant::now();
}
}
dst.flush()?;
drop(dst);
verify_archive(&part_path, filename)?;
fs::rename(&part_path, &target)?;
Ok(target)
}
/// Download (if needed) and extract custom races client assets into the target WoW client.
pub fn install_client_patches(
client_path: &Path,
cancel: &Cancel,
report: &dyn Fn(&str, f32),
) -> Result<()> {
if !client_path.is_dir() {
return Err(Error::Invalid("Game client directory does not exist.".into()));
}
if crate::client::is_running(client_path) {
return Err(Error::Invalid("Close the game before installing custom races patches.".into()));
}
let data_dir = client_path.join("Data");
fs::create_dir_all(&data_dir)?;
// 1. Back up original Ascension.exe and patch-T.MPQ if they exist and haven't been backed up yet
let exe = client_path.join("Ascension.exe");
let exe_bak = client_path.join("Ascension.exe.original");
if exe.is_file() && !exe_bak.is_file() {
report("Backing up original Ascension.exe...", 0.02);
fs::copy(&exe, &exe_bak)?;
}
let t_mpq = data_dir.join("patch-T.MPQ");
let t_mpq_bak = data_dir.join("patch-T.MPQ.original");
if t_mpq.is_file() && !t_mpq_bak.is_file() {
report("Backing up original patch-T.MPQ...", 0.04);
fs::copy(&t_mpq, &t_mpq_bak)?;
}
let dll = client_path.join("dinput8.dll");
let dll_backup = client_path.join("dinput8.dll.original");
if dll.is_file() && !dll_backup.is_file() {
fs::copy(&dll, &dll_backup)?;
}
// 2. Resolve/download archives (0.05 .. 0.50)
let http = reqwest::blocking::Client::builder()
.user_agent(concat!("CoA-Server-Manager/", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(600))
.build()
.map_err(|e| Error::Invalid(format!("Cannot prepare downloader: {e}")))?;
let mut resolved_archives = Vec::new();
let n_archives = ARCHIVES.len() as f32;
for (i, (fname, url)) in ARCHIVES.iter().enumerate() {
let base_pct = 0.05 + (i as f32 / n_archives) * 0.45;
let slice = 0.45 / n_archives;
let archive_path =
resolve_or_download_archive(fname, url, &http, cancel, report, base_pct, slice)?;
resolved_archives.push(archive_path);
}
// 3. Extract archives (0.50 .. 0.95)
let mut installed_mpqs = Vec::new();
let mut installed_roots = Vec::new();
for (i, arch_path) in resolved_archives.iter().enumerate() {
if cancel.is_set() {
return Err(Error::Invalid("Operation cancelled.".into()));
}
let arch_name = arch_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
report(
&format!("Unpacking {arch_name}..."),
0.50 + (i as f32 / n_archives) * 0.45,
);
let file = File::open(arch_path)?;
let mut zip = zip::ZipArchive::new(file)
.map_err(|e| Error::Invalid(format!("Failed to open zip {arch_name}: {e}")))?;
let num_files = zip.len();
for file_idx in 0..num_files {
if cancel.is_set() {
return Err(Error::Invalid("Operation cancelled.".into()));
}
let mut zfile = zip
.by_index(file_idx)
.map_err(|e| Error::Invalid(format!("Zip entry error in {arch_name}: {e}")))?;
if zfile.is_dir() {
continue;
}
let zname = zfile.name().to_string();
let zname_norm = zname.replace('\\', "/");
if zname_norm.contains("files/client/") {
let base = Path::new(&zname_norm)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if base.to_ascii_lowercase().ends_with(".mpq") {
let dest = data_dir.join(&base);
let mut out = File::create(&dest)?;
io::copy(&mut zfile, &mut out)?;
installed_mpqs.push(base);
} else if base.eq_ignore_ascii_case("dinput8.dll") {
let dest = client_path.join(&base);
let mut out = File::create(&dest)?;
io::copy(&mut zfile, &mut out)?;
installed_roots.push(base);
}
} else if zname_norm.contains("files/client_root/") {
let base = Path::new(&zname_norm)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if !base.is_empty() {
let dest = client_path.join(&base);
let mut out = File::create(&dest)?;
io::copy(&mut zfile, &mut out)?;
installed_roots.push(base);
}
}
}
}
// 4. Record manifest
report("Finalizing manifest...", 0.98);
let manifest_path = client_path.join(MANIFEST_FILENAME);
installed_mpqs.sort();
installed_mpqs.dedup();
installed_roots.sort();
installed_roots.dedup();
let mut manifest_body = String::from("# Custom Race MPQ files\n");
for m in &installed_mpqs {
manifest_body.push_str(&format!("MPQ:{m}\n"));
}
manifest_body.push_str("# Custom Race root files\n");
for r in &installed_roots {
manifest_body.push_str(&format!("ROOT:{r}\n"));
}
fsx::atomic_write(&manifest_path, manifest_body.as_bytes())?;
report("Custom races client patches installed successfully!", 1.0);
tracing::info!(
mpqs = installed_mpqs.len(),
roots = installed_roots.len(),
"custom races client patch installation complete"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn disabling_restores_original_client_files_and_enabling_restores_custom_files() {
let temp = tempfile::tempdir().unwrap();
let data = temp.path().join("Data");
fs::create_dir_all(&data).unwrap();
for path in [data.join("patch-T.MPQ"), temp.path().join("Ascension.exe"), temp.path().join("dinput8.dll")] {
fs::write(&path, b"custom").unwrap();
let backup = path.with_extension(format!("{}.original", path.extension().unwrap().to_string_lossy()));
fs::write(&backup, b"original").unwrap();
}
fs::write(temp.path().join(MANIFEST_FILENAME), "MPQ:patch-T.MPQ\n").unwrap();
set_client_patch_enabled(temp.path(), false).unwrap();
assert_eq!(fs::read(data.join("patch-T.MPQ")).unwrap(), b"original");
assert_eq!(fs::read(temp.path().join("Ascension.exe")).unwrap(), b"original");
set_client_patch_enabled(temp.path(), true).unwrap();
assert_eq!(fs::read(data.join("patch-T.MPQ")).unwrap(), b"custom");
assert_eq!(fs::read(temp.path().join("Ascension.exe")).unwrap(), b"custom");
}
#[test]
fn an_unpatched_client_is_left_untouched() {
let temp = tempfile::tempdir().unwrap();
fs::create_dir_all(temp.path().join("Data")).unwrap();
fs::write(temp.path().join("Data/patch-T.MPQ"), b"original").unwrap();
set_client_patch_enabled(temp.path(), false).unwrap();
assert_eq!(fs::read(temp.path().join("Data/patch-T.MPQ")).unwrap(), b"original");
}
#[test]
fn corrupt_downloads_are_rejected() {
let temp = tempfile::NamedTempFile::new().unwrap();
fs::write(temp.path(), b"corrupt archive").unwrap();
assert!(verify_archive(temp.path(), ARCHIVES[0].0).is_err());
}
#[test]
fn test_patch_status_and_toggle() {
let temp = tempfile::tempdir().unwrap();
let client_path = temp.path();
let data_dir = client_path.join("Data");
fs::create_dir_all(&data_dir).unwrap();
// 1. Initial state: Not installed
let st = client_patch_status(client_path);
assert_eq!(st.state, ClientPatchState::NotInstalled);
// 2. Create MPQs and root files
for mpq in RACE_MPQS {
fs::write(data_dir.join(mpq), b"test mpq content").unwrap();
}
fs::write(client_path.join("dinput8.dll"), b"test dll").unwrap();
fs::write(client_path.join("EsteriaAppearance.dll"), b"test dll").unwrap();
let st = client_patch_status(client_path);
assert_eq!(st.state, ClientPatchState::Enabled);
assert_eq!(st.installed_mpqs, RACE_MPQS.len());
// 3. Disable patches
set_client_patch_enabled(client_path, false).unwrap();
let st = client_patch_status(client_path);
assert_eq!(st.state, ClientPatchState::Disabled);
assert!(data_dir.join("patch-T.MPQ.disabled").is_file());
assert!(!data_dir.join("patch-T.MPQ").is_file());
assert!(client_path.join("dinput8.dll.disabled").is_file());
assert!(!client_path.join("dinput8.dll").is_file());
// 4. Re-enable patches
set_client_patch_enabled(client_path, true).unwrap();
let st = client_patch_status(client_path);
assert_eq!(st.state, ClientPatchState::Enabled);
assert!(data_dir.join("patch-T.MPQ").is_file());
assert!(!data_dir.join("patch-T.MPQ.disabled").is_file());
assert!(client_path.join("dinput8.dll").is_file());
assert!(!client_path.join("dinput8.dll.disabled").is_file());
}
}
+4
View File
@@ -428,6 +428,10 @@ fn game_args(cfg: &Config, n: &Names, kind: GameKind, host: &Path, data: &Path,
a.extend(env("AC_UPDATES_ENABLE_DATABASES", "0"));
if kind == GameKind::World {
a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]);
let races = host.join("Data/dbc_races");
if races.is_dir() && races != data.join("dbc_races") {
a.extend(["--volume".into(), format!("{}:{DATA}/dbc_races:ro", races.display())]);
}
a.extend(env("AC_DATA_DIR", DATA));
// The remote console is only ever reachable from this computer.
a.extend(["--publish".into(), format!("127.0.0.1:{ra_port}:{RA_PORT}")]);
+1
View File
@@ -2,6 +2,7 @@ pub mod accounts;
pub mod backup;
pub mod cleanbase;
pub mod companions;
pub mod custom_races;
pub mod client;
pub mod remote_client;
pub mod clientdl;
+12
View File
@@ -203,6 +203,18 @@ pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
Some(lock)
} else { None };
if on { crate::realms::guard_module(root, id)?; }
if id == "custom-races" {
if let Ok(meta_content) = fs::read_to_string(meta.join("install.json")) {
if let Ok(install_meta) = serde_json::from_str::<crate::registry::InstallMeta>(&meta_content) {
if let Some(cp) = install_meta.client_path {
let client_path = PathBuf::from(cp);
if client_path.is_dir() {
crate::custom_races::set_client_patch_enabled(&client_path, on)?;
}
}
}
}
}
set_enabled_in(&catalog(), root, meta, id, on)
}
+18
View File
@@ -121,6 +121,24 @@
"default_on": false,
"page": "bots"
},
{
"id": "custom-races",
"name": "Custom Races",
"description": {
"en": "Playable custom races (Esteria and additional races) with extended appearances.",
"ru": "Пользовательские расы (Esteria и дополнительные расы) с расширенной внешностью.",
"de": "Spielbare benutzerdefinierte Völker (Esteria und weitere Völker) mit erweitertem Aussehen.",
"fr": "Races personnalisées jouables (Esteria et autres) avec apparences étendues.",
"es": "Razas personalizadas jugables (Esteria y razas adicionales) con apariencias ampliadas."
},
"repo": "https://github.com/Corfirean/azerothcore-wotlk-coa",
"conf": "coa_custom_races.conf",
"switchable": true,
"status": "beta",
"icon": "races",
"enable_key": "CoACustomRaces.Enable",
"default_on": false
},
{
"id": "client-compat",
"name": "Client compatibility",
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.6.8",
"version": "0.6.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.6.8",
"version": "0.6.9",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.6.8",
"version": "0.6.9",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+48 -1
View File
@@ -661,6 +661,50 @@ async fn module_set_enabled(state: State<'_, AppState>, id: String, module: Stri
})
.await
}
#[tauri::command]
async fn custom_races_status(state: State<'_, AppState>, id: String) -> std::result::Result<Option<coa_core::custom_races::ClientPatchStatus>, UiError> {
let root = path_of(&state, &id)?;
blocking(move || {
let client = linked_client(&root)?;
Ok(client.as_deref().map(coa_core::custom_races::client_patch_status))
})
.await
}
#[tauri::command]
async fn custom_races_install(app: AppHandle, state: State<'_, AppState>, id: String) -> std::result::Result<(), UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
let cancel = begin_client_job(&state)?;
let sid = id.clone();
let result = blocking(move || {
let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?;
coa_core::custom_races::install_client_patches(&client, &cancel, &|step, percent| {
let _ = app.emit("custom-races-progress", serde_json::json!({
"id": sid,
"step": step,
"percent": percent,
}));
})?;
let enabled = coa_core::modules::list(&root).iter().any(|module| module.id == "custom-races" && module.enabled);
coa_core::custom_races::set_client_patch_enabled(&client, enabled)
})
.await;
end_client_job(&state);
result
}
#[tauri::command]
async fn custom_races_toggle_client(state: State<'_, AppState>, id: String, enabled: bool) -> std::result::Result<(), UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || {
let client = linked_client(&root)?.ok_or_else(|| Error::Invalid("No game client is linked to this server.".into()))?;
coa_core::custom_races::set_client_patch_enabled(&client, enabled)
})
.await
}
#[tauri::command]
async fn module_settings(state: State<'_, AppState>, id: String, module: String) -> std::result::Result<Vec<coa_core::modules::Setting>, UiError> {
@@ -1709,7 +1753,10 @@ pub fn run() {
list_crashes,
console_tail,
console_risk,
console_command
console_command,
custom_races_status,
custom_races_install,
custom_races_toggle_client
])
.run(tauri::generate_context!())
.expect("error while running CoA Server Manager");
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.6.8",
"version": "0.6.9",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+19
View File
@@ -389,6 +389,22 @@ export interface ClientDownloadCheck {
dest: string;
}
export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
export interface CustomRacesClientStatus {
state: ClientPatchState;
installedMpqs: number;
totalMpqs: number;
hasRootFiles: boolean;
clientPath: string | null;
}
export interface CustomRacesProgress {
id: string;
step: string;
percent: number;
}
export type FriendsMode = "local" | "lan" | "direct" | "private";
export interface LanAddress {
@@ -529,6 +545,9 @@ export const api = {
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"),
customRacesStatus: (id: string) => invoke<CustomRacesClientStatus | null>("custom_races_status", { id }),
customRacesInstall: (id: string) => invoke<void>("custom_races_install", { id }),
customRacesToggleClient: (id: string, enabled: boolean) => invoke<void>("custom_races_toggle_client", { id, enabled }),
play: (id: string) => invoke<DriverOutcome>("play", { id }),
friendsStatus: (id: string) => invoke<FriendsStatus>("friends_status", { id }),
friendsCheckInternet: () => invoke<InternetCheck>("friends_check_internet"),
+5
View File
@@ -85,6 +85,11 @@ for (const [key, title, desc] of [
] as [string, string[], string[]][]) add(`Enchanter.${key}`, "int", title, desc, { min: 0, advanced: true });
for (let n = 1; n <= 3; n++) add(`EC.P${n}`, "string", [`NPC phrase ${n}`, `Реплика НПС ${n}`, `NPC-Satz ${n}`, `Phrase du PNJ ${n}`, `Frase del PNJ ${n}`, `NPC台词 ${n}`], ["Text spoken by the NPC. Keep the enclosing quotes.", "Текст реплики НПС. Сохраните кавычки вокруг текста.", "Gesprochener Text. Anführungszeichen beibehalten.", "Texte prononcé. Conservez les guillemets.", "Texto hablado. Conserva las comillas.", "NPC发言内容,请保留外层引号。"], { advanced: true });
add("CoACustomRaces.BotsEnable", "bool",
["Bots can be custom races", "Боты кастомных рас", "Bots benutzerdefinierter Völker", "Bots de races personnalisées", "Bots de razas personalizadas", "允许机器人为自定义种族"],
["Allow Playerbots to spawn as custom races.", "Разрешает ботам-игрокам появляться кастомными расами.", "Erlaubt Spieler-Bots, benutzerdefinierte Völker zu nutzen.", "Autorise les bots joueurs à s’incarner avec des races personnalisées.", "Permite a los bots jugadores crearse con razas personalizadas.", "允许玩家机器人扮演自定义种族。"]
);
const ah = "AuctionHouseBot.";
add(ah + "GUIDs", "string", ["Auction characters", "Персонажи аукциона", "Auktionscharaktere", "Personnages d’enchères", "Personajes de subasta", "拍卖角色"], ["Leave 0 and the server creates and uses its own auction character. To use your own, enter GUIDs separated by commas, without spaces; use dedicated offline characters, not companion bots.", "Оставьте 0, и сервер сам создаст и будет использовать своего персонажа аукциона. Чтобы использовать своих, укажите GUID через запятую без пробелов; нужны отдельные офлайн-персонажи, не боты-компаньоны.", "Bei 0 legt der Server selbst einen Auktionscharakter an und nutzt ihn. Eigene Charaktere: GUIDs durch Kommas, ohne Leerzeichen; separate Offline-Charaktere verwenden, keine Begleiter-Bots.", "Laissez 0 : le serveur crée et utilise son propre personnage d’enchères. Pour les vôtres, indiquez des GUID séparés par des virgules sans espaces ; personnages dédiés hors ligne, pas des bots compagnons.", "Deja 0 y el servidor crea y usa su propio personaje de subastas. Para usar los tuyos, indica GUID separados por comas sin espacios; personajes dedicados desconectados, no bots acompañantes.", "保持0时由服务器自动创建并使用拍卖角色。要使用自己的角色,请以逗号分隔填写GUID,不加空格;使用专用离线角色,勿用伙伴机器人。"], { advanced: true });
add(ah + "EnableSeller", "bool", ["Post auctions", "Выставлять лоты", "Auktionen einstellen", "Publier des enchères", "Publicar subastas", "发布拍卖"], ["Let the auction characters sell items. The module switch is also required.", "Разрешает персонажам продавать предметы. Нужен включённый модуль.", "Erlaubt Verkäufe. Der Modulschalter muss ebenfalls aktiv sein.", "Autorise les ventes. Le module doit aussi être activé.", "Permite vender. También requiere el módulo activado.", "允许拍卖角色出售物品,还需启用模块。"]);
+112 -5
View File
@@ -1,6 +1,7 @@
import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, type LucideProps } from "lucide-react";
import { api, asUiError, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
import { listen } from "@tauri-apps/api/event";
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -28,6 +29,7 @@ const TILES: Record<string, { icon: ComponentType<LucideProps>; from: string; to
gavel: { icon: Gavel, from: "from-yellow-500", to: "to-amber-700" },
sparkles: { icon: Sparkles, from: "from-fuchsia-500", to: "to-purple-700" },
swords: { icon: Swords, from: "from-rose-500", to: "to-red-800" },
races: { icon: Users, from: "from-cyan-500", to: "to-blue-800" },
};
const DEFAULT_TILE = { icon: Puzzle, from: "from-slate-500", to: "to-slate-700" };
@@ -86,6 +88,18 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
const [open, setOpen] = useState<string | null>(null);
const [error, setError] = useState<UiError | null>(null);
const [changed, setChanged] = useState(false);
const [racesPatchStatus, setRacesPatchStatus] = useState<CustomRacesClientStatus | null>(null);
const [racesInstalling, setRacesInstalling] = useState(false);
const [racesProgress, setRacesProgress] = useState<CustomRacesProgress | null>(null);
const loadRacesStatus = useCallback(async () => {
try {
const st = await api.customRacesStatus(serverId);
setRacesPatchStatus(st);
} catch {
// ignore
}
}, [serverId]);
const [guard, setGuard] = useState<UnsavedChangesGuard | null>(null);
useEffect(() => {
@@ -96,14 +110,39 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
const load = useCallback(async () => {
try {
setModules((await api.modulesList(serverId)).filter((m) => !m.hidden));
await loadRacesStatus();
} catch (e) {
setError(asUiError(e));
}
}, [serverId]);
}, [serverId, loadRacesStatus]);
useEffect(() => {
void load();
}, [load]);
const un = listen<CustomRacesProgress>("custom-races-progress", (e) => {
if (e.payload.id === serverId) {
setRacesProgress(e.payload);
}
});
return () => {
void un.then((f) => f());
};
}, [load, serverId]);
async function installClientPatch() {
setRacesInstalling(true);
setError(null);
try {
await api.customRacesInstall(serverId);
await loadRacesStatus();
await load();
onChanged?.();
} catch (e) {
setError(asUiError(e));
} finally {
setRacesInstalling(false);
setRacesProgress(null);
}
}
async function toggle(m: ModuleView) {
setError(null);
@@ -111,6 +150,9 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
await api.moduleSetEnabled(serverId, m.id, !m.enabled);
setChanged(true);
await load();
if (m.id === "custom-races") {
await loadRacesStatus();
}
onChanged?.();
} catch (e) {
setError(asUiError(e));
@@ -152,8 +194,9 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
role="switch"
aria-checked={m.enabled}
aria-label={t("mod.switch", { name: m.name })}
disabled={m.id === "custom-races" && racesInstalling}
onClick={() => void toggle(m)}
className={cn("relative mt-1 h-6 w-11 shrink-0 cursor-pointer rounded-full transition-colors", m.enabled ? "bg-gold" : "bg-white/15")}
className={cn("relative mt-1 h-6 w-11 shrink-0 cursor-pointer rounded-full transition-colors", m.enabled ? "bg-gold" : "bg-white/15", (m.id === "custom-races" && racesInstalling) && "opacity-50 cursor-not-allowed")}
>
<span className={cn("absolute top-0.5 h-5 w-5 rounded-full bg-white transition-all", m.enabled ? "left-[22px]" : "left-0.5")} />
</button>
@@ -161,6 +204,70 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
{m.installed && !m.switchable && m.status !== "soon" && m.compatibility !== "unsupported" && <span className="mt-1.5 shrink-0 text-xs text-muted">{t("mod.alwaysOn")}</span>}
{!m.installed && m.status !== "soon" && <span className="mt-1.5 shrink-0 text-xs text-muted">{t("mod.notHere")}</span>}
</div>
{m.id === "custom-races" && (
<div className="w-full">
{racesInstalling && racesProgress ? (
<div className="rounded-lg border border-gold/30 bg-gold/5 p-3">
<div className="flex items-center justify-between gap-3 text-xs">
<span className="flex min-w-0 items-center gap-2 font-medium text-ink">
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-gold" />
<span className="truncate">{racesProgress.step}</span>
</span>
<span className="shrink-0 font-mono text-xs font-semibold text-gold">
{Math.round(racesProgress.percent * 100)}%
</span>
</div>
<div className="mt-2.5 h-2 w-full overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={Math.round(racesProgress.percent * 100)} aria-valuemin={0} aria-valuemax={100}>
<div
className="h-full rounded-full bg-gold transition-all duration-300"
style={{ width: `${Math.round(racesProgress.percent * 100)}%` }}
/>
</div>
</div>
) : (
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-line/40 pt-3 text-xs">
<div className="flex items-center gap-2">
{racesPatchStatus?.state === "enabled" && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-xs text-ok border border-ok/30">
<span className="h-1.5 w-1.5 rounded-full bg-ok" />
{locale === "ru" ? "Патч клиента: Включен" : "Client Patch: Active"}
</span>
)}
{racesPatchStatus?.state === "disabled" && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/5 px-2.5 py-1 text-xs text-muted border border-white/15" title="MPQ files disabled with .disabled suffix">
<span className="h-1.5 w-1.5 rounded-full bg-muted" />
{locale === "ru" ? "Патч клиента: Отключен (.disabled)" : "Client Patch: Disabled (.disabled)"}
</span>
)}
{racesPatchStatus?.state === "not-installed" && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-warn/10 px-2.5 py-1 text-xs text-warn border border-warn/30">
<span className="h-1.5 w-1.5 rounded-full bg-warn" />
{locale === "ru" ? "Патч клиента: Не установлен" : "Client Patch: Not Installed"}
</span>
)}
{racesPatchStatus?.state === "partially-installed" && (
<span className="inline-flex items-center gap-1.5 rounded-full bg-warn/10 px-2.5 py-1 text-xs text-warn border border-warn/30">
<span className="h-1.5 w-1.5 rounded-full bg-warn" />
{locale === "ru" ? `Патч клиента: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ` : `Client Patch: ${racesPatchStatus.installedMpqs}/${racesPatchStatus.totalMpqs} MPQ`}
</span>
)}
</div>
{(!racesPatchStatus || racesPatchStatus.state === "not-installed" || racesPatchStatus.state === "partially-installed") && (
<Button
size="sm"
variant="secondary"
className="h-7 px-3 text-xs border border-gold/40 hover:border-gold"
disabled={racesInstalling || !racesPatchStatus?.clientPath}
onClick={() => void installClientPatch()}
>
{racesInstalling && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
{locale === "ru" ? "Установить патч клиента" : "Install Client Patch"}
</Button>
)}
</div>
)}
</div>
)}
<div className="mt-auto flex items-center gap-2">
<button
onClick={() => void api.openLink(m.repo)}