mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Merge integrate/manager-0.9.14 into preview: game cache, friend's login, addon catalog
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # crates/coa-core/src/lib.rs
This commit is contained in:
commit
34f6fa1cd1
22 files changed
+8026
No files matched your search
+7247
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: players
|
||||
title: Install community addons from the Manager
|
||||
---
|
||||
The game client card lists SquidBots Lite, DragonUI, IncahootsCoA and CoACombat. Each comes from its author's GitHub at a pinned version, every file is checked before it goes into Interface/AddOns, and the Manager updates or removes only what it installed.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: players
|
||||
title: The game cache is cleared before every Play
|
||||
---
|
||||
After a server update the game showed old names and stats from its own cache (Cache/WDB). Play now clears that cache first; it fills again within seconds. A switch next to the client graphics settings turns it off.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: players
|
||||
title: The account for a friend's server is in the login box at every Play
|
||||
---
|
||||
The account the Manager made on a listed server was filled in only when joining. Play now fills it in every time, also after another server's account was used.
|
||||
@@ -0,0 +1,459 @@
|
||||
//! A catalog of game addons the Manager can install into a client's `Interface/AddOns`.
|
||||
//!
|
||||
//! Every addon is pinned to a commit of its GitHub repository; the catalog lists each file it installs with its
|
||||
//! git blob SHA-1 and size, which are checked after download (GitHub's archives are not byte-stable, their
|
||||
//! contents are). The Manager records what it installed in `Interface/AddOns/.coa-addons.json` and only ever
|
||||
//! removes or replaces those folders; a folder of the same name that someone else put there is moved to
|
||||
//! `Interface/AddOns/.coa-addons-backup` first.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
use crate::download::{Cancel, Transport};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
static CATALOG: &str = include_str!("../../../addons/catalog.json");
|
||||
const STATE: &str = ".coa-addons.json";
|
||||
const BACKUP: &str = ".coa-addons-backup";
|
||||
/// No addon archive is anywhere near this; a larger answer is not what the catalog describes.
|
||||
const MAX_ARCHIVE: u64 = 1 << 30;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct AddonFile {
|
||||
path: String,
|
||||
from: String,
|
||||
sha1: String,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
struct Entry {
|
||||
id: String,
|
||||
name: String,
|
||||
description: BTreeMap<String, String>,
|
||||
author: String,
|
||||
license: String,
|
||||
#[serde(default)]
|
||||
needs: Option<String>,
|
||||
repo: String,
|
||||
commit: String,
|
||||
archive: String,
|
||||
folders: Vec<String>,
|
||||
files: Vec<AddonFile>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog {
|
||||
addons: Vec<Entry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
|
||||
struct Installed {
|
||||
commit: String,
|
||||
folders: Vec<String>,
|
||||
}
|
||||
|
||||
/// One addon of the catalog as the Manager shows it for a client.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AddonView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: BTreeMap<String, String>,
|
||||
pub author: String,
|
||||
pub license: String,
|
||||
/// A server module the addon is made for (`playerbots`), shown as a hint.
|
||||
pub needs: Option<String>,
|
||||
pub repo: String,
|
||||
pub size: u64,
|
||||
pub installed: bool,
|
||||
pub update_available: bool,
|
||||
/// Folders of this addon that are in the client but were not installed by the Manager.
|
||||
pub foreign_folders: Vec<String>,
|
||||
}
|
||||
|
||||
fn catalog() -> Result<Vec<Entry>> {
|
||||
let catalog: Catalog = serde_json::from_str(CATALOG)?;
|
||||
for entry in &catalog.addons {
|
||||
for folder in &entry.folders {
|
||||
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
|
||||
return Err(Error::Invalid(format!("Invalid addon folder in the catalog: {folder}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(catalog.addons)
|
||||
}
|
||||
|
||||
fn addons_dir(client: &Path) -> PathBuf {
|
||||
client.join("Interface").join("AddOns")
|
||||
}
|
||||
|
||||
fn read_state(client: &Path) -> BTreeMap<String, Installed> {
|
||||
fsx::read_json(&addons_dir(client).join(STATE)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn write_state(client: &Path, state: &BTreeMap<String, Installed>) -> Result<()> {
|
||||
fsx::atomic_write_json(&addons_dir(client).join(STATE), state)
|
||||
}
|
||||
|
||||
/// The catalog with what is installed in `client`.
|
||||
pub fn list(client: &Path) -> Result<Vec<AddonView>> {
|
||||
let state = read_state(client);
|
||||
let dir = addons_dir(client);
|
||||
let owned: Vec<&String> = state.values().flat_map(|i| i.folders.iter()).collect();
|
||||
Ok(catalog()?
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let installed = state.get(&entry.id);
|
||||
AddonView {
|
||||
foreign_folders: entry
|
||||
.folders
|
||||
.iter()
|
||||
.filter(|f| dir.join(f).exists() && !owned.contains(f))
|
||||
.cloned()
|
||||
.collect(),
|
||||
size: entry.files.iter().map(|f| f.size).sum(),
|
||||
installed: installed.is_some(),
|
||||
update_available: installed.is_some_and(|i| i.commit != entry.commit),
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
description: entry.description,
|
||||
author: entry.author,
|
||||
license: entry.license,
|
||||
needs: entry.needs,
|
||||
repo: entry.repo,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// The git blob id of `bytes` (what the catalog records for each file).
|
||||
fn git_blob_sha1(bytes: &[u8]) -> String {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
|
||||
hasher.update(bytes);
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
fn download(transport: &dyn Transport, url: &str, dest: &Path, cancel: &Cancel) -> Result<()> {
|
||||
crate::download::check_url(url)?;
|
||||
let reply = transport.get(url, 0).map_err(Error::Invalid)?;
|
||||
if reply.status != 200 {
|
||||
return Err(Error::Invalid(format!("The addon download answered HTTP {}.", reply.status)));
|
||||
}
|
||||
let mut body = reply.body.take(MAX_ARCHIVE + 1);
|
||||
let mut file = fs::File::create(dest)?;
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
let mut total = 0u64;
|
||||
loop {
|
||||
if cancel.is_set() {
|
||||
return Err(Error::Invalid("Operation cancelled.".into()));
|
||||
}
|
||||
let n = body.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
total += n as u64;
|
||||
if total > MAX_ARCHIVE {
|
||||
return Err(Error::Invalid("The addon download is larger than any catalog addon.".into()));
|
||||
}
|
||||
file.write_all(&buf[..n])?;
|
||||
}
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Unpack the catalog's files of `entry` from `archive` into `staging`, checking every one.
|
||||
fn unpack(entry: &Entry, archive: &Path, staging: &Path) -> Result<()> {
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(archive)?)
|
||||
.map_err(|e| Error::Invalid(format!("The addon download is not a zip archive: {e}")))?;
|
||||
// GitHub archives hold everything under one top folder (`<repo>-<commit>/`).
|
||||
let mut by_path = BTreeMap::new();
|
||||
for index in 0..zip.len() {
|
||||
let name = zip
|
||||
.by_index(index)
|
||||
.map_err(|e| Error::Invalid(e.to_string()))?
|
||||
.name()
|
||||
.replace('\\', "/");
|
||||
if let Some((_, inner)) = name.split_once('/') {
|
||||
by_path.insert(inner.to_string(), index);
|
||||
}
|
||||
}
|
||||
for file in &entry.files {
|
||||
let index = *by_path
|
||||
.get(&file.from)
|
||||
.ok_or_else(|| Error::Invalid(format!("The addon download lacks {}.", file.from)))?;
|
||||
let mut zipped = zip.by_index(index).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
let mut bytes = Vec::with_capacity(file.size as usize);
|
||||
zipped.by_ref().take(file.size + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() as u64 != file.size || git_blob_sha1(&bytes) != file.sha1 {
|
||||
return Err(Error::Invalid(format!("{} failed verification.", file.from)));
|
||||
}
|
||||
let target = fsx::safe_join(staging, &file.path)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(target, bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stamp() -> String {
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S").to_string()
|
||||
}
|
||||
|
||||
/// Install or update `id` in `client` from `transport`.
|
||||
pub fn install_with(transport: &dyn Transport, client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
|
||||
if crate::client::is_running(client) {
|
||||
return Err(Error::Invalid("Close the game before installing addons.".into()));
|
||||
}
|
||||
let entry = catalog()?
|
||||
.into_iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| Error::Invalid(format!("Unknown addon {id}.")))?;
|
||||
install_entry(transport, client, &entry, cancel)?;
|
||||
list(client)
|
||||
}
|
||||
|
||||
fn install_entry(transport: &dyn Transport, client: &Path, entry: &Entry, cancel: &Cancel) -> Result<()> {
|
||||
let dir = addons_dir(client);
|
||||
fs::create_dir_all(&dir)?;
|
||||
// Staged next to AddOns' own folders, so the final moves stay on one volume even for a linked AddOns.
|
||||
let staging = tempfile::Builder::new().prefix(".coa-addon-").tempdir_in(&dir)?;
|
||||
let archive = staging.path().join("archive.zip");
|
||||
download(transport, &entry.archive, &archive, cancel)?;
|
||||
let unpacked = staging.path().join("files");
|
||||
unpack(entry, &archive, &unpacked)?;
|
||||
if cancel.is_set() {
|
||||
return Err(Error::Invalid("Operation cancelled.".into()));
|
||||
}
|
||||
let mut state = read_state(client);
|
||||
let ours: Vec<String> = state.values().flat_map(|i| i.folders.clone()).collect();
|
||||
// Move what is in the way out first, so a failed move leaves the client as it was.
|
||||
let mut moved: Vec<(PathBuf, PathBuf)> = Vec::new();
|
||||
let undo = |moved: &[(PathBuf, PathBuf)]| {
|
||||
for (from, to) in moved.iter().rev() {
|
||||
let _ = fs::rename(to, from);
|
||||
}
|
||||
};
|
||||
for folder in &entry.folders {
|
||||
let target = dir.join(folder);
|
||||
if !target.exists() {
|
||||
continue;
|
||||
}
|
||||
let aside = if ours.contains(folder) {
|
||||
staging.path().join("old").join(folder)
|
||||
} else {
|
||||
dir.join(BACKUP).join(format!("{folder}-{}", stamp()))
|
||||
};
|
||||
if let Some(parent) = aside.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if let Err(e) = fs::rename(&target, &aside) {
|
||||
undo(&moved);
|
||||
return Err(Error::Invalid(format!("{folder} is in use and could not be replaced: {e}")));
|
||||
}
|
||||
moved.push((target, aside));
|
||||
}
|
||||
let mut placed: Vec<PathBuf> = Vec::new();
|
||||
for folder in &entry.folders {
|
||||
let target = dir.join(folder);
|
||||
if let Err(e) = fs::rename(unpacked.join(folder), &target) {
|
||||
for p in &placed {
|
||||
let _ = fs::remove_dir_all(p);
|
||||
}
|
||||
undo(&moved);
|
||||
return Err(Error::Invalid(format!("{folder} could not be installed: {e}")));
|
||||
}
|
||||
placed.push(target);
|
||||
}
|
||||
state.insert(
|
||||
entry.id.clone(),
|
||||
Installed {
|
||||
commit: entry.commit.clone(),
|
||||
folders: entry.folders.clone(),
|
||||
},
|
||||
);
|
||||
write_state(client, &state)?;
|
||||
tracing::info!(addon = %entry.id, commit = %entry.commit, "addon installed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
|
||||
install_with(&crate::download::HttpTransport::with_total_timeout(1800)?, client, id, cancel)
|
||||
}
|
||||
|
||||
/// Remove an addon the Manager installed (only its recorded folders).
|
||||
pub fn remove(client: &Path, id: &str) -> Result<Vec<AddonView>> {
|
||||
if crate::client::is_running(client) {
|
||||
return Err(Error::Invalid("Close the game before removing addons.".into()));
|
||||
}
|
||||
let mut state = read_state(client);
|
||||
let Some(installed) = state.remove(id) else {
|
||||
return list(client);
|
||||
};
|
||||
let dir = addons_dir(client);
|
||||
for folder in &installed.folders {
|
||||
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
let target = dir.join(folder);
|
||||
if target.exists() {
|
||||
fs::remove_dir_all(&target)?;
|
||||
}
|
||||
}
|
||||
write_state(client, &state)?;
|
||||
list(client)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::download::Reply;
|
||||
|
||||
struct Serve(Vec<u8>);
|
||||
impl Transport for Serve {
|
||||
fn get(&self, _: &str, _: u64) -> std::result::Result<Reply, String> {
|
||||
Ok(Reply { status: 200, content_range: None, body: Box::new(std::io::Cursor::new(self.0.clone())) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A GitHub-like archive of the catalog entry `id` with the given file bodies (path in repo -> bytes).
|
||||
fn archive(entry: &Entry, body: &dyn Fn(&AddonFile) -> Vec<u8>) -> Vec<u8> {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
let mut zip = zip::ZipWriter::new(&mut out);
|
||||
for file in &entry.files {
|
||||
zip.start_file(format!("repo-{}/{}", entry.commit, file.from), zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(&body(file)).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
out.into_inner()
|
||||
}
|
||||
|
||||
/// A small catalog entry whose files hash to what the archive will hold.
|
||||
fn small_entry() -> Entry {
|
||||
let bytes = b"## Interface: 30300\n".to_vec();
|
||||
Entry {
|
||||
id: "t".into(),
|
||||
name: "T".into(),
|
||||
description: BTreeMap::new(),
|
||||
author: "a".into(),
|
||||
license: "x".into(),
|
||||
needs: None,
|
||||
repo: "r".into(),
|
||||
commit: "c1".into(),
|
||||
archive: "https://example.invalid/a.zip".into(),
|
||||
folders: vec!["TestAddon".into()],
|
||||
files: vec![AddonFile {
|
||||
path: "TestAddon/TestAddon.toc".into(),
|
||||
from: "TestAddon/TestAddon.toc".into(),
|
||||
sha1: git_blob_sha1(&bytes),
|
||||
size: bytes.len() as u64,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_catalog_is_valid_and_pins_every_addon() {
|
||||
let entries = catalog().unwrap();
|
||||
assert!(entries.len() >= 4);
|
||||
for e in &entries {
|
||||
assert_eq!(e.commit.len(), 40, "{}", e.id);
|
||||
assert!(e.archive.starts_with("https://codeload.github.com/") && e.archive.ends_with(&e.commit));
|
||||
assert!(e.description.contains_key("en") && e.description.contains_key("ru"));
|
||||
for folder in &e.folders {
|
||||
assert!(e.files.iter().any(|f| f.path.eq_ignore_ascii_case(&format!("{folder}/{folder}.toc"))
|
||||
|| f.path.starts_with(&format!("{folder}/")) && f.path.ends_with(".toc")), "{folder} has no toc");
|
||||
}
|
||||
for f in &e.files {
|
||||
fsx::safe_join(Path::new("C:/x"), &f.path).unwrap();
|
||||
assert!(e.folders.iter().any(|folder| f.path.starts_with(&format!("{folder}/"))));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Downloads the catalog's small addons from GitHub"]
|
||||
fn the_real_catalog_installs_from_github() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
for id in ["incahoots", "coacombat", "squidbots-lite"] {
|
||||
let views = install(client.path(), id, &Cancel::default()).unwrap();
|
||||
let view = views.iter().find(|v| v.id == id).unwrap();
|
||||
assert!(view.installed && !view.update_available, "{id}");
|
||||
}
|
||||
assert!(addons_dir(client.path()).join("IncahootsCoA/IncahootsCoA.toc").is_file());
|
||||
assert!(addons_dir(client.path()).join("SquidBotsLite/SquidBotsLite.toc").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_blob_ids_match_git() {
|
||||
// `printf 'hello\n' | git hash-object --stdin`
|
||||
assert_eq!(git_blob_sha1(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
|
||||
}
|
||||
|
||||
fn unpack_and_place(entry: &Entry, client: &Path, bytes: Vec<u8>) -> Result<()> {
|
||||
let dir = addons_dir(client);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let staging = tempfile::tempdir_in(&dir)?;
|
||||
let archive = staging.path().join("a.zip");
|
||||
download(&Serve(bytes), &entry.archive, &archive, &Cancel::default())?;
|
||||
unpack(entry, &archive, &staging.path().join("files"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tampered_or_incomplete_download_is_refused() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let entry = small_entry();
|
||||
let good = archive(&entry, &|_| b"## Interface: 30300\n".to_vec());
|
||||
unpack_and_place(&entry, client.path(), good).unwrap();
|
||||
let bad = archive(&entry, &|_| b"## Interface: 30300 evil\n".to_vec());
|
||||
assert!(unpack_and_place(&entry, client.path(), bad).unwrap_err().to_string().contains("verification"));
|
||||
let empty = {
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
zip::ZipWriter::new(&mut out).finish().unwrap();
|
||||
out.into_inner()
|
||||
};
|
||||
assert!(unpack_and_place(&entry, client.path(), empty).unwrap_err().to_string().contains("lacks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_update_and_remove_keep_other_folders() {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let mut entry = small_entry();
|
||||
let dir = addons_dir(client.path());
|
||||
fs::create_dir_all(dir.join("TestAddon")).unwrap();
|
||||
fs::write(dir.join("TestAddon/mine.lua"), b"player's own").unwrap();
|
||||
fs::create_dir_all(dir.join("Other")).unwrap();
|
||||
let serve = Serve(archive(&entry, &|_| b"## Interface: 30300
|
||||
".to_vec()));
|
||||
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
|
||||
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
|
||||
assert!(!dir.join("TestAddon/mine.lua").exists(), "the player's folder was set aside");
|
||||
let backups: Vec<_> = fs::read_dir(dir.join(BACKUP)).unwrap().flatten().collect();
|
||||
assert_eq!(backups.len(), 1);
|
||||
assert!(backups[0].path().join("mine.lua").is_file());
|
||||
assert_eq!(read_state(client.path())["t"].commit, "c1");
|
||||
// An update replaces the Manager's own folder without another backup.
|
||||
entry.commit = "c2".into();
|
||||
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
|
||||
assert_eq!(read_state(client.path())["t"].commit, "c2");
|
||||
assert_eq!(fs::read_dir(dir.join(BACKUP)).unwrap().count(), 1);
|
||||
// A failed download changes nothing.
|
||||
let broken = Serve(archive(&entry, &|_| b"tampered".to_vec()));
|
||||
assert!(install_entry(&broken, client.path(), &entry, &Cancel::default()).is_err());
|
||||
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
|
||||
remove(client.path(), "t").unwrap();
|
||||
assert!(!dir.join("TestAddon").exists());
|
||||
assert!(dir.join("Other").is_dir());
|
||||
assert!(!read_state(client.path()).contains_key("t"));
|
||||
// No leftover staging folders.
|
||||
assert!(fs::read_dir(&dir).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with(".coa-addon-")));
|
||||
}
|
||||
}
|
||||
@@ -415,6 +415,38 @@ pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove the game's cache of server data (`Cache/WDB/<locale>/*.wdb`: creatures, items, quests, pages). The client
|
||||
/// keeps answers it got from a server; after the server's data changes they show old names and stats until the
|
||||
/// cache is gone. Only `.wdb` files under `Cache/WDB` are removed. Returns how many.
|
||||
pub fn clear_game_cache(client: &Path) -> Result<usize> {
|
||||
if is_running(client) {
|
||||
return Ok(0);
|
||||
}
|
||||
let root = client.join("Cache").join("WDB");
|
||||
let mut removed = 0;
|
||||
let Ok(locales) = fs::read_dir(&root) else {
|
||||
return Ok(0);
|
||||
};
|
||||
for locale in locales.flatten() {
|
||||
if !locale.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(files) = fs::read_dir(locale.path()) else {
|
||||
continue;
|
||||
};
|
||||
for file in files.flatten() {
|
||||
let path = file.path();
|
||||
let is_wdb = path
|
||||
.extension()
|
||||
.is_some_and(|e| e.eq_ignore_ascii_case("wdb"));
|
||||
if is_wdb && file.file_type().is_ok_and(|t| t.is_file()) && fs::remove_file(&path).is_ok() {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Start the game client. The caller is responsible for making sure the server is ready first.
|
||||
pub fn launch(client: &Path) -> Result<u32> {
|
||||
let exe =
|
||||
@@ -613,6 +645,23 @@ pub fn recover_all_realmlist_overrides(meta_roots: &[PathBuf]) -> usize {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_the_server_data_cache_is_cleared() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let wdb = d.path().join("Cache/WDB/enUS");
|
||||
fs::create_dir_all(&wdb).unwrap();
|
||||
fs::write(wdb.join("creaturecache.wdb"), b"x").unwrap();
|
||||
fs::write(wdb.join("itemcache.WDB"), b"x").unwrap();
|
||||
fs::write(wdb.join("notes.txt"), b"keep").unwrap();
|
||||
fs::create_dir_all(d.path().join("Data/Retail/Cache")).unwrap();
|
||||
fs::write(d.path().join("Data/Retail/Cache/id-1.bin"), b"keep").unwrap();
|
||||
assert_eq!(clear_game_cache(d.path()).unwrap(), 2);
|
||||
assert!(wdb.join("notes.txt").is_file());
|
||||
assert!(d.path().join("Data/Retail/Cache/id-1.bin").is_file());
|
||||
assert_eq!(clear_game_cache(d.path()).unwrap(), 0);
|
||||
assert_eq!(clear_game_cache(&d.path().join("missing")).unwrap(), 0);
|
||||
}
|
||||
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
pub mod accounts;
|
||||
pub mod allsettings;
|
||||
pub mod addons;
|
||||
pub mod analyzer;
|
||||
pub mod backup;
|
||||
pub mod build_cache;
|
||||
|
||||
@@ -7,6 +7,10 @@ use std::path::{Path, PathBuf};
|
||||
pub struct Profile {
|
||||
pub host: String,
|
||||
pub client_path: Option<String>,
|
||||
/// The listed server `host` belongs to, when the player joined it through the server list: its account is
|
||||
/// filled into the game's login box at every Play.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub realm: Option<String>,
|
||||
}
|
||||
|
||||
pub fn load(dir: &Path) -> Result<Profile> {
|
||||
@@ -43,12 +47,21 @@ pub fn save(dir: &Path, profile: &Profile) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_profile_from_before_the_realm_field_still_loads() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
std::fs::write(d.path().join("connection.json"), br#"{"host":"1.2.3.4","client_path":null}"#).unwrap();
|
||||
let p = load(d.path()).unwrap();
|
||||
assert_eq!((p.host.as_str(), p.realm), ("1.2.3.4", None));
|
||||
}
|
||||
#[test]
|
||||
fn connection_needs_no_server_and_survives_restart() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let profile = Profile {
|
||||
host: "192.168.1.10".into(),
|
||||
client_path: None,
|
||||
realm: None,
|
||||
};
|
||||
save(dir.path(), &profile).unwrap();
|
||||
assert_eq!(load(dir.path()).unwrap().host, profile.host);
|
||||
@@ -70,6 +83,7 @@ mod tests {
|
||||
let profile = Profile {
|
||||
host: "192.168.1.10".into(),
|
||||
client_path: Some(game.to_string_lossy().into()),
|
||||
realm: None,
|
||||
};
|
||||
save(dir.path(), &profile).unwrap();
|
||||
assert!(
|
||||
|
||||
@@ -439,6 +439,7 @@ pub(crate) async fn join_realm(
|
||||
let mut profile = coa_core::remote_client::load(&dir)
|
||||
.map_err(|e| fail("other", e.to_string()))?;
|
||||
profile.host = host;
|
||||
profile.realm = Some(realm.clone());
|
||||
coa_core::remote_client::save(&dir, &profile)
|
||||
.map_err(|e| fail("launch", e.to_string()))?;
|
||||
super::play(state, REMOTE_CLIENT_ID.to_string())
|
||||
|
||||
@@ -240,6 +240,7 @@ async fn portable_launch(
|
||||
let mut profile =
|
||||
coa_core::remote_client::load(&dir).map_err(|e| other(e.into()))?;
|
||||
profile.host = address;
|
||||
profile.realm = Some(realm.clone());
|
||||
coa_core::remote_client::save(&dir, &profile).map_err(|e| other(e.into()))?;
|
||||
if let Some(ref cp) = profile.client_path {
|
||||
if let Ok(pc) = control_cmds::player(&state) {
|
||||
@@ -1664,6 +1665,41 @@ async fn custom_races_install(
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn addons_list(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<Vec<coa_core::addons::AddonView>, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
blocking(move || coa_core::addons::list(&ctx.require()?)).await
|
||||
}
|
||||
|
||||
/// Install or update a catalog addon in the linked game client (pinned commit, every file checked).
|
||||
#[tauri::command]
|
||||
async fn addons_install(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
addon: String,
|
||||
) -> std::result::Result<Vec<coa_core::addons::AddonView>, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
let cancel = begin_client_job(&state)?;
|
||||
let result = blocking(move || coa_core::addons::install(&ctx.require()?, &addon, &cancel)).await;
|
||||
end_client_job(&state);
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn addons_remove(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
addon: String,
|
||||
) -> std::result::Result<Vec<coa_core::addons::AddonView>, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || coa_core::addons::remove(&ctx.require()?, &addon)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn custom_races_uninstall(
|
||||
state: State<'_, AppState>,
|
||||
@@ -2262,6 +2298,10 @@ fn remote_connect(
|
||||
if host.is_empty() {
|
||||
return Err(Error::Invalid("Enter the host's IP address or hostname.".into()).into());
|
||||
}
|
||||
if profile.host != host {
|
||||
// A host typed by hand is not the listed server whose account was remembered.
|
||||
profile.realm = None;
|
||||
}
|
||||
profile.host = host.into();
|
||||
coa_core::remote_client::save(&dir, &profile)?;
|
||||
Ok(profile)
|
||||
@@ -2662,6 +2702,15 @@ async fn play(
|
||||
if id == REMOTE_CLIENT_ID {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let client = ctx.require()?;
|
||||
// The account the Manager made (or linked) on that listed server goes into the login box at every Play,
|
||||
// also when another server's account was used in between.
|
||||
let login = coa_core::remote_client::load(&remote_dir())
|
||||
.ok()
|
||||
.and_then(|profile| profile.realm)
|
||||
.and_then(|realm| {
|
||||
let pc = control_cmds::player(&state).ok()?;
|
||||
pc.credentials(&control_cmds::realm_id(&realm).ok()?).ok()?
|
||||
});
|
||||
return blocking(move || {
|
||||
if ctx.host.is_empty() {
|
||||
return Err(Error::Invalid(
|
||||
@@ -2672,6 +2721,12 @@ async fn play(
|
||||
return Err(Error::Invalid("The game is already running.".into()));
|
||||
}
|
||||
coa_core::client::begin_realmlist_override(&client, &ctx.dir, &ctx.host)?;
|
||||
if let Some(creds) = &login {
|
||||
let _ = coa_core::glue_config::prefill_login(&client, &creds.username, &creds.password);
|
||||
}
|
||||
if window_preferences::clear_cache_on_play(&data_dir()) {
|
||||
let _ = coa_core::client::clear_game_cache(&client);
|
||||
}
|
||||
coa_core::client::launch(&client)?;
|
||||
let client_c = client.clone();
|
||||
let meta_c = ctx.dir.clone();
|
||||
@@ -2718,6 +2773,9 @@ async fn play(
|
||||
if existing.is_empty() {
|
||||
let _ = coa_core::glue_config::prefill_login(&client, "local", "local");
|
||||
}
|
||||
if window_preferences::clear_cache_on_play(&data_dir()) {
|
||||
let _ = coa_core::client::clear_game_cache(&client);
|
||||
}
|
||||
coa_core::client::launch(&client)?;
|
||||
Ok(DriverOutcome {
|
||||
ok: true,
|
||||
@@ -3583,6 +3641,16 @@ fn set_close_to_tray(enabled: bool) -> std::result::Result<(), UiError> {
|
||||
Ok(window_preferences::save(&data_dir(), enabled)?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn clear_game_cache_on_play() -> bool {
|
||||
window_preferences::clear_cache_on_play(&data_dir())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn set_clear_game_cache_on_play(enabled: bool) -> std::result::Result<(), UiError> {
|
||||
Ok(window_preferences::save_clear_cache_on_play(&data_dir(), enabled)?)
|
||||
}
|
||||
|
||||
fn show_main_window(app: &AppHandle) {
|
||||
let handle = app.clone();
|
||||
if let Err(error) = app.run_on_main_thread(move || {
|
||||
@@ -3691,6 +3759,11 @@ pub fn run() {
|
||||
mysql_custom_save,
|
||||
restart_schedule,
|
||||
restart_schedule_save,
|
||||
clear_game_cache_on_play,
|
||||
set_clear_game_cache_on_play,
|
||||
addons_list,
|
||||
addons_install,
|
||||
addons_remove,
|
||||
check_database,
|
||||
repair_server,
|
||||
plugins_repair,
|
||||
|
||||
@@ -11,3 +11,15 @@ pub fn close_to_tray(dir: &Path) -> coa_core::Result<bool> {
|
||||
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
|
||||
coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled)
|
||||
}
|
||||
|
||||
/// Clear the game's cache of server data before every Play (on unless the player turned it off).
|
||||
pub fn clear_cache_on_play(dir: &Path) -> bool {
|
||||
std::fs::read(dir.join("clear-game-cache.json"))
|
||||
.ok()
|
||||
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub fn save_clear_cache_on_play(dir: &Path, enabled: bool) -> coa_core::Result<()> {
|
||||
coa_core::fsx::atomic_write_json(&dir.join("clear-game-cache.json"), &enabled)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// Dev-only: lets the UI run in a plain browser for visual review. Never bundled in production builds.
|
||||
import { auctionCategories, auctionQualities } from "../lib/moduleSettings";
|
||||
import moduleCatalog from "../../modules/catalog.json";
|
||||
import addonCatalog from "../../addons/catalog.json";
|
||||
import botsSchema from "../../schemas/bots.json";
|
||||
import serverSchema from "../../schemas/server.json";
|
||||
import botsPresets from "../../schemas/presets/bots.json";
|
||||
@@ -29,6 +30,8 @@ export {};
|
||||
(window as any).__TAURI_INTERNALS__ = {
|
||||
transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x,
|
||||
invoke: async (cmd: string, args?: any)=>{
|
||||
if(cmd==="clear_game_cache_on_play") return localStorage.getItem("demo-clear-cache")!=="0";
|
||||
if(cmd==="set_clear_game_cache_on_play"){localStorage.setItem("demo-clear-cache",args.enabled?"1":"0");return;}
|
||||
if(cmd==="close_to_tray") return localStorage.getItem("demo-close-tray")==="1";
|
||||
if(cmd==="set_close_to_tray"){localStorage.setItem("demo-close-tray",args.enabled?"1":"0");return;}
|
||||
if(cmd==="client_graphics") return JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}');
|
||||
@@ -39,6 +42,7 @@ export {};
|
||||
if(cmd==="pending_update") return null;
|
||||
if(cmd==="plugin:app|version") return "0.8.2";
|
||||
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
|
||||
if(cmd==="addons_list"||cmd==="addons_install"||cmd==="addons_remove"){const w=window as any;w.__addons=w.__addons??{dragonui:"old"};if(cmd==="addons_install"){await new Promise(r=>setTimeout(r,700));w.__addons[args.addon]="new";}if(cmd==="addons_remove")delete w.__addons[args.addon];return addonCatalog.addons.map((a:any)=>({id:a.id,name:a.name,description:a.description,author:a.author,license:a.license,needs:a.needs??null,repo:a.repo,size:a.files.reduce((s:number,f:any)=>s+f.size,0),installed:a.id in w.__addons,updateAvailable:w.__addons[a.id]==="old",foreignFolders:a.id==="coacombat"&&!(a.id in w.__addons)?["CoACombat"]:[]}));}
|
||||
if(cmd==="restart_schedule"||cmd==="restart_schedule_save"){const w=window as any;w.__sched=w.__sched??{enabled:false,time:"05:00",warningMinutes:5};if(cmd==="restart_schedule_save"){const s=args.schedule;if(s.enabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.time))throw new Error("The restart time must be HH:MM, for example 05:00.");w.__sched={...s};}return {schedule:w.__sched,supported:true};}
|
||||
if(cmd==="mysql_custom"||cmd==="mysql_custom_save"){const w=window as any;if(cmd==="mysql_custom_save")w.__my=args.text;const text:string=w.__my??"";const applied=text.split("\n").map((l:string)=>l.trim()).filter((l:string)=>l&&!l.startsWith("#")&&!/^(port|datadir|basedir|bind[-_]address)\b/i.test(l)).map((l:string)=>l+"\n").join("");return {text,applied};}
|
||||
if(cmd==="realm_names"||cmd==="realm_rename"){const w=window as any;w.__rn=w.__rn??{};const defs:[number,string][]=[[1,"Conquest of Azeroth"],[2,"Wildcard"]];if(cmd==="realm_rename"){await new Promise(r=>setTimeout(r,300));const n=(args.name??"").trim();if(n.length>32||n.includes('"'))throw new Error("The realm name can have at most 32 characters.");if(n)w.__rn[args.realmId]=n;else delete w.__rn[args.realmId];}return defs.map(([id,d])=>({id,name:w.__rn[id]??d,defaultName:d,custom:id in w.__rn}));}
|
||||
|
||||
@@ -788,6 +788,18 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"sched.save": "Speichern",
|
||||
"sched.saved": "Gespeichert.",
|
||||
"sched.unsupported": "Dieser Server kann das noch nicht: Aktualisiere ihn auf einen Build mit dem neuen Launcher.",
|
||||
"client.clearCache": "Spiel-Cache vor jedem Start leeren",
|
||||
"client.clearCacheHint": "Das Spiel merkt sich Kreaturen, Gegenstände und Quests vom Server (Cache/WDB). Nach einem Server-Update zeigen sie sonst alte Namen und Werte; der Cache füllt sich in Sekunden wieder.",
|
||||
"addons.title": "Addons",
|
||||
"addons.hint": "Community-Addons für Conquest of Azeroth. Jedes kommt in einer geprüften Version vom GitHub seines Autors; jede Datei wird vor der Installation in Interface/AddOns geprüft. Schließe zuerst das Spiel.",
|
||||
"addons.by": "von {author}",
|
||||
"addons.installed": "Installiert",
|
||||
"addons.update": "Update verfügbar",
|
||||
"addons.needsSquid": "Für SQUID's Playerbots.",
|
||||
"addons.foreign": "Ein Ordner {folders} ist schon da; er wird nach AddOns/.coa-addons-backup verschoben.",
|
||||
"addons.doInstall": "Installieren",
|
||||
"addons.doUpdate": "Aktualisieren",
|
||||
"addons.doRemove": "Entfernen",
|
||||
"realm.namesTitle": "Realmnamen",
|
||||
"realm.namesHint": "So heißt der Realm in der Realmliste der Spieler. Ein laufender Server zeigt den Namen sofort, und er bleibt nach Updates erhalten.",
|
||||
"realm.nameSave": "Speichern",
|
||||
|
||||
@@ -72,6 +72,18 @@ const en = {
|
||||
"sched.save": "Save",
|
||||
"sched.saved": "Saved.",
|
||||
"sched.unsupported": "This server cannot do it yet: update the server to a build with the new launcher.",
|
||||
"client.clearCache": "Clear the game cache before every Play",
|
||||
"client.clearCacheHint": "The game remembers creatures, items and quests it got from a server (Cache/WDB). After a server update they can show old names and stats; the cache fills again within seconds.",
|
||||
"addons.title": "Addons",
|
||||
"addons.hint": "Community addons for Conquest of Azeroth. Each comes from its author's GitHub at a checked version; every file is verified before it is installed into Interface/AddOns. Close the game first.",
|
||||
"addons.by": "by {author}",
|
||||
"addons.installed": "Installed",
|
||||
"addons.update": "Update available",
|
||||
"addons.needsSquid": "For SQUID's Playerbots.",
|
||||
"addons.foreign": "A folder named {folders} is already there; it will be moved to AddOns/.coa-addons-backup.",
|
||||
"addons.doInstall": "Install",
|
||||
"addons.doUpdate": "Update",
|
||||
"addons.doRemove": "Remove",
|
||||
"realm.namesTitle": "Realm names",
|
||||
"realm.namesHint": "The name players see in the realm list. A running server shows it at once, and it stays after updates.",
|
||||
"realm.nameSave": "Save",
|
||||
|
||||
@@ -788,6 +788,18 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"sched.save": "Guardar",
|
||||
"sched.saved": "Guardado.",
|
||||
"sched.unsupported": "Este servidor aún no puede hacerlo: actualízalo a una versión con el nuevo lanzador.",
|
||||
"client.clearCache": "Vaciar la caché del juego antes de cada inicio",
|
||||
"client.clearCacheHint": "El juego recuerda criaturas, objetos y misiones recibidos del servidor (Cache/WDB). Tras actualizar el servidor pueden mostrar nombres y estadísticas antiguos; la caché se llena de nuevo en segundos.",
|
||||
"addons.title": "Addons",
|
||||
"addons.hint": "Addons de la comunidad para Conquest of Azeroth. Cada uno viene del GitHub de su autor en una versión comprobada; cada archivo se verifica antes de instalarlo en Interface/AddOns. Cierra antes el juego.",
|
||||
"addons.by": "de {author}",
|
||||
"addons.installed": "Instalado",
|
||||
"addons.update": "Actualización disponible",
|
||||
"addons.needsSquid": "Para SQUID's Playerbots.",
|
||||
"addons.foreign": "Ya hay una carpeta {folders}; se moverá a AddOns/.coa-addons-backup.",
|
||||
"addons.doInstall": "Instalar",
|
||||
"addons.doUpdate": "Actualizar",
|
||||
"addons.doRemove": "Quitar",
|
||||
"realm.namesTitle": "Nombres de los reinos",
|
||||
"realm.namesHint": "El nombre que ven los jugadores en la lista de reinos. Un servidor en marcha lo muestra al instante y se mantiene tras las actualizaciones.",
|
||||
"realm.nameSave": "Guardar",
|
||||
|
||||
@@ -788,6 +788,18 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"sched.save": "Enregistrer",
|
||||
"sched.saved": "Enregistré.",
|
||||
"sched.unsupported": "Ce serveur ne le permet pas encore : mettez-le à jour vers une version avec le nouveau lanceur.",
|
||||
"client.clearCache": "Vider le cache du jeu avant chaque lancement",
|
||||
"client.clearCacheHint": "Le jeu garde les créatures, objets et quêtes reçus du serveur (Cache/WDB). Après une mise à jour du serveur, ils peuvent montrer d'anciens noms et statistiques ; le cache se remplit en quelques secondes.",
|
||||
"addons.title": "Addons",
|
||||
"addons.hint": "Addons de la communauté pour Conquest of Azeroth. Chacun vient du GitHub de son auteur dans une version vérifiée ; chaque fichier est contrôlé avant l'installation dans Interface/AddOns. Fermez d'abord le jeu.",
|
||||
"addons.by": "par {author}",
|
||||
"addons.installed": "Installé",
|
||||
"addons.update": "Mise à jour disponible",
|
||||
"addons.needsSquid": "Pour SQUID's Playerbots.",
|
||||
"addons.foreign": "Un dossier {folders} existe déjà ; il sera déplacé vers AddOns/.coa-addons-backup.",
|
||||
"addons.doInstall": "Installer",
|
||||
"addons.doUpdate": "Mettre à jour",
|
||||
"addons.doRemove": "Supprimer",
|
||||
"realm.namesTitle": "Noms des royaumes",
|
||||
"realm.namesHint": "Le nom que les joueurs voient dans la liste des royaumes. Un serveur en marche l'affiche aussitôt, et il reste après les mises à jour.",
|
||||
"realm.nameSave": "Enregistrer",
|
||||
|
||||
@@ -75,6 +75,18 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"sched.save": "Сохранить",
|
||||
"sched.saved": "Сохранено.",
|
||||
"sched.unsupported": "Этот сервер пока так не умеет: обновите его до сборки с новым лаунчером.",
|
||||
"client.clearCache": "Очищать кэш игры перед каждым запуском",
|
||||
"client.clearCacheHint": "Игра запоминает существ, предметы и задания, полученные от сервера (Cache/WDB). После обновления сервера там остаются старые названия и характеристики; кэш снова заполняется за секунды.",
|
||||
"addons.title": "Аддоны",
|
||||
"addons.hint": "Аддоны сообщества для Conquest of Azeroth. Каждый берётся с GitHub автора в проверенной версии; перед установкой в Interface/AddOns проверяется каждый файл. Сначала закройте игру.",
|
||||
"addons.by": "автор: {author}",
|
||||
"addons.installed": "Установлен",
|
||||
"addons.update": "Есть обновление",
|
||||
"addons.needsSquid": "Для SQUID's Playerbots.",
|
||||
"addons.foreign": "Папка {folders} уже есть; она будет перенесена в AddOns/.coa-addons-backup.",
|
||||
"addons.doInstall": "Установить",
|
||||
"addons.doUpdate": "Обновить",
|
||||
"addons.doRemove": "Удалить",
|
||||
"realm.namesTitle": "Названия реалмов",
|
||||
"realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.",
|
||||
"realm.nameSave": "Сохранить",
|
||||
|
||||
@@ -73,6 +73,18 @@ const zh = {
|
||||
"sched.save": "保存",
|
||||
"sched.saved": "已保存。",
|
||||
"sched.unsupported": "此服务器暂不支持:请将服务器更新到带有新启动器的版本。",
|
||||
"client.clearCache": "每次启动前清空游戏缓存",
|
||||
"client.clearCacheHint": "游戏会保存从服务器获得的生物、物品和任务(Cache/WDB)。服务器更新后,这些缓存可能显示旧的名称和属性;缓存会在几秒内重新生成。",
|
||||
"addons.title": "插件",
|
||||
"addons.hint": "Conquest of Azeroth 的社区插件。每个插件都来自作者的 GitHub 的已核验版本;安装到 Interface/AddOns 前会逐个校验文件。请先关闭游戏。",
|
||||
"addons.by": "作者:{author}",
|
||||
"addons.installed": "已安装",
|
||||
"addons.update": "有可用更新",
|
||||
"addons.needsSquid": "用于 SQUID's Playerbots。",
|
||||
"addons.foreign": "已存在名为 {folders} 的文件夹;它会被移到 AddOns/.coa-addons-backup。",
|
||||
"addons.doInstall": "安装",
|
||||
"addons.doUpdate": "更新",
|
||||
"addons.doRemove": "移除",
|
||||
"realm.namesTitle": "服务器名称",
|
||||
"realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。",
|
||||
"realm.nameSave": "保存",
|
||||
|
||||
@@ -64,6 +64,7 @@ export interface StatusView {
|
||||
}
|
||||
|
||||
export type RealmMode = "coa" | "wildcard" | "reborn";
|
||||
export interface AddonView { id: string; name: string; description: Record<string, string>; author: string; license: string; needs: string | null; repo: string; size: number; installed: boolean; updateAvailable: boolean; foreignFolders: string[] }
|
||||
export interface RestartSchedule { enabled: boolean; time: string; warningMinutes: number }
|
||||
export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean }
|
||||
export interface CustomMysql { text: string; applied: string }
|
||||
@@ -735,6 +736,11 @@ export const api = {
|
||||
realmProfiles: (id: string) => invoke<RealmProfiles>("realm_profiles", { id }),
|
||||
realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke<RealmProfiles>("realm_select", { id, mode, restart }),
|
||||
realmSimultaneous: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_simultaneous", { id, enabled }),
|
||||
addonsList: (id: string) => invoke<AddonView[]>("addons_list", { id }),
|
||||
addonsInstall: (id: string, addon: string) => invoke<AddonView[]>("addons_install", { id, addon }),
|
||||
addonsRemove: (id: string, addon: string) => invoke<AddonView[]>("addons_remove", { id, addon }),
|
||||
clearGameCacheOnPlay: () => invoke<boolean>("clear_game_cache_on_play"),
|
||||
setClearGameCacheOnPlay: (enabled: boolean) => invoke<void>("set_clear_game_cache_on_play", { enabled }),
|
||||
restartSchedule: (id: string) => invoke<RestartScheduleView>("restart_schedule", { id }),
|
||||
restartScheduleSave: (id: string, schedule: RestartSchedule) => invoke<RestartScheduleView>("restart_schedule_save", { id, schedule }),
|
||||
mysqlCustom: (id: string) => invoke<CustomMysql>("mysql_custom", { id }),
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { ExternalLink, Loader2 } from "lucide-react";
|
||||
import { api, asUiError, type AddonView } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useI18n } from "@/i18n";
|
||||
|
||||
function megabytes(bytes: number): string {
|
||||
return (bytes / 1024 / 1024).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0);
|
||||
}
|
||||
|
||||
/** Addons from the Manager's catalog: each pinned to a commit of its author's repository and checked file by file. */
|
||||
export function AddonCatalog({ serverId }: { serverId: string }) {
|
||||
const { t, locale } = useI18n();
|
||||
const [addons, setAddons] = useState<AddonView[] | null>(null);
|
||||
const [working, setWorking] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
void api.addonsList(serverId).then(list => { if (alive) setAddons(list); }).catch(e => { if (alive) setError(asUiError(e).technical); });
|
||||
return () => { alive = false; };
|
||||
}, [serverId]);
|
||||
|
||||
async function run(id: string, action: "install" | "remove") {
|
||||
setWorking(id); setError(null);
|
||||
try { setAddons(await (action === "install" ? api.addonsInstall : api.addonsRemove)(serverId, id)); }
|
||||
catch (e) { setError(asUiError(e).technical); }
|
||||
finally { setWorking(null); }
|
||||
}
|
||||
|
||||
return <div className="mt-5 border-t border-line pt-4">
|
||||
<h3 className="text-sm font-semibold">{t("addons.title")}</h3>
|
||||
<p className="mt-1 text-xs text-muted">{t("addons.hint")}</p>
|
||||
<ul className="mt-3 space-y-3">
|
||||
{addons?.map(a => <li key={a.id} className="rounded-md border border-line p-3">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium">{a.name}</span>
|
||||
<span className="text-xs text-muted">{t("addons.by", { author: a.author })} · {megabytes(a.size)} MB</span>
|
||||
{a.installed && !a.updateAvailable && <span className="text-xs text-ok">{t("addons.installed")}</span>}
|
||||
{a.updateAvailable && <span className="text-xs text-warn">{t("addons.update")}</span>}
|
||||
<button type="button" className="ml-auto text-muted hover:text-ink" title={a.repo} aria-label={`GitHub: ${a.name}`} onClick={() => void api.openLink(a.repo)}><ExternalLink className="h-4 w-4" aria-hidden /></button>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-muted">{a.description[locale] ?? a.description.en}</p>
|
||||
{a.needs === "playerbots" && <p className="mt-1 text-xs text-muted">{t("addons.needsSquid")}</p>}
|
||||
{a.foreignFolders.length > 0 && !a.installed && <p className="mt-1 text-xs text-warn">{t("addons.foreign", { folders: a.foreignFolders.join(", ") })}</p>}
|
||||
<div className="mt-2 flex gap-2">
|
||||
{(!a.installed || a.updateAvailable) && <Button size="sm" disabled={working !== null} onClick={() => void run(a.id, "install")}>
|
||||
{working === a.id && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{a.updateAvailable ? t("addons.doUpdate") : t("addons.doInstall")}
|
||||
</Button>}
|
||||
{a.installed && <Button size="sm" variant="ghost" disabled={working !== null} onClick={() => void run(a.id, "remove")}>{t("addons.doRemove")}</Button>}
|
||||
</div>
|
||||
</li>)}
|
||||
</ul>
|
||||
{error && <p className="mt-2 text-sm text-bad" role="alert">{error}</p>}
|
||||
</div>;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
|
||||
import { checkClient } from "@/lib/clientUpdate";
|
||||
import { ClientGraphics } from "./ClientGraphics";
|
||||
import { AddonCatalog } from "./AddonCatalog";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -97,6 +98,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
<dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
|
||||
</dl>
|
||||
<ClientGraphics key={info.path} serverId={serverId} />
|
||||
<AddonCatalog key={"addons-" + info.path} serverId={serverId} />
|
||||
{!remote && (
|
||||
<label className="mt-4 flex cursor-pointer items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={playAfter} onChange={(e) => setPlayAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
|
||||
|
||||
@@ -9,6 +9,12 @@ export function ClientGraphics({ serverId }: { serverId: string }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => { void api.clientGraphics(serverId).then(setState).catch(e => setError(asUiError(e).technical)); }, [serverId]);
|
||||
const [clearCache, setClearCache] = useState<boolean | null>(null);
|
||||
useEffect(() => { void api.clearGameCacheOnPlay().then(setClearCache).catch(() => setClearCache(true)); }, []);
|
||||
async function changeClearCache(on: boolean) {
|
||||
setClearCache(on);
|
||||
try { await api.setClearGameCacheOnPlay(on); } catch (e) { setClearCache(!on); setError(asUiError(e).technical); }
|
||||
}
|
||||
async function change(name: string, disabled: boolean) {
|
||||
setBusy(true); setError(null);
|
||||
try { setState(await api.clientSetGraphics(serverId, name, disabled)); await checkClient(serverId); }
|
||||
@@ -19,6 +25,8 @@ export function ClientGraphics({ serverId }: { serverId: string }) {
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.dxvk_disabled ?? false} disabled={!state || busy} onChange={e => void change("d3d9.dll", e.target.checked)} />{t("client.graphics.dxvk")}</label>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={state?.enhancements_disabled ?? false} disabled={!state || busy} onChange={e => void change("dxgi.dll", e.target.checked)} />{t("client.graphics.enhancements")}</label>
|
||||
<p className="text-xs text-muted">{t("client.graphics.hint")}</p>
|
||||
<label className="flex items-center gap-2 text-sm"><input type="checkbox" checked={clearCache ?? true} disabled={clearCache === null} onChange={e => void changeClearCache(e.target.checked)} />{t("client.clearCache")}</label>
|
||||
<p className="text-xs text-muted">{t("client.clearCacheHint")}</p>
|
||||
{error && <p className="text-sm text-bad" role="alert">{error}</p>}
|
||||
</div>;
|
||||
}
|
||||
Reference in new issue
Block a user