Compare commits

...
Author SHA1 Message Date
ДмитрийandClaude Sonnet 5.5 8e1eb825df fix: clearer listing states, joining options chosen before publishing
Portable characters are on by default in a new listing; account creation and
portable characters are shown in the publish form (and in publish all) and
saved right after the realm is published.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:22:51 +05:00
ДмитрийandClaude Sonnet 5.5 4fcf0dde3f fix: changelog fragment without a byte order mark
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:54 +05:00
ДмитрийandClaude Sonnet 5.5 e4791fc45c feat: public listing as a realm list with a window, a publish-all button and a chip on each realm card
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:35 +05:00
ДмитрийandClaude Sonnet 5.5 af82963f35 feat: open firewall ports for every running world and list every realm publicly
- Starting a server that is open to friends adds the firewall rules for the
  world ports of all realms that start together (only missing ones; a refused
  Windows prompt does not undo the start).
- Settings shows one public-listing block per realm that starts together. The
  main realm keeps its plain local id, so an existing listing is untouched.
- A realm that runs as an extra world is reached through that world's own
  console port, so its listing reports its own state and capabilities.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 15:29:09 +05:00
ДмитрийandClaude Sonnet 5.5 321ac597ce feat: start Wildcard and Warcraft Reborn together with Conquest of Azeroth
Settings gets two options, one per extra realm; turning on both runs all
three realms. Each extra world keeps its own folder, configs, logs and
ports (multiworld now handles a set of worlds instead of one second world),
and Warcraft Reborn gets its own status card, realm list entry and firewall
rule.

Starting a server also sets CoA.ClassModel of the realm chosen on Overview
to exactly that realm's model, so the shipped "coa wcr" default no longer
shows two class models on a Conquest of Azeroth realm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:09:14 +05:00
Corfirean 925a81f4f2 Merge pull request #164 from Corfirean/feat/custom-races-report-target
Add Custom Races and Content Scaling report destinations
2026-10-27 11:02:46 +05:00
Corfirean df1901ea90 Merge pull request #163 from Corfirean/fix/issue-153-skill-controls
Add profession and defense skill gain controls
2026-10-27 10:28:06 +05:00
Corfirean 569d5fffc4 Merge pull request #162 from Corfirean/fix/issue-158-persistent-lan
Restore LAN realm addresses in Internet sharing mode
2026-10-27 10:28:02 +05:00
Дмитрий 7888dbc763 feat(reports): add separate Content Scaling destination 2026-10-27 10:25:10 +05:00
Дмитрий f0e8a8c12f feat(reports): add Custom Races upstream destination 2026-10-27 09:13:34 +05:00
Дмитрий af5a9717d4 feat(config): expose profession and defense skill gains (#153) 2026-10-27 08:38:08 +05:00
47 changed files with 1320 additions and 287 deletions

No files matched your search

@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Report Content Scaling problems directly to its repository
---
The report form now includes a separate Content Scaling destination.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Send custom race problem reports directly to their maintainer
---
The report form now includes Custom Races as a separate destination.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Public listing offers every realm that starts together, not just the main one
---
With Wildcard or Warcraft Reborn started next to Conquest of Azeroth, Settings now has one listing block per realm, each with its own name, description and access options.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Public listing is a short list of realms with a window for the details
---
Settings shows one line per realm with its state, and publishing opens a window. Publish all realms at once. Account creation and portable characters are chosen before publishing; portable characters are on by default.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Configure profession and defense skill gains in server settings
---
Advanced rate settings now include prospecting and milling skill gains, plus the points gained from crafting, defense and gathering.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Starting a server sets the character classes of the realm chosen on Overview
---
A new Conquest of Azeroth server could show two class models, or none, on the character creation screen. The Manager now sets the model of the chosen realm before every start.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Start Wildcard and Warcraft Reborn together with Conquest of Azeroth
---
Settings now has two options, one for Wildcard and one for Warcraft Reborn. Turn on either one, or both to run all three realms at once, each with its own characters and port.
+25
View File
@@ -1034,6 +1034,31 @@ Spellbook.New = 5
assert!(v.drift_keys.is_empty());
}
#[test]
fn skill_controls_persist_and_reject_invalid_gains() {
let (_d, root, meta) = fixture();
let changes = BTreeMap::from([
("SkillChance.Prospecting".into(), json!(true)),
("SkillChance.Milling".into(), json!(true)),
("SkillGain.Crafting".into(), json!(3)),
("SkillGain.Defense".into(), json!(4)),
("SkillGain.Gathering".into(), json!(5)),
]);
let report = save(&root, &meta, Scope::Server, &changes).unwrap();
assert_eq!(report.changed.len(), 5);
assert_eq!(report.restart, Some(Restart::World));
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
let conf = load_conf(&root.join(path)).unwrap();
for (key, expected) in [("SkillChance.Prospecting", "1"), ("SkillChance.Milling", "1"), ("SkillGain.Crafting", "3"), ("SkillGain.Defense", "4"), ("SkillGain.Gathering", "5")] {
assert_eq!(conf.get(key), Some(expected));
}
assert_eq!(conf.get("Unknown.Custom"), Some("\"keep me\""));
}
for value in [json!(-1), json!(1.5), json!(451)] {
assert!(save(&root, &meta, Scope::Server, &BTreeMap::from([("SkillGain.Crafting".into(), value)])).is_err());
}
}
#[test]
fn creature_rates_save_independently_in_template_and_active_config() {
let (_d, root, meta) = fixture();
+4
View File
@@ -96,6 +96,9 @@ pub fn run(root: &Path, meta: &InstallMeta) -> Report {
if let Some(second) = &o.secondary_world {
services.push(("Second world", second));
}
if let Some(reborn) = &o.reborn_world {
services.push(("Warcraft Reborn world", reborn));
}
for (title, s) in services {
let (lvl, text) = match (s.state, &s.conflict) {
(ServiceState::Running, _) => (Level::Ok, "Running".to_string()),
@@ -639,6 +642,7 @@ fn processes_report(root: &Path, ports: &layout::Ports) -> String {
Some(&o.auth),
Some(&o.world),
o.secondary_world.as_ref(),
o.reborn_world.as_ref(),
]
.into_iter()
.flatten()
+3
View File
@@ -758,6 +758,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
auth: unknown("auth", ports.auth),
world: unknown("world", ports.world),
secondary_world: None,
reborn_world: None,
};
};
let n = cfg.names();
@@ -767,6 +768,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
auth: unknown("auth", ports.auth),
world: unknown("world", ports.world),
secondary_world: None,
reborn_world: None,
};
};
let ip = connect_ip(&cfg);
@@ -795,6 +797,7 @@ pub fn observe_with(d: &dyn Docker, root: &Path, ports: &Ports) -> Observed {
listening(state.get(&n.world), ports.world),
),
secondary_world: None,
reborn_world: None,
}
}
+1 -1
View File
@@ -254,7 +254,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverO
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
for service in [&observed.mysql, &observed.auth, &observed.world]
.into_iter()
.chain(observed.secondary_world.iter())
.chain(observed.extra_worlds())
{
if let Some(conflict) = &service.conflict {
output.push_str(&format!(
+10 -6
View File
@@ -88,23 +88,27 @@ fn run_elevated(commands: &[String]) -> Result<()> {
/// Make sure both rules exist (adds only the missing ones) and confirm afterwards.
pub fn ensure_rules(ports: &Ports) -> Result<Status> {
ensure_rules_with_secondary(ports, None)
ensure_rules_with_extra(ports, &[])
}
pub fn ensure_rules_with_secondary(ports: &Ports, secondary: Option<u16>) -> Result<Status> {
/// As `ensure_rules`, plus one rule for the world port of each extra realm that runs next to the main one.
pub fn ensure_rules_with_extra(ports: &Ports, extra: &[u16]) -> Result<Status> {
let have = status();
let mut cmds = plan(ports, &have);
let second_name = secondary.map(|port| format!("CoA Server Manager - Second World {port}"));
if let (Some(port), Some(name)) = (secondary, &second_name) {
let extra_names: Vec<String> = extra
.iter()
.map(|port| format!("CoA Server Manager - Second World {port}"))
.collect();
for (port, name) in extra.iter().zip(&extra_names) {
if !rule_exists(name) {
cmds.push(add_cmd(name, port));
cmds.push(add_cmd(name, *port));
}
}
if !cmds.is_empty() {
run_elevated(&cmds)?;
}
let now = status();
if now.auth && now.world && second_name.as_ref().is_none_or(|name| rule_exists(name)) {
if now.auth && now.world && extra_names.iter().all(|name| rule_exists(name)) {
Ok(now)
} else {
Err(Error::Invalid(
+10 -6
View File
@@ -210,12 +210,16 @@ pub fn apply_realm_address(root: &Path, settings: &Settings) -> Result<()> {
Mode::Private => None,
};
let db = Db::from_repack(root, Account::Admin)?;
let realm = crate::realms::state(root)?.active.realm_id();
let where_realms = if crate::realms::state(root)?.simultaneous {
"id IN (1,2)".into()
} else {
format!("id={realm}")
};
let state = crate::realms::state(root)?;
let mut ids = vec![state.active];
ids.extend(state.extra_modes());
let where_realms = format!(
"id IN ({})",
ids.iter()
.map(|m| m.realm_id().to_string())
.collect::<Vec<_>>()
.join(",")
);
db.query(&realm_address_sql(host, local, &where_realms)?)?;
Ok(())
}
+253 -60
View File
@@ -12,12 +12,66 @@ use std::{
path::{Path, PathBuf},
};
pub fn root(main: &Path) -> PathBuf {
main.join(".realms/secondary")
/// A world that runs next to the primary one. Each has its own folder, configs, logs and ports; auth and MySQL stay shared.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tree {
/// Wildcard next to Conquest of Azeroth (or Conquest of Azeroth next to Wildcard when Wildcard is the primary).
Second,
/// Warcraft Reborn next to Conquest of Azeroth.
Reborn,
}
pub fn is_running(main: &Path) -> bool {
let second = root(main);
impl Tree {
pub const ALL: [Tree; 2] = [Tree::Second, Tree::Reborn];
fn dir(self) -> &'static str {
match self {
Tree::Second => ".realms/secondary",
Tree::Reborn => ".realms/reborn",
}
}
fn label(self) -> &'static str {
match self {
Tree::Second => "second realm",
Tree::Reborn => "Warcraft Reborn realm",
}
}
fn mode(self, active: Mode) -> Mode {
match self {
Tree::Second if active == Mode::Coa => Mode::Wildcard,
Tree::Second => Mode::Coa,
Tree::Reborn => Mode::Reborn,
}
}
fn enabled(self, s: &RealmState) -> bool {
match self {
Tree::Second => s.simultaneous,
Tree::Reborn => s.with_reborn,
}
}
fn ports(self, s: &RealmState) -> (Option<u16>, Option<u16>) {
match self {
Tree::Second => (s.secondary_world_port, s.secondary_ra_port),
Tree::Reborn => (s.reborn_world_port, s.reborn_ra_port),
}
}
}
pub fn tree_root(main: &Path, tree: Tree) -> PathBuf {
main.join(tree.dir())
}
/// The folder of the second realm (Wildcard next to Conquest of Azeroth).
pub fn root(main: &Path) -> PathBuf {
tree_root(main, Tree::Second)
}
pub fn tree_running(main: &Path, tree: Tree) -> bool {
let second = tree_root(main, tree);
if !second.exists() {
return false;
}
@@ -28,6 +82,26 @@ pub fn is_running(main: &Path) -> bool {
.any(|n| process::read_state_record(&second, n).is_some_and(|p| process::is_alive(&p)))
}
/// The folder whose world server runs `mode`: the main folder, or the folder of the extra world that runs that realm.
/// Its settings hold the console port that belongs to that world.
pub fn world_root(main: &Path, mode: Mode) -> PathBuf {
let Ok(s) = realms::state(main) else {
return main.to_path_buf();
};
if mode == s.active {
return main.to_path_buf();
}
Tree::ALL
.into_iter()
.find(|t| t.enabled(&s) && t.mode(s.active) == mode)
.map_or_else(|| main.to_path_buf(), |t| tree_root(main, t))
}
/// Any of the extra worlds is running or still stopping.
pub fn is_running(main: &Path) -> bool {
Tree::ALL.into_iter().any(|t| tree_running(main, t))
}
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
fs::create_dir_all(to)?;
for entry in fs::read_dir(from)? {
@@ -55,23 +129,52 @@ fn copy_tree(from: &Path, to: &Path) -> Result<()> {
Ok(())
}
/// Start Wildcard together with Conquest of Azeroth.
pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
set_tree(main, Tree::Second, enabled)
}
/// Start Warcraft Reborn together with Conquest of Azeroth.
pub fn set_reborn_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
set_tree(main, Tree::Reborn, enabled)
}
fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result<realms::View> {
if enabled && !cfg!(windows) {
return Err(Error::Invalid(
"Simultaneous realms currently require Windows.".into(),
));
}
if enabled {
if realms::state(main)?.active == Mode::Reborn {
return Err(Error::Invalid(
"Simultaneous startup supports CoA and Wildcard. Select one of these realms first."
.into(),
));
}
if !realms::view(main)?.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
let active = realms::state(main)?.active;
let view = realms::view(main)?;
match tree {
Tree::Second => {
if active == Mode::Reborn {
return Err(Error::Invalid(
"Wildcard starts together with Conquest of Azeroth. Select Conquest of Azeroth first."
.into(),
));
}
if !view.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
}
}
Tree::Reborn => {
if active != Mode::Coa {
return Err(Error::Invalid(
"Warcraft Reborn starts together with Conquest of Azeroth. Select Conquest of Azeroth first."
.into(),
));
}
if !view.reborn_supported {
return Err(Error::Invalid(
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
}
}
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
}
@@ -81,20 +184,21 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
|| is_running(main)
{
return Err(Error::Invalid(
"Stop both realms before changing simultaneous startup.".into(),
"Stop all realms before changing which realms start together.".into(),
));
}
let original = realms::state(main)?.active;
if enabled && !realms::state(main)?.wildcard_created {
realms::select(main, Mode::Wildcard)?;
if original != Mode::Wildcard {
realms::select(main, original)?;
}
if enabled {
realms::ensure_created(main, tree.mode(realms::state(main)?.active))?;
}
let mut s = realms::state(main)?;
if enabled {
let p = crate::layout::read_ports(main);
let mut reserved = vec![p.mysql, p.auth, p.world, p.ra];
// Ports already saved for any other extra world stay reserved, so two worlds never get the same one.
for other in Tree::ALL.into_iter().filter(|t| *t != tree) {
let (world, ra) = other.ports(&s);
reserved.extend(world.into_iter().chain(ra));
}
let mut choose = |saved: Option<u16>, near: u16| -> Result<u16> {
if let Some(port) = saved.filter(|p| *p > 0 && !reserved.contains(p)) {
reserved.push(port);
@@ -104,31 +208,41 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
.find(|p| {
!reserved.contains(p) && std::net::TcpListener::bind(("127.0.0.1", *p)).is_ok()
})
.ok_or_else(|| Error::Invalid("No free port for the second realm.".into()))?;
.ok_or_else(|| Error::Invalid(format!("No free port for the {}.", tree.label())))?;
reserved.push(port);
Ok(port)
};
s.secondary_world_port = Some(choose(s.secondary_world_port, p.world)?);
s.secondary_ra_port = Some(choose(s.secondary_ra_port, p.ra)?);
let (world, ra) = tree.ports(&s);
let (world, ra) = (choose(world, p.world)?, choose(ra, p.ra)?);
match tree {
Tree::Second => {
s.secondary_world_port = Some(world);
s.secondary_ra_port = Some(ra);
}
Tree::Reborn => {
s.reborn_world_port = Some(world);
s.reborn_ra_port = Some(ra);
}
}
}
match tree {
Tree::Second => s.simultaneous = enabled,
Tree::Reborn => s.with_reborn = enabled,
}
s.simultaneous = enabled;
fsx::atomic_write_json(&main.join("Settings/realm-profile.json"), &s)?;
realms::view(main)
}
fn prepare(main: &Path) -> Result<PathBuf> {
if is_running(main) {
return Err(Error::Invalid(
"The second realm is still running; stop it before preparing its files.".into(),
));
fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
if tree_running(main, tree) {
return Err(Error::Invalid(format!(
"The {} is still running; stop it before preparing its files.",
tree.label()
)));
}
let s = realms::state(main)?;
let mode = if s.active == Mode::Coa {
Mode::Wildcard
} else {
Mode::Coa
};
let second = fsx::ensure_within(main, &root(main))?;
let mode = tree.mode(s.active);
let second = fsx::ensure_within(main, &tree_root(main, tree))?;
for folder in ["Runtime", "BugReport", "mysql/bin"] {
copy_tree(
&main.join(folder),
@@ -214,13 +328,12 @@ fn prepare(main: &Path) -> Result<PathBuf> {
)?;
}
let mut cfg: serde_json::Value = fsx::read_json(&main.join("Settings/repack.json"))?;
cfg["worldPort"] = s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm world port is missing.".into()))?
let (world_port, ra_port) = tree.ports(&s);
cfg["worldPort"] = world_port
.ok_or_else(|| Error::Invalid(format!("The {} world port is missing.", tree.label())))?
.into();
cfg["raPort"] = s
.secondary_ra_port
.ok_or_else(|| Error::Invalid("Second realm console port is missing.".into()))?
cfg["raPort"] = ra_port
.ok_or_else(|| Error::Invalid(format!("The {} console port is missing.", tree.label())))?
.into();
fsx::atomic_write_json(&second.join("Settings/repack.json"), &cfg)?;
fsx::atomic_write(
@@ -232,6 +345,7 @@ fn prepare(main: &Path) -> Result<PathBuf> {
&RealmState {
active: mode,
wildcard_created: true,
reborn_created: true,
..Default::default()
},
)?;
@@ -256,12 +370,9 @@ fn secondary_launcher(source: &str) -> Result<String> {
))
}
pub fn start(main: &Path) -> Result<()> {
if !realms::state(main)?.simultaneous {
return Ok(());
}
if is_running(main) {
let second = root(main);
fn start_tree(main: &Path, tree: Tree) -> Result<()> {
if tree_running(main, tree) {
let second = tree_root(main, tree);
if process::observe(&second, &crate::layout::read_ports(&second))
.world
.state
@@ -269,35 +380,50 @@ pub fn start(main: &Path) -> Result<()> {
{
return Ok(());
}
return Err(Error::Invalid(
"The second realm is still starting or stopping.".into(),
));
return Err(Error::Invalid(format!(
"The {} is still starting or stopping.",
tree.label()
)));
}
let second = prepare(main)?;
let second = prepare(main, tree)?;
let out = driver::run(&second, Verb::StartWorld)?;
if !out.ok {
return Err(Error::Invalid(format!(
"The second realm did not start: {}",
"The {} did not start: {}",
tree.label(),
out.output
)));
}
Ok(())
}
pub fn stop(main: &Path) -> Result<()> {
let second = root(main);
/// Start every extra world that is switched on.
pub fn start(main: &Path) -> Result<()> {
let s = realms::state(main)?;
for tree in Tree::ALL.into_iter().filter(|t| t.enabled(&s)) {
start_tree(main, tree)?;
}
Ok(())
}
fn stop_tree(main: &Path, tree: Tree) -> Result<()> {
let second = tree_root(main, tree);
if !second.join("Scripts/manage.py").exists() {
if is_running(main) {
return Err(Error::Invalid("The running second realm's launcher is missing. The shared database was left running.".into()));
if tree_running(main, tree) {
return Err(Error::Invalid(format!(
"The running {}'s launcher is missing. The shared database was left running.",
tree.label()
)));
}
return Ok(());
}
// Its state has no auth/MySQL records: the shared database remains up until the primary world stops.
if is_running(main) {
if tree_running(main, tree) {
let out = driver::run(&second, Verb::StopAll)?;
if !out.ok || is_running(main) {
if !out.ok || tree_running(main, tree) {
return Err(Error::Invalid(format!(
"The second realm could not stop; the database was left running: {}",
"The {} could not stop; the database was left running: {}",
tree.label(),
out.output
)));
}
@@ -305,9 +431,76 @@ pub fn stop(main: &Path) -> Result<()> {
Ok(())
}
/// Stop every extra world; one that fails does not keep the others running.
pub fn stop(main: &Path) -> Result<()> {
let mut first = None;
for tree in Tree::ALL {
if let Err(e) = stop_tree(main, tree) {
first.get_or_insert(e);
}
}
first.map_or(Ok(()), Err)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_extra_world_has_its_own_folder_realm_and_ports() {
let mut s = RealmState::default();
assert_eq!(Tree::Second.mode(Mode::Coa), Mode::Wildcard);
assert_eq!(Tree::Second.mode(Mode::Wildcard), Mode::Coa);
assert_eq!(Tree::Reborn.mode(Mode::Coa), Mode::Reborn);
assert_ne!(Tree::Second.dir(), Tree::Reborn.dir());
s.secondary_world_port = Some(8086);
s.reborn_world_port = Some(8087);
assert_eq!(Tree::Second.ports(&s).0, Some(8086));
assert_eq!(Tree::Reborn.ports(&s).0, Some(8087));
assert!(!Tree::Second.enabled(&s) && !Tree::Reborn.enabled(&s));
s.with_reborn = true;
assert!(!Tree::Second.enabled(&s) && Tree::Reborn.enabled(&s));
}
#[test]
fn a_realm_is_reached_through_the_folder_of_its_own_world() {
let t = tempfile::tempdir().unwrap();
let main = t.path();
fsx::atomic_write(
&main.join("Settings/realm-profile.json"),
br#"{"active":"coa","wildcard_created":true,"reborn_created":true,"simultaneous":true,"with_reborn":true}"#,
)
.unwrap();
assert_eq!(world_root(main, Mode::Coa), main);
assert_eq!(world_root(main, Mode::Wildcard), main.join(".realms/secondary"));
assert_eq!(world_root(main, Mode::Reborn), main.join(".realms/reborn"));
// A realm that is not switched on has no world of its own: the main folder answers.
fsx::atomic_write(
&main.join("Settings/realm-profile.json"),
br#"{"active":"coa","wildcard_created":true,"reborn_created":true,"with_reborn":true}"#,
)
.unwrap();
assert_eq!(world_root(main, Mode::Wildcard), main);
assert_eq!(world_root(main, Mode::Reborn), main.join(".realms/reborn"));
}
#[test]
fn reborn_starts_together_with_conquest_of_azeroth_only() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write(
&t.path().join("Core/worldserver.exe"),
b"Warcraft Reborn class spells are unavailable",
)
.unwrap();
fsx::atomic_write(
&t.path().join("Settings/realm-profile.json"),
br#"{"active":"wildcard","wildcard_created":true}"#,
)
.unwrap();
let err = set_reborn_enabled(t.path(), true).unwrap_err().to_string();
assert!(err.contains("Select Conquest of Azeroth first"), "{err}");
assert!(!realms::state(t.path()).unwrap().with_reborn);
}
#[test]
fn secondary_never_starts_the_shared_database() {
let patched = secondary_launcher("def start_world(config, offset):\r\n start_mysql(config)\r\n wait_ready('world', 8086)\r\n").unwrap();
+2 -1
View File
@@ -284,7 +284,7 @@ fn stop_failure(
)];
for service in [&status.mysql, &status.auth, &status.world]
.into_iter()
.chain(status.secondary_world.iter())
.chain(status.extra_worlds())
{
if service.state != crate::process::ServiceState::Stopped {
details.push(format!(
@@ -506,6 +506,7 @@ mod tests {
auth: stopped("auth"),
world: stopped("world"),
secondary_world: None,
reborn_world: None,
};
let outcome = crate::driver::DriverOutcome {
ok: false,
@@ -248,9 +248,15 @@ impl RealmAccess {
}
}
/// The folder of the world server this realm runs in: an extra world next to the main one has its own console port.
fn world_folder(&self, root: &Path) -> PathBuf {
self.mode
.map_or_else(|| root.to_path_buf(), |m| crate::multiworld::world_root(root, m))
}
pub fn ra(&self) -> Result<Ra> {
match &self.source {
Source::Install { root } => Ra::connect(root),
Source::Install { root } => Ra::connect(&self.world_folder(root)),
Source::Descriptor(d) => Ra::connect_to(d.ra_port, &d.ra_user, d.ra_password.expose()),
}
}
@@ -261,7 +267,7 @@ impl RealmAccess {
pub fn ports(&self) -> (Option<u16>, u16) {
match &self.source {
Source::Install { root } => (None, read_ports(root).ra),
Source::Install { root } => (None, read_ports(&self.world_folder(root)).ra),
Source::Descriptor(d) => (Some(d.db_port), d.ra_port),
}
}
+34 -13
View File
@@ -64,6 +64,16 @@ pub struct Observed {
pub auth: ServiceStatus,
pub world: ServiceStatus,
pub secondary_world: Option<ServiceStatus>,
/// The Warcraft Reborn world that starts together with Conquest of Azeroth.
#[serde(default)]
pub reborn_world: Option<ServiceStatus>,
}
impl Observed {
/// The worlds that run next to the primary one.
pub fn extra_worlds(&self) -> impl Iterator<Item = &ServiceStatus> {
self.secondary_world.iter().chain(self.reborn_world.iter())
}
}
pub fn read_state_record(root: &Path, name: &str) -> Option<ProcessIdentity> {
@@ -392,20 +402,30 @@ pub fn observe(root: &Path, ports: &Ports) -> Observed {
}
let listen = listeners();
let (world, auth, mysql) = crate::layout::executables(root);
let secondary = crate::multiworld::root(root);
let secondary_world = if crate::realms::state(root).is_ok_and(|s| s.simultaneous)
|| crate::multiworld::is_running(root)
{
Some(service(
&secondary,
"world-secondary",
secondary.join("Core/worldserver.exe"),
crate::layout::read_ports(&secondary).world,
&listen,
))
} else {
None
use crate::multiworld::Tree;
let realm_state = crate::realms::state(root).ok();
let extra_world = |tree: Tree, name: &'static str, enabled: bool| {
let folder = crate::multiworld::tree_root(root, tree);
(enabled || crate::multiworld::tree_running(root, tree)).then(|| {
service(
&folder,
name,
folder.join("Core/worldserver.exe"),
crate::layout::read_ports(&folder).world,
&listen,
)
})
};
let secondary_world = extra_world(
Tree::Second,
"world-secondary",
realm_state.as_ref().is_some_and(|s| s.simultaneous),
);
let reborn_world = extra_world(
Tree::Reborn,
"world-reborn",
realm_state.as_ref().is_some_and(|s| s.with_reborn),
);
Observed {
mysql: service(root, "mysql", mysql, ports.mysql, &listen),
auth: service(root, "auth", auth, ports.auth, &listen),
@@ -418,6 +438,7 @@ pub fn observe(root: &Path, ports: &Ports) -> Observed {
&listen,
),
secondary_world,
reborn_world,
}
}
+4 -1
View File
@@ -154,7 +154,10 @@ pub fn find_access(
st.active == crate::realms::Mode::Wildcard
|| (st.simultaneous && st.wildcard_created)
}
crate::realms::Mode::Reborn => st.active == crate::realms::Mode::Reborn,
crate::realms::Mode::Reborn => {
st.active == crate::realms::Mode::Reborn
|| (st.with_reborn && st.reborn_created)
}
};
if !supported {
return None;
+300 -50
View File
@@ -63,15 +63,50 @@ pub struct RealmState {
pub wildcard_created: bool,
#[serde(default)]
pub reborn_created: bool,
/// Wildcard starts together with Conquest of Azeroth (the second of the two when Wildcard is the primary realm).
#[serde(default)]
pub simultaneous: bool,
#[serde(default)]
pub secondary_world_port: Option<u16>,
#[serde(default)]
pub secondary_ra_port: Option<u16>,
/// Warcraft Reborn starts together with Conquest of Azeroth, which is then the primary realm.
#[serde(default)]
pub with_reborn: bool,
#[serde(default)]
pub reborn_world_port: Option<u16>,
#[serde(default)]
pub reborn_ra_port: Option<u16>,
}
impl RealmState {
/// World ports of the realms that run next to the primary one (the ones that are switched on).
pub fn extra_world_ports(&self) -> Vec<u16> {
[
self.secondary_world_port.filter(|_| self.simultaneous),
self.reborn_world_port.filter(|_| self.with_reborn),
]
.into_iter()
.flatten()
.collect()
}
/// Realms that run as a world of their own next to the primary one.
pub fn extra_modes(&self) -> Vec<Mode> {
let mut modes = Vec::new();
if self.simultaneous {
modes.push(if self.active == Mode::Coa {
Mode::Wildcard
} else {
Mode::Coa
});
}
if self.with_reborn {
modes.push(Mode::Reborn);
}
modes
}
pub fn created(&self, mode: Mode) -> bool {
match mode {
Mode::Coa => true,
@@ -101,6 +136,9 @@ pub struct View {
pub simultaneous: bool,
pub secondary_world_port: Option<u16>,
pub secondary_running: bool,
pub with_reborn: bool,
pub reborn_world_port: Option<u16>,
pub reborn_running: bool,
}
pub fn state(root: &Path) -> Result<RealmState> {
@@ -139,7 +177,10 @@ pub fn view(root: &Path) -> Result<View> {
recovery_pending: root.join(JOURNAL).exists(),
simultaneous: s.simultaneous,
secondary_world_port: s.secondary_world_port,
secondary_running: crate::multiworld::is_running(root),
secondary_running: crate::multiworld::tree_running(root, crate::multiworld::Tree::Second),
with_reborn: s.with_reborn,
reborn_world_port: s.reborn_world_port,
reborn_running: crate::multiworld::tree_running(root, crate::multiworld::Tree::Reborn),
})
}
@@ -447,6 +488,58 @@ fn create_databases(root: &Path, mode: Mode) -> Result<()> {
})
}
/// Create the saved settings and the databases of a realm that was never set up. `before` is the current
/// configuration, the base of a new realm while Conquest of Azeroth is the active one.
fn create_realm(root: &Path, s: &mut RealmState, mode: Mode, before: &Files) -> Result<()> {
if s.created(mode) {
return Ok(());
}
let base = if s.active == Mode::Coa {
before.clone()
} else {
fsx::read_json(&snapshot(root, Mode::Coa))?
};
let files = match mode {
Mode::Wildcard => wildcard_configs(base)?,
Mode::Reborn => reborn_configs(base)?,
Mode::Coa => unreachable!(),
};
fsx::atomic_write_json(&snapshot(root, mode), &files)?;
create_databases(root, mode)?;
match mode {
Mode::Wildcard => s.wildcard_created = true,
Mode::Reborn => s.reborn_created = true,
Mode::Coa => {}
}
fsx::atomic_write_json(&root.join(STATE), s)?;
Ok(())
}
/// Set a realm up without making it the active one, so it can start next to the active realm.
pub fn ensure_created(root: &Path, mode: Mode) -> Result<()> {
let meta = crate::registry::metadata_dir_for(root)?;
let _update_lock = crate::update::operation_lock(&meta)?;
crate::update::ensure_recovered(&meta)?;
require_world_stopped(root)?;
recover(root)?;
let mut s = state(root)?;
let supported = view(root)?;
if mode == Mode::Wildcard && !supported.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
}
if mode == Mode::Reborn && !supported.reborn_supported {
return Err(Error::Invalid(
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
// Verify launcher support before creating databases, as selecting a realm does.
prepare_launcher(root)?;
let before = configs(root)?;
create_realm(root, &mut s, mode, &before)
}
pub fn select(root: &Path, mode: Mode) -> Result<View> {
let meta = crate::registry::metadata_dir_for(root)?;
let _update_lock = crate::update::operation_lock(&meta)?;
@@ -467,35 +560,16 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
if s.simultaneous && mode != s.active {
if (s.simultaneous || s.with_reborn) && mode != s.active {
return Err(Error::Invalid(
"Disable simultaneous startup before switching realms.".into(),
"Disable the realms that start together before switching realms.".into(),
));
}
// Verify launcher support before creating databases or changing the selected realm.
prepare_launcher(root)?;
let before = configs(root)?;
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
if !s.created(mode) {
let base = if s.active == Mode::Coa {
before.clone()
} else {
fsx::read_json(&snapshot(root, Mode::Coa))?
};
let files = match mode {
Mode::Wildcard => wildcard_configs(base)?,
Mode::Reborn => reborn_configs(base)?,
Mode::Coa => unreachable!(),
};
fsx::atomic_write_json(&snapshot(root, mode), &files)?;
create_databases(root, mode)?;
match mode {
Mode::Wildcard => s.wildcard_created = true,
Mode::Reborn => s.reborn_created = true,
Mode::Coa => {}
}
fsx::atomic_write_json(&root.join(STATE), &s)?;
}
create_realm(root, &mut s, mode, &before)?;
let target: Files = fsx::read_json(&snapshot(root, mode))?;
// The launcher and batch files share this lock; recheck after the potentially long database copy.
fs::create_dir_all(root.join(".state"))?;
@@ -653,9 +727,46 @@ pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
(check == source).then_some(original)
}
/// The character-creation model the world server advertises for a realm. Every realm has its own database and its own
/// entry on Overview, so it advertises exactly one model: a list such as `"coa wcr"` would let players create
/// Warcraft Reborn characters in the Conquest of Azeroth realm.
fn class_model_for(mode: Mode) -> &'static str {
match mode {
Mode::Coa => "coa",
Mode::Wildcard => "hero",
Mode::Reborn => "wcr",
}
}
/// The client builds its character-creation screen from `CoA.ClassModel`, so a realm whose setting lacks its own
/// model would show the wrong screen (a Conquest of Azeroth realm set to `"hero"` has no classes). The realm chosen in
/// the Manager wins: any other setting is replaced by the realm's own model.
/// A missing key means the server default, `"coa"`; a missing file is left to the server.
fn align_class_model(root: &Path, mode: Mode) -> Result<()> {
let path = root.join("Core/configs/modules/coa.conf");
let Ok(bytes) = fs::read(&path) else {
return Ok(());
};
let mut conf = ConfFile::parse_bytes(&bytes)?;
let current = conf
.get("CoA.ClassModel")
.map(crate::config::parser::unquote)
.unwrap_or("coa")
.to_string();
let wanted = class_model_for(mode);
if current.split_whitespace().eq([wanted]) {
return Ok(());
}
conf.set("CoA.ClassModel", &format!("\"{wanted}\""), &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
tracing::warn!(realm = mode.name(), from = %current, to = wanted, "CoA.ClassModel did not fit the selected realm and was corrected");
Ok(())
}
pub fn before_start(root: &Path) -> Result<()> {
recover(root)?;
let s = state(root)?;
align_class_model(root, s.active)?;
if !root.join(STATE).exists() {
return Ok(());
}
@@ -665,12 +776,22 @@ pub fn before_start(root: &Path) -> Result<()> {
"The installed server build does not support simultaneous Wildcard startup.".into(),
));
}
if s.simultaneous && s.active == Mode::Reborn {
if (s.simultaneous || s.with_reborn) && s.active == Mode::Reborn {
return Err(Error::Invalid(
"Simultaneous startup supports CoA and Wildcard only.".into(),
"Realms that start together need Conquest of Azeroth or Wildcard as the main realm.".into(),
));
}
if s.simultaneous {
if s.with_reborn && s.active != Mode::Coa {
return Err(Error::Invalid(
"Warcraft Reborn can start together with Conquest of Azeroth only. Select Conquest of Azeroth first.".into(),
));
}
if s.with_reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid(
"The installed server build does not support Warcraft Reborn.".into(),
));
}
if s.simultaneous || s.with_reborn {
fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?;
}
if s.active == Mode::Reborn && !view(root)?.reborn_supported {
@@ -734,37 +855,38 @@ pub fn setup_realmlist(root: &Path) -> Result<()> {
};
db.query(&format!("UPDATE acore_auth.realmlist SET port=CASE id WHEN 1 THEN {coa} ELSE {wildcard} END,flag=0 WHERE id IN (1,2);"))?;
}
if s.with_reborn {
let reborn = s
.reborn_world_port
.ok_or_else(|| Error::Invalid("Warcraft Reborn realm port is missing.".into()))?;
db.query(&format!(
"UPDATE acore_auth.realmlist SET port={reborn},flag=0 WHERE id={};",
Mode::Reborn.realm_id()
))?;
}
Ok(())
}
pub fn world_port_for_mode(root: &Path, mode: Mode) -> Result<u16> {
let ports = crate::layout::read_ports(root);
let s = state(root)?;
if s.simultaneous {
let second = s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm port is missing.".into()))?;
let port = match (s.active, mode) {
(Mode::Coa, Mode::Coa) => ports.world,
(Mode::Coa, Mode::Wildcard) => second,
(Mode::Wildcard, Mode::Wildcard) => ports.world,
(Mode::Wildcard, Mode::Coa) => second,
_ => {
return Err(Error::Invalid(format!(
"Unsupported mode {mode:?} for simultaneous hosting (active: {:?})",
s.active
)))
}
};
Ok(port)
} else if mode == s.active {
Ok(ports.world)
} else {
Err(Error::Invalid(format!(
"Realm mode {mode:?} is not active (active: {:?}) and simultaneous mode is disabled.",
s.active
)))
if mode == s.active {
return Ok(ports.world);
}
if mode == Mode::Reborn && s.with_reborn && s.active == Mode::Coa {
return s
.reborn_world_port
.ok_or_else(|| Error::Invalid("Warcraft Reborn realm port is missing.".into()));
}
if s.simultaneous && matches!((s.active, mode), (Mode::Coa, Mode::Wildcard) | (Mode::Wildcard, Mode::Coa)) {
return s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm port is missing.".into()));
}
Err(Error::Invalid(format!(
"Realm mode {mode:?} is not active (active: {:?}) and simultaneous mode is disabled.",
s.active
)))
}
#[cfg(test)]
@@ -838,6 +960,134 @@ mod tests {
assert!(guard_module(t.path(), "content-scaling").is_ok());
}
fn write_class_model(root: &Path, text: &str) {
fsx::atomic_write(&root.join("Core/configs/modules/coa.conf"), text.as_bytes()).unwrap();
}
fn class_model(root: &Path) -> String {
let bytes = fs::read(root.join("Core/configs/modules/coa.conf")).unwrap();
ConfFile::parse_bytes(&bytes)
.unwrap()
.get("CoA.ClassModel")
.unwrap_or_default()
.to_string()
}
#[test]
fn a_class_model_that_does_not_fit_the_realm_is_replaced_by_the_realms_own() {
let t = tempfile::tempdir().unwrap();
// No file: left to the server. No key: the server default "coa" applies, which fits Conquest of Azeroth.
align_class_model(t.path(), Mode::Coa).unwrap();
assert!(!t.path().join("Core/configs/modules/coa.conf").exists());
write_class_model(t.path(), "[worldserver]
# CoA.ClassModel = \"hero\"
");
align_class_model(t.path(), Mode::Coa).unwrap();
assert_eq!(class_model(t.path()), "");
write_class_model(t.path(), "# note
CoA.ClassModel = \"hero\"
CoA.GameModeMask = 0
");
align_class_model(t.path(), Mode::Coa).unwrap();
assert_eq!(
fs::read_to_string(t.path().join("Core/configs/modules/coa.conf")).unwrap(),
"# note
CoA.ClassModel = \"coa\"
CoA.GameModeMask = 0
"
);
align_class_model(t.path(), Mode::Wildcard).unwrap();
assert_eq!(class_model(t.path()), "\"hero\"");
align_class_model(t.path(), Mode::Reborn).unwrap();
assert_eq!(class_model(t.path()), "\"wcr\"");
// A missing key does not fit a realm other than Conquest of Azeroth.
write_class_model(t.path(), "[worldserver]
");
align_class_model(t.path(), Mode::Wildcard).unwrap();
assert_eq!(class_model(t.path()), "\"hero\"");
}
#[test]
fn a_class_model_list_is_narrowed_to_the_realms_own_model() {
let t = tempfile::tempdir().unwrap();
// The shipped default serves two models; the realm chosen in the Manager keeps only its own.
for (mode, want) in [(Mode::Coa, "\"coa\""), (Mode::Reborn, "\"wcr\"")] {
write_class_model(t.path(), "CoA.ClassModel = \"coa wcr\"
");
align_class_model(t.path(), mode).unwrap();
assert_eq!(class_model(t.path()), want);
}
// A setting that is already exactly right is not rewritten, quoted or not.
for (text, mode) in [
("CoA.ClassModel = \"coa\"
", Mode::Coa),
("CoA.ClassModel = hero
", Mode::Wildcard),
] {
write_class_model(t.path(), text);
align_class_model(t.path(), mode).unwrap();
assert_eq!(
fs::read_to_string(t.path().join("Core/configs/modules/coa.conf")).unwrap(),
text
);
}
}
#[test]
fn before_start_aligns_the_class_model_with_the_active_realm() {
let t = tempfile::tempdir().unwrap();
write_class_model(t.path(), "CoA.ClassModel = \"hero\"
");
before_start(t.path()).unwrap();
assert_eq!(class_model(t.path()), "\"coa\"");
}
#[test]
fn extra_realms_follow_the_two_switches_and_old_states_still_load() {
let old: RealmState = serde_json::from_str(
r#"{"active":"coa","wildcard_created":true,"simultaneous":true,"secondary_world_port":8086}"#,
)
.unwrap();
assert!(!old.with_reborn && old.reborn_world_port.is_none());
assert_eq!(old.extra_modes(), [Mode::Wildcard]);
let mut s = RealmState::default();
assert!(s.extra_modes().is_empty());
s.with_reborn = true;
assert_eq!(s.extra_modes(), [Mode::Reborn]);
s.simultaneous = true;
assert_eq!(s.extra_modes(), [Mode::Wildcard, Mode::Reborn]);
s.secondary_world_port = Some(8086);
s.reborn_world_port = Some(8087);
assert_eq!(s.extra_world_ports(), [8086, 8087]);
s.with_reborn = false;
assert_eq!(s.extra_world_ports(), [8086]);
s.with_reborn = true;
// Wildcard as the main realm still pairs with Conquest of Azeroth.
s.active = Mode::Wildcard;
s.with_reborn = false;
assert_eq!(s.extra_modes(), [Mode::Coa]);
}
#[test]
fn each_running_realm_has_its_own_world_port() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write(&t.path().join("Settings/repack.json"), br#"{"worldPort": 8085}"#).unwrap();
let write = |json: &str| fsx::atomic_write(&t.path().join(STATE), json.as_bytes()).unwrap();
write(r#"{"active":"coa","wildcard_created":true,"reborn_created":true,"simultaneous":true,"secondary_world_port":8086,"with_reborn":true,"reborn_world_port":8087}"#);
assert_eq!(world_port_for_mode(t.path(), Mode::Coa).unwrap(), 8085);
assert_eq!(world_port_for_mode(t.path(), Mode::Wildcard).unwrap(), 8086);
assert_eq!(world_port_for_mode(t.path(), Mode::Reborn).unwrap(), 8087);
// Only Reborn next to Conquest of Azeroth: Wildcard is not running anywhere.
write(r#"{"active":"coa","wildcard_created":true,"reborn_created":true,"with_reborn":true,"reborn_world_port":8087}"#);
assert_eq!(world_port_for_mode(t.path(), Mode::Reborn).unwrap(), 8087);
assert!(world_port_for_mode(t.path(), Mode::Wildcard).is_err());
// Reborn only pairs with Conquest of Azeroth as the main realm.
write(r#"{"active":"wildcard","wildcard_created":true,"reborn_created":true,"with_reborn":true,"reborn_world_port":8087}"#);
assert!(world_port_for_mode(t.path(), Mode::Reborn).is_err());
}
#[test]
fn reborn_support_requires_the_new_code_in_the_installed_binary() {
let t = tempfile::tempdir().unwrap();
+16 -5
View File
@@ -1,5 +1,4 @@
//! Where a problem report goes. A report about the bots goes to the repository of the bot system in question, anything
//! else to the Manager's own. The repositories come from the module catalog, so there is one list to keep right.
//! Problem-report destinations for the Manager, bot systems and upstream custom races.
use std::path::Path;
@@ -36,14 +35,14 @@ fn catalog_repo(id: &str) -> Option<String> {
.and_then(|e| repo_of(&e.repo))
}
/// The three places, in the order the page lists them. A bot system whose repository is unknown falls back to the Manager's.
/// Report destinations in display order. Custom-race reports go to the upstream asset maintainer.
pub fn targets() -> Vec<Target> {
let mut v = vec![Target {
id: "manager",
repo: MANAGER_REPO.into(),
ours: true,
}];
for (id, module) in [("companions", "companions"), ("squid", "playerbots")] {
for (id, module) in [("companions", "companions"), ("squid", "playerbots"), ("content-scaling", "content-scaling")] {
if let Some(repo) = catalog_repo(module) {
v.push(Target {
id,
@@ -52,6 +51,11 @@ pub fn targets() -> Vec<Target> {
});
}
}
v.push(Target {
id: "custom-races",
repo: "ilusixn/azerothcore-wotlk-coa".into(),
ours: false,
});
v
}
@@ -103,7 +107,7 @@ mod tests {
use super::*;
#[test]
fn the_three_targets_come_from_the_catalog() {
fn report_targets_route_to_their_maintainers() {
let t = targets();
let repo = |id: &str| t.iter().find(|x| x.id == id).map(|x| x.repo.clone());
assert_eq!(
@@ -116,6 +120,10 @@ mod tests {
);
assert_eq!(repo("squid").as_deref(), Some("Zyth45/mod-playerbots"));
assert!(t.iter().find(|x| x.id == "squid").is_some_and(|x| !x.ours));
assert_eq!(repo("custom-races").as_deref(), Some("ilusixn/azerothcore-wotlk-coa"));
assert!(t.iter().find(|x| x.id == "custom-races").is_some_and(|x| !x.ours));
assert_eq!(repo("content-scaling").as_deref(), Some("Corfirean/mod-coa-content-scaling"));
assert!(t.iter().find(|x| x.id == "content-scaling").is_some_and(|x| x.ours));
}
#[test]
@@ -135,6 +143,9 @@ mod tests {
#[test]
fn only_the_new_issue_pages_of_the_targets_are_allowed() {
assert!(is_new_issue_url("https://github.com/Corfirean/mod-coa-content-scaling/issues/new?title=a&body=b"));
assert!(is_new_issue_url("https://github.com/ilusixn/azerothcore-wotlk-coa/issues/new?title=a&body=b"));
assert!(!is_new_issue_url("https://github.com/ilusixn/azerothcore-wotlk-coa/issues/newer"));
assert!(is_new_issue_url(
"https://github.com/Zyth45/mod-playerbots/issues/new"
));
+2 -3
View File
@@ -1851,9 +1851,8 @@ impl RepackEnv<'_> {
if o.mysql.state == ServiceState::Running
&& o.auth.state == ServiceState::Running
&& o.world.state == ServiceState::Running
&& o.secondary_world
.as_ref()
.is_none_or(|s| s.state == ServiceState::Running)
&& o.extra_worlds()
.all(|s| s.state == ServiceState::Running)
{
let since = ready_since.get_or_insert_with(std::time::Instant::now);
if since.elapsed() >= std::time::Duration::from_secs(10) {
+16 -2
View File
@@ -18,6 +18,20 @@ const FILES: &[&str] = &[
".realms/secondary/Core/configs/worldserver.conf",
".realms/secondary/Core/configs/authserver.conf",
"Settings/realm-profiles/reborn.json",
".realms/reborn/Settings/repack.json",
".realms/reborn/Settings/realm-profile.json",
".realms/reborn/Settings/worldserver.conf.template",
".realms/reborn/Settings/authserver.conf.template",
".realms/reborn/Core/configs/worldserver.conf",
".realms/reborn/Core/configs/authserver.conf",
];
/// Ports of the extra worlds kept in the realm profile.
const REALM_PORT_KEYS: [&str; 4] = [
"secondary_world_port",
"secondary_ra_port",
"reborn_world_port",
"reborn_ra_port",
];
#[derive(Serialize, Deserialize)]
@@ -62,7 +76,7 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
.collect();
if let Some(state) = &realm {
excluded.extend(
["secondary_world_port", "secondary_ra_port"]
REALM_PORT_KEYS
.iter()
.filter_map(|key| state[*key].as_u64()),
);
@@ -82,7 +96,7 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
settings[key] = reserve()?.into();
}
if let Some(state) = &mut realm {
for key in ["secondary_world_port", "secondary_ra_port"] {
for key in REALM_PORT_KEYS {
state[key] = reserve()?.into();
}
}
+61
View File
@@ -1025,6 +1025,67 @@
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "SkillChance.Prospecting",
"type": "bool",
"category": "rates",
"title": "Prospecting skill gains",
"description": "Allow prospecting to increase the profession skill.",
"default": false,
"advanced": true,
"restartRequired": "world",
"dangerous": false
},
{
"key": "SkillChance.Milling",
"type": "bool",
"category": "rates",
"title": "Milling skill gains",
"description": "Allow milling to increase the profession skill.",
"default": false,
"advanced": true,
"restartRequired": "world",
"dangerous": false
},
{
"key": "SkillGain.Crafting",
"type": "int",
"category": "rates",
"title": "Crafting skill gain",
"description": "Skill points awarded by a successful crafting skill increase.",
"default": 1,
"advanced": true,
"restartRequired": "world",
"dangerous": false,
"min": 0,
"max": 450
},
{
"key": "SkillGain.Defense",
"type": "int",
"category": "rates",
"title": "Defense skill gain",
"description": "Skill points awarded by a successful defense skill increase.",
"default": 1,
"advanced": true,
"restartRequired": "world",
"dangerous": false,
"min": 0,
"max": 450
},
{
"key": "SkillGain.Gathering",
"type": "int",
"category": "rates",
"title": "Gathering skill gain",
"description": "Skill points awarded by a successful gathering skill increase.",
"default": 1,
"advanced": true,
"restartRequired": "world",
"dangerous": false,
"min": 0,
"max": 450
}
]
}
+32 -4
View File
@@ -604,7 +604,19 @@ async fn start_server(
})
.await;
let _ = tauri::async_runtime::spawn_blocking(move || {
meta_dir(&root).and_then(|m| coa_core::friends::reapply(&root, &m))
let meta = meta_dir(&root)?;
coa_core::friends::reapply(&root, &meta)?;
// A world switched on after the server was opened to friends has no firewall rule yet. Rules are only
// added when missing (one Windows confirmation); a refusal must not undo a start that worked.
if platform::flavor() == Flavor::Repack
&& coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local
{
let extra = coa_core::realms::state(&root)?.extra_world_ports();
if let Err(e) = coa_core::firewall::ensure_rules_with_extra(&layout::read_ports(&root), &extra) {
tracing::warn!("firewall rules for the running worlds were not added: {e}");
}
}
Ok::<(), Error>(())
})
.await;
}
@@ -1169,6 +1181,17 @@ async fn realm_simultaneous(
blocking(move || coa_core::multiworld::set_enabled(&root, enabled)).await
}
#[tauri::command]
async fn realm_with_reborn(
state: State<'_, AppState>,
id: String,
enabled: bool,
) -> std::result::Result<coa_core::realms::View, UiError> {
let root = path_of(&state, &id)?;
let _guard = BusyGuard::acquire(&state, &id)?;
blocking(move || coa_core::multiworld::set_reborn_enabled(&root, enabled)).await
}
#[tauri::command]
async fn check_database(
state: State<'_, AppState>,
@@ -2322,6 +2345,7 @@ struct FriendsStatus {
auth_port: u16,
world_port: u16,
secondary_world_port: Option<u16>,
reborn_world_port: Option<u16>,
}
/// Open one of a few known help pages in the default browser. Anything else is refused, so a page can never ask the
@@ -2485,6 +2509,9 @@ async fn friends_status(
secondary_world_port: coa_core::realms::state(&root)?
.secondary_world_port
.filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.simultaneous)),
reborn_world_port: coa_core::realms::state(&root)?
.reborn_world_port
.filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.with_reborn)),
})
})
.await
@@ -2542,7 +2569,7 @@ async fn friends_enable(
let ports = layout::read_ports(&root);
let mut note = None;
let realms = coa_core::realms::state(&root)?;
let secondary = realms.secondary_world_port.filter(|_| realms.simultaneous);
let extra = realms.extra_world_ports();
let host = match mode {
Mode::Local => "127.0.0.1".to_string(),
Mode::Lan => coa_core::net::resolve_lan_host(lan_address_override.as_deref(), coa_core::net::lan_ip())?,
@@ -2552,7 +2579,7 @@ async fn friends_enable(
let open = mode != Mode::Local;
let changed = friends::set_open(&root, &meta, open)?;
if open && platform::flavor() == Flavor::Repack {
coa_core::firewall::ensure_rules_with_secondary(&ports, secondary)?;
coa_core::firewall::ensure_rules_with_extra(&ports, &extra)?;
}
if mode == Mode::Direct && use_upnp {
match coa_core::upnp::discover() {
@@ -2560,7 +2587,7 @@ async fn friends_enable(
let lan = coa_core::net::lan_ip().ok_or_else(|| Error::Invalid("No local address.".into()))?;
coa_core::upnp::add_mapping(&gw, ports.auth, lan, "Auth")?;
coa_core::upnp::add_mapping(&gw, ports.world, lan, "World")?;
if let Some(port) = secondary { coa_core::upnp::add_mapping(&gw, port, lan, "Second world")?; }
for port in &extra { coa_core::upnp::add_mapping(&gw, *port, lan, "Extra world")?; }
note = Some("Your router was asked to forward the game ports.".to_string());
}
None => note = Some("Your router does not support automatic setup; forward the two game ports by hand or use the private network.".to_string()),
@@ -2793,6 +2820,7 @@ pub fn run() {
realm_profiles,
realm_select,
realm_simultaneous,
realm_with_reborn,
check_database,
repair_server,
module_set_enabled,
+7 -5
View File
@@ -11,6 +11,7 @@ export {};
let added = new URLSearchParams(location.search).has("demo"), running = false;
let realm: "coa" | "wildcard" | "reborn" = "coa", wildcardCreated = false, rebornCreated = false;
let simultaneous = false;
let withReborn = false;
let remoteHost = localStorage.getItem("demo-remote-host") ?? "";
const moduleEdits: Record<string, Record<string, string>> = {};
const modState: Record<string, boolean> = { "companions": true, "content-scaling": true, "client-compat": true, "tbc-content": true, "wotlk-content": true, "npc-enchanter": true };
@@ -27,18 +28,19 @@ export {};
(window as any).__TAURI_INTERNALS__ = {
transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x,
invoke: async (cmd: string, args?: any)=>{
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running};
if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false}; }
if(cmd==="realm_profiles") return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};
if(cmd==="realm_simultaneous") { if(running) throw new Error("Stop both realms before changing simultaneous startup."); simultaneous=args.enabled; wildcardCreated ||= simultaneous; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
if(cmd==="realm_with_reborn") { if(running) throw new Error("Stop all realms before changing which realms start together."); withReborn=args.enabled; rebornCreated ||= withReborn; return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:false,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:false}; }
if(cmd==="check_database") return [{realm, migrations:[],problems:[],full_schema:false}];
if(cmd==="repair_server") { if(running) throw new Error("Stop the server before repairing it."); return {restored:[],applied:[],backup:"demo-before-repair",database:[{realm,migrations:[],problems:[],full_schema:false}],error:null}; }
if(cmd==="realm_select"){await new Promise(r=>setTimeout(r,600));realm=args.mode;rebornCreated ||= realm==="reborn";wildcardCreated ||= realm==="wildcard";modState.companions=realm==="coa";return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running};}
if(cmd==="realm_select"){await new Promise(r=>setTimeout(r,600));realm=args.mode;rebornCreated ||= realm==="reborn";wildcardCreated ||= realm==="wildcard";modState.companions=realm==="coa";return {active:realm,wildcard_created:wildcardCreated,reborn_created:rebornCreated,reborn_supported:true,supported:true,recovery_pending:false,simultaneous,secondary_world_port:simultaneous?8086:null,secondary_running:simultaneous&&running,with_reborn:withReborn,reborn_world_port:withReborn?8087:null,reborn_running:withReborn&&running};}
if(cmd==="remote_connection") return {host:remoteHost,client_path:null};
if(cmd==="remote_connect") { remoteHost=args.host.trim(); localStorage.setItem("demo-remote-host",remoteHost); return {host:remoteHost,client_path:null}; }
if(cmd==="play") return {ok:true,exit_code:null,code:null,human:null,output:""};
if(cmd==="list_servers") return added?[{id:"1",name:"CoA-Repack",path:report.path}]:[];
if(cmd==="scan_server") return report;
if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};}
if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null},busy:false,path_exists:true};}
if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};}
if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};}
if(cmd==="stop_server"){await new Promise((r: any)=>setTimeout(r,1500));running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};}
if(cmd.startsWith("plugin:dialog")) return "C:\\games\\CoA-Repack";
@@ -90,7 +92,7 @@ export {};
}
if(cmd==="module_save_settings") { moduleEdits[args.module] = {...moduleEdits[args.module], ...args.changes}; return Object.keys(args.changes); }
if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10",suggested_target:"companions",bots_version:"0.2.1 · 1a2b3c4d"};
if(cmd==="report_targets") return [{id:"manager",repo:"Corfirean/coa-server-manager",ours:true},{id:"companions",repo:"Corfirean/mod-coa-playerbots",ours:true},{id:"squid",repo:"Zyth45/mod-playerbots",ours:false}];
if(cmd==="report_targets") return [{id:"manager",repo:"Corfirean/coa-server-manager",ours:true},{id:"companions",repo:"Corfirean/mod-coa-playerbots",ours:true},{id:"squid",repo:"Zyth45/mod-playerbots",ours:false},{id:"custom-races",repo:"ilusixn/azerothcore-wotlk-coa",ours:false},{id:"content-scaling",repo:"Corfirean/mod-coa-content-scaling",ours:true}];
if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;}
if(cmd==="export_diagnostics") return "C:\\Users\\you\\Desktop\\CoA-Diagnostics-20261001-140000.zip";
if(cmd==="list_crashes") return [];
+2
View File
@@ -721,6 +721,8 @@ const de: Partial<Record<keyof typeof en, string>> = {
"rep.target.manager": "CoA Server Manager, der Server oder andere Module",
"rep.target.companions": "CoA Companions (Bots und das CoABotUI-Addon)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling (Schwierigkeits- und Stufenskalierung)",
"rep.target.custom-races": "Custom Races (Völker und Client-Patches)",
"rep.targetPublic": "Der Bericht wird öffentlich auf GitHub in {repo} veröffentlicht.",
"rep.botsVersion": "Bot-Version",
"rep.withDiag": "Diagnose für mich sammeln (empfohlen)",
+26 -3
View File
@@ -19,11 +19,16 @@ const en = {
"realm.profileLabel": "Realm",
"realm.startupTitle": "Realm startup",
"realm.secondWorld": "Second world",
"realm.simultaneous": "Start CoA and Wildcard together",
"realm.simultaneousHint": "Stop the server before changing this option. Start runs both worlds with separate characters, settings and ports, sharing accounts. Two worlds need more memory. The first setup creates Wildcard if needed.",
"realm.simultaneous": "Start Wildcard together with CoA",
"realm.withReborn": "Start Warcraft Reborn together with CoA",
"realm.rebornPort": "Warcraft Reborn world port: {port}",
"realm.rebornWorld": "Warcraft Reborn world",
"realm.rebornNeedsCoa": "Warcraft Reborn can start together with Conquest of Azeroth only. Select Conquest of Azeroth on Overview first.",
"realm.allThree": "Both options are on: Conquest of Azeroth, Wildcard and Warcraft Reborn start together.",
"realm.simultaneousHint": "Stop the server before changing these options. Start runs every chosen world with separate characters, settings and ports, sharing accounts. Each extra world needs more memory. The first setup creates the realm if needed.",
"realm.secondPort": "Second world port: {port}",
"realm.preparing": "Preparing realm databases…",
"realm.bothRunning": "Both worlds start together. Each realm keeps its own characters, progress and module settings.",
"realm.bothRunning": "These worlds start together. Each realm keeps its own characters, progress and module settings.",
"repair.title": "Check and repair server",
"repair.hint": "Stop both realms and update to the latest server package before repair. Repair backs up databases and replaced files, restores official program files and applies pending SQL. Your characters and existing settings are preserved.",
"repair.check": "Check files and database",
@@ -777,6 +782,8 @@ const en = {
"rep.target.manager": "CoA Server Manager, the server or other modules",
"rep.target.companions": "CoA Companions (bots and the CoABotUI addon)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling (difficulty and level scaling)",
"rep.target.custom-races": "Custom Races (races and client patches)",
"rep.targetPublic": "The report will be public on GitHub in {repo}.",
"rep.botsVersion": "Bot release",
"rep.withDiag": "Collect the diagnostics for me (recommended)",
@@ -1102,6 +1109,22 @@ const en = {
"browse.play": "Play",
"browse.playSoon": "Joining arrives with the account support of the next step.",
"registry.title": "Public listing",
"registry.dialogTitle": "Public listing · {realm}",
"registry.publishAll": "Publish all realms",
"registry.publishAllText": "One description, language and region for every realm that is not listed yet. Each realm is listed under the server name; the realms that start next to the main one get their realm name added.",
"registry.publishAllButton": "Publish {n} realms",
"registry.alreadyListed": "Already published",
"registry.configure": "Configure",
"registry.publishShort": "Publish",
"registry.short.starting": "Publishing…",
"registry.accessFailed": "The realm is published, but its joining options were not saved: {reason}",
"registry.short.waiting_for_realm": "Not published",
"registry.short.realm_stopped": "Published, realm is off",
"registry.short.online": "Published",
"registry.short.retrying": "Registry unreachable",
"registry.short.rejected": "Refused by the registry",
"registry.short.unpublishing": "Removing from the list",
"registry.short.disabled": "Not published",
"registry.text": "Publish this realm in the central list so that players can find it. Only its name, description, language, region, rates, modules, player counts, version and capabilities are shared: no passwords, no characters, no accounts. The realm keeps running if the list is unreachable.",
"registry.url": "Registry address",
"registry.urlSave": "Save address",
+2
View File
@@ -721,6 +721,8 @@ const es: Partial<Record<keyof typeof en, string>> = {
"rep.target.manager": "CoA Server Manager, el servidor u otros módulos",
"rep.target.companions": "CoA Companions (bots y el addon CoABotUI)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling (ajuste de dificultad y niveles)",
"rep.target.custom-races": "Custom Races (razas y parches del cliente)",
"rep.targetPublic": "El informe será público en GitHub, en {repo}.",
"rep.botsVersion": "Versión de los bots",
"rep.withDiag": "Reunir el diagnóstico por mí (recomendado)",
+2
View File
@@ -721,6 +721,8 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"rep.target.manager": "CoA Server Manager, le serveur ou d’autres modules",
"rep.target.companions": "CoA Companions (bots et addon CoABotUI)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling (ajustement de la difficulté et des niveaux)",
"rep.target.custom-races": "Custom Races (races et correctifs client)",
"rep.targetPublic": "Le rapport sera public sur GitHub dans {repo}.",
"rep.botsVersion": "Version des bots",
"rep.withDiag": "Rassembler le diagnostic pour moi (recommandé)",
+26 -3
View File
@@ -22,11 +22,16 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"realm.profileLabel": "Реалм",
"realm.startupTitle": "Запуск реалмов",
"realm.secondWorld": "Второй мир",
"realm.simultaneous": "Запускать CoA и Wildcard одновременно",
"realm.simultaneousHint": "Остановите сервер перед изменением настройки. Запуск поднимет оба мира с отдельными персонажами, настройками и портами, но общими аккаунтами. Два мира требуют больше памяти. При первом включении Wildcard будет создан, если его ещё нет.",
"realm.simultaneous": "Запускать Wildcard вместе с CoA",
"realm.withReborn": "Запускать Warcraft Reborn вместе с CoA",
"realm.rebornPort": "Порт мира Warcraft Reborn: {port}",
"realm.rebornWorld": "Мир Warcraft Reborn",
"realm.rebornNeedsCoa": "Warcraft Reborn запускается только вместе с Conquest of Azeroth. Сначала выберите Conquest of Azeroth на главной.",
"realm.allThree": "Включены обе настройки: Conquest of Azeroth, Wildcard и Warcraft Reborn запускаются вместе.",
"realm.simultaneousHint": "Остановите сервер перед изменением настроек. Запуск поднимет каждый выбранный мир с отдельными персонажами, настройками и портами, но общими аккаунтами. Каждый дополнительный мир требует больше памяти. При первом включении реалм будет создан, если его ещё нет.",
"realm.secondPort": "Порт второго мира: {port}",
"realm.preparing": "Подготовка баз реалма…",
"realm.bothRunning": "Оба мира запускаются одновременно. У каждого свои персонажи, прогресс и настройки модулей.",
"realm.bothRunning": "Эти миры запускаются одновременно. У каждого свои персонажи, прогресс и настройки модулей.",
"repair.title": "Проверка и восстановление сервера",
"repair.hint": "Перед восстановлением остановите оба реалма и обновите сервер до последнего пакета. Repair сохранит резервную копию БД и заменяемых файлов, восстановит файлы программы и применит недостающие SQL. Персонажи и существующие настройки сохраняются.",
"repair.check": "Проверить файлы и БД",
@@ -760,6 +765,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"rep.target.manager": "CoA Server Manager, сервер или другие модули",
"rep.target.companions": "CoA Companions (боты и аддон CoABotUI)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling (масштабирование сложности и уровней)",
"rep.target.custom-races": "Custom Races (расы и клиентские патчи)",
"rep.targetPublic": "Репорт будет публичным на GitHub в {repo}.",
"rep.botsVersion": "Версия ботов",
"rep.withDiag": "Собрать диагностику за меня (рекомендуется)",
@@ -1084,6 +1091,22 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"browse.play": "Играть",
"browse.playSoon": "Вход на сервер появится вместе с поддержкой аккаунтов на следующем шаге.",
"registry.title": "Публичный список",
"registry.dialogTitle": "Публичный список · {realm}",
"registry.publishAll": "Опубликовать все реалмы",
"registry.publishAllText": "Одно описание, язык и регион для каждого реалма, которого ещё нет в списке. Реалмы публикуются под названием сервера; к реалмам, которые запускаются рядом с основным, добавляется название реалма.",
"registry.publishAllButton": "Опубликовать реалмов: {n}",
"registry.alreadyListed": "Уже опубликован",
"registry.configure": "Настроить",
"registry.publishShort": "Опубликовать",
"registry.short.starting": "Публикуется…",
"registry.accessFailed": "Реалм опубликован, но настройки входа игроков не сохранены: {reason}",
"registry.short.waiting_for_realm": "Не опубликован",
"registry.short.realm_stopped": "Опубликован, реалм выключен",
"registry.short.online": "Опубликован",
"registry.short.retrying": "Нет связи с реестром",
"registry.short.rejected": "Реестр отклонил",
"registry.short.unpublishing": "Снимается с публикации",
"registry.short.disabled": "Не опубликован",
"registry.text": "Опубликуйте этот реалм в общем списке, чтобы игроки могли его найти. Передаются только название, описание, язык, регион, рейты, модули, число игроков и ботов, версия и возможности реалма: никаких паролей, персонажей и аккаунтов. Если список недоступен, реалм продолжает работать.",
"registry.url": "Адрес реестра",
"registry.urlSave": "Сохранить адрес",
+2
View File
@@ -736,6 +736,8 @@ const zh = {
"rep.target.manager": "CoA Server Manager、服务器或其他模块",
"rep.target.companions": "CoA Companions(机器人与 CoABotUI 插件)",
"rep.target.squid": "SQUID Playerbots",
"rep.target.content-scaling": "Content Scaling(难度与等级缩放)",
"rep.target.custom-races": "Custom Races(种族与客户端补丁)",
"rep.targetPublic": "该报告将公开发布在 GitHub 的 {repo}。",
"rep.botsVersion": "机器人版本",
"rep.withDiag": "替我收集诊断信息(推荐)",
+5
View File
@@ -31,6 +31,11 @@
"copper": "Kupfer"
},
"settings": {
"SkillChance.Prospecting": {"t": "Fertigkeitszuwachs beim Sondieren", "d": "Sondieren darf die Berufsfertigkeit erhöhen."},
"SkillChance.Milling": {"t": "Fertigkeitszuwachs beim Mahlen", "d": "Mahlen darf die Berufsfertigkeit erhöhen."},
"SkillGain.Crafting": {"t": "Fertigkeitszuwachs beim Herstellen", "d": "Fertigkeitspunkte pro erfolgreicher Steigerung beim Herstellen."},
"SkillGain.Defense": {"t": "Zuwachs der Verteidigungsfertigkeit", "d": "Fertigkeitspunkte pro erfolgreicher Steigerung der Verteidigung."},
"SkillGain.Gathering": {"t": "Fertigkeitszuwachs beim Sammeln", "d": "Fertigkeitspunkte pro erfolgreicher Steigerung beim Sammeln."},
"CoaBots.RandomSpawn.DefaultCount": {
"t": "Bots pro Erstellungsbefehl",
"d": "Wie viele Bots der Erstellungsbefehl anlegt, wenn du keine Zahl angibst."
+5
View File
@@ -31,6 +31,11 @@
"copper": "cobre"
},
"settings": {
"SkillChance.Prospecting": {"t": "Mejora de habilidad al prospectar", "d": "Permitir que prospectar aumente la habilidad de profesión."},
"SkillChance.Milling": {"t": "Mejora de habilidad al moler", "d": "Permitir que moler aumente la habilidad de profesión."},
"SkillGain.Crafting": {"t": "Puntos de habilidad al fabricar", "d": "Puntos otorgados por una mejora de habilidad al fabricar."},
"SkillGain.Defense": {"t": "Puntos de habilidad de defensa", "d": "Puntos otorgados por una mejora de habilidad de defensa."},
"SkillGain.Gathering": {"t": "Puntos de habilidad al recolectar", "d": "Puntos otorgados por una mejora de habilidad al recolectar."},
"CoaBots.RandomSpawn.DefaultCount": {
"t": "Bots creados por comando",
"d": "Cuántos bots crea el comando de creación cuando no indicas un número."
+5
View File
@@ -31,6 +31,11 @@
"copper": "cuivre"
},
"settings": {
"SkillChance.Prospecting": {"t": "Progression avec la prospection", "d": "Permettre à la prospection d’améliorer la compétence de métier."},
"SkillChance.Milling": {"t": "Progression avec la mouture", "d": "Permettre à la mouture d’améliorer la compétence de métier."},
"SkillGain.Crafting": {"t": "Gain de compétence en fabrication", "d": "Points accordés lors d’une progression réussie en fabrication."},
"SkillGain.Defense": {"t": "Gain de compétence en défense", "d": "Points accordés lors d’une progression réussie en défense."},
"SkillGain.Gathering": {"t": "Gain de compétence en récolte", "d": "Points accordés lors d’une progression réussie en récolte."},
"CoaBots.RandomSpawn.DefaultCount": {
"t": "Bots créés par commande",
"d": "Nombre de bots que la commande de création crée quand vous n’indiquez pas de nombre."
+5
View File
@@ -31,6 +31,11 @@
"copper": "меди"
},
"settings": {
"SkillChance.Prospecting": {"t": "Рост навыка при просеивании", "d": "Разрешить повышение навыка профессии при просеивании."},
"SkillChance.Milling": {"t": "Рост навыка при измельчении", "d": "Разрешить повышение навыка профессии при измельчении."},
"SkillGain.Crafting": {"t": "Прирост ремесленного навыка", "d": "Число очков за успешное повышение ремесленного навыка."},
"SkillGain.Defense": {"t": "Прирост навыка защиты", "d": "Число очков за успешное повышение навыка защиты."},
"SkillGain.Gathering": {"t": "Прирост навыка сбора", "d": "Число очков за успешное повышение навыка сбора."},
"CoaBots.RandomSpawn.DefaultCount": {
"t": "Ботов за одну команду создания",
"d": "Сколько ботов создаёт команда создания, если вы не указали число."
+5
View File
@@ -31,6 +31,11 @@
"copper": "铜币"
},
"settings": {
"SkillChance.Prospecting": {"t": "选矿技能提升", "d": "允许通过选矿提升专业技能。"},
"SkillChance.Milling": {"t": "研磨技能提升", "d": "允许通过研磨提升专业技能。"},
"SkillGain.Crafting": {"t": "制造技能提升点数", "d": "制造成功触发技能提升时获得的点数。"},
"SkillGain.Defense": {"t": "防御技能提升点数", "d": "防御成功触发技能提升时获得的点数。"},
"SkillGain.Gathering": {"t": "采集技能提升点数", "d": "采集成功触发技能提升时获得的点数。"},
"CoaBots.RandomSpawn.DefaultCount": {
"t": "单次生成命令创建数量",
"d": "当生成命令未指定数量时,默认创建的机器人数量。"
+5 -3
View File
@@ -48,13 +48,13 @@ export interface ServiceStatus {
}
export interface StatusView {
observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null };
observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null };
busy: boolean;
path_exists: boolean;
}
export type RealmMode = "coa" | "wildcard" | "reborn";
export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean }
export interface RealmProfiles { active: RealmMode; wildcard_created: boolean; reborn_created: boolean; reborn_supported: boolean; supported: boolean; recovery_pending: boolean; simultaneous: boolean; secondary_world_port: number | null; secondary_running: boolean; with_reborn: boolean; reborn_world_port: number | null; reborn_running: boolean }
export interface DatabaseCheck {
realm: RealmMode;
migrations: { id: string; db: string; status: "applied" | "pending" | "failed"; error: string | null }[];
@@ -257,7 +257,7 @@ export interface ReportContext {
bots_version: string | null;
}
export type ReportTargetId = "manager" | "companions" | "squid";
export type ReportTargetId = "manager" | "companions" | "squid" | "custom-races" | "content-scaling";
/** A place a problem report can go: its GitHub repository as `owner/name`. */
export interface ReportTarget {
@@ -429,6 +429,7 @@ export interface FriendsStatus {
auth_port: number;
world_port: number;
secondary_world_port?: number | null;
reborn_world_port?: number | null;
}
export interface InternetCheck {
@@ -472,6 +473,7 @@ 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 }),
realmWithReborn: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_with_reborn", { id, enabled }),
checkDatabase: (id: string) => invoke<DatabaseCheck[]>("check_database", { id }),
repairServer: (id: string) => invoke<RepairReport>("repair_server", { id }),
defaultInstallDir: () => invoke<string>("default_install_dir"),
+48
View File
@@ -0,0 +1,48 @@
import { useEffect, useState } from "react";
import { api, type RealmMode } from "@/lib/api";
import type { PublishState, RealmPublishStatus } from "@/lib/registry";
export const REALM_LABEL: Record<RealmMode, string> = { coa: "Conquest of Azeroth", wildcard: "Wildcard", reborn: "Warcraft Reborn" };
/** One realm of this server that can be listed publicly. */
export interface PublishRealm {
/** The main realm keeps the plain id it was published under; each realm that starts next to it has its own. */
localId: string;
mode: RealmMode;
label: string;
/** The server name; the realms that start next to the main one get their realm name added. */
defaultName: string;
}
/** The realms this server runs, main realm first; `null` until they are known. */
export function usePublishRealms(serverId: string, serverName: string): PublishRealm[] | null {
const [realms, setRealms] = useState<PublishRealm[] | null>(null);
useEffect(() => {
let alive = true;
const build = (active: RealmMode, extra: RealmMode[]) => [
{ localId: `srv-${serverId}`, mode: active, label: REALM_LABEL[active], defaultName: serverName },
...extra.map((mode) => ({ localId: `srv-${serverId}:${mode}`, mode, label: REALM_LABEL[mode], defaultName: `${serverName} · ${REALM_LABEL[mode]}` })),
];
void api.realmProfiles(serverId).then((r) => {
if (!alive) return;
const extra: RealmMode[] = [];
if (r.simultaneous) extra.push(r.active === "coa" ? "wildcard" : "coa");
if (r.with_reborn) extra.push("reborn");
setRealms(build(r.active, extra));
}).catch(() => { if (alive) setRealms(build("coa", [])); });
return () => { alive = false; };
}, [serverId, serverName]);
return realms;
}
export function stateTone(state: PublishState | undefined): string {
if (state === "online") return "text-ok";
if (state === "rejected") return "text-bad";
if (state === "retrying" || state === "realm_stopped" || state === "waiting_for_realm") return "text-warn";
return "text-muted";
}
/** Listed on the public list now (or being removed from it). */
export function isListed(s: RealmPublishStatus | undefined): boolean {
return !!s && (s.enabled || s.state === "unpublishing");
}
+3 -1
View File
@@ -31,7 +31,9 @@ export function reportBody(r: ReportInput): string {
`**Windows version:** ${r.windows || "unknown"} `,
`**Fresh install or imported server:** ${r.installKind === "new" ? "Fresh install" : "Imported server"} `,
...(r.serverVersion ? [`**Server version:** ${r.serverVersion} `] : []),
...(r.target !== "manager" ? [`**Bot system:** ${r.target === "squid" ? "SQUID Playerbots" : "CoA Companions"}${r.botsVersion ? ` ${r.botsVersion}` : ""} `] : []),
...(r.target === "squid" || r.target === "companions" ? [`**Bot system:** ${r.target === "squid" ? "SQUID Playerbots" : "CoA Companions"}${r.botsVersion ? ` ${r.botsVersion}` : ""} `] : []),
...(r.target === "custom-races" ? ["**Component:** Custom Races "] : []),
...(r.target === "content-scaling" ? ["**Component:** Content Scaling "] : []),
"",
"**What happened?** ",
text(r.what, "Describe the problem."),
+1
View File
@@ -176,6 +176,7 @@ export function FriendsPage({ serverId }: { serverId: string }) {
</Line>
</ul>
{st.secondary_world_port && <p className="mt-3 text-sm text-muted">{t("realm.secondPort", { port: st.secondary_world_port })}</p>}
{st.reborn_world_port && <p className="mt-3 text-sm text-muted">{t("realm.rebornPort", { port: st.reborn_world_port })}</p>}
</Card>
<div className="mt-6 grid gap-3">
+42 -7
View File
@@ -10,6 +10,10 @@ import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
import { RealmlistMenu } from "@/screens/RealmlistMenu";
import { RealmPicker } from "@/screens/RealmPicker";
import { CrashHistoryModal } from "@/screens/CrashHistoryModal";
import { ListingChip } from "@/screens/PublishCard";
import { PublishRealmDialog } from "@/screens/PublishDialog";
import { useRegistryStatus } from "@/lib/registry";
import { usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import { useAutoRestart } from "@/lib/autoRestartPrefs";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -72,15 +76,15 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const human = useHuman();
const [status, setStatus] = useState<StatusView | null>(null);
// With both worlds started together, each realm gets its own card; the first realm owns the database and auth.
const [realms, setRealms] = useState<{ first: string; second: string } | null>(null);
const bothWorlds = !!status?.observed.secondary_world;
const [realms, setRealms] = useState<{ first: string; second: string; reborn: string } | null>(null);
const bothWorlds = !!status?.observed.secondary_world || !!status?.observed.reborn_world;
useEffect(() => {
if (!bothWorlds) { setRealms(null); return; }
let alive = true;
void api.realmProfiles(server.id).then((r) => {
if (!alive) return;
const name = (m: "coa" | "wildcard" | "reborn") => (m === "coa" ? "Conquest of Azeroth" : m === "reborn" ? "Warcraft Reborn" : "Wildcard");
setRealms({ first: name(r.active), second: name(r.active === "coa" ? "wildcard" : "coa") });
setRealms({ first: name(r.active), second: name(r.active === "coa" ? "wildcard" : "coa"), reborn: name("reborn") });
}).catch(() => { if (alive) setRealms(null); });
return () => { alive = false; };
}, [bothWorlds, server.id]);
@@ -114,6 +118,14 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
const [crashCount, setCrashCount] = useState(0);
const crashCountRef = useRef(0);
const [showCrashModal, setShowCrashModal] = useState(false);
const publishRealms = usePublishRealms(server.id, server.name);
const { status: registry } = useRegistryStatus(5000);
const [publishing, setPublishing] = useState<PublishRealm | null>(null);
// The realm a card shows: the first card is the main realm, then the realm that starts next to it, then Warcraft Reborn.
const chipOf = (realm: PublishRealm | undefined) => realm && <ListingChip status={registry?.realms.find((r) => r.local_id === realm.localId)} hasUrl={!!registry?.url} onOpen={() => setPublishing(realm)} />;
const mainRealm = publishRealms?.[0];
const secondRealm = publishRealms?.find((r) => r !== mainRealm && r.mode !== "reborn");
const rebornRealm = publishRealms?.find((r) => r !== mainRealm && r.mode === "reborn");
const [hasCrashHistory, setHasCrashHistory] = useState(false);
const [crashLoopPaused, setCrashLoopPaused] = useState(false);
const [crashRestartNotice, setCrashRestartNotice] = useState<string | null>(null);
@@ -292,8 +304,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
);
}
const { mysql, auth, world, secondary_world } = status.observed;
const all = [mysql, auth, world, ...(secondary_world ? [secondary_world] : [])];
const { mysql, auth, world, secondary_world, reborn_world } = status.observed;
const all = [mysql, auth, world, ...(secondary_world ? [secondary_world] : []), ...(reborn_world ? [reborn_world] : [])];
const running = all.every((s) => s.state === "running");
const anyUp = all.some((s) => s.state !== "stopped");
const transitioning = action !== null || status.busy || realmBusy;
@@ -317,7 +329,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
<RealmPicker serverId={server.id} running={anyUp} disabled={transitioning || upd.applying} onBusy={setRealmBusy} onChanged={() => { onRealmChanged(); void poll(); }} />
<Card className="mt-6 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.first} · ${t("overview.server")}` : t("overview.server")}</span>{chipOf(mainRealm)}</div>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className={cn("flex items-center gap-3 text-3xl font-semibold", tone)} role="status" aria-live="polite">
<span
@@ -565,7 +577,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
{secondary_world && (
<Card className="mt-4 p-7">
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</div>
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.second} · ${t("overview.server")}` : t("realm.secondWorld")}</span>{chipOf(secondRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", secondary_world.state === "running" ? "text-ok" : secondary_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
@@ -585,6 +597,28 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
</Card>
)}
{reborn_world && (
<Card className="mt-4 p-7">
<div className="mb-1 flex items-center justify-between gap-3 text-xs font-medium uppercase tracking-[0.14em] text-muted"><span>{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</span>{chipOf(rebornRealm)}</div>
<div
className={cn("flex items-center gap-3 text-3xl font-semibold", reborn_world.state === "running" ? "text-ok" : reborn_world.state === "starting" || transitioning ? "text-warn" : "text-muted")}
role="status"
aria-live="polite"
>
<span aria-hidden className={cn("h-3 w-3 rounded-full", reborn_world.state === "running" ? "bg-ok" : reborn_world.state === "starting" || transitioning ? "bg-warn" : "bg-muted/50")} />
{reborn_world.state === "running" ? t("status.online") : reborn_world.state === "starting" ? t("status.starting") : t("status.offline")}
</div>
<div className="mt-5 divide-y divide-line border-y border-line">
<Row label={t("overview.world")} s={reborn_world} />
</div>
<dl className="mt-4 text-sm">
<dt className="text-muted">{t("overview.uptime")}</dt>
<dd className="mt-0.5 text-lg">{reborn_world.state === "running" ? formatUptime(reborn_world.uptime_secs) : "—"}</dd>
</dl>
<p className="mt-3 text-xs text-muted">{t("realm.bothRunning")}</p>
</Card>
)}
{conflict && !anyUp && (
<Card className="mt-4 border-warn/40 p-4" role="alert">
<p className="font-medium text-warn">{t("overview.portTitle")}</p>
@@ -627,6 +661,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
/>
)}
{publishing && <PublishRealmDialog realm={publishing} onClose={() => setPublishing(null)} />}
{showCrashModal && (
<CrashHistoryModal
serverId={server.id}
+49 -101
View File
@@ -1,116 +1,64 @@
import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { asUiError } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { useRegistryStatus } from "@/lib/registry";
import { isListed, stateTone, usePublishRealms, type PublishRealm } from "@/lib/publishRealms";
import type { RealmPublishStatus } from "@/lib/registry";
import { PublishAllDialog, PublishRealmDialog } from "@/screens/PublishDialog";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
/** A small button on a realm card: the listing state of that realm; it opens the window to publish or configure it. */
export function ListingChip({ status, hasUrl, onOpen }: { status: RealmPublishStatus | undefined; hasUrl: boolean; onOpen: () => void }) {
const t = useT();
const listed = isListed(status);
if (!listed && !hasUrl) return null;
return (
<button
type="button"
onClick={onOpen}
className={cn("inline-flex cursor-pointer items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium normal-case tracking-normal transition-colors", listed ? "border-line bg-card-2 hover:border-gold/40" : "border-gold/40 text-gold hover:bg-gold/10")}
title={t("registry.title")}
>
{listed ? <span className={stateTone(status?.state)}>{t(`registry.short.${status!.state}` as Key)}</span> : t("registry.publishShort")}
</button>
);
}
/** Publishing this server's realm to the central Registry: a name, a description, a language. Nothing else leaves this machine. */
/** The public listing of this server's realms: one line per realm; the form opens in a window. */
export function PublishCard({ serverId, serverName }: { serverId: string; serverName: string }) {
const t = useT();
const localId = `srv-${serverId}`;
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(serverName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [allowPortable, setAllowPortable] = useState(false);
const [existingOnly, setExistingOnly] = useState(false);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setAllowPortable(mine.allow_portable); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.allow_portable, mine?.route]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); await refresh(); setAccessSaved(true); } catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
}
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
const tone = mine?.state === "online" ? "text-ok" : mine?.state === "rejected" ? "text-bad" : mine?.state === "retrying" || mine?.state === "realm_stopped" || mine?.state === "waiting_for_realm" ? "text-warn" : "text-muted";
const realms = usePublishRealms(serverId, serverName);
const { status } = useRegistryStatus();
const [open, setOpen] = useState<PublishRealm | "all" | null>(null);
if (!realms) return null;
const listed = (r: PublishRealm) => isListed(status?.realms.find((s) => s.local_id === r.localId));
const someUnlisted = realms.some((r) => !listed(r));
return (
<Card className="mt-6 p-6">
<h2 className="font-semibold">{t("registry.title")}</h2>
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="font-semibold">{t("registry.title")}</h2>
{realms.length > 1 && someUnlisted && <Button size="sm" onClick={() => setOpen("all")}>{t("registry.publishAll")}</Button>}
</div>
<p className="mt-1 text-sm text-muted">{t("registry.text")}</p>
{!published && <>
<label htmlFor="registry-name" className="mt-4 block text-sm font-medium">{t("registry.name")}</label>
<input id="registry-name" value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<label htmlFor="registry-description" className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id="registry-description" value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<label htmlFor="registry-language" className="mt-3 block text-sm font-medium">{t("registry.language")}</label>
<select id="registry-language" value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
<label htmlFor="registry-region" className="mt-3 block text-sm font-medium">{t("registry.region")}</label>
<input id="registry-region" value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void run(() => realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim()))}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", tone)} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && (published || mine.state === "unpublishing") && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" data-testid="allow-portable" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
<label htmlFor="access-route" className="mt-3 block font-medium">{t("access.route")}</label>
<input id="access-route" value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid="access-route" />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
<p className={cn("mt-2 text-xs", host?.relay?.connected ? "text-ok" : "text-warn")} data-testid="relay-link">{host?.relay?.connected ? t("access.relayUp") : t("access.relayDown")}{host?.relay?.last_error ? ` — ${host.relay.last_error}` : ""}</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
<ul className="mt-4 divide-y divide-line border-y border-line">
{realms.map((r) => {
const mine = status?.realms.find((s) => s.local_id === r.localId);
return (
<li key={r.localId} className="flex flex-wrap items-center justify-between gap-3 py-3">
<div>
<p className="font-medium">{r.label}</p>
<p className={cn("text-xs", stateTone(isListed(mine) ? mine?.state : undefined))} data-state={mine?.state}>{t(`registry.short.${isListed(mine) ? mine!.state : "disabled"}` as Key)}</p>
</div>
<Button size="sm" onClick={() => setOpen(r)}>{isListed(mine) ? t("registry.configure") : t("registry.publishShort")}</Button>
</li>
);
})}
</ul>
{!status?.url && <p className="mt-3 text-xs text-muted">{t("registry.noUrl")}</p>}
{open === "all" && <PublishAllDialog realms={realms} onClose={() => setOpen(null)} />}
{open && open !== "all" && <PublishRealmDialog realm={open} onClose={() => setOpen(null)} />}
</Card>
);
}
+229
View File
@@ -0,0 +1,229 @@
import { useEffect, useState, type ReactNode } from "react";
import { Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { cn } from "@/lib/utils";
import { useT, type Key } from "@/i18n";
import { asUiError } from "@/lib/api";
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
import { asControlError, control, type ControlStatus } from "@/lib/control";
import { isListed, stateTone, type PublishRealm } from "@/lib/publishRealms";
const LANGUAGES = ["en", "ru", "de", "fr", "es", "zh", "pt", "pl", "uk"];
function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
const t = useT();
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 md:p-6" role="presentation" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
<Card className="flex max-h-[88vh] w-full max-w-xl flex-col p-6 shadow-2xl" role="dialog" aria-modal="true" aria-label={title}>
<div className="flex items-center justify-between border-b border-line pb-4">
<h2 className="text-lg font-semibold">{title}</h2>
<button type="button" onClick={onClose} className="cursor-pointer text-muted transition-colors hover:text-ink" aria-label={t("btn.close")}>
<X className="h-5 w-5" aria-hidden />
</button>
</div>
<div className="flex-1 overflow-y-auto pt-4">{children}</div>
</Card>
</div>
);
}
/** The name, description, language and region of a listing; the fields are the same for one realm and for all of them. */
function ListingFields({ idPrefix, name, setName, description, setDescription, language, setLanguage, region, setRegion, hideName }: {
idPrefix: string; name: string; setName: (v: string) => void; description: string; setDescription: (v: string) => void;
language: string; setLanguage: (v: string) => void; region: string; setRegion: (v: string) => void; hideName?: boolean;
}) {
const t = useT();
return <>
{!hideName && <>
<label htmlFor={`${idPrefix}-name`} className="block text-sm font-medium">{t("registry.name")}</label>
<input id={`${idPrefix}-name`} value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
</>}
<label htmlFor={`${idPrefix}-description`} className="mt-3 block text-sm font-medium">{t("registry.description")}</label>
<textarea id={`${idPrefix}-description`} value={description} rows={3} onChange={(e) => setDescription(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" />
<p className="mt-1 text-xs text-muted">{t("registry.descriptionHint")}</p>
<div className="mt-3 flex flex-wrap gap-4">
<div>
<label htmlFor={`${idPrefix}-language`} className="block text-sm font-medium">{t("registry.language")}</label>
<select id={`${idPrefix}-language`} value={language} onChange={(e) => setLanguage(e.target.value)} className="mt-1 rounded-md border border-line bg-card px-3 py-2">
{LANGUAGES.map((l) => <option key={l} value={l}>{l}</option>)}
</select>
</div>
<div>
<label htmlFor={`${idPrefix}-region`} className="block text-sm font-medium">{t("registry.region")}</label>
<input id={`${idPrefix}-region`} value={region} maxLength={16} placeholder="EU" onChange={(e) => setRegion(e.target.value)} className="mt-1 w-32 rounded-md border border-line bg-card px-3 py-2" />
</div>
</div>
</>;
}
/** Who may join and how: shown before publishing, so the choice is made once, not found later. */
function JoinChoices({ existingOnly, setExistingOnly, allowPortable, setAllowPortable }: { existingOnly: boolean; setExistingOnly: (v: boolean) => void; allowPortable: boolean; setAllowPortable: (v: boolean) => void }) {
const t = useT();
return (
<div className="mt-4 rounded-md border border-line p-3 text-sm">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
</div>
);
}
/** Publishing, stopping and the access options of one realm. */
export function PublishRealmDialog({ realm, onClose }: { realm: PublishRealm; onClose: () => void }) {
const t = useT();
const { localId } = realm;
const { status, refresh } = useRegistryStatus();
const mine = status?.realms.find((r) => r.local_id === localId);
const published = !!mine?.enabled;
const [name, setName] = useState(realm.defaultName);
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// New listings start with portable characters allowed and accounts created for new players; the choice is shown before publishing.
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [route, setRoute] = useState("");
const [accessSaved, setAccessSaved] = useState(false);
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
const load = () => void control.status().then(setCtl).catch(() => {});
load();
const timer = setInterval(load, 3000);
return () => clearInterval(timer);
}, []);
useEffect(() => { if (mine) { setExistingOnly(mine.existing_only); setAllowPortable(mine.allow_portable); setRoute(mine.route ?? ""); } }, [mine?.existing_only, mine?.allow_portable, mine?.route]);
useEffect(() => {
if (mine && mine.display_name) { setName(mine.display_name); setDescription(mine.description); setLanguage(mine.language || "en"); setRegion(mine.region ?? ""); }
}, [mine?.display_name, mine?.description, mine?.language]);
async function saveAccess() {
setBusy(true); setError(null); setAccessSaved(false);
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); await refresh(); setAccessSaved(true); } catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
}
async function run(action: () => Promise<void>) {
setBusy(true);
setError(null);
try { await action(); await refresh(); } catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
async function publish() {
setBusy(true);
setError(null);
try {
await realmRegistry.publish(localId, name, description, language, region.trim() === "" ? null : region.trim());
// Saving the joining options needs the listing to exist; if it cannot be saved now (for example the server is running), the options stay available below.
try { await control.setAccess(localId, existingOnly, allowPortable, route.trim() === "" ? null : route.trim()); }
catch (e) { setError(t("registry.accessFailed", { reason: asControlError(e).message })); }
await refresh();
} catch (e) { setError(asUiError(e).technical); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.dialogTitle", { realm: realm.label })} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.text")}</p>
{!published && <div className="mt-4">
<ListingFields idPrefix={`pub-${localId}`} name={name} setName={setName} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url || name.trim() === ""} onClick={() => void publish()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publish")}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" role="status">
<p className={cn("font-medium", stateTone(mine.state))} data-state={mine.state}>{t(`registry.state.${mine.state}` as Key)}</p>
<p className="mt-1 text-xs text-muted">{mine.display_name}{mine.metadata_revision ? ` · ${t("registry.revision", { n: mine.metadata_revision })}` : ""}</p>
{mine.last_error && <p className="mt-1 text-xs text-warn">{mine.last_error}</p>}
{mine.state === "retrying" && mine.retry_in_secs !== null && <p className="mt-1 text-xs text-muted">{t("registry.retryIn", { s: mine.retry_in_secs })}</p>}
<div className="mt-3 flex gap-2">
{mine.state === "rejected" && <Button size="sm" onClick={() => void run(async () => { await realmRegistry.retry(localId); })}>{t("registry.retry")}</Button>}
<Button size="sm" disabled={busy} onClick={() => void run(() => realmRegistry.unpublish(localId))}>{t("registry.stop")}</Button>
</div>
</div>}
{mine && isListed(mine) && <div className="mt-4 rounded-md border border-line p-3 text-sm" data-testid="access-options">
<p className="font-medium">{t("access.title")}</p>
<p className="mt-1 text-xs text-muted">{t("access.text")}</p>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={existingOnly} onChange={(e) => setExistingOnly(e.target.checked)} className="mt-1" data-testid="existing-only" /><span>{t("access.existingOnly")}<span className="block text-xs text-muted">{t("access.existingOnlyHint")}</span></span></label>
<label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={allowPortable} onChange={(e) => setAllowPortable(e.target.checked)} className="mt-1" data-testid="allow-portable" /><span>{t("access.allowPortable")}<span className="block text-xs text-muted">{t("access.allowPortableHint")}</span></span></label>
<label htmlFor={`access-route-${localId}`} className="mt-3 block font-medium">{t("access.route")}</label>
<input id={`access-route-${localId}`} value={route} placeholder="play.example.org:3724" onChange={(e) => setRoute(e.target.value)} className="mt-1 w-full rounded-md border border-line bg-card px-3 py-2" data-testid="access-route" />
<p className="mt-1 text-xs text-muted">{t("access.routeHint")}</p>
<div className="mt-3 flex items-center gap-3">
<Button size="sm" disabled={busy} onClick={() => void saveAccess()}>{t("access.save")}</Button>
{accessSaved && <span className="text-xs text-ok" role="status">{t("access.saved")}</span>}
</div>
<p className={cn("mt-3 text-xs", link?.connected ? "text-ok" : "text-muted")} data-testid="control-link" data-connected={link?.connected ? "yes" : "no"}>
{link?.connected ? t("access.linkUp") : t("access.linkDown")}{link?.last_error && !link.connected ? ` — ${link.last_error}` : ""}
</p>
<p className={cn("mt-2 text-xs", host?.relay?.connected ? "text-ok" : "text-warn")} data-testid="relay-link">{host?.relay?.connected ? t("access.relayUp") : t("access.relayDown")}{host?.relay?.last_error ? ` — ${host.relay.last_error}` : ""}</p>
{ctl && ctl.secret_store === "file" && <p className="mt-1 text-xs text-warn">{t("access.fileStore")}</p>}
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
/** One description, language and region for every realm that is not listed yet. */
export function PublishAllDialog({ realms, onClose }: { realms: PublishRealm[]; onClose: () => void }) {
const t = useT();
const { status, refresh } = useRegistryStatus();
const [description, setDescription] = useState("");
const [language, setLanguage] = useState("en");
const [region, setRegion] = useState("");
const [allowPortable, setAllowPortable] = useState(true);
const [existingOnly, setExistingOnly] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const todo = realms.filter((r) => !isListed(status?.realms.find((s) => s.local_id === r.localId)));
async function publishAll() {
setBusy(true); setError(null);
try {
for (const r of todo) await realmRegistry.publish(r.localId, r.defaultName, description, language, region.trim() === "" ? null : region.trim());
// The joining options are saved realm by realm; one that cannot be saved now (for example the server is running) does not stop the others.
const failed: string[] = [];
for (const r of todo) {
try { await control.setAccess(r.localId, existingOnly, allowPortable, null); }
catch (e) { failed.push(`${r.label}: ${asControlError(e).message}`); }
}
await refresh();
if (failed.length === 0) onClose();
else setError(t("registry.accessFailed", { reason: failed.join(" · ") }));
} catch (e) { setError(asUiError(e).technical); await refresh(); } finally { setBusy(false); }
}
return (
<Modal title={t("registry.publishAll")} onClose={onClose}>
<p className="text-sm text-muted">{t("registry.publishAllText")}</p>
<ul className="mt-3 space-y-1 text-sm">
{realms.map((r) => <li key={r.localId} className="flex justify-between gap-3"><span>{r.defaultName}</span><span className="text-muted">{todo.includes(r) ? t("registry.short.disabled") : t("registry.alreadyListed")}</span></li>)}
</ul>
{todo.length > 0 && <div className="mt-4">
<ListingFields idPrefix="pub-all" name="" setName={() => undefined} description={description} setDescription={setDescription} language={language} setLanguage={setLanguage} region={region} setRegion={setRegion} hideName />
<JoinChoices existingOnly={existingOnly} setExistingOnly={setExistingOnly} allowPortable={allowPortable} setAllowPortable={setAllowPortable} />
<div className="mt-4">
<Button variant="primary" disabled={busy || !status?.url} onClick={() => void publishAll()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}{t("registry.publishAllButton", { n: todo.length })}
</Button>
{!status?.url && <p className="mt-2 text-xs text-muted">{t("registry.noUrl")}</p>}
</div>
</div>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Modal>
);
}
+6 -4
View File
@@ -13,6 +13,8 @@ export function RealmPicker({ serverId, running, disabled, onChanged, onBusy }:
const [selected, setSelected] = useState<RealmMode>("coa");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// More than one world starts together: the main realm cannot be switched then.
const together = !!view && (view.simultaneous || view.with_reborn);
useEffect(() => {
let alive = true;
void api.realmProfiles(serverId).then(v => { if (alive) { setView(v); setSelected(v.active); } }).catch(e => { if (alive) setError(asUiError(e).technical); });
@@ -34,18 +36,18 @@ export function RealmPicker({ serverId, running, disabled, onChanged, onBusy }:
<div className="flex flex-wrap items-center gap-3">
<Layers className="h-5 w-5 text-gold" aria-hidden />
<label htmlFor="realm-profile" className="font-medium">{t("realm.profileLabel")}</label>
{view?.simultaneous ? <span className="text-sm text-muted">Conquest of Azeroth + Wildcard</span> : <select id="realm-profile" value={selected} disabled={!view || disabled || busy} onChange={e => setSelected(e.target.value as RealmMode)} className="min-w-52 rounded-md border border-line bg-card-2 px-3 py-2 text-ink">
{together ? <span className="text-sm text-muted">{[view.active, ...(view.simultaneous ? [view.active === "coa" ? "wildcard" : "coa"] : []), ...(view.with_reborn ? ["reborn"] : [])].map(m => m === "coa" ? "Conquest of Azeroth" : m === "reborn" ? "Warcraft Reborn" : "Wildcard").join(" + ")}</span> : <select id="realm-profile" value={selected} disabled={!view || disabled || busy} onChange={e => setSelected(e.target.value as RealmMode)} className="min-w-52 rounded-md border border-line bg-card-2 px-3 py-2 text-ink">
<option value="coa">Conquest of Azeroth</option>
<option value="wildcard" disabled={!view?.supported && !view?.wildcard_created}>Wildcard · Darkmoon</option>
<option value="reborn" disabled={!view?.reborn_supported && !view?.reborn_created}>Warcraft Reborn</option>
</select>}
{view && !view.simultaneous && (selected !== view.active || view.recovery_pending) && <Button size="sm" disabled={disabled || busy} onClick={() => void select()}>
{view && !together && (selected !== view.active || view.recovery_pending) && <Button size="sm" disabled={disabled || busy} onClick={() => void select()}>
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
{busy ? t("realm.switching") : selected === "wildcard" && !view.wildcard_created ? t("realm.create") : selected === "reborn" && !view.reborn_created ? t("realm.rebornCreate") : running ? t("realm.restart") : t("realm.select")}
</Button>}
{view && !view.simultaneous && <span className="ml-auto text-xs text-muted">{t("realm.active", { name: view.active === "coa" ? "CoA" : view.active === "reborn" ? "Warcraft Reborn" : "Wildcard" })}</span>}
{view && !together && <span className="ml-auto text-xs text-muted">{t("realm.active", { name: view.active === "coa" ? "CoA" : view.active === "reborn" ? "Warcraft Reborn" : "Wildcard" })}</span>}
</div>
<p className="mt-3 text-sm text-muted">{t(view?.simultaneous ? "realm.bothRunning" : "realm.separate")}</p>
<p className="mt-3 text-sm text-muted">{t(together ? "realm.bothRunning" : "realm.separate")}</p>
{selected === "reborn" && <p className="mt-2 text-sm text-warn">{t("realm.rebornModules")}</p>}
{view && selected === "reborn" && !view.reborn_supported && <p className="mt-2 text-sm text-warn">{t("realm.rebornUpdate")}</p>}
{selected === "wildcard" && <p className="mt-2 text-sm text-warn">{t("realm.modules")}</p>}
+12 -5
View File
@@ -13,20 +13,27 @@ export function RealmStartupSettings({ serverId }: { serverId: string }) {
void api.realmProfiles(serverId).then(v => { if (alive) setView(v); }).catch(e => { if (alive) setError(asUiError(e).technical); });
return () => { alive = false; };
}, [serverId]);
async function change(enabled: boolean) {
async function change(realm: "wildcard" | "reborn", enabled: boolean) {
setBusy(true); setError(null);
try { setView(await api.realmSimultaneous(serverId, enabled)); }
try { setView(await (realm === "wildcard" ? api.realmSimultaneous : api.realmWithReborn)(serverId, enabled)); }
catch (e) { setError(asUiError(e).technical); }
finally { setBusy(false); }
}
return <Card className="mt-6 p-6" aria-busy={busy}>
<h2 className="font-semibold">{t("realm.startupTitle")}</h2>
<label className="mt-3 flex items-center gap-3">
<input type="checkbox" checked={view?.simultaneous ?? false} disabled={!view || busy || !view.supported || view.active === "reborn"} onChange={e => void change(e.target.checked)} />
<input type="checkbox" checked={view?.simultaneous ?? false} disabled={!view || busy || !view.supported || view.active === "reborn"} onChange={e => void change("wildcard", e.target.checked)} />
<span>{t("realm.simultaneous")}</span>
</label>
<p className="mt-2 text-sm text-muted">{t("realm.simultaneousHint")}</p>
{view?.simultaneous && <p className="mt-2 text-sm text-muted">{t("realm.secondPort", { port: view.secondary_world_port ?? "—" })}</p>}
{view?.simultaneous && <p className="mt-1 text-sm text-muted">{t("realm.secondPort", { port: view.secondary_world_port ?? "—" })}</p>}
<label className="mt-3 flex items-center gap-3">
<input type="checkbox" checked={view?.with_reborn ?? false} disabled={!view || busy || !view.reborn_supported || view.active !== "coa"} onChange={e => void change("reborn", e.target.checked)} />
<span>{t("realm.withReborn")}</span>
</label>
{view?.with_reborn && <p className="mt-1 text-sm text-muted">{t("realm.rebornPort", { port: view.reborn_world_port ?? "—" })}</p>}
{view && view.active !== "coa" && !view.with_reborn && <p className="mt-1 text-sm text-warn">{t("realm.rebornNeedsCoa")}</p>}
{view?.simultaneous && view.with_reborn && <p className="mt-3 text-sm">{t("realm.allThree")}</p>}
<p className="mt-3 text-sm text-muted">{t("realm.simultaneousHint")}</p>
{busy && <p className="mt-2 text-sm" role="status">{t("realm.preparing")}</p>}
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
</Card>;
+1 -1
View File
@@ -15,7 +15,7 @@ export function RemoveServerCard({ serverId, path, onForget }: { serverId: strin
let active = true;
void api.status(serverId).then((s) => {
if (!active) return;
const all = [s.observed.mysql, s.observed.auth, s.observed.world, ...(s.observed.secondary_world ? [s.observed.secondary_world] : [])];
const all = [s.observed.mysql, s.observed.auth, s.observed.world, ...(s.observed.secondary_world ? [s.observed.secondary_world] : []), ...(s.observed.reborn_world ? [s.observed.reborn_world] : [])];
setRunning(all.some((x) => x.state === "running" || x.state === "starting" || x.state === "stopping"));
}).catch(() => { /* an unreadable status must not hide the button */ });
return () => { active = false; };
+2
View File
@@ -12,6 +12,8 @@ const TARGET_LABEL: Record<ReportTargetId, Key> = {
manager: "rep.target.manager",
companions: "rep.target.companions",
squid: "rep.target.squid",
"custom-races": "rep.target.custom-races",
"content-scaling": "rep.target.content-scaling",
};
const FALLBACK: ReportTarget = { id: "manager", repo: "Corfirean/coa-server-manager", ours: true };