mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-18 19:25:56 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b97f86fc00 | ||
|
|
1a71f18def | ||
|
|
7d7bc530ec |
No files matched your search
@@ -1,7 +0,0 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Graceful server shutdowns no longer trigger crash recovery
|
||||
---
|
||||
Automatic crash recovery requires a confirmed abnormal exit. Normal shutdowns and scheduled restarts are not counted as crashes.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Configure the visual day and night cycle from Modules
|
||||
---
|
||||
Modules now offers TimeIsTime clock settings when supported by the installed server.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Select parallel or global scaling and remove item class requirements
|
||||
---
|
||||
The scaling settings now offer the parallel and global progression modes and a switch for class-restricted equipment, including tier sets.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Module cards show installed server revisions and the client race patch version
|
||||
---
|
||||
Module revisions come from the currently installed release metadata. The race card shows the client patch version separately; missing version metadata is reported honestly instead of showing a download version as installed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Client race patches can be repaired and removed while preserving original files
|
||||
---
|
||||
Every overwritten client file gets an original backup. Switching preserves newer launcher files; checksums detect missing or replaced assets. Repair and removal are always available, with rollback if a file operation fails.
|
||||
+368
-128
@@ -146,107 +146,218 @@ pub enum ClientPatchState {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientPatchStatus {
|
||||
pub state: ClientPatchState,
|
||||
pub version: Option<String>,
|
||||
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 current_version = fs::read_to_string(client_path.join(MANIFEST_FILENAME)).ok()
|
||||
.is_some_and(|manifest| manifest.lines().any(|line| line == format!("# CoA Custom {CLIENT_VERSION}")));
|
||||
let state = if enabled_count == total && current_version && client_path.join("dinput8.dll").is_file() {
|
||||
ClientPatchState::Enabled
|
||||
} else if disabled_count == total && current_version && 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()),
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
struct PatchFile {
|
||||
path: String,
|
||||
sha256: String,
|
||||
}
|
||||
|
||||
/// 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();
|
||||
if let Ok(manifest) = fs::read_to_string(client_path.join(MANIFEST_FILENAME)) {
|
||||
for line in manifest.lines() {
|
||||
if let Some(name) = line.strip_prefix("MPQ:") {
|
||||
if name.contains(['/', '\\']) || !name.to_ascii_lowercase().ends_with(".mpq") {
|
||||
return Err(Error::Invalid("Invalid custom races patch manifest.".into()));
|
||||
}
|
||||
paths.push(fsx::safe_join(&client_path.join("Data"), name)?);
|
||||
}
|
||||
fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
|
||||
let bundled: std::collections::BTreeMap<String, String> = serde_json::from_str(include_str!("custom_races_hashes.json"))?;
|
||||
let manifest = fs::read_to_string(client.join(MANIFEST_FILENAME)).unwrap_or_default();
|
||||
let mut files = std::collections::BTreeMap::new();
|
||||
for line in manifest.lines() {
|
||||
let path = if let Some(name) = line.strip_prefix("MPQ:") {
|
||||
if name.contains(['/', '\\']) { return Err(Error::Invalid("Invalid custom races patch manifest.".into())); }
|
||||
Some(format!("Data/{name}"))
|
||||
} else if let Some(name) = line.strip_prefix("ROOT:") {
|
||||
if name.contains(['/', '\\']) { return Err(Error::Invalid("Invalid custom races patch manifest.".into())); }
|
||||
Some(name.to_string())
|
||||
} else { None };
|
||||
if let Some(path) = path {
|
||||
fsx::safe_join(client, &path)?;
|
||||
files.insert(path.clone(), bundled.get(&path).cloned().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
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)?;
|
||||
}
|
||||
if files.is_empty() { files = bundled; }
|
||||
for line in manifest.lines().filter_map(|line| line.strip_prefix("SHA256:")) {
|
||||
let (hash, path) = line.split_once(':').ok_or_else(|| Error::Invalid("Invalid custom races checksum.".into()))?;
|
||||
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) || !files.contains_key(path) {
|
||||
return Err(Error::Invalid("Invalid custom races checksum.".into()));
|
||||
}
|
||||
files.insert(path.into(), hash.into());
|
||||
}
|
||||
Ok(files.into_iter().map(|(path, sha256)| PatchFile { path, sha256 }).collect())
|
||||
}
|
||||
|
||||
fn suffix(path: &Path, extension: &str) -> PathBuf {
|
||||
path.with_file_name(format!("{}.{extension}", path.file_name().unwrap_or_default().to_string_lossy()))
|
||||
}
|
||||
|
||||
fn matches_patch(path: &Path, file: &PatchFile) -> bool {
|
||||
path.is_file() && fsx::sha256_file(path).is_ok_and(|hash| hash == file.sha256)
|
||||
}
|
||||
|
||||
/// Only complete, verified payloads are reported as enabled or disabled.
|
||||
pub fn client_patch_status(client_path: &Path) -> ClientPatchStatus {
|
||||
let data = client_path.join("Data");
|
||||
let installed_mpqs = RACE_MPQS.iter().filter(|name| data.join(name).is_file() || suffix(&data.join(name), "disabled").is_file()).count();
|
||||
let has_root_files = client_path.join("EsteriaAppearance.dll").is_file() || client_path.join("dinput8.dll").is_file() || client_path.join("dinput8.dll.disabled").is_file();
|
||||
let manifest = fs::read_to_string(client_path.join(MANIFEST_FILENAME)).unwrap_or_default();
|
||||
let current = manifest.lines().any(|line| line == format!("# CoA Custom {CLIENT_VERSION}"));
|
||||
let state = if !manifest.is_empty() && current && !client_path.join(".coa-races-transaction").exists() {
|
||||
match patch_files(client_path) {
|
||||
Ok(files) if files.iter().all(|f| matches_patch(&client_path.join(&f.path), f) && !suffix(&client_path.join(&f.path), "disabled").exists()) => ClientPatchState::Enabled,
|
||||
Ok(files) if files.iter().all(|f| matches_patch(&suffix(&client_path.join(&f.path), "disabled"), f)) => ClientPatchState::Disabled,
|
||||
_ => ClientPatchState::PartiallyInstalled,
|
||||
}
|
||||
} else if !manifest.is_empty() || patch_files(client_path).is_ok_and(|files| files.iter().filter(|file| file.path.starts_with("Data/") && file.path != "Data/patch-T.MPQ").any(|file| matches_patch(&client_path.join(&file.path), file) || matches_patch(&suffix(&client_path.join(&file.path), "disabled"), file))) {
|
||||
ClientPatchState::PartiallyInstalled
|
||||
} else { ClientPatchState::NotInstalled };
|
||||
let version = manifest.lines().find_map(|line| line.strip_prefix("# CoA Custom ").map(str::to_string));
|
||||
ClientPatchStatus { state, version, installed_mpqs, total_mpqs: RACE_MPQS.len(), has_root_files,
|
||||
client_path: Some(client_path.to_string_lossy().into_owned()) }
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct SavedFile { path: String, existed: bool }
|
||||
|
||||
struct PatchTransaction<'a> { root: &'a Path, entries: Vec<SavedFile>, finished: bool }
|
||||
impl<'a> PatchTransaction<'a> {
|
||||
fn new(root: &'a Path) -> Result<Self> {
|
||||
recover_patch_transaction(root)?;
|
||||
fs::create_dir(root.join(".coa-races-transaction"))?;
|
||||
Ok(Self { root, entries: Vec::new(), finished: false })
|
||||
}
|
||||
fn save(&mut self, path: &Path) -> Result<()> {
|
||||
let relative = path.strip_prefix(self.root).map_err(|_| Error::Invalid("Patch path escaped the client directory.".into()))?.to_string_lossy().replace('\\', "/");
|
||||
fsx::safe_join(self.root, &relative)?;
|
||||
if self.entries.iter().any(|entry| entry.path == relative) { return Ok(()); }
|
||||
let index = self.entries.len();
|
||||
self.entries.push(SavedFile { path: relative, existed: path.is_file() });
|
||||
fsx::atomic_write_json(&self.root.join(".coa-races-transaction/journal.json"), &self.entries)?;
|
||||
if path.is_file() { fs::rename(path, self.root.join(".coa-races-transaction").join(index.to_string()))?; }
|
||||
Ok(())
|
||||
}
|
||||
fn copy(&mut self, source: &Path, target: &Path) -> Result<()> {
|
||||
self.save(target)?;
|
||||
fs::create_dir_all(target.parent().ok_or_else(|| Error::Invalid("Patch file has no parent directory.".into()))?)?;
|
||||
fs::copy(source, target)?;
|
||||
Ok(())
|
||||
}
|
||||
fn move_file(&mut self, source: &Path, target: &Path) -> Result<()> {
|
||||
self.save(source)?;
|
||||
let index = self.entries.iter().position(|entry| self.root.join(&entry.path) == source).unwrap();
|
||||
// Copy from the journal so rollback retains the previous bytes.
|
||||
let saved = self.root.join(".coa-races-transaction").join(index.to_string());
|
||||
self.copy(&saved, target)
|
||||
}
|
||||
fn finish(mut self) -> Result<()> {
|
||||
fsx::atomic_write(&self.root.join(".coa-races-transaction/committed"), b"committed")?;
|
||||
self.finished = true;
|
||||
fs::remove_dir_all(self.root.join(".coa-races-transaction"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for PatchTransaction<'_> {
|
||||
fn drop(&mut self) { if !self.finished { let _ = recover_patch_transaction(self.root); } }
|
||||
}
|
||||
|
||||
fn recover_patch_transaction(root: &Path) -> Result<()> {
|
||||
let directory = root.join(".coa-races-transaction");
|
||||
if !directory.is_dir() { return Ok(()); }
|
||||
if !directory.join("committed").exists() && directory.join("journal.json").exists() {
|
||||
let entries: Vec<SavedFile> = fsx::read_json(&directory.join("journal.json"))?;
|
||||
for (index, entry) in entries.iter().enumerate().rev() {
|
||||
let path = fsx::safe_join(root, &entry.path)?;
|
||||
let saved = directory.join(index.to_string());
|
||||
if saved.is_file() {
|
||||
if path.is_file() { fs::remove_file(&path)?; }
|
||||
fs::rename(saved, path)?;
|
||||
} else if !entry.existed && path.is_file() { fs::remove_file(path)?; }
|
||||
}
|
||||
}
|
||||
|
||||
tracing::info!(enabled, "custom races client patches toggled");
|
||||
fs::remove_dir_all(directory)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn patch_lock(client: &Path) -> Result<File> {
|
||||
use fs4::fs_std::FileExt;
|
||||
let lock = fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(client.join(".coa-races.lock"))?;
|
||||
if !lock.try_lock_exclusive()? { return Err(Error::Invalid("Another custom races operation is using this client.".into())); }
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
fn preserve_original(tx: &mut PatchTransaction<'_>, active: &Path) -> Result<()> {
|
||||
let original = suffix(active, "original");
|
||||
if original.is_file() && fsx::sha256_file(active)? == fsx::sha256_file(&original)? { return Ok(()); }
|
||||
if original.is_file() {
|
||||
let previous = suffix(active, &format!("original.previous-{}", uuid::Uuid::new_v4().simple()));
|
||||
tx.copy(&original, &previous)?;
|
||||
}
|
||||
tx.copy(active, &original)
|
||||
}
|
||||
|
||||
/// Preserve launcher replacements, and switch every file owned by the package.
|
||||
pub fn set_client_patch_enabled(client: &Path, enabled: bool) -> Result<()> {
|
||||
if !client.is_dir() { return Err(Error::Invalid("Game client directory not found.".into())); }
|
||||
if crate::client::is_running(client) { return Err(Error::Invalid("Close the game before changing custom races patches.".into())); }
|
||||
let _lock = patch_lock(client)?;
|
||||
recover_patch_transaction(client)?;
|
||||
if !client.join(MANIFEST_FILENAME).is_file() { return Ok(()); }
|
||||
let files = patch_files(client)?;
|
||||
if enabled {
|
||||
for file in &files {
|
||||
let active = client.join(&file.path);
|
||||
if !matches_patch(&active, file) && !matches_patch(&suffix(&active, "disabled"), file) {
|
||||
return Err(Error::Invalid(format!("Custom races file {} was replaced or is missing. Repair the client patch before enabling it.", file.path)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut tx = PatchTransaction::new(client)?;
|
||||
for file in files {
|
||||
let active = client.join(&file.path);
|
||||
let disabled = suffix(&active, "disabled");
|
||||
let original = suffix(&active, "original");
|
||||
if enabled {
|
||||
if active.is_file() && !matches_patch(&active, &file) { preserve_original(&mut tx, &active)?; }
|
||||
if matches_patch(&disabled, &file) { tx.move_file(&disabled, &active)?; }
|
||||
} else if matches_patch(&active, &file) {
|
||||
if disabled.is_file() && !matches_patch(&disabled, &file) {
|
||||
tx.move_file(&disabled, &suffix(&disabled, &format!("replaced-{}", uuid::Uuid::new_v4().simple())))?;
|
||||
}
|
||||
tx.move_file(&active, &disabled)?;
|
||||
if original.is_file() { tx.copy(&original, &active)?; }
|
||||
} else if active.is_file() {
|
||||
preserve_original(&mut tx, &active)?;
|
||||
}
|
||||
}
|
||||
tx.finish()
|
||||
}
|
||||
|
||||
pub fn uninstall_client_patches(client: &Path) -> Result<()> {
|
||||
if crate::client::is_running(client) { return Err(Error::Invalid("Close the game before removing custom races patches.".into())); }
|
||||
let _lock = patch_lock(client)?;
|
||||
recover_patch_transaction(client)?;
|
||||
if !client.join(MANIFEST_FILENAME).is_file() { return Ok(()); }
|
||||
let mut tx = PatchTransaction::new(client)?;
|
||||
for file in patch_files(client)? {
|
||||
let active = client.join(&file.path);
|
||||
if matches_patch(&active, &file) {
|
||||
tx.save(&active)?;
|
||||
let original = suffix(&active, "original");
|
||||
if original.is_file() { tx.copy(&original, &active)?; }
|
||||
}
|
||||
let disabled = suffix(&active, "disabled");
|
||||
if active.is_file() && !matches_patch(&active, &file) && !suffix(&active, "original").is_file() {
|
||||
tx.move_file(&active, &suffix(&active, &format!("replaced-{}", uuid::Uuid::new_v4().simple())))?;
|
||||
}
|
||||
if disabled.is_file() {
|
||||
if !matches_patch(&disabled, &file) { tx.move_file(&disabled, &suffix(&disabled, &format!("replaced-{}", uuid::Uuid::new_v4().simple())))?; }
|
||||
else { tx.save(&disabled)?; }
|
||||
}
|
||||
}
|
||||
tx.save(&client.join(MANIFEST_FILENAME))?;
|
||||
tx.finish()
|
||||
}
|
||||
|
||||
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
|
||||
let expected = match filename {
|
||||
"CoA-Custom-1.5-main-20261009-cb2a0ca4.zip" => "117f5d99add18191676be6648fb0f2e99019a06c18705c71454e371e7df2afd2",
|
||||
@@ -376,30 +487,12 @@ pub fn install_client_patches(
|
||||
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");
|
||||
let _lock = patch_lock(client_path)?;
|
||||
recover_patch_transaction(client_path)?;
|
||||
let staging = tempfile::Builder::new().prefix(".coa-races-stage-").tempdir_in(client_path)?;
|
||||
let data_dir = staging.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")))
|
||||
@@ -470,10 +563,10 @@ pub fn install_client_patches(
|
||||
if disabled.is_file() { fs::remove_file(disabled)?; }
|
||||
installed_mpqs.push(base);
|
||||
} else if base.eq_ignore_ascii_case("dinput8.dll") {
|
||||
let dest = client_path.join(&base);
|
||||
let dest = staging.path().join(&base);
|
||||
let mut out = File::create(&dest)?;
|
||||
io::copy(&mut zfile, &mut out)?;
|
||||
let disabled = client_path.join(format!("{base}.disabled"));
|
||||
let disabled = staging.path().join(format!("{base}.disabled"));
|
||||
if disabled.is_file() { fs::remove_file(disabled)?; }
|
||||
installed_roots.push(base);
|
||||
}
|
||||
@@ -484,10 +577,10 @@ pub fn install_client_patches(
|
||||
.unwrap_or_default();
|
||||
|
||||
if !base.is_empty() {
|
||||
let dest = client_path.join(&base);
|
||||
let dest = staging.path().join(&base);
|
||||
let mut out = File::create(&dest)?;
|
||||
io::copy(&mut zfile, &mut out)?;
|
||||
let disabled = client_path.join(format!("{base}.disabled"));
|
||||
let disabled = staging.path().join(format!("{base}.disabled"));
|
||||
if disabled.is_file() { fs::remove_file(disabled)?; }
|
||||
installed_roots.push(base);
|
||||
}
|
||||
@@ -516,7 +609,35 @@ pub fn install_client_patches(
|
||||
manifest_body.push_str(&format!("ROOT:{r}\n"));
|
||||
}
|
||||
|
||||
let bundled: std::collections::BTreeMap<String, String> = serde_json::from_str(include_str!("custom_races_hashes.json"))?;
|
||||
let mut payload = Vec::new();
|
||||
for path in installed_mpqs.iter().map(|name| format!("Data/{name}")).chain(installed_roots.iter().cloned()) {
|
||||
let staged = fsx::safe_join(staging.path(), &path)?;
|
||||
let hash = fsx::sha256_file(&staged)?;
|
||||
if bundled.get(&path) != Some(&hash) { return Err(Error::Invalid(format!("Custom races file {path} failed verification."))); }
|
||||
manifest_body.push_str(&format!("SHA256:{hash}:{path}\n"));
|
||||
payload.push(PatchFile { path, sha256: hash });
|
||||
}
|
||||
if cancel.is_set() { return Err(Error::Invalid("Operation cancelled.".into())); }
|
||||
if payload.len() != bundled.len() { return Err(Error::Invalid("Custom races archives are missing required runtime files.".into())); }
|
||||
let previous = patch_files(client_path)?;
|
||||
let mut tx = PatchTransaction::new(client_path)?;
|
||||
for file in payload {
|
||||
let dest = fsx::safe_join(client_path, &file.path)?;
|
||||
if dest.is_file() && !previous.iter().any(|old| old.path == file.path && matches_patch(&dest, old)) && !matches_patch(&dest, &file) {
|
||||
preserve_original(&mut tx, &dest)?;
|
||||
}
|
||||
tx.copy(&staging.path().join(&file.path), &dest)?;
|
||||
let disabled = suffix(&dest, "disabled");
|
||||
if disabled.is_file() {
|
||||
if !previous.iter().any(|old| old.path == file.path && matches_patch(&disabled, old)) && !matches_patch(&disabled, &file) {
|
||||
tx.move_file(&disabled, &suffix(&disabled, &format!("replaced-{}", uuid::Uuid::new_v4().simple())))?;
|
||||
} else { tx.save(&disabled)?; }
|
||||
}
|
||||
}
|
||||
tx.save(&manifest_path)?;
|
||||
fsx::atomic_write(&manifest_path, manifest_body.as_bytes())?;
|
||||
tx.finish()?;
|
||||
report("Custom races client patches installed successfully!", 1.0);
|
||||
tracing::info!(
|
||||
mpqs = installed_mpqs.len(),
|
||||
@@ -531,23 +652,140 @@ pub fn install_client_patches(
|
||||
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();
|
||||
fn record_files(root: &Path, names: &[&str]) {
|
||||
let mut manifest = format!("# CoA Custom {CLIENT_VERSION}\n");
|
||||
for name in names {
|
||||
let (kind, base) = name.strip_prefix("Data/").map_or(("ROOT", *name), |base| ("MPQ", base));
|
||||
manifest.push_str(&format!("{kind}:{base}\nSHA256:{}:{name}\n", fsx::sha256_file(&root.join(name)).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");
|
||||
fs::write(root.join(MANIFEST_FILENAME), manifest).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Requires the three downloaded release archives"]
|
||||
fn bundled_hashes_match_verified_release_archives() {
|
||||
use sha2::{Digest, Sha256};
|
||||
let folder = PathBuf::from(std::env::var_os("COA_RACES_ARCHIVE_DIR").expect("COA_RACES_ARCHIVE_DIR"));
|
||||
let expected: std::collections::BTreeMap<String, String> = serde_json::from_str(include_str!("custom_races_hashes.json")).unwrap();
|
||||
let mut actual = std::collections::BTreeMap::new();
|
||||
for (name, _) in ARCHIVES {
|
||||
let path = folder.join(name);
|
||||
verify_archive(&path, name).unwrap();
|
||||
let mut archive = zip::ZipArchive::new(File::open(path).unwrap()).unwrap();
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index).unwrap();
|
||||
let name = entry.name().replace('\\', "/");
|
||||
if entry.is_dir() { continue; }
|
||||
let relative = if let Some(name) = name.split("files/client_root/").nth(1) { name.to_string() }
|
||||
else if let Some(name) = name.split("files/client/").nth(1) { if name == "dinput8.dll" { name.to_string() } else { format!("Data/{name}") } }
|
||||
else { continue };
|
||||
let mut hash = Sha256::new();
|
||||
let mut buffer = vec![0; 1024 * 1024];
|
||||
loop { let read = entry.read(&mut buffer).unwrap(); if read == 0 { break; } hash.update(&buffer[..read]); }
|
||||
actual.insert(relative, hex::encode(hash.finalize()));
|
||||
}
|
||||
}
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_patch_operation_cannot_enter_the_same_client() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = patch_lock(temp.path()).unwrap();
|
||||
assert!(patch_lock(temp.path()).is_err());
|
||||
drop(first);
|
||||
patch_lock(temp.path()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_preserves_launcher_updates_for_every_owned_file() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
fs::create_dir_all(root.join("Data")).unwrap();
|
||||
let names = ["Data/patch-T.MPQ", "Data/patch-ZE1.MPQ", "Ascension.exe", "dinput8.dll", "EsteriaAppearance.dll"];
|
||||
for name in names { fs::write(root.join(name), b"custom").unwrap(); fs::write(suffix(&root.join(name), "original"), b"old official").unwrap(); }
|
||||
record_files(root, &names);
|
||||
set_client_patch_enabled(root, false).unwrap();
|
||||
for name in names { assert_eq!(fs::read(root.join(name)).unwrap(), b"old official"); fs::write(root.join(name), b"new official").unwrap(); }
|
||||
set_client_patch_enabled(root, true).unwrap();
|
||||
for name in names { assert_eq!(fs::read(root.join(name)).unwrap(), b"custom"); assert_eq!(fs::read(suffix(&root.join(name), "original")).unwrap(), b"new official"); }
|
||||
// An official launcher can also replace a currently enabled file.
|
||||
fs::write(root.join("Ascension.exe"), b"newest official").unwrap();
|
||||
assert_eq!(client_patch_status(root).state, ClientPatchState::PartiallyInstalled);
|
||||
set_client_patch_enabled(root, false).unwrap();
|
||||
assert_eq!(fs::read(root.join("Ascension.exe")).unwrap(), b"newest official");
|
||||
assert!(set_client_patch_enabled(root, true).unwrap_err().to_string().contains("Repair"));
|
||||
uninstall_client_patches(root).unwrap();
|
||||
assert_eq!(fs::read(root.join("Ascension.exe")).unwrap(), b"newest official");
|
||||
assert_eq!(client_patch_status(root).state, ClientPatchState::NotInstalled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_and_interrupted_transactions_restore_previous_bytes() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let file = root.join("Ascension.exe");
|
||||
fs::write(&file, b"previous").unwrap();
|
||||
{
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.save(&file).unwrap();
|
||||
fs::write(&file, b"replacement").unwrap();
|
||||
let staged = root.join("staged.dll");
|
||||
fs::write(&staged, b"new").unwrap();
|
||||
tx.copy(&staged, &root.join("Data/new.dll")).unwrap();
|
||||
assert_eq!(fs::read(root.join("Data/new.dll")).unwrap(), b"new");
|
||||
}
|
||||
assert_eq!(fs::read(&file).unwrap(), b"previous");
|
||||
assert!(!root.join("Data/new.dll").exists());
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.save(&file).unwrap();
|
||||
fs::write(&file, b"interrupted").unwrap();
|
||||
std::mem::forget(tx);
|
||||
recover_patch_transaction(root).unwrap();
|
||||
assert_eq!(fs::read(&file).unwrap(), b"previous");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_backups_and_foreign_disabled_files_are_retained() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
let file = root.join("dinput8.dll");
|
||||
fs::write(&file, b"custom").unwrap();
|
||||
record_files(root, &["dinput8.dll"]);
|
||||
fs::write(suffix(&file, "disabled"), b"third party").unwrap();
|
||||
fs::write(suffix(&file, "original"), b"original").unwrap();
|
||||
set_client_patch_enabled(root, false).unwrap();
|
||||
assert_eq!(fs::read(&file).unwrap(), b"original");
|
||||
assert!(fs::read_dir(root).unwrap().flatten().any(|entry| entry.file_name().to_string_lossy().contains("replaced-")));
|
||||
fs::write(&file, b"updated original").unwrap();
|
||||
set_client_patch_enabled(root, true).unwrap();
|
||||
assert!(fs::read_dir(root).unwrap().flatten().any(|entry| entry.file_name().to_string_lossy().contains("original.previous-")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uninstall_moves_corrupted_custom_only_assets_out_of_the_active_client() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
fs::create_dir_all(root.join("Data")).unwrap();
|
||||
let file = root.join("Data/patch-ZE1.MPQ");
|
||||
fs::write(&file, b"custom").unwrap();
|
||||
record_files(root, &["Data/patch-ZE1.MPQ"]);
|
||||
fs::write(&file, b"corrupted custom").unwrap();
|
||||
uninstall_client_patches(root).unwrap();
|
||||
assert!(!file.exists());
|
||||
assert!(fs::read_dir(root.join("Data")).unwrap().flatten().any(|entry| entry.file_name().to_string_lossy().contains("replaced-")));
|
||||
assert_eq!(client_patch_status(root).state, ClientPatchState::NotInstalled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_or_corrupt_bytes_are_not_reported_as_enabled() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
fs::create_dir_all(root.join("Data")).unwrap();
|
||||
for name in RACE_MPQS { fs::write(root.join("Data").join(name), b"corrupt").unwrap(); }
|
||||
fs::write(root.join("dinput8.dll"), b"corrupt").unwrap();
|
||||
fs::write(root.join(MANIFEST_FILENAME), format!("# CoA Custom {CLIENT_VERSION}\n")).unwrap();
|
||||
assert_eq!(client_patch_status(root).state, ClientPatchState::PartiallyInstalled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -595,6 +833,8 @@ mod tests {
|
||||
fs::write(client_path.join("dinput8.dll"), b"test dll").unwrap();
|
||||
fs::write(client_path.join("EsteriaAppearance.dll"), b"test dll").unwrap();
|
||||
|
||||
let names: Vec<String> = RACE_MPQS.iter().map(|name| format!("Data/{name}")).chain(["dinput8.dll".into(), "EsteriaAppearance.dll".into()]).collect();
|
||||
record_files(client_path, &names.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
let st = client_patch_status(client_path);
|
||||
assert_eq!(st.state, ClientPatchState::Enabled);
|
||||
assert_eq!(st.installed_mpqs, RACE_MPQS.len());
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
|
||||
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
|
||||
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
|
||||
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
|
||||
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
|
||||
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
|
||||
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
|
||||
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
|
||||
"EsteriaAppearance.bin": "b3fb7c69b7600c39f888ea1925701be5667097dcb02bb6ddd830e5489306bb50",
|
||||
"EsteriaAppearance.dll": "392c5a2a25f9a69d705bdf841bb899aab768d4a3ee62734d576286c7198710d8",
|
||||
"EsteriaAppearanceGeometry.bin": "c95c53ca19c53c3434e12b99c1966f9c015ec3944c46dff7784d5e4ffc472d5d",
|
||||
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
|
||||
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
|
||||
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
|
||||
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
|
||||
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
|
||||
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
|
||||
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
|
||||
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
|
||||
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
|
||||
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
|
||||
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
|
||||
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
|
||||
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
|
||||
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
|
||||
"EsteriaThinHuman.bin": "75794d192ea0c228b3da7bf7d0bdff1119f79d3f9bfef6650cd5e1a2b5d106eb",
|
||||
"EsteriaThinHumanTextures.bin": "02aeb4c05893d06125b8b58fdb7c2a56fe3d66a7d094706a44b43cb503d1731e",
|
||||
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
|
||||
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
|
||||
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
|
||||
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
|
||||
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
|
||||
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
|
||||
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
|
||||
"Data/patch-T.MPQ": "9403e0680c74754eb0cb063718119aa6ace3616f7cecf488c8faf46f22505ae5",
|
||||
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
|
||||
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
|
||||
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
|
||||
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
|
||||
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
|
||||
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
|
||||
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
|
||||
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
|
||||
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
|
||||
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
|
||||
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
|
||||
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020"
|
||||
}
|
||||
@@ -119,7 +119,26 @@ fn conf_name(root: &Path, e: &Entry) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
|
||||
let Ok(directory) = crate::registry::metadata_dir_for(root) else { return Default::default() };
|
||||
let Ok((_, meta)) = crate::registry::MetaDir::open(&directory) else { return Default::default() };
|
||||
let Some(version) = meta.core.version else { return Default::default() };
|
||||
let candidates = [directory.join("manifests").join(format!("update-{version}.json")), directory.join("manifests/base.json")];
|
||||
for path in candidates {
|
||||
let Ok(manifest) = crate::fsx::read_json::<serde_json::Value>(&path) else { continue };
|
||||
if manifest.get("version").and_then(|value| value.as_str()) != Some(&version) { continue; }
|
||||
if let Some(commits) = manifest.get("compatibility").and_then(|value| value.get("moduleCommits")).and_then(|value| value.as_object()) {
|
||||
return commits.iter().filter_map(|(name, commit)| {
|
||||
let commit = commit.as_str()?;
|
||||
(commit.len() == 40 && commit.bytes().all(|byte| byte.is_ascii_hexdigit())).then(|| (name.clone(), commit.chars().take(8).collect()))
|
||||
}).collect();
|
||||
}
|
||||
}
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
|
||||
let installed_commits = installed_module_commits(root);
|
||||
let wildcard = crate::realms::state(root).map(|s| s.active == crate::realms::Mode::Wildcard).unwrap_or(true);
|
||||
cat.iter()
|
||||
.cloned()
|
||||
@@ -141,6 +160,8 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
|
||||
let version = if e.id == "playerbots" { crate::squid::release(root).map(|release| {
|
||||
[release.tag, release.commit.map(|commit| commit.chars().take(8).collect())].into_iter().flatten().collect::<Vec<_>>().join(" · ")
|
||||
}) } else { None };
|
||||
let key = match e.id.as_str() { "companions" => "bots", "playerbots" => "squid", "content-scaling" => "scaling", "custom-races" => "races", id => id };
|
||||
let version = if installed { version.or_else(|| installed_commits.get(key).cloned()) } else { None };
|
||||
ModuleView {
|
||||
version,
|
||||
compatibility: if blocked { "unsupported" } else if wildcard && e.id != "client-compat" { "experimental" } else { "compatible" }.into(),
|
||||
@@ -341,20 +362,6 @@ fn save_settings_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, changes:
|
||||
for (key, value) in changes {
|
||||
let value = value.trim();
|
||||
if let Some(field) = fields.get(key) { crate::squid::validate(field, value)?; }
|
||||
if id == "time-is-time" {
|
||||
let bounds = match key.as_str() {
|
||||
"TimeIsTime.SpeedRate" => Some((0.01, 60.0)),
|
||||
"TimeIsTime.HourOffset" => Some((-24.0, 24.0)),
|
||||
"TimeIsTime.TimeStart" => Some((0.0, 2147483647.0)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((min, max)) = bounds {
|
||||
let number = value.parse::<f64>().map_err(|_| Error::Invalid(format!("{key} must be a number.")))?;
|
||||
if !number.is_finite() || number < min || number > max || (key == "TimeIsTime.TimeStart" && number.fract() != 0.0) {
|
||||
return Err(Error::Invalid(format!("{key} must be between {min} and {max}.")));
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.switchable && key == &e.enable_key {
|
||||
return Err(Error::Invalid("Use the module switch to turn this module on or off.".into()));
|
||||
}
|
||||
@@ -411,24 +418,6 @@ fn save_settings_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, changes:
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn time_settings_are_validated_before_writing() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path();
|
||||
fs::create_dir_all(dir(root)).unwrap();
|
||||
fs::write(dir(root).join("mod-time_is_time.conf.dist"), "TimeIsTime.Enable = 0\nTimeIsTime.SpeedRate = 1\nTimeIsTime.HourOffset = 0\nTimeIsTime.TimeStart = 0\n").unwrap();
|
||||
let cat = catalog();
|
||||
for (key, value) in [("TimeIsTime.SpeedRate", "NaN"), ("TimeIsTime.SpeedRate", "0"),
|
||||
("TimeIsTime.HourOffset", "25"), ("TimeIsTime.TimeStart", "1.5")] {
|
||||
assert!(save_settings_in(&cat, root, root, "time-is-time", &BTreeMap::from([
|
||||
(key.into(), value.into())
|
||||
])).is_err());
|
||||
}
|
||||
assert!(save_settings_in(&cat, root, root, "time-is-time", &BTreeMap::from([
|
||||
("TimeIsTime.SpeedRate".into(), "60".into())
|
||||
])).is_ok());
|
||||
}
|
||||
|
||||
fn test_catalog() -> Vec<Entry> {
|
||||
let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
|
||||
id: id.into(),
|
||||
@@ -457,6 +446,22 @@ mod tests {
|
||||
(root, meta)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn module_revisions_come_from_the_installed_release_only() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("server");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::Imported, &root);
|
||||
meta.core.version = Some("2.0.0".into());
|
||||
let directory = crate::registry::MetaDir::create(&root, &meta).unwrap();
|
||||
let value = serde_json::json!({"version": "2.0.0", "compatibility": {"moduleCommits": {"races": "a".repeat(40), "bots": "b".repeat(40)}}});
|
||||
fsx::atomic_write_json(&directory.root.join("manifests/update-2.0.0.json"), &value).unwrap();
|
||||
assert_eq!(installed_module_commits(&root).get("races").map(String::as_str), Some("aaaaaaaa"));
|
||||
let stale = serde_json::json!({"version": "1.0.0", "compatibility": {"moduleCommits": {"races": "c".repeat(40)}}});
|
||||
fsx::atomic_write_json(&directory.root.join("manifests/update-2.0.0.json"), &stale).unwrap();
|
||||
assert!(installed_module_commits(&root).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn squid_missing_keys_use_code_defaults_and_saves_enforce_json_ranges() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -68,24 +68,6 @@ pub fn read_state_record(root: &Path, name: &str) -> Option<ProcessIdentity> {
|
||||
fsx::read_json(&root.join(".state").join(format!("{name}.json"))).ok()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ProcessExit {
|
||||
process: ProcessIdentity,
|
||||
exit_code: i64,
|
||||
}
|
||||
|
||||
fn exited_state(root: &Path, name: &str, expected: &[String]) -> ServiceState {
|
||||
let exit: Option<ProcessExit> = fsx::read_json(&root.join(".state").join(format!("{name}-exit.json"))).ok();
|
||||
let record = read_state_record(root, name);
|
||||
match (exit, record) {
|
||||
(Some(exit), Some(record))
|
||||
if exit.process.same_as(&record)
|
||||
&& expected.iter().any(|exe| record.exe.eq_ignore_ascii_case(exe))
|
||||
&& exit.exit_code != 0 && exit.exit_code != 2 => ServiceState::Crashed,
|
||||
_ => ServiceState::Stopped,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod sys {
|
||||
use super::ProcessIdentity;
|
||||
@@ -322,7 +304,7 @@ fn service_with(root: &Path, name: &'static str, exe: PathBuf, alternatives: &[P
|
||||
(None, Some(o)) => {
|
||||
(ServiceState::Stopped, false, Some(PortConflict { port, pid: o, exe: identity(o).map(|i| i.exe) }))
|
||||
}
|
||||
(None, None) => (exited_state(root, name, &expected), false, None),
|
||||
(None, None) => (ServiceState::Stopped, false, None),
|
||||
};
|
||||
ServiceStatus {
|
||||
name,
|
||||
@@ -418,25 +400,4 @@ mod tests {
|
||||
assert_eq!(o.world.state, ServiceState::Stopped);
|
||||
assert!(o.world.pid.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_matching_abnormal_exits_are_crashes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let state = dir.path().join(".state");
|
||||
std::fs::create_dir_all(&state).unwrap();
|
||||
let record = ProcessIdentity { pid: 42, created: 123, exe: "C:\\server\\worldserver.exe".into() };
|
||||
let expected = vec![record.exe.clone()];
|
||||
std::fs::write(state.join("world.json"), serde_json::to_vec(&record).unwrap()).unwrap();
|
||||
for (code, want) in [(0i64, ServiceState::Stopped), (2, ServiceState::Stopped), (1, ServiceState::Crashed),
|
||||
(3221225477, ServiceState::Crashed)] {
|
||||
std::fs::write(state.join("world-exit.json"), serde_json::to_vec(&serde_json::json!({
|
||||
"process": record, "exit_code": code
|
||||
})).unwrap()).unwrap();
|
||||
assert_eq!(exited_state(dir.path(), "world", &expected), want);
|
||||
}
|
||||
let newer = ProcessIdentity { created: 124, ..record };
|
||||
std::fs::write(state.join("world.json"), serde_json::to_vec(&newer).unwrap()).unwrap();
|
||||
assert_eq!(exited_state(dir.path(), "world", &expected), ServiceState::Stopped);
|
||||
assert_eq!(exited_state(dir.path(), "world", &["C:\\other.exe".into()]), ServiceState::Stopped);
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,6 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"modules": [
|
||||
{
|
||||
"id": "time-is-time",
|
||||
"name": "TimeIsTime",
|
||||
"description": {
|
||||
"en": "Adjust the visual day and night cycle without changing server timers.",
|
||||
"ru": "Настройка визуального цикла дня и ночи без изменения серверных таймеров.",
|
||||
"de": "Passt den sichtbaren Tag-Nacht-Zyklus an, ohne Serverzeiten zu ändern.",
|
||||
"fr": "Ajuste le cycle visuel jour-nuit sans modifier les minuteries du serveur.",
|
||||
"es": "Ajusta el ciclo visual día-noche sin cambiar los temporizadores del servidor."
|
||||
},
|
||||
"repo": "https://github.com/dunjeon/mod-TimeIsTime",
|
||||
"conf": "mod-time_is_time.conf",
|
||||
"enable_key": "TimeIsTime.Enable",
|
||||
"switchable": true,
|
||||
"default_on": false,
|
||||
"status": "beta",
|
||||
"icon": "clock"
|
||||
},
|
||||
{
|
||||
"id": "companions",
|
||||
"name": "CoA Companions",
|
||||
|
||||
@@ -699,6 +699,13 @@ async fn custom_races_install(app: AppHandle, state: State<'_, AppState>, id: St
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn custom_races_uninstall(state: State<'_, AppState>, id: String) -> std::result::Result<(), UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || coa_core::custom_races::uninstall_client_patches(&ctx.require()?)).await
|
||||
}
|
||||
|
||||
#[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)?;
|
||||
@@ -1764,6 +1771,7 @@ pub fn run() {
|
||||
console_command,
|
||||
custom_races_status,
|
||||
custom_races_install,
|
||||
custom_races_uninstall,
|
||||
custom_races_toggle_client
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
|
||||
@@ -393,6 +393,7 @@ export interface ClientDownloadCheck {
|
||||
export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
|
||||
|
||||
export interface CustomRacesClientStatus {
|
||||
version: string | null;
|
||||
state: ClientPatchState;
|
||||
installedMpqs: number;
|
||||
totalMpqs: number;
|
||||
@@ -547,6 +548,7 @@ export const api = {
|
||||
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 }),
|
||||
customRacesUninstall: (id: string) => invoke<void>("custom_races_uninstall", { 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 }),
|
||||
|
||||
@@ -14,10 +14,6 @@ const text = (values: string[], locale: Locale) => values[locales.indexOf(locale
|
||||
type Entry = { key: string; type: string; title: string[]; description: string[]; min?: number; max?: number; advanced?: boolean; options?: { value: string; label: string[] }[] };
|
||||
export const moduleSettingDefinitions: Entry[] = [];
|
||||
const fields = moduleSettingDefinitions;
|
||||
add("TimeIsTime.Announce", "bool", ["Announce on login", "Сообщение при входе"], ["Show a module notice when a character logs in.", "Показывать сообщение о модуле при входе персонажа."]);
|
||||
add("TimeIsTime.SpeedRate", "float", ["Day/night speed", "Скорость смены дня и ночи"], ["1 follows real time; 60 gives one game day every 24 minutes. Changes only the client visual clock.", "1 — реальное время; 60 — игровые сутки за 24 минуты. Меняет только визуальное время клиента."], { min: 0.01, max: 60 });
|
||||
add("TimeIsTime.HourOffset", "float", ["Hour offset", "Смещение часов"], ["Offset applied to the visual client clock, in hours.", "Смещение визуальных часов клиента в часах."], { min: -24, max: 24 });
|
||||
add("TimeIsTime.TimeStart", "int", ["Starting time", "Начальное время"], ["Unix timestamp used at every login; 0 uses the server clock.", "Unix-время при каждом входе; 0 использует часы сервера."], { min: 0, max: 2147483647 });
|
||||
function add(key: string, type: string, title: string[], description: string[], extra: Partial<Entry> = {}) {
|
||||
fields.push({ key, type, title, description, ...extra });
|
||||
}
|
||||
@@ -73,11 +69,8 @@ add(scaling + "LFG.DefaultChallengeSize", "int", ["Challenge group size", "Ра
|
||||
add(scaling + "GroupScaling.LockOnEncounterStart", "bool", ["Lock scaling during combat", "Фиксировать скейлинг на время боя", "Skalierung im Kampf sperren", "Figer l’adaptation en combat", "Fijar ajuste durante combate", "战斗期间锁定缩放"], ["Joining or leaving during a boss fight does not change its scaling.", "Вход и выход игроков во время боя с боссом не меняют скейлинг.", "Beitreten oder Verlassen während eines Bosskampfs ändert die Skalierung nicht.", "Les arrivées et départs pendant un boss ne changent pas l’adaptation.", "Entrar o salir durante un jefe no cambia el ajuste.", "首领战期间玩家进出不会改变缩放。"], { advanced: true });
|
||||
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic boundaries follow the level cap and enabled expansions. Custom uses the levels below.", "Автоматические границы зависят от максимального уровня и включённых дополнений. Ручные используют уровни ниже.", "Automatisch folgt der Maximalstufe und Erweiterungen. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique suit le niveau maximal et les extensions. Manuel utilise les niveaux ci-dessous.", "Automático sigue el nivel máximo y las expansiones. Manual usa los niveles siguientes.", "自动边界按等级上限和启用的资料片计算,自定义使用以下等级。"], { advanced: true, options: [
|
||||
{ value: "Auto", label: ["Automatic", "Автоматически", "Automatisch", "Automatique", "Automático", "自动"] },
|
||||
{ value: "Parallel", label: ["Parallel: Classic 1–60, TBC/WotLK 45–60", "Параллельно: классика 1–60, БК/ЛК 45–60", "Parallel: Classic 1–60, TBC/WotLK 45–60", "Parallèle : Classic 1–60, TBC/WotLK 45–60", "Paralelo: Classic 1–60, TBC/WotLK 45–60", "并行:经典1–60,TBC/WotLK45–60"] },
|
||||
{ value: "Global", label: ["Global: all eras 1–60", "Всё содержимое 1–60", "Alle Erweiterungen 1–60", "Toutes les extensions 1–60", "Todas las expansiones 1–60", "全部资料片1–60"] },
|
||||
{ value: "Custom", label: ["Custom", "Вручную", "Benutzerdefiniert", "Manuel", "Manual", "自定义"] },
|
||||
] });
|
||||
add(scaling + "Items.RemoveClassRestrictions", "bool", ["Remove item class requirements", "Убрать классовые ограничения предметов"], ["Allow all classes to equip class-restricted items, including tier sets. Requires a world server restart.", "Разрешает всем классам надевать предметы с классовыми ограничениями, включая комплекты T10. Требуется перезапуск игрового сервера."]);
|
||||
for (const era of ["Classic", "Tbc"]) add(scaling + `Progression.${era}End`, "int", [`${era} last level`, `Последний уровень ${era}`, `${era}-Endstufe`, `Dernier niveau ${era}`, `Último nivel ${era}`, `${era} 最高等级`], ["Used in custom progression. 0 chooses automatically.", "Для ручной прогрессии. 0 — автоматически.", "Für benutzerdefinierten Fortschritt. 0 wählt automatisch.", "Pour la progression manuelle. 0 choisit automatiquement.", "Para progresión manual. 0 elige automáticamente.", "用于自定义进度,0为自动。"], { min: 0, max: 80, advanced: true });
|
||||
add(scaling + "Debug", "bool", ["Detailed scaling logs", "Подробные логи скейлинга", "Ausführliche Skalierungsprotokolle", "Journaux détaillés", "Registros detallados", "详细缩放日志"], ["Log scaling calculations for troubleshooting.", "Записывает расчёты скейлинга для диагностики.", "Protokolliert Berechnungen zur Fehleranalyse.", "Enregistre les calculs pour le diagnostic.", "Registra cálculos para diagnóstico.", "记录缩放计算以排查问题。"], { advanced: true });
|
||||
|
||||
@@ -210,6 +203,6 @@ export function canonicalModuleValue(key: string, value: string): string {
|
||||
const v = value.trim().replace(/^"|"$/g, "");
|
||||
if (key === scaling + "SoloAssist.Mode") return ({ "0": "None", "1": "Light", "2": "Full", none: "None", light: "Light", full: "Full" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
if (key === scaling + "LFG.DefaultMode") return ({ "0": "Matchmaking", "1": "BotFill", "2": "CurrentParty", matchmaking: "Matchmaking", botfill: "BotFill", currentparty: "CurrentParty" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
if (key === scaling + "Progression.Mode") return ({ auto: "Auto", custom: "Custom", parallel: "Parallel", global: "Global" } as Record<string, string>)[v.toLowerCase()] ?? v;
|
||||
if (key === scaling + "Progression.Mode") return v.toLowerCase() === "auto" ? "Auto" : v.toLowerCase() === "custom" ? "Custom" : v;
|
||||
return v;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Bot, Clock, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
|
||||
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";
|
||||
@@ -21,7 +21,6 @@ function GithubMark(props: { className?: string }) {
|
||||
|
||||
/** Icon and colours of a module's square tile, by the name the catalog gives it. */
|
||||
const TILES: Record<string, { icon: ComponentType<LucideProps>; from: string; to: string }> = {
|
||||
clock: { icon: Clock, from: "from-amber-500", to: "to-indigo-700" },
|
||||
bot: { icon: Bot, from: "from-emerald-500", to: "to-teal-700" },
|
||||
scaling: { icon: Scaling, from: "from-violet-500", to: "to-indigo-700" },
|
||||
plug: { icon: Plug, from: "from-amber-500", to: "to-orange-700" },
|
||||
@@ -145,6 +144,17 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
}
|
||||
}
|
||||
|
||||
async function uninstallClientPatch() {
|
||||
setRacesInstalling(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.customRacesUninstall(serverId);
|
||||
await load();
|
||||
onChanged?.();
|
||||
} catch (e) { setError(asUiError(e)); }
|
||||
finally { setRacesInstalling(false); }
|
||||
}
|
||||
|
||||
async function toggle(m: ModuleView) {
|
||||
setError(null);
|
||||
try {
|
||||
@@ -206,7 +216,9 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
{!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">
|
||||
<p className="text-xs text-muted">{locale === "ru" ? "Установленная версия патча клиента: " : "Installed client patch version: "}{racesPatchStatus?.version ?? (locale === "ru" ? "не записана" : "not recorded")}</p>
|
||||
{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">
|
||||
@@ -253,7 +265,8 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{(!racesPatchStatus || racesPatchStatus.state === "not-installed" || racesPatchStatus.state === "partially-installed") && (
|
||||
{racesPatchStatus?.state === "partially-installed" && <p className="text-xs text-warn">{locale === "ru" ? "Файлы отсутствуют или изменены. Восстановите патч клиента." : "Files are missing or changed. Repair the client patch."}</p>}
|
||||
{(
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
@@ -262,9 +275,11 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
onClick={() => void installClientPatch()}
|
||||
>
|
||||
{racesInstalling && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
{locale === "ru" ? "Установить патч клиента" : "Install Client Patch 1.5"}
|
||||
{racesPatchStatus?.state === "not-installed" ? (locale === "ru" ? "Установить патч клиента" : "Install Client Patch") : (locale === "ru" ? "Восстановить патч клиента" : "Repair Client Patch")}
|
||||
</Button>
|
||||
)}
|
||||
{racesPatchStatus && racesPatchStatus.state !== "not-installed" && <Button size="sm" variant="ghost" disabled={racesInstalling} onClick={() => void uninstallClientPatch()}>{locale === "ru" ? "Удалить патч клиента" : "Uninstall Client Patch"}</Button>}
|
||||
<p className="text-xs text-muted">{locale === "ru" ? (m.enabled ? "После установки патч будет включён." : "После установки патч останется отключённым: модуль сервера выключен или отсутствует.") : (m.enabled ? "The patch will be enabled after installation." : "The patch will stay disabled after installation: the server module is off or missing.")}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -196,7 +196,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
if (alive.current) setPop(null);
|
||||
if (
|
||||
wasWorldRunningRef.current &&
|
||||
s.observed.world.state === "crashed" &&
|
||||
!userStoppedRef.current &&
|
||||
actionRef.current === null
|
||||
) {
|
||||
|
||||
Reference in new issue
Block a user