Files
coa-server-manager/crates/coa-core/src/modules.rs
T
ДмитрийandClaude Opus 5.5 9f48cfc8d5 preview 0.9.10: bare modular core for new servers, modular copy of classic servers
- A new server goes on to the preview core without compiling any module
  (recommended modules are declined once; modules come from the Modules page).
- Choosing a server with the classic core makes a modular copy next to it:
  every acore_* database (read from the running database, or from a private
  copy of the stopped data files opened by the new server's own mysqld),
  module configs and realm profiles, ports and console login. The old server
  is only read. The copy then takes the preview core with the modules the old
  server had switched on.
- Installs and the preview update run on unused ports, so a server running on
  the shipped ports (the old one, or any other) no longer stops them; the
  schema check after "Preparing database" used the shipped port before.
- Dungeon Clear is part of SQUID's Playerbots: no card of its own (it said
  "Always on" while SQUID was off), switched with SQUID, settings on the SQUID card.

E2E (examples/preview_bare_and_copy_e2e, disposable servers, another server
running on the shipped ports): fresh install committed with no plugins and a
clean boot report; copy of a stopped and of a running classic server: data
identical, old server's files byte-for-byte unchanged, Content Scaling and
Companions built on the copy, preview core committed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:49:03 +05:00

1962 lines
80 KiB
Rust

//! Optional server modules. They are compiled into the server; what the owner decides is whether each one is on and how it is
//! configured, which lives in `Core/configs/modules/<module>.conf` (the documented defaults are in the `.dist` beside it).
//! The list of known modules is a bundled catalog, so a module is added to the Manager by adding a few lines to it.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::config::parser::ConfFile;
use crate::error::{Error, Result};
use crate::fsx;
static CATALOG: &str = include_str!("../../../modules/catalog.json");
#[derive(Debug, Clone, Deserialize)]
pub struct Entry {
pub id: String,
pub name: String,
/// language code -> text; "en" is always there.
pub description: BTreeMap<String, String>,
pub repo: String,
/// File in `Core/configs/modules` that holds this module's settings.
pub conf: String,
/// The name an older server build gave that file (used when `conf` is not there).
#[serde(default)]
pub alt_conf: Option<String>,
/// The setting that switches the whole module on or off (1 / 0). Empty for a part that cannot be switched off.
#[serde(default)]
pub enable_key: String,
/// Can be turned on and off here. A part the game client needs to talk to the server is only configured.
#[serde(default = "yes")]
pub switchable: bool,
/// What the module is when its setting is not in the file: a server from before the setting existed runs it.
#[serde(default = "yes")]
pub default_on: bool,
/// How far along it is: `early` (experimental, may change or break), `beta` (works, still being tested) or
/// `release` (stable); `soon` is a place held for a module that is planned but not part of any build yet.
#[serde(default = "release")]
pub status: String,
/// Which icon the page draws (a name the page knows).
#[serde(default)]
pub icon: String,
/// A page of the Manager that only makes sense while the module is on (it is hidden while it is off).
#[serde(default)]
pub page: Option<String>,
/// Not shown on the Modules page; its settings are offered elsewhere (a server setting card).
#[serde(default)]
pub hidden: bool,
}
fn yes() -> bool {
true
}
fn release() -> String {
"release".into()
}
#[derive(Deserialize)]
struct Catalog {
modules: Vec<Entry>,
}
pub fn catalog() -> Vec<Entry> {
serde_json::from_str::<Catalog>(CATALOG)
.map(|c| c.modules)
.unwrap_or_default()
}
fn entry_in(cat: &[Entry], id: &str) -> Result<Entry> {
cat.iter()
.find(|e| e.id == id)
.cloned()
.ok_or_else(|| Error::Invalid("That module is not known to the Manager.".into()))
}
fn dir(root: &Path) -> PathBuf {
crate::plugins::modules_config_dir(root)
}
fn find_conf_for_id(root: &Path, id: &str) -> Option<(PathBuf, Option<PathBuf>)> {
let conf_dir = dir(root);
// 1. Check if known in catalog
if let Ok(e) = entry_in(&catalog(), id) {
let name = conf_name(root, &e);
let conf = conf_dir.join(&name);
let dist = conf_dir.join(format!("{name}.dist"));
return Some((conf, dist.is_file().then_some(dist)));
}
// 2. Check plugin registry
if let Ok(reg) = crate::plugins::load_registry(root) {
if let Some(entry) = reg.plugins.get(id) {
for conf_entry in &entry.conf_files {
let base_name = conf_entry.strip_suffix(".dist").unwrap_or(conf_entry);
let conf = conf_dir.join(base_name);
let dist = conf_dir.join(format!("{base_name}.dist"));
if conf.is_file() || dist.is_file() {
return Some((conf, dist.is_file().then_some(dist)));
}
}
}
}
// 3. Fallback search by ID or name in conf_dir
let normalized = id.replace('-', "_");
if let Ok(entries) = fs::read_dir(&conf_dir) {
for entry in entries.flatten() {
let p = entry.path();
if let Some(fname) = p.file_name().and_then(|n| n.to_str()) {
if fname.starts_with(&normalized) || fname.starts_with(id) {
let base_name = fname.strip_suffix(".dist").unwrap_or(fname);
let conf = conf_dir.join(base_name);
let dist = conf_dir.join(format!("{base_name}.dist"));
return Some((conf, dist.is_file().then_some(dist)));
}
}
}
}
None
}
fn read(path: &Path) -> Option<ConfFile> {
fs::read(path)
.ok()
.and_then(|b| ConfFile::parse_bytes(&b).ok())
}
fn truthy(v: &str) -> bool {
matches!(
v.trim().trim_matches('"').to_ascii_lowercase().as_str(),
"1" | "true" | "yes" | "on"
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ComponentType {
DynamicDll,
CoreEmbedded,
ContentPack,
ClientPatch,
LogicalFeature,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ModuleView {
pub id: String,
pub name: String,
pub version: Option<String>,
pub description: BTreeMap<String, String>,
pub repo: String,
/// The module's component is truly present and installed on this server.
pub installed: bool,
/// At least one editable setting besides the master switch exists in this server build.
pub has_settings: bool,
pub enabled: bool,
pub switchable: bool,
pub status: String,
pub icon: String,
pub page: Option<String>,
pub hidden: bool,
pub compatibility: String,
pub component_type: ComponentType,
pub can_remove: bool,
pub source_commit: Option<String>,
}
pub fn list(root: &Path) -> Vec<ModuleView> {
list_in(&catalog(), root)
}
/// The configuration file name this server uses for the module: the current one, or the name an older build gave it.
fn conf_name(root: &Path, e: &Entry) -> String {
let there =
|n: &str| dir(root).join(n).is_file() || dir(root).join(format!("{n}.dist")).is_file();
if there(&e.conf) {
return e.conf.clone();
}
match &e.alt_conf {
Some(alt) if there(alt) => alt.clone(),
_ => e.conf.clone(),
}
}
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 plugin_reg = crate::plugins::load_registry(root).ok();
let wildcard = crate::realms::state(root)
.map(|s| s.active != crate::realms::Mode::Coa)
.unwrap_or(true);
let is_modular_host = root.join("plugins").is_dir()
|| root.join(".manager/plugins.json").is_file()
|| root.join(".manager/plugin-store").is_dir()
|| root.join("sdk.json").is_file();
let mut views: Vec<ModuleView> = cat.iter()
.cloned()
.map(|e| {
let name = conf_name(root, &e);
let conf = dir(root).join(&name);
let dist = dir(root).join(format!("{name}.dist"));
// 1. Dynamic DLL detection
let plugin_entry = plugin_reg.as_ref().and_then(|r| {
r.plugins.get(&e.id)
.or_else(|| r.plugins.get(&e.id.replace('-', "_")))
.or_else(|| r.plugins.get(&format!("mod-{}", e.id)))
.or_else(|| r.plugins.get(&format!("mod-coa-{}", e.id)))
.or_else(|| r.plugins.get(&format!("coa-{}", e.id)))
.or_else(|| r.plugins.get(&format!("coa_{}", e.id)))
.or_else(|| match e.id.as_str() {
"content-scaling" => r.plugins.get("coa-content-scaling").or_else(|| r.plugins.get("mod-coa-content-scaling")),
"companions" => r.plugins.get("coa-playerbots").or_else(|| r.plugins.get("mod-coa-playerbots")),
"playerbots" => r.plugins.get("squid-playerbots").or_else(|| r.plugins.get("mod-playerbots")),
_ => None,
})
});
let alias_dlls: Vec<PathBuf> = match e.id.as_str() {
"content-scaling" => vec![
root.join("plugins").join("coa-content-scaling").join("coa-content-scaling.dll"),
root.join("plugins").join("coa-content-scaling.dll"),
],
"companions" => vec![
root.join("plugins").join("coa-playerbots").join("coa-playerbots.dll"),
root.join("plugins").join("coa-playerbots.dll"),
root.join("plugins").join("mod-coa-playerbots.dll"),
],
"playerbots" => vec![
root.join("plugins").join("mod-playerbots").join("mod-playerbots.dll"),
root.join("plugins").join("squid-playerbots").join("squid-playerbots.dll"),
root.join("plugins").join("mod-playerbots.dll"),
],
_ => Vec::new(),
};
let mut dll_candidates = vec![
root.join("plugins").join(format!("{}.dll", e.id)),
root.join("plugins").join(format!("{}.dll", e.id.replace('-', "_"))),
root.join("plugins").join(format!("coa-{}.dll", e.id)),
root.join("plugins").join(format!("coa_{}.dll", e.id.replace('-', "_"))),
root.join("plugins").join(format!("mod-{}.dll", e.id)),
root.join("plugins").join(format!("mod-{}.dll", e.id.replace('-', "_"))),
root.join("plugins").join(format!("mod-coa-{}.dll", e.id)),
root.join("plugins").join(format!("mod_coa_{}.dll", e.id.replace('-', "_"))),
// Subdirectory checks (plugins/{id}/{id}.dll)
root.join("plugins").join(&e.id).join(format!("{}.dll", e.id)),
root.join("plugins").join(format!("coa-{}", e.id)).join(format!("coa-{}.dll", e.id)),
root.join("plugins").join(format!("mod-{}", e.id)).join(format!("mod-{}.dll", e.id)),
root.join("plugins").join(format!("mod-coa-{}", e.id)).join(format!("mod-coa-{}.dll", e.id)),
// .manager/plugins checks
root.join(".manager/plugins").join(format!("{}.dll", e.id)),
root.join(".manager/plugins").join(format!("coa-{}.dll", e.id)),
root.join(".manager/plugins").join(format!("mod-coa-{}.dll", e.id)),
];
dll_candidates.extend(alias_dlls);
let dll_present = dll_candidates.iter().any(|p| p.is_file());
let is_dynamic = plugin_entry.is_some() || dll_present;
// 2. Classify ComponentType and determine installation strictly
let (component_type, installed, can_remove) = if is_dynamic {
(ComponentType::DynamicDll, true, true)
} else if e.id == "custom-races" {
let has_patch = root.join("Data/patch-Z.mpq").is_file()
|| root.join("Data/patch-4.mpq").is_file()
|| root.join("Data/ruRU/patch-ruRU-4.mpq").is_file()
|| root.join("Data/enGB/patch-enGB-4.mpq").is_file()
|| root.join("Data/enUS/patch-enUS-4.mpq").is_file();
(ComponentType::ClientPatch, has_patch, false)
} else if matches!(e.id.as_str(), "tbc-content" | "wotlk-content") {
let is_scaling_installed = {
let se_plugin = plugin_reg.as_ref().and_then(|r| {
r.plugins.get("content-scaling")
.or_else(|| r.plugins.get("content_scaling"))
.or_else(|| r.plugins.get("coa-content-scaling"))
.or_else(|| r.plugins.get("mod-coa-content-scaling"))
});
let se_dll = root.join("plugins").join("content-scaling.dll").is_file()
|| root.join("plugins").join("content-scaling").join("content-scaling.dll").is_file()
|| root.join("plugins").join("coa-content-scaling").join("coa-content-scaling.dll").is_file()
|| root.join("plugins").join("coa-content-scaling.dll").is_file()
|| root.join("plugins").join("mod-coa-content-scaling.dll").is_file()
|| root.join(".manager/plugins").join("content-scaling.dll").is_file()
|| root.join(".manager/plugins").join("coa-content-scaling.dll").is_file()
|| root.join(".manager/plugins").join("mod-coa-content-scaling.dll").is_file();
se_plugin.is_some() || se_dll || (!is_modular_host && (conf.is_file() || dist.is_file()))
};
(ComponentType::ContentPack, is_scaling_installed, false)
} else if e.id == "dungeon-clear" {
let has_files = conf.is_file() || dist.is_file() || installed_commits.contains_key("dungeon-clear");
(if is_modular_host && !has_files { ComponentType::DynamicDll } else { ComponentType::CoreEmbedded }, has_files, false)
} else if !is_modular_host {
let key = match e.id.as_str() {
"companions" => "bots",
"playerbots" => "squid",
"content-scaling" => "scaling",
id => id,
};
let has_files = conf.is_file() || dist.is_file() || installed_commits.contains_key(key);
(ComponentType::CoreEmbedded, has_files, false)
} else {
// In a modular host (with plugins/ directory or plugins.json), if dynamic DLL is not present, it is NOT installed!
(ComponentType::DynamicDll, false, false)
};
let has_settings = installed
&& settings_in(cat, root, &e.id)
.map(|settings| settings.iter().any(|s| s.key != e.enable_key))
.unwrap_or(false);
// the active file or plugin registry decides enabled state
let enabled = if !installed {
false
} else if let Some(p) = plugin_entry {
p.enabled
} else if matches!(e.id.as_str(), "companions" | "playerbots") {
let comp_entry = cat.iter().find(|ce| ce.id == "companions");
let comp_on = comp_entry.map(|ce| bot_enabled(root, ce).unwrap_or(false)).unwrap_or(false);
if e.id == "playerbots" {
if comp_on {
false
} else {
bot_enabled(root, &e).unwrap_or(false)
}
} else {
bot_enabled(root, &e).unwrap_or(true)
}
} else if matches!(e.id.as_str(), "tbc-content" | "wotlk-content") {
let sc_entry = cat.iter().find(|entry| entry.id == "content-scaling");
let sc_conf = sc_entry.map(|se| dir(root).join(conf_name(root, se)));
let sc_enabled = sc_conf
.and_then(|p| read(&p))
.and_then(|c| c.get("CoAContentScaling.Enable").map(truthy))
.unwrap_or(true);
sc_enabled && read(&conf)
.or_else(|| read(&dist))
.and_then(|c| c.get(&e.enable_key).map(truthy))
.unwrap_or(e.default_on)
} else {
!e.switchable
|| read(&conf)
.or_else(|| read(&dist))
.and_then(|c| c.get(&e.enable_key).map(truthy))
.unwrap_or(e.default_on)
};
let is_squid_active = {
let comp_entry = cat.iter().find(|ce| ce.id == "companions");
let comp_on = comp_entry.map(|ce| bot_enabled(root, ce).unwrap_or(false)).unwrap_or(false);
if comp_on {
false
} else {
let pb_entry = cat.iter().find(|ce| ce.id == "playerbots");
pb_entry.map(|pe| bot_enabled(root, pe).unwrap_or(false)).unwrap_or(false)
}
};
let dependency_missing = e.id == "dungeon-clear" && !is_squid_active;
let blocked = dependency_missing
|| (wildcard && matches!(e.id.as_str(), "companions" | "playerbots" | "dungeon-clear"));
let version = if let Some(p) = plugin_entry {
Some(p.version.clone())
} else 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
};
let source_commit = installed_commits.get(key).cloned();
ModuleView {
version,
compatibility: if dependency_missing {
"requires-squid"
} else if blocked {
"unsupported"
} else if wildcard && e.id != "client-compat" {
"experimental"
} else {
"compatible"
}
.into(),
id: e.id,
name: e.name,
description: e.description,
repo: e.repo,
installed,
has_settings,
enabled: enabled && !blocked,
switchable: e.switchable && !blocked,
status: e.status,
icon: e.icon,
page: e.page,
hidden: e.hidden,
component_type,
can_remove,
source_commit,
}
})
.collect();
// Also include installed dynamic plugins from plugin_reg that aren't already in views
if let Some(ref reg) = plugin_reg {
for (plugin_id, plugin_entry) in &reg.plugins {
let matched_idx = views.iter().position(|v| {
v.id == *plugin_id
|| format!("coa-{}", v.id) == *plugin_id
|| format!("mod-coa-{}", v.id) == *plugin_id
|| format!("mod-{}", v.id) == *plugin_id
|| (v.id == "content-scaling" && matches!(plugin_id.as_str(), "coa-content-scaling" | "mod-coa-content-scaling"))
|| (v.id == "companions" && matches!(plugin_id.as_str(), "coa-playerbots" | "mod-coa-playerbots"))
|| (v.id == "playerbots" && matches!(plugin_id.as_str(), "squid-playerbots" | "mod-playerbots"))
|| (v.id == "ah-bot" && matches!(plugin_id.as_str(), "mod_ahbot" | "ahbot"))
|| (v.id == "npc-buffer" && (plugin_id.contains("buffer") || plugin_entry.conf_files.iter().any(|c| c.contains("npc_buffer"))))
|| (v.id == "npc-enchanter" && (plugin_id.contains("enchanter") || plugin_entry.conf_files.iter().any(|c| c.contains("enchanter"))))
|| (v.id == "congrats-on-level" && (plugin_id.contains("congrats") || plugin_entry.conf_files.iter().any(|c| c.contains("congrats"))))
|| (v.id == "reward-played-time" && (plugin_id.contains("reward") || plugin_entry.conf_files.iter().any(|c| c.contains("reward"))))
});
if let Some(idx) = matched_idx {
// Update existing canonical module entry instead of duplicating
views[idx].installed = true;
views[idx].enabled = plugin_entry.enabled;
views[idx].version = Some(plugin_entry.version.clone());
views[idx].component_type = ComponentType::DynamicDll;
views[idx].can_remove = true;
continue;
}
if true {
let mut display_name = if let Ok(meta) = crate::plugins::load_store_metadata(root, plugin_id, &plugin_entry.sha256) {
meta.name
} else {
String::new()
};
let mut source_commit = None;
if display_name.is_empty() || (display_name.len() == 40 && display_name.chars().all(|c| c.is_ascii_hexdigit())) {
source_commit = Some(plugin_id.clone());
display_name = if plugin_id.len() == 40 && plugin_id.chars().all(|c| c.is_ascii_hexdigit()) {
if plugin_entry.conf_files.iter().any(|c| c.contains("npc_buffer")) {
"NPC Buffer".to_string()
} else if plugin_entry.conf_files.iter().any(|c| c.contains("ah_bot") || c.contains("ahbot")) {
"Auction House Bot".to_string()
} else if plugin_entry.conf_files.iter().any(|c| c.contains("enchanter")) {
"NPC Enchanter".to_string()
} else if plugin_entry.conf_files.iter().any(|c| c.contains("congrats")) {
"Congrats On Level".to_string()
} else if plugin_entry.conf_files.iter().any(|c| c.contains("reward_played_time")) {
"Reward Played Time".to_string()
} else {
format!("Module ({})", &plugin_id[..8])
}
} else if plugin_id == "npc-buffer" {
"NPC Buffer".to_string()
} else if plugin_id == "ah-bot" {
"Auction House Bot".to_string()
} else if plugin_id == "congrats-on-level" {
"Congrats On Level".to_string()
} else if plugin_id == "npc-enchanter" {
"NPC Enchanter".to_string()
} else if plugin_id == "reward-played-time" {
"Reward Played Time".to_string()
} else {
plugin_id.split('-').map(|s| {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}).collect::<Vec<_>>().join(" ")
};
}
let mut desc_map = BTreeMap::new();
desc_map.insert("ru".to_string(), format!("Динамический модуль {}", display_name));
desc_map.insert("en".to_string(), format!("Dynamic module {}", display_name));
let has_settings = settings_in(cat, root, plugin_id).map(|s| !s.is_empty()).unwrap_or(false);
views.push(ModuleView {
version: Some(plugin_entry.version.clone()),
compatibility: "compatible".into(),
id: plugin_id.clone(),
name: display_name,
description: desc_map,
repo: format!("https://github.com/azerothcore/{}", plugin_id),
installed: true,
has_settings,
enabled: plugin_entry.enabled,
switchable: true,
status: "release".into(),
icon: "plug".into(),
page: None,
hidden: false,
component_type: ComponentType::DynamicDll,
can_remove: true,
source_commit,
});
}
}
}
views
}
/// The active file, created from its `.dist` when it does not exist yet.
fn active_file(root: &Path, e: &Entry) -> Result<PathBuf> {
let name = conf_name(root, e);
let conf = dir(root).join(&name);
if !conf.is_file() {
let dist = dir(root).join(format!("{name}.dist"));
if !dist.is_file() {
return Err(Error::Invalid(
"This module is not part of this server.".into(),
));
}
fsx::atomic_write(&conf, &fs::read(&dist)?)?;
}
Ok(conf)
}
fn backup(meta: &Path, conf: &Path) -> Result<()> {
let name = conf
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let to = meta.join("backups").join("modules").join(format!(
"{name}-{}",
chrono::Utc::now().format("%Y%m%d-%H%M%S")
));
fsx::atomic_write(&to, &fs::read(conf)?)
}
fn require_bot_server_stopped(root: &Path) -> Result<()> {
let observed = crate::process::observe(root, &crate::layout::read_ports(root));
if observed.world.state != crate::process::ServiceState::Stopped
|| crate::multiworld::is_running(root)
{
return Err(Error::Invalid(
"Stop the server before changing the bot system.".into(),
));
}
Ok(())
}
pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
let _update_lock = crate::update::operation_lock(meta)?;
crate::update::ensure_recovered(meta)?;
let is_dynamic_plugin = crate::plugins::load_registry(root)
.map(|r| r.plugins.contains_key(id))
.unwrap_or(false);
let _lock = if is_dynamic_plugin || matches!(id, "companions" | "playerbots" | "dungeon-clear") {
require_bot_server_stopped(root)?;
fs::create_dir_all(root.join(".state"))?;
let lock = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(root.join(".state/control.lock"))?;
if !fs4::fs_std::FileExt::try_lock_exclusive(&lock)? {
return Err(Error::Invalid(
"Another start/stop action is in progress.".into(),
));
}
require_bot_server_stopped(root)?;
Some(lock)
} else {
None
};
if on {
crate::realms::guard_module(root, id)?;
if id == "dungeon-clear" {
crate::realms::guard_module(root, "playerbots")?;
}
}
if id == "custom-races" {
if let Ok(meta_content) = fs::read_to_string(meta.join("install.json")) {
if let Ok(install_meta) =
serde_json::from_str::<crate::registry::InstallMeta>(&meta_content)
{
if let Some(cp) = install_meta.client_path {
let client_path = PathBuf::from(cp);
if client_path.is_dir() {
crate::custom_races::set_client_patch_enabled(&client_path, on)?;
}
}
}
}
if !on {
let _ = crate::custom_races::sync_bot_races_config(root, false);
} else {
let allow =
crate::custom_races::is_bot_custom_races_allowed(root).unwrap_or_else(|| {
read(&dir(root).join("coa_custom_races.conf"))
.and_then(|c| c.get("CoACustomRaces.BotsEnable").map(truthy))
.unwrap_or(false)
});
let _ = crate::custom_races::sync_bot_races_config(root, allow);
}
}
set_enabled_in(&catalog(), root, meta, id, on)
}
fn bot_enabled(root: &Path, e: &Entry) -> Result<bool> {
if let Ok(reg) = crate::plugins::load_registry(root) {
if let Some(p) = reg.plugins.get(&e.id)
.or_else(|| reg.plugins.get(&format!("coa-{}", e.id)))
.or_else(|| reg.plugins.get(&format!("mod-coa-{}", e.id)))
.or_else(|| reg.plugins.get(&format!("mod-{}", e.id)))
.or_else(|| if e.id == "playerbots" { reg.plugins.get("squid-playerbots") } else { None })
{
return Ok(p.enabled);
}
}
let name = conf_name(root, e);
let conf = dir(root).join(&name);
let dist = dir(root).join(format!("{name}.dist"));
let path = if conf.exists() { conf } else { dist };
if !path.exists() {
return Ok(false);
}
let file = ConfFile::parse_bytes(&fs::read(path)?)?;
// Invalid booleans use the modules' enabled compiled default: fail closed.
Ok(file
.get(&e.enable_key)
.map(|v| {
!matches!(
v.trim().trim_matches('"').to_ascii_lowercase().as_str(),
"0" | "false" | "no" | "off"
)
})
.unwrap_or(true))
}
pub fn ensure_bot_exclusivity(root: &Path) -> Result<()> {
let cat = catalog();
let comp_on = entry_in(&cat, "companions").map(|e| bot_enabled(root, &e).unwrap_or(false)).unwrap_or(false);
let pb_on = entry_in(&cat, "playerbots").map(|e| bot_enabled(root, &e).unwrap_or(false)).unwrap_or(false);
if comp_on && pb_on {
return Err(Error::BotModulesConflict);
}
if comp_on {
let dc_on = entry_in(&cat, "dungeon-clear").map(|e| bot_enabled(root, &e).unwrap_or(false)).unwrap_or(false);
if dc_on {
return Err(Error::Invalid("Dungeon Clear cannot be active while CoA Companions is enabled.".into()));
}
}
Ok(())
}
/// Dungeon Clear is part of SQUID's Playerbots (the plugin core builds it into the SQUID DLL): it goes on
/// with SQUID, and off with it, wherever its config exists.
fn switch_on_dungeon_clear_with_squid(cat: &[Entry], root: &Path, meta: &Path) {
if let Some(dc) = cat.iter().find(|entry| entry.id == "dungeon-clear") {
let name = conf_name(root, dc);
if dir(root).join(&name).exists() || dir(root).join(format!("{name}.dist")).exists() {
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", true);
}
}
}
fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
match entry_in(cat, id) {
Ok(e) => {
if on && id == "dungeon-clear" {
let comp_entry = cat.iter().find(|ce| ce.id == "companions");
let comp_on = comp_entry.map(|ce| bot_enabled(root, ce).unwrap_or(false)).unwrap_or(false);
let pb_entry = entry_in(cat, "playerbots");
let squid_on = !comp_on && pb_entry.as_ref().map(|pe| bot_enabled(root, pe).unwrap_or(false)).unwrap_or(false);
if !squid_on {
return Err(Error::Invalid("Enable SQUID bots before enabling Dungeon Clear.".into()));
}
}
if !e.switchable || e.enable_key.is_empty() {
return Err(Error::Invalid("This part cannot be switched off.".into()));
}
if on && matches!(id, "companions" | "playerbots") {
let other = if id == "companions" {
"playerbots"
} else {
"companions"
};
if let Some(other) = cat.iter().find(|e| e.id == other) {
if bot_enabled(root, other)? {
return Err(Error::BotModulesConflict);
}
}
}
if (id == "playerbots" && !on) || (id == "companions" && on) {
if let Some(dependency) = cat.iter().find(|entry| entry.id == "dungeon-clear") {
let conf_path = dir(root).join(&dependency.conf);
let dist_path = dir(root).join(format!("{}.dist", dependency.conf));
if conf_path.exists() || dist_path.exists() {
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", false);
}
}
}
let conf = active_file(root, &e)?;
let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?;
if file.get(&e.enable_key).map(truthy).unwrap_or(e.default_on) == on
&& file.get(&e.enable_key).is_some()
{
return Ok(());
}
backup(meta, &conf)?;
file.set(
&e.enable_key,
if on { "1" } else { "0" },
&["Changed by CoA Server Manager"],
);
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
// If registered as a dynamic plugin, synchronize plugins.lock and plugin state
if let Ok(reg) = crate::plugins::load_registry(root) {
if reg.plugins.contains_key(id) {
let _ = crate::plugins::set_enabled(root, id, on);
}
}
if id == "playerbots" && on {
let _ = crate::plugins::record_squid_migrations_applied(root);
switch_on_dungeon_clear_with_squid(cat, root, meta);
}
tracing::info!(module = id, on, "module switched");
Ok(())
}
Err(_) => {
// Dynamic plugin / module fallback
let mut found_conf = false;
if let Some((conf, dist_opt)) = find_conf_for_id(root, id) {
if !conf.is_file() {
if let Some(d) = dist_opt {
let _ = fsx::atomic_write(&conf, &fs::read(d)?);
}
}
if conf.is_file() {
if let Ok(mut file) = ConfFile::parse_bytes(&fs::read(&conf)?) {
let enable_key = file.entries().into_iter()
.find(|(k, _)| k.ends_with(".Enable") || k.ends_with(".Enabled"))
.map(|(k, _)| k.to_string());
if let Some(k) = enable_key {
let _ = backup(meta, &conf);
file.set(&k, if on { "1" } else { "0" }, &["Changed by CoA Server Manager"]);
let _ = fsx::atomic_write(&conf, file.to_text().as_bytes());
found_conf = true;
}
}
}
}
if let Ok(reg) = crate::plugins::load_registry(root) {
if reg.plugins.contains_key(id) {
crate::plugins::set_enabled(root, id, on)?;
if (id == "playerbots" && !on) || (id == "companions" && on) {
if cat.iter().any(|entry| entry.id == "dungeon-clear") {
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", false);
}
}
if id == "playerbots" && on {
switch_on_dungeon_clear_with_squid(cat, root, meta);
}
return Ok(());
}
}
if found_conf {
return Ok(());
}
Err(Error::Invalid("That module is not known to the Manager.".into()))
}
}
}
#[derive(Debug, Serialize, PartialEq)]
pub struct Setting {
pub key: String,
pub value: String,
pub default: Option<String>,
/// The documentation the module ships above the setting.
pub doc: String,
pub field: Option<crate::squid::Field>,
}
/// Every active setting of the module with its current value, its documented default and its description.
pub fn settings(root: &Path, id: &str) -> Result<Vec<Setting>> {
settings_in(&catalog(), root, id)
}
fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result<Vec<Setting>> {
let (conf, dist) = match entry_in(cat, id) {
Ok(e) => {
let name = conf_name(root, &e);
(dir(root).join(&name), read(&dir(root).join(format!("{name}.dist"))))
}
Err(_) => {
if let Some((c, d_opt)) = find_conf_for_id(root, id) {
(c, d_opt.and_then(|d| read(&d)))
} else {
return Err(Error::Invalid("This module is not part of this server.".into()));
}
}
};
let active = read(&conf)
.or_else(|| dist.clone())
.ok_or_else(|| Error::Invalid("This module is not part of this server.".into()))?;
let fields = if id == "playerbots" {
crate::squid::fields(root)?
} else {
Default::default()
};
let mut effective = active.clone();
if let Some(defaults) = &dist {
for (key, value) in defaults.entries() {
if effective.get(key).is_none() {
effective.set(key, value, &[]);
}
}
}
let bot_custom_races_allowed = if id == "custom-races" {
crate::custom_races::is_bot_custom_races_allowed(root)
} else {
None
};
Ok(effective
.entries()
.map(|(k, v)| {
let mut val = fields
.get(k)
.and_then(|field| field.default_if_missing.as_ref())
.filter(|_| active.get(k).is_none())
.and_then(crate::squid::scalar)
.unwrap_or_else(|| v.to_string());
if k == "CoACustomRaces.BotsEnable" {
if let Some(allowed) = bot_custom_races_allowed {
val = if allowed { "1".into() } else { "0".into() };
}
}
Setting {
key: k.to_string(),
value: val,
default: fields
.get(k)
.and_then(|field| crate::squid::scalar(&field.default))
.or_else(|| dist.as_ref().and_then(|d| d.get(k)).map(str::to_string)),
field: fields.get(k).cloned(),
doc: dist
.as_ref()
.map(|d| d.doc_for(k))
.filter(|d| !d.is_empty())
.unwrap_or_else(|| active.doc_for(k))
.join(" "),
}
})
.collect())
}
/// Change values of settings the module already has. A value is one line of at most 500 characters.
pub fn save_settings(
root: &Path,
meta: &Path,
id: &str,
changes: &BTreeMap<String, String>,
) -> Result<Vec<String>> {
crate::realms::guard_module(root, id)?;
save_settings_in(&catalog(), root, meta, id, changes)
}
fn save_settings_in(
cat: &[Entry],
root: &Path,
meta: &Path,
id: &str,
changes: &BTreeMap<String, String>,
) -> Result<Vec<String>> {
let (conf, dist, switchable, enable_key) = match entry_in(cat, id) {
Ok(e) => {
let conf = active_file(root, &e)?;
let dist = read(&dir(root).join(format!("{}.dist", conf_name(root, &e))));
(conf, dist, e.switchable, e.enable_key)
}
Err(_) => {
if let Some((c, d_opt)) = find_conf_for_id(root, id) {
if !c.is_file() {
if let Some(ref d) = d_opt {
fsx::atomic_write(&c, &fs::read(d)?)?;
} else {
return Err(Error::Invalid("This module is not part of this server.".into()));
}
}
let dist = d_opt.and_then(|d| read(&d));
let enable_k = dist.as_ref()
.and_then(|d| d.entries().into_iter().find(|(k, _)| k.ends_with(".Enable") || k.ends_with(".Enabled")).map(|(k, _)| k.to_string()))
.unwrap_or_default();
(c, dist, true, enable_k)
} else {
return Err(Error::Invalid("This module is not part of this server.".into()));
}
}
};
let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?;
let fields = if id == "playerbots" {
crate::squid::fields(root)?
} else {
Default::default()
};
let mut changed = Vec::new();
for (key, value) in changes {
let value = value.trim();
if id == "custom-races" && key == crate::race_availability::KEY {
require_bot_server_stopped(root)?;
let catalog = crate::race_availability::status(root)?;
if !catalog.server_config_supported {
return Err(Error::Invalid("Update the server before configuring individual race restrictions.".into()));
}
crate::race_availability::parse_disabled(value, &catalog.races)?;
}
if id == "custom-races" && key == crate::race_availability::CATALOG_KEY {
let hash = value.trim_matches('"');
if !hash.is_empty() && (hash.len() != 64 || !hash.bytes().all(|byte| byte.is_ascii_hexdigit())) {
return Err(Error::Invalid("Invalid race catalog fingerprint.".into()));
}
}
if let Some(field) = fields.get(key) {
crate::squid::validate(field, value)?;
}
if switchable && !enable_key.is_empty() && key == &enable_key {
return Err(Error::Invalid(
"Use the module switch to turn this module on or off.".into(),
));
}
if id == "time-is-time" {
let valid = match key.as_str() {
"TimeIsTime.Announce" => matches!(value, "0" | "1"),
"TimeIsTime.SpeedRate" => value.parse::<f32>().is_ok_and(|v| v.is_finite() && (0.0..=60.0).contains(&v)),
"TimeIsTime.TimeStart" => value.parse::<i32>().is_ok_and(|v| v >= 0),
"TimeIsTime.HourOffset" => value.parse::<f32>().is_ok_and(|v| v.is_finite() && (-24.0..=24.0).contains(&v)),
_ => true,
};
if !valid {
return Err(Error::Invalid(format!("Invalid value for {key}.")));
}
}
if id == "content-scaling" && key == "CoAContentScaling.Difficulty.DamageMultiplier" {
let multiplier = value.parse::<f32>().map_err(|_| {
Error::Invalid("Enemy damage must be a number from 0.25 to 2.0.".into())
})?;
if !multiplier.is_finite() || !(0.25..=2.0).contains(&multiplier) {
return Err(Error::Invalid(
"Enemy damage must be a number from 0.25 to 2.0.".into(),
));
}
}
if id == "content-scaling"
&& key.starts_with("CoAContentScaling.Difficulty.Health.")
&& key.ends_with("Multiplier")
{
let multiplier = value.parse::<f32>().map_err(|_| {
Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into())
})?;
if !multiplier.is_finite() || !(0.1..=10.0).contains(&multiplier) {
return Err(Error::Invalid(
"Health multipliers must be a number from 0.1 to 10.".into(),
));
}
}
if id == "content-scaling" && key == "CoAContentScaling.World.Leech.Percent" {
let percent = value.parse::<f32>().map_err(|_| {
Error::Invalid("Life steal must be a number from 0 to 100 percent.".into())
})?;
if !percent.is_finite() || !(0.0..=100.0).contains(&percent) {
return Err(Error::Invalid(
"Life steal must be a number from 0 to 100 percent.".into(),
));
}
}
if id == "content-scaling"
&& matches!(
key.as_str(),
"CoAContentScaling.LFG.AllowPartialGroups" | "CoAContentScaling.World.Leech.Enable"
)
&& !matches!(value, "0" | "1")
{
return Err(Error::Invalid(format!("{key} must be 0 or 1.")));
}
if id == "ah-bot"
&& key.starts_with("AuctionHouseBot.ListProportion.Category")
&& key.contains(".Quality")
{
let weight = value.parse::<u32>().map_err(|_| {
Error::Invalid(
"Auction listing weights must be whole numbers from 0 to 1000.".into(),
)
})?;
if weight > 1000 {
return Err(Error::Invalid(
"Auction listing weights must be whole numbers from 0 to 1000.".into(),
));
}
}
if file.get(key).is_none() && dist.as_ref().and_then(|d| d.get(key)).is_none() {
return Err(Error::Invalid(format!(
"{key} is not a setting of this module."
)));
}
let documented_empty = dist.as_ref().and_then(|d| d.get(key)).map(str::trim) == Some("");
if (value.is_empty() && !documented_empty)
|| value.len() > 500
|| value.chars().any(char::is_control)
{
return Err(Error::Invalid(format!(
"The value of {key} must be one line of text."
)));
}
if file.get(key).map(str::trim) != Some(value) {
changed.push((key.clone(), value.to_string()));
}
}
if id == "custom-races" {
if let Some(bots_enable) = changes.get("CoACustomRaces.BotsEnable") {
let allow = truthy(bots_enable);
crate::custom_races::sync_bot_races_config(root, allow)?;
}
}
if changed.is_empty() {
return Ok(Vec::new());
}
backup(meta, &conf)?;
for (k, v) in &changed {
file.set(k, v, &[]);
}
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
Ok(changed.into_iter().map(|(k, _)| k).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn time_is_time_card_settings_and_backups_match_the_module() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("server");
let meta = temp.path().join("metadata");
fs::create_dir_all(dir(&root)).unwrap();
fs::create_dir_all(&meta).unwrap();
let cat = catalog();
assert!(!list_in(&cat, &root).iter().find(|m| m.id == "time-is-time").unwrap().installed);
let defaults = "# Keep module documentation\n[worldserver]\nTimeIsTime.Enable = 1\nTimeIsTime.Announce = 1\nTimeIsTime.SpeedRate = 1.0\nTimeIsTime.TimeStart = 0\nTimeIsTime.HourOffset = 0.0\n";
let dist = dir(&root).join("mod-time_is_time.conf.dist");
let active = dir(&root).join("mod-time_is_time.conf");
fs::write(&dist, defaults).unwrap();
let view = list_in(&cat, &root).into_iter().find(|m| m.id == "time-is-time").unwrap();
assert!(view.installed && view.enabled && view.switchable && view.has_settings);
for locale in ["en", "ru", "de", "fr", "es", "zh"] {
assert!(!view.description[locale].is_empty());
}
assert_eq!(settings_in(&cat, &root, "time-is-time").unwrap().len(), 5);
let changes = BTreeMap::from([
("TimeIsTime.SpeedRate".into(), "7.5".into()),
("TimeIsTime.TimeStart".into(), "1213963200".into()),
("TimeIsTime.HourOffset".into(), "5.5".into()),
("TimeIsTime.Announce".into(), "0".into()),
]);
assert_eq!(save_settings_in(&cat, &root, &meta, "time-is-time", &changes).unwrap().len(), 4);
let saved = fs::read(&active).unwrap();
assert!(String::from_utf8_lossy(&saved).contains("# Keep module documentation"));
assert_eq!(fs::read_to_string(&dist).unwrap(), defaults);
assert!(save_settings_in(&cat, &root, &meta, "time-is-time", &changes).unwrap().is_empty());
for (key, value) in [
("TimeIsTime.Enable", "0"), ("TimeIsTime.SpeedRate", "NaN"),
("TimeIsTime.SpeedRate", "-1"), ("TimeIsTime.SpeedRate", "61"),
("TimeIsTime.HourOffset", "inf"), ("TimeIsTime.HourOffset", "25"),
("TimeIsTime.TimeStart", "-1"), ("TimeIsTime.TimeStart", "2147483648"),
("TimeIsTime.TimeStart", "1.5"), ("TimeIsTime.Announce", "2"),
] {
assert!(save_settings_in(&cat, &root, &meta, "time-is-time", &BTreeMap::from([(key.into(), value.into())])).is_err(), "{key}={value}");
assert_eq!(fs::read(&active).unwrap(), saved);
}
set_enabled_in(&cat, &root, &meta, "time-is-time", false).unwrap();
assert_eq!(read(&active).unwrap().get("TimeIsTime.Enable"), Some("0"));
set_enabled_in(&cat, &root, &meta, "time-is-time", true).unwrap();
assert_eq!(read(&active).unwrap().get("TimeIsTime.SpeedRate"), Some("7.5"));
assert!(meta.join("backups").exists());
}
fn test_catalog() -> Vec<Entry> {
let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
id: id.into(),
name: name.into(),
description: ["en", "ru", "de", "fr", "es"]
.iter()
.map(|l| (l.to_string(), format!("{name} ({l})")))
.collect(),
repo: format!("https://github.com/Corfirean/example/{id}"),
conf: conf.into(),
alt_conf: None,
enable_key: key.into(),
switchable: true,
default_on: true,
status: "beta".into(),
icon: String::new(),
page: None,
hidden: false,
};
vec![
one(
"war-games",
"War Games",
"war_games.conf",
"WarGames.Enable",
),
one(
"spellbook",
"Spellbook",
"spellbook.conf",
"Spellbook.Enable",
),
]
}
fn server(d: &Path) -> (PathBuf, PathBuf) {
let (root, meta) = (d.join("srv"), d.join("meta"));
let m = dir(&root);
fs::create_dir_all(&m).unwrap();
fs::create_dir_all(&meta).unwrap();
fs::write(m.join("war_games.conf.dist"), "# Turns War Games on.\r\n# Second line.\r\nWarGames.Enable = 1\r\n\r\n# How long a challenge stays open.\r\nWarGames.ChallengeSeconds = 60\r\n").unwrap();
(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();
let root = d.path();
fs::create_dir_all(dir(root)).unwrap();
fs::write(
dir(root).join("playerbots.conf"),
"AiPlayerbot.Enabled = 0\n",
)
.unwrap();
fs::write(
dir(root).join("playerbots.conf.dist"),
"AiPlayerbot.Enabled = 0\nAiPlayerbot.MinRandomBots = 500\n",
)
.unwrap();
fs::write(dir(root).join("playerbots.conf.settings.json"), r#"{"format":1,"groups":{"population":"Population"},"settings":[{"key":"AiPlayerbot.MinRandomBots","type":"int","group":"population","title":"Minimum bots","description":"Lower bound","default":500,"default_if_missing":50,"min":0,"max":5000}]}"#).unwrap();
let cat = catalog();
let options = settings_in(&cat, root, "playerbots").unwrap();
let option = options
.iter()
.find(|setting| setting.key == "AiPlayerbot.MinRandomBots")
.unwrap();
assert_eq!(option.value, "50");
assert_eq!(option.default.as_deref(), Some("500"));
assert_eq!(
option.field.as_ref().unwrap().group_title.as_deref(),
Some("Population")
);
let before = fs::read(dir(root).join("playerbots.conf")).unwrap();
assert!(save_settings_in(
&cat,
root,
root,
"playerbots",
&BTreeMap::from([("AiPlayerbot.MinRandomBots".into(), "5001".into())])
)
.is_err());
assert_eq!(fs::read(dir(root).join("playerbots.conf")).unwrap(), before);
save_settings_in(
&cat,
root,
root,
"playerbots",
&BTreeMap::from([("AiPlayerbot.MinRandomBots".into(), "42".into())]),
)
.unwrap();
assert_eq!(
settings_in(&cat, root, "playerbots")
.unwrap()
.iter()
.find(|setting| setting.key == "AiPlayerbot.MinRandomBots")
.unwrap()
.value,
"42"
);
}
#[test]
fn dungeon_clear_requires_squid_and_follows_it() {
let d = tempfile::tempdir().unwrap();
let root = d.path();
fs::create_dir_all(dir(root)).unwrap();
fs::write(dir(root).join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
fs::write(dir(root).join("mod_coa_playerbots.conf"), "CoaBots.Enable = 0\n").unwrap();
let dungeon = dir(root).join("mod_dungeon_clear.conf");
fs::write(&dungeon, "DungeonClear.Enable = 0\n").unwrap();
let cat = catalog();
assert!(set_enabled_in(&cat, root, root, "dungeon-clear", true).is_err());
assert!(!list_in(&cat, root).iter().find(|entry| entry.id == "dungeon-clear").unwrap().switchable);
// part of SQUID: on with it, off with it, on again with it
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
set_enabled_in(&cat, root, root, "playerbots", false).unwrap();
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
}
#[test]
fn bot_systems_are_mutually_exclusive_in_both_directions_and_manual_configs() {
let d = tempfile::tempdir().unwrap();
let root = d.path();
fs::create_dir_all(dir(root)).unwrap();
let a = dir(root).join("mod_coa_playerbots.conf");
let b = dir(root).join("playerbots.conf");
fs::write(&a, "CoaBots.Enable = 1\n").unwrap();
fs::write(&b, "AiPlayerbot.Enabled = 0\n").unwrap();
assert!(ensure_bot_exclusivity(root).is_ok());
assert!(matches!(
set_enabled_in(&catalog(), root, root, "playerbots", true),
Err(Error::BotModulesConflict)
));
assert_eq!(fs::read_to_string(&b).unwrap(), "AiPlayerbot.Enabled = 0\n");
fs::write(&a, "CoaBots.Enable = 0\n").unwrap();
set_enabled_in(&catalog(), root, root, "playerbots", true).unwrap();
assert!(matches!(
set_enabled_in(&catalog(), root, root, "companions", true),
Err(Error::BotModulesConflict)
));
fs::write(&a, "CoaBots.Enable = true\n").unwrap();
assert!(matches!(
ensure_bot_exclusivity(root),
Err(Error::BotModulesConflict)
));
fs::write(&b, "# missing key uses the compiled enabled default\n").unwrap();
assert!(matches!(
ensure_bot_exclusivity(root),
Err(Error::BotModulesConflict)
));
set_enabled_in(&catalog(), root, root, "companions", false).unwrap();
assert!(ensure_bot_exclusivity(root).is_ok());
}
#[test]
fn startup_rejects_conflicting_bots_before_launching_any_service() {
let d = tempfile::tempdir().unwrap();
fs::create_dir_all(dir(d.path())).unwrap();
fs::write(
dir(d.path()).join("mod_coa_playerbots.conf"),
"CoaBots.Enable = 1",
)
.unwrap();
fs::write(
dir(d.path()).join("playerbots.conf"),
"AiPlayerbot.Enabled = 1",
)
.unwrap();
for verb in [
crate::driver::Verb::StartAll,
crate::driver::Verb::StartWorld,
] {
assert!(matches!(
crate::driver::run(d.path(), verb),
Err(Error::BotModulesConflict)
));
}
}
#[test]
fn the_bundled_catalog_is_valid() {
let c = catalog();
// it may be empty (modules are added to it one by one); whatever is in it must be complete
for e in &c {
assert!(
["en", "ru", "de", "fr", "es"].iter().all(|locale| e.description.get(*locale).is_some_and(|text| !text.is_empty())),
"{} has the existing catalog languages (additional translations are allowed)",
e.id
);
assert!(
e.repo.starts_with("https://github.com/") && e.conf.ends_with(".conf"),
"{}",
e.id
);
assert!(
!e.switchable
|| (e.enable_key.ends_with(".Enable") || e.enable_key.ends_with(".Enabled")),
"{} needs the setting that switches it",
e.id
);
assert!(
["soon", "early", "beta", "release"].contains(&e.status.as_str()),
"{} has an unknown status",
e.id
);
assert!(
e.status != "soon" || !e.switchable,
"{} is only announced, so it cannot be switched",
e.id
);
}
let mut ids: Vec<_> = c.iter().map(|e| e.id.as_str()).collect();
ids.sort();
ids.dedup();
assert_eq!(ids.len(), c.len(), "ids are unique");
}
#[test]
fn a_module_is_listed_as_installed_with_its_documented_default_until_a_file_exists() {
let d = tempfile::tempdir().unwrap();
let (root, _) = server(d.path());
let wg = list_in(&test_catalog(), &root)
.into_iter()
.find(|m| m.id == "war-games")
.unwrap();
assert!(wg.installed && wg.enabled, "the .dist says 1");
assert!(
!list_in(&test_catalog(), &root)
.into_iter()
.find(|m| m.id == "spellbook")
.unwrap()
.installed,
"no configuration of that module on this server"
);
}
#[test]
fn switching_a_module_creates_its_file_saves_the_old_one_and_changes_only_that_line() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
set_enabled_in(&test_catalog(), &root, &meta, "war-games", false).unwrap();
let conf = fs::read_to_string(dir(&root).join("war_games.conf")).unwrap();
assert!(
conf.contains("WarGames.Enable = 0") && conf.contains("WarGames.ChallengeSeconds = 60"),
"{conf}"
);
assert!(
!list_in(&test_catalog(), &root)
.into_iter()
.find(|m| m.id == "war-games")
.unwrap()
.enabled
);
set_enabled_in(&test_catalog(), &root, &meta, "war-games", false).unwrap();
assert_eq!(
fs::read_dir(meta.join("backups/modules")).unwrap().count(),
1,
"no change, no backup"
);
set_enabled_in(&test_catalog(), &root, &meta, "war-games", true).unwrap();
assert!(fs::read_to_string(dir(&root).join("war_games.conf"))
.unwrap()
.contains("WarGames.Enable = 1"));
assert!(
set_enabled_in(&test_catalog(), &root, &meta, "spellbook", true).is_err(),
"not part of this server"
);
assert!(set_enabled_in(&test_catalog(), &root, &meta, "nonsense", true).is_err());
}
#[test]
fn settings_show_the_documentation_and_only_known_keys_with_one_line_values_can_be_saved() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let s = settings_in(&test_catalog(), &root, "war-games").unwrap();
assert_eq!(s.len(), 2);
assert_eq!(
s[1],
Setting {
key: "WarGames.ChallengeSeconds".into(),
value: "60".into(),
default: Some("60".into()),
doc: "How long a challenge stays open.".into(),
field: None
}
);
assert_eq!(s[0].doc, "Turns War Games on. Second line.");
let ok = BTreeMap::from([("WarGames.ChallengeSeconds".to_string(), "90".to_string())]);
assert_eq!(
save_settings_in(&test_catalog(), &root, &meta, "war-games", &ok).unwrap(),
["WarGames.ChallengeSeconds"]
);
assert!(settings_in(&test_catalog(), &root, "war-games").unwrap()[1].value == "90");
assert!(
save_settings_in(&test_catalog(), &root, &meta, "war-games", &ok)
.unwrap()
.is_empty(),
"same value: nothing to do"
);
for bad in [
("Other.Key", "1"),
("WarGames.ChallengeSeconds", ""),
("WarGames.ChallengeSeconds", "1\nInjected = 1"),
] {
let c = BTreeMap::from([(bad.0.to_string(), bad.1.to_string())]);
assert!(
save_settings_in(&test_catalog(), &root, &meta, "war-games", &c).is_err(),
"{bad:?}"
);
}
assert!(!fs::read_to_string(dir(&root).join("war_games.conf"))
.unwrap()
.contains("Injected"));
}
#[test]
fn updated_module_defaults_are_visible_and_can_be_saved_in_an_existing_config() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(dir(&root).join("war_games.conf"), "WarGames.Enable = 0\n").unwrap();
let cat = test_catalog();
let values = settings_in(&cat, &root, "war-games").unwrap();
assert_eq!(
values
.iter()
.find(|s| s.key == "WarGames.Enable")
.unwrap()
.value,
"0"
);
assert_eq!(
values
.iter()
.find(|s| s.key == "WarGames.ChallengeSeconds")
.unwrap()
.value,
"60"
);
let changes = BTreeMap::from([("WarGames.ChallengeSeconds".to_string(), "90".to_string())]);
save_settings_in(&cat, &root, &meta, "war-games", &changes).unwrap();
let text = fs::read_to_string(dir(&root).join("war_games.conf")).unwrap();
assert!(
text.contains("WarGames.Enable = 0") && text.contains("WarGames.ChallengeSeconds = 90")
);
}
#[test]
fn module_enable_cannot_be_changed_through_the_settings_editor() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let changes = BTreeMap::from([("WarGames.Enable".into(), "0".into())]);
assert!(save_settings_in(&test_catalog(), &root, &meta, "war-games", &changes).is_err());
assert_eq!(
settings_in(&test_catalog(), &root, "war-games").unwrap()[0].value,
"1"
);
}
#[test]
fn settings_button_requires_more_than_the_master_switch() {
let d = tempfile::tempdir().unwrap();
let (root, _) = server(d.path());
let cat = test_catalog();
assert!(
list_in(&cat, &root)
.iter()
.find(|m| m.id == "war-games")
.unwrap()
.has_settings
);
fs::write(
dir(&root).join("war_games.conf.dist"),
"WarGames.Enable = 1\n",
)
.unwrap();
assert!(
!list_in(&cat, &root)
.iter()
.find(|m| m.id == "war-games")
.unwrap()
.has_settings
);
fs::write(
dir(&root).join("war_games.conf"),
"WarGames.Enable = 0\nWarGames.ChallengeSeconds = 90\n",
)
.unwrap();
assert!(
list_in(&cat, &root)
.iter()
.find(|m| m.id == "war-games")
.unwrap()
.has_settings,
"custom active settings remain editable"
);
}
#[test]
fn documented_empty_lists_can_be_restored() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(
dir(&root).join("war_games.conf.dist"),
"WarGames.Enable = 1\nWarGames.ExcludedItems = \n",
)
.unwrap();
fs::write(
dir(&root).join("war_games.conf"),
"WarGames.Enable = 1\nWarGames.ExcludedItems = 42\n",
)
.unwrap();
let changes = BTreeMap::from([("WarGames.ExcludedItems".into(), "".into())]);
save_settings_in(&test_catalog(), &root, &meta, "war-games", &changes).unwrap();
assert_eq!(
settings_in(&test_catalog(), &root, "war-games")
.unwrap()
.iter()
.find(|s| s.key == "WarGames.ExcludedItems")
.unwrap()
.value,
""
);
}
#[test]
fn auction_type_weights_are_validated_before_any_setting_is_written() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let cat = catalog();
let key = "AuctionHouseBot.ListProportion.CategoryWeapon.QualityNormal";
let conf = dir(&root).join("mod_ahbot.conf");
fs::write(
&conf,
format!(
"AuctionHouseBot.Enable = true\nAuctionHouseBot.ItemsPerCycle = 150\n{key} = 20\n"
),
)
.unwrap();
let original = fs::read(&conf).unwrap();
for bad in ["-1", "1.5", "NaN", "1001", "", "4294967296"] {
let changes = BTreeMap::from([
("AuctionHouseBot.ItemsPerCycle".into(), "25".into()),
(key.into(), bad.into()),
]);
assert!(
save_settings_in(&cat, &root, &meta, "ah-bot", &changes).is_err(),
"{bad}"
);
assert_eq!(
fs::read(&conf).unwrap(),
original,
"no partial save for {bad}"
);
}
let off = BTreeMap::from([(key.into(), "0".into())]);
save_settings_in(&cat, &root, &meta, "ah-bot", &off).unwrap();
assert_eq!(
settings_in(&cat, &root, "ah-bot")
.unwrap()
.iter()
.find(|s| s.key == key)
.unwrap()
.value,
"0"
);
}
#[test]
fn partial_lfg_and_world_leech_settings_round_trip_and_reject_invalid_values() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let cat = catalog();
let conf = dir(&root).join("mod-coa-content-scaling.conf.dist");
let partial = "CoAContentScaling.LFG.AllowPartialGroups";
let enable = "CoAContentScaling.World.Leech.Enable";
let percent = "CoAContentScaling.World.Leech.Percent";
let change = |k: &str, v: &str| BTreeMap::from([(k.into(), v.into())]);
fs::write(&conf, "CoAContentScaling.Enable = 1\n").unwrap();
for key in [partial, enable, percent] {
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &change(key, "1")).is_err()
);
}
fs::write(
&conf,
format!("CoAContentScaling.Enable = 1\n{partial} = 1\n{enable} = 0\n{percent} = 5.0\n"),
)
.unwrap();
for bad in ["NaN", "inf", "-0.1", "100.1", "abc"] {
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &change(percent, bad))
.is_err()
);
}
for key in [partial, enable] {
for bad in ["2", "-1", "true", "abc"] {
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &change(key, bad))
.is_err()
);
}
for good in ["0", "1"] {
save_settings_in(&cat, &root, &meta, "content-scaling", &change(key, good))
.unwrap();
}
}
for good in ["0", "10.5", "100"] {
save_settings_in(
&cat,
&root,
&meta,
"content-scaling",
&change(percent, good),
)
.unwrap();
let settings = settings_in(&cat, &root, "content-scaling").unwrap();
assert_eq!(
settings.iter().find(|s| s.key == percent).unwrap().value,
good
);
}
}
#[test]
fn damage_difficulty_is_validated_and_older_server_builds_do_not_accept_it() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let cat = catalog();
let conf = dir(&root).join("mod-coa-content-scaling.conf.dist");
fs::write(&conf, "CoAContentScaling.Enable = 1\n").unwrap();
let key = "CoAContentScaling.Difficulty.DamageMultiplier";
let changes = |v: &str| BTreeMap::from([(key.into(), v.into())]);
assert!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes("0.5")).is_err());
fs::write(
&conf,
format!("CoAContentScaling.Enable = 1\n{key} = 1.0\n"),
)
.unwrap();
for bad in ["NaN", "inf", "0", "0.24", "2.01", "abc"] {
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(),
"{bad}"
);
}
assert_eq!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes("0.25")).unwrap(),
[key]
);
assert_eq!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes("2")).unwrap(),
[key]
);
assert_eq!(
settings_in(&cat, &root, "content-scaling")
.unwrap()
.iter()
.find(|s| s.key == key)
.unwrap()
.value,
"2"
);
}
#[test]
fn creature_health_multipliers_are_validated_per_key() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let cat = catalog();
let conf = dir(&root).join("mod-coa-content-scaling.conf.dist");
let keys = [
"CoAContentScaling.Difficulty.Health.WorldMultiplier",
"CoAContentScaling.Difficulty.Health.DungeonMultiplier",
"CoAContentScaling.Difficulty.Health.RaidMultiplier",
"CoAContentScaling.Difficulty.Health.TrashMultiplier",
"CoAContentScaling.Difficulty.Health.BossMultiplier",
];
let mut text = String::from("CoAContentScaling.Enable = 1\n");
for key in keys {
text.push_str(&format!("{key} = 1.0\n"));
}
fs::write(&conf, text).unwrap();
for key in keys {
let changes = |v: &str| BTreeMap::from([(key.to_string(), v.to_string())]);
for bad in ["NaN", "inf", "0", "0.09", "10.01", "-1", "abc", ""] {
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(),
"{key} {bad}"
);
}
for good in ["0.1", "0.4", "1", "2.5", "10"] {
assert_eq!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good))
.unwrap(),
[key]
);
assert_eq!(
settings_in(&cat, &root, "content-scaling")
.unwrap()
.iter()
.find(|s| s.key == key)
.unwrap()
.value,
good
);
}
}
}
#[test]
fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on(
) {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(
dir(&root).join("old_name.conf"),
"CoA.Enable = 0\r\nCoA.UnlockAllVanity = 1\r\n",
)
.unwrap();
let compat = Entry {
id: "compat".into(),
name: "Compat".into(),
description: ["en", "ru", "de", "fr", "es"]
.iter()
.map(|l| (l.to_string(), "x".to_string()))
.collect(),
repo: "https://github.com/Corfirean/x".into(),
conf: "coa.conf".into(),
alt_conf: Some("old_name.conf".into()),
enable_key: String::new(),
switchable: false,
default_on: true,
status: "release".into(),
icon: String::new(),
page: None,
hidden: false,
};
let cat = vec![compat];
let v = list_in(&cat, &root).remove(0);
assert!(
v.installed && v.enabled && !v.switchable,
"found under the old name, never reported as off"
);
assert_eq!(settings_in(&cat, &root, "compat").unwrap().len(), 2);
let change = BTreeMap::from([("CoA.UnlockAllVanity".to_string(), "0".to_string())]);
assert_eq!(
save_settings_in(&cat, &root, &meta, "compat", &change).unwrap(),
["CoA.UnlockAllVanity"]
);
assert!(fs::read_to_string(dir(&root).join("old_name.conf"))
.unwrap()
.contains("CoA.UnlockAllVanity = 0"));
assert!(
set_enabled_in(&cat, &root, &meta, "compat", false).is_err(),
"cannot be switched off"
);
}
#[test]
fn a_module_whose_setting_is_not_in_the_file_counts_as_on_and_can_be_switched_off() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(
dir(&root).join("war_games.conf"),
"WarGames.ChallengeSeconds = 60\r\n",
)
.unwrap();
let cat = test_catalog();
assert!(
list_in(&cat, &root)
.into_iter()
.find(|m| m.id == "war-games")
.unwrap()
.enabled,
"a missing key means the default (on)"
);
set_enabled_in(&cat, &root, &meta, "war-games", false).unwrap();
assert!(fs::read_to_string(dir(&root).join("war_games.conf"))
.unwrap()
.contains("WarGames.Enable = 0"));
assert!(
!list_in(&cat, &root)
.into_iter()
.find(|m| m.id == "war-games")
.unwrap()
.enabled
);
}
#[test]
fn custom_races_bot_settings_synchronize_playerbots_conf() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let cat = catalog();
fs::write(
dir(&root).join("coa_custom_races.conf.dist"),
"CoACustomRaces.Enable = 1\nCoACustomRaces.BotsEnable = 0\n",
)
.unwrap();
fs::write(
dir(&root).join("coa_custom_races.conf"),
"CoACustomRaces.Enable = 1\nCoACustomRaces.BotsEnable = 0\n",
)
.unwrap();
fs::write(
dir(&root).join("playerbots.conf"),
"AiPlayerbot.Enabled = 1\n",
)
.unwrap();
// 1. Initially CoACustomRaces.BotsEnable is 0
let s = settings_in(&cat, &root, "custom-races").unwrap();
assert_eq!(
s.iter()
.find(|s| s.key == "CoACustomRaces.BotsEnable")
.unwrap()
.value,
"0"
);
// 2. Enable bots for custom races: should write experimental exclusions to playerbots.conf
let change_on = BTreeMap::from([("CoACustomRaces.BotsEnable".into(), "1".into())]);
assert_eq!(
save_settings_in(&cat, &root, &meta, "custom-races", &change_on).unwrap(),
["CoACustomRaces.BotsEnable"]
);
let pb = fs::read_to_string(dir(&root).join("playerbots.conf")).unwrap();
assert!(pb.contains("AiPlayerbot.ExcludedBotRaces"));
assert!(pb.contains(crate::custom_races::EXCLUDED_BOT_RACES_EXPERIMENTAL));
// Settings view now sees "1"
let s = settings_in(&cat, &root, "custom-races").unwrap();
assert_eq!(
s.iter()
.find(|s| s.key == "CoACustomRaces.BotsEnable")
.unwrap()
.value,
"1"
);
// 3. Disable bots for custom races: should write recommended exclusions to playerbots.conf
let change_off = BTreeMap::from([("CoACustomRaces.BotsEnable".into(), "0".into())]);
assert_eq!(
save_settings_in(&cat, &root, &meta, "custom-races", &change_off).unwrap(),
["CoACustomRaces.BotsEnable"]
);
let pb = fs::read_to_string(dir(&root).join("playerbots.conf")).unwrap();
assert!(pb.contains(crate::custom_races::EXCLUDED_BOT_RACES_RECOMMENDED));
// Settings view now sees "0"
let s = settings_in(&cat, &root, "custom-races").unwrap();
assert_eq!(
s.iter()
.find(|s| s.key == "CoACustomRaces.BotsEnable")
.unwrap()
.value,
"0"
);
}
#[test]
fn dynamic_plugin_settings_and_enable_roundtrip() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(
dir(&root).join("npc_buffer.conf.dist"),
"# Enable NPC Buffer\nNpcBuffer.Enable = 1\n# Cost of buff\nNpcBuffer.Cost = 500\n",
)
.unwrap();
let cat = catalog();
let s = settings_in(&cat, &root, "npc-buffer").unwrap();
assert_eq!(s.len(), 2);
let cost = s.iter().find(|item| item.key == "NpcBuffer.Cost").unwrap();
assert_eq!(cost.value, "500");
assert_eq!(cost.doc, "Cost of buff");
let change = BTreeMap::from([("NpcBuffer.Cost".to_string(), "1000".to_string())]);
let saved = save_settings_in(&cat, &root, &meta, "npc-buffer", &change).unwrap();
assert_eq!(saved, ["NpcBuffer.Cost"]);
let conf_content = fs::read_to_string(dir(&root).join("npc_buffer.conf")).unwrap();
assert!(conf_content.contains("NpcBuffer.Cost = 1000"));
set_enabled_in(&cat, &root, &meta, "npc-buffer", false).unwrap();
let conf_content = fs::read_to_string(dir(&root).join("npc_buffer.conf")).unwrap();
assert!(conf_content.contains("NpcBuffer.Enable = 0"));
}
}