mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-18 19:25:56 +00:00
Addon catalog in the game client card
addons/catalog.json pins SquidBots Lite, DragonUI (+Options), IncahootsCoA and CoACombat to a commit and lists every file with its git blob SHA-1 and size. Install downloads GitHub's archive of that commit, verifies each file (archives are not byte-stable, their contents are), stages next to AddOns and moves the folders in; a foreign folder of the same name goes to AddOns/.coa-addons-backup. .coa-addons.json records what the Manager installed; update and remove touch only that. CoA_DevMenu ships with Custom Races V2, so the separate dev menu addon is not in the catalog. Checked against the real GitHub archives of the three small addons (ignored test). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d64fdb51be
commit
05630ec9eb
15 files changed
+7877
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,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-")));
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
pub mod accounts;
|
||||
pub mod allsettings;
|
||||
pub mod addons;
|
||||
pub mod backup;
|
||||
pub mod channels;
|
||||
pub mod character_start_check;
|
||||
|
||||
@@ -1479,6 +1479,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>,
|
||||
@@ -3117,6 +3152,9 @@ pub fn run() {
|
||||
restart_schedule_save,
|
||||
clear_game_cache_on_play,
|
||||
set_clear_game_cache_on_play,
|
||||
addons_list,
|
||||
addons_install,
|
||||
addons_remove,
|
||||
check_database,
|
||||
repair_server,
|
||||
module_set_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";
|
||||
@@ -41,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,16 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"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,16 @@ const en = {
|
||||
"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,16 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"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,16 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"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,16 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"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,16 @@ const zh = {
|
||||
"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": "保存",
|
||||
|
||||
@@ -58,6 +58,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 }
|
||||
@@ -491,6 +492,9 @@ 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 }),
|
||||
|
||||
@@ -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]" />
|
||||
|
||||
Reference in new issue
Block a user