Compare commits

..
Author SHA1 Message Date
Дмитрий dc97095bd6 Prepare Manager 0.9.0 candidate and translate integrated realm controls 2026-10-28 08:25:41 +05:00
Дмитрий c6d8e5554d Integrate Manager features and preserve portable controls in the realm dialog 2026-10-28 08:23:35 +05:00
Дмитрий 0900a4a143 Merge remote-tracking branch 'origin/feat/publish-realms-dialog' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий eeb102e260 Merge remote-tracking branch 'origin/feat/realms-start-together' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий ea376a66d3 Merge remote-tracking branch 'origin/feat/progression-modes-setting' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий 88747c8da1 feat: portable play settings, improved offline messaging, and system tray support 2026-10-28 08:14:36 +05:00
Дмитрий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
ДмитрийandClaude Sonnet 5.5 55b0087455 feat(modules): choose Parallel or Global scaling progression in module settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 15:59:29 +05:00
50 changed files with 1423 additions and 295 deletions

No files matched your search

Generated
+3 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"chrono",
"coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.8.2"
version = "0.9.0"
dependencies = [
"coa-control-proto",
"coa-core",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.8.2"
version = "0.9.0"
edition = "2021"
license = "AGPL-3.0-only"
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Choose Parallel or Global level scaling in module settings
---
Content Scaling progression can now be set to Parallel (Classic over 1 to the level cap, TBC and WotLK over 45 to the cap) or Global (all expansions over 1 to the cap) without editing the config file by hand.
@@ -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: 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.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Control portable characters and keep Manager running in the system tray
---
Realm access settings can enable portable characters. Closing the window keeps Manager in the tray, with commands to reopen or exit. Offline realm messages explain why players cannot connect.
+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();
+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();
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.8.2",
"version": "0.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.8.2",
"version": "0.9.0",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.8.2",
"version": "0.9.0",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+11
View File
@@ -445,6 +445,17 @@
"max": 3600000,
"unit": "ms"
},
{
"key": "PortableSession.Enable",
"type": "bool",
"category": "characters",
"title": "Portable characters",
"description": "Allow players to play on this realm with portable characters saved in their Manager.",
"default": true,
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CharactersPerAccount",
"type": "int",
+1 -1
View File
@@ -12,7 +12,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
+102 -7
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>,
@@ -2348,6 +2371,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
@@ -2511,6 +2535,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
@@ -2568,7 +2595,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())?,
@@ -2578,7 +2605,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() {
@@ -2586,7 +2613,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()),
@@ -2755,6 +2782,8 @@ async fn console_command(
.await
}
static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn run() {
let dir = data_dir();
let _ = coa_core::logging::init(&dir.join("logs").join("manager.log"));
@@ -2819,6 +2848,7 @@ pub fn run() {
realm_profiles,
realm_select,
realm_simultaneous,
realm_with_reborn,
check_database,
repair_server,
module_set_enabled,
@@ -2909,11 +2939,75 @@ pub fn run() {
control_cmds::join_characters,
control_cmds::join_claim
])
.on_window_event(|window, event| {
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
api.prevent_close();
let _ = window.hide();
}
})
.setup(|app| {
#[cfg(desktop)]
{
use tauri::menu::{Menu, MenuItem};
use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
use tauri::Manager;
let show = MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?;
let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?;
let menu = Menu::with_items(app, &[&show, &quit])?;
let mut builder = TrayIconBuilder::new()
.tooltip("CoA Server Manager")
.menu(&menu)
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"show" => {
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}
"quit" => {
QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
app.exit(0);
}
_ => {}
})
.on_tray_icon_event(|tray, event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
let app = tray.app_handle();
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.unminimize();
let _ = window.set_focus();
}
}
});
if let Some(icon) = app.default_window_icon() {
builder = builder.icon(icon.clone());
}
builder.build(app)?;
}
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building CoA Server Manager")
.run(|app, event| {
// the Host loop stops with the application: what it is doing is finished first, the stores keep every session
if let tauri::RunEvent::Exit = event {
.run(|app, event| match event {
tauri::RunEvent::ExitRequested { api, .. } => {
if !QUIT_REQUESTED.load(std::sync::atomic::Ordering::SeqCst) {
api.prevent_exit();
}
}
tauri::RunEvent::Exit => {
// the Host loop stops with the application: what it is doing is finished first, the stores keep every session
if let Some(rt) = app.state::<AppState>().portable.clone() {
rt.shutdown();
}
@@ -2924,6 +3018,7 @@ pub fn run() {
rt.shutdown();
}
}
_ => {}
});
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.8.2",
"version": "0.9.0",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
+6 -4
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";
+26
View File
@@ -1012,6 +1012,32 @@ const de: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Spiel-Relay verbunden",
"access.relayDown": "Spiel-Relay nicht verbunden",
"realm.withReborn": "Warcraft Reborn zusammen mit CoA starten",
"realm.rebornPort": "Warcraft Reborn-Weltport: {port}",
"realm.rebornWorld": "Warcraft Reborn-Welt",
"realm.rebornNeedsCoa": "Warcraft Reborn kann nur zusammen mit Conquest of Azeroth starten. Zuerst Conquest of Azeroth in der Übersicht auswählen.",
"realm.allThree": "Beide Optionen sind aktiv: Conquest of Azeroth, Wildcard und Warcraft Reborn starten zusammen.",
"browse.realmOffline": "Offline",
"browse.offlineWarning": "Der Server ist derzeit offline. Der Beitritt mit einem portablen Charakter ist möglich, sobald der Betreiber den Server startet.",
"registry.dialogTitle": "Öffentlicher Eintrag · {realm}",
"registry.publishAll": "Alle Realms veröffentlichen",
"registry.publishAllText": "Beschreibung, Sprache und Region gelten für alle noch nicht veröffentlichten Realms. Jeder Realm erscheint unter dem Servernamen; zusätzliche Realms erhalten ihren Realmnamen als Zusatz.",
"registry.publishAllButton": "{n} Realms veröffentlichen",
"registry.alreadyListed": "Bereits veröffentlicht",
"registry.configure": "Konfigurieren",
"registry.publishShort": "Veröffentlichen",
"registry.short.starting": "Wird veröffentlicht…",
"registry.accessFailed": "Der Realm ist veröffentlicht, aber die Beitrittsoptionen wurden nicht gespeichert: {reason}",
"registry.short.waiting_for_realm": "Nicht veröffentlicht",
"registry.short.realm_stopped": "Veröffentlicht, Realm gestoppt",
"registry.short.online": "Veröffentlicht",
"registry.short.retrying": "Verzeichnis nicht erreichbar",
"registry.short.rejected": "Vom Verzeichnis abgelehnt",
"registry.short.unpublishing": "Wird aus der Liste entfernt",
"registry.short.disabled": "Nicht veröffentlicht",
"registry.realmStoppedHint": "Der Realm ist gestoppt. Den Server starten, damit Spieler beitreten und Charaktersitzungen verfolgen können.",
"access.portableEnabled": "Portable Charaktere zulassen",
"access.portableEnabledHint": "Spieler können auf diesem Realm mit ihren im Manager gespeicherten Charakteren spielen.",
};
export default de;
+30 -4
View File
@@ -32,11 +32,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",
@@ -1019,7 +1024,7 @@ const en = {
"portable.note.blocked_ruleset": "This character is for another kind of realm.",
"portable.note.blocked_format": "This realm reads another version of the character format. Update the Manager or the realm.",
"portable.note.blocked_online_import": "This realm cannot take characters while it runs. Update the realm.",
"portable.note.blocked_sessions": "This realm cannot follow a game session. Ask its owner to enable portable play.",
"portable.note.blocked_sessions": "This realm cannot follow a game session. The server or host's Server Manager is offline, or portable play is not enabled.",
"portable.note.blocked_client_data": "The game data the Manager sees is not the data the realm loaded.",
"portable.note.blocked_progression": "The realm’s level cap is not known yet or cannot be handled. Start the realm and try again.",
"portable.note.realm_offline": "The realm cannot be reached.",
@@ -1114,9 +1119,27 @@ const en = {
"browse.noCharacter": "You have no portable character yet. Make one portable on the Characters page to see whether it can play here.",
"browse.canPlay": "Can play",
"browse.cannotPlay": "Cannot play here",
"browse.realmOffline": "Offline",
"browse.offlineWarning": "The server is currently offline. Joining with a portable character will become available once the host starts the server.",
"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",
@@ -1134,6 +1157,7 @@ const en = {
"registry.state.starting": "Starting to publish…",
"registry.state.waiting_for_realm": "Waiting for the realm to be ready…",
"registry.state.realm_stopped": "The realm is not running; it is listed as offline.",
"registry.realmStoppedHint": "The realm is currently stopped. Start the server so players can join and track character sessions.",
"registry.state.online": "Published and online.",
"registry.state.retrying": "The Registry could not be reached; trying again. Your realm is not affected.",
"registry.state.rejected": "The Registry refused this realm. Publishing is stopped.",
@@ -1193,6 +1217,8 @@ const en = {
"join.err.unavailable": "The server could not do that right now.",
"access.title": "Joining players",
"access.text": "How players who find this realm in the list get in.",
"access.portableEnabled": "Allow portable characters (portable play)",
"access.portableEnabledHint": "Allows players with Manager-saved characters to play on this realm (PortableSession.Enable).",
"access.existingOnly": "Do not create accounts for new players",
"access.existingOnlyHint": "Players can only link an account they already have on this realm.",
"access.route": "Address players connect to",
+26
View File
@@ -1012,6 +1012,32 @@ const es: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Relay del juego conectado",
"access.relayDown": "Relay del juego desconectado",
"realm.withReborn": "Iniciar Warcraft Reborn junto con CoA",
"realm.rebornPort": "Puerto del mundo de Warcraft Reborn: {port}",
"realm.rebornWorld": "Mundo de Warcraft Reborn",
"realm.rebornNeedsCoa": "Warcraft Reborn solo puede iniciarse junto con Conquest of Azeroth. Selecciona primero Conquest of Azeroth en Resumen.",
"realm.allThree": "Ambas opciones están activadas: Conquest of Azeroth, Wildcard y Warcraft Reborn se inician juntos.",
"browse.realmOffline": "Sin conexión",
"browse.offlineWarning": "El servidor está desconectado. Podrás entrar con un personaje portátil cuando el anfitrión inicie el servidor.",
"registry.dialogTitle": "Publicación · {realm}",
"registry.publishAll": "Publicar todos los reinos",
"registry.publishAllText": "Una descripción, idioma y región para todos los reinos aún no publicados. Cada reino usa el nombre del servidor; los reinos adicionales añaden su nombre.",
"registry.publishAllButton": "Publicar {n} reinos",
"registry.alreadyListed": "Ya publicado",
"registry.configure": "Configurar",
"registry.publishShort": "Publicar",
"registry.short.starting": "Publicando…",
"registry.accessFailed": "El reino está publicado, pero no se guardaron sus opciones de acceso: {reason}",
"registry.short.waiting_for_realm": "Sin publicar",
"registry.short.realm_stopped": "Publicado, reino detenido",
"registry.short.online": "Publicado",
"registry.short.retrying": "Directorio inaccesible",
"registry.short.rejected": "Rechazado por el directorio",
"registry.short.unpublishing": "Quitando de la lista",
"registry.short.disabled": "Sin publicar",
"registry.realmStoppedHint": "El reino está detenido. Inicia el servidor para que los jugadores entren y se registren las sesiones de personajes.",
"access.portableEnabled": "Permitir personajes portátiles",
"access.portableEnabledHint": "Los jugadores pueden usar en este reino sus personajes guardados en Manager.",
};
export default es;
+26
View File
@@ -1012,6 +1012,32 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"access.relay": "Relay",
"access.relayUp": "Relais de jeu connecté",
"access.relayDown": "Relais de jeu déconnecté",
"realm.withReborn": "Démarrer Warcraft Reborn avec CoA",
"realm.rebornPort": "Port du monde Warcraft Reborn : {port}",
"realm.rebornWorld": "Monde Warcraft Reborn",
"realm.rebornNeedsCoa": "Warcraft Reborn ne peut démarrer qu’avec Conquest of Azeroth. Sélectionnez d’abord Conquest of Azeroth dans la vue d’ensemble.",
"realm.allThree": "Les deux options sont activées : Conquest of Azeroth, Wildcard et Warcraft Reborn démarrent ensemble.",
"browse.realmOffline": "Hors ligne",
"browse.offlineWarning": "Le serveur est hors ligne. La connexion avec un personnage portable sera disponible lorsque l’hôte démarrera le serveur.",
"registry.dialogTitle": "Publication publique · {realm}",
"registry.publishAll": "Publier tous les royaumes",
"registry.publishAllText": "Une description, une langue et une région pour tous les royaumes non publiés. Chaque royaume utilise le nom du serveur ; les royaumes supplémentaires ajoutent leur nom.",
"registry.publishAllButton": "Publier {n} royaumes",
"registry.alreadyListed": "Déjà publié",
"registry.configure": "Configurer",
"registry.publishShort": "Publier",
"registry.short.starting": "Publication…",
"registry.accessFailed": "Le royaume est publié, mais ses options de connexion n’ont pas été enregistrées : {reason}",
"registry.short.waiting_for_realm": "Non publié",
"registry.short.realm_stopped": "Publié, royaume arrêté",
"registry.short.online": "Publié",
"registry.short.retrying": "Annuaire inaccessible",
"registry.short.rejected": "Refusé par l’annuaire",
"registry.short.unpublishing": "Retrait de la liste",
"registry.short.disabled": "Non publié",
"registry.realmStoppedHint": "Le royaume est arrêté. Démarrez le serveur pour permettre la connexion et le suivi des sessions des personnages.",
"access.portableEnabled": "Autoriser les personnages portables",
"access.portableEnabledHint": "Les joueurs peuvent utiliser sur ce royaume leurs personnages enregistrés dans Manager.",
};
export default fr;
+30 -4
View File
@@ -35,11 +35,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": "Проверить файлы и БД",
@@ -1001,7 +1006,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"portable.note.blocked_ruleset": "Этот персонаж — для реалма другого типа.",
"portable.note.blocked_format": "Реалм читает другую версию формата персонажа. Обновите Менеджер или реалм.",
"portable.note.blocked_online_import": "Этот реалм не принимает персонажей, пока работает. Обновите реалм.",
"portable.note.blocked_sessions": "Этот реалм не может следить за игровой сессией. Попросите владельца включить переносимую игру.",
"portable.note.blocked_sessions": "Этот реалм не может следить за игровой сессией. Сервер или Server Manager хоста выключен, либо в ядре не включена переносимая игра.",
"portable.note.blocked_client_data": "Игровые данные, которые видит Менеджер, не те, что загрузил реалм.",
"portable.note.blocked_progression": "Предел уровня реалма пока неизвестен или не поддерживается. Запустите реалм и попробуйте снова.",
"portable.note.realm_offline": "Реалм недоступен.",
@@ -1096,9 +1101,27 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"browse.noCharacter": "У вас пока нет переносимого персонажа. Сделайте его переносимым на странице «Персонажи», чтобы увидеть, сможет ли он играть здесь.",
"browse.canPlay": "Можно играть",
"browse.cannotPlay": "Здесь играть нельзя",
"browse.realmOffline": "Оффлайн",
"browse.offlineWarning": "Сервер сейчас не запущен хостом. Игра переносимым персонажем станет доступна, когда владелец включит сервер.",
"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": "Сохранить адрес",
@@ -1116,6 +1139,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"registry.state.starting": "Начинаю публикацию…",
"registry.state.waiting_for_realm": "Жду, пока реалм будет готов…",
"registry.state.realm_stopped": "Реалм не запущен; в списке он отмечен как недоступный.",
"registry.realmStoppedHint": "Сервер сейчас выключен. Запустите реалм, чтобы игроки могли подключаться и отслеживать сессии персонажей.",
"registry.state.online": "Опубликован и доступен.",
"registry.state.retrying": "Реестр недоступен, пробую снова. На ваш реалм это не влияет.",
"registry.state.rejected": "Реестр отклонил этот реалм. Публикация остановлена.",
@@ -1175,6 +1199,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"join.err.unavailable": "Сервер сейчас не смог этого сделать.",
"access.title": "Вход игроков",
"access.text": "Как попадают на этот мир игроки, нашедшие его в списке.",
"access.portableEnabled": "Разрешить вход переносимым персонажам (переносимая игра)",
"access.portableEnabledHint": "Позволяет игрокам с сохранёнными в Менеджере персонажами играть на этом сервере (PortableSession.Enable).",
"access.existingOnly": "Не создавать аккаунты для новых игроков",
"access.existingOnlyHint": "Игроки смогут только привязать аккаунт, который у них уже есть на этом мире.",
"access.route": "Адрес для подключения игроков",
+26
View File
@@ -1014,6 +1014,32 @@ const zh = {
"access.relay": "Relay",
"access.relayUp": "游戏中继已连接",
"access.relayDown": "游戏中继未连接",
"realm.withReborn": "与 CoA 一起启动 Warcraft Reborn",
"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 将一起启动。",
"browse.realmOffline": "离线",
"browse.offlineWarning": "服务器当前离线。服主启动服务器后,才能使用便携角色加入。",
"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.realmStoppedHint": "世界当前已停止。请启动服务器,以便玩家加入并跟踪角色会话。",
"access.portableEnabled": "允许便携角色",
"access.portableEnabledHint": "允许玩家在此服务器使用保存在 Manager 中的角色。",
} as const;
export default zh;
+4
View File
@@ -380,6 +380,10 @@
"t": "Autospeicher-Intervall",
"d": "Wie oft Spielercharaktere gespeichert werden, solange sie online sind."
},
"PortableSession.Enable": {
"t": "Portable Charaktere (portables Spiel)",
"d": "Erlaubt Spielern, mit ihren im Manager gespeicherten portablen Charakteren auf diesem Realm zu spielen."
},
"CharactersPerAccount": {
"t": "Charaktere pro Konto",
"d": "Maximale Zahl an Charakteren, die ein Konto über alle Realms hat."
+4
View File
@@ -380,6 +380,10 @@
"t": "Intervalo de autoguardado",
"d": "Con qué frecuencia se guardan los personajes de los jugadores mientras están conectados."
},
"PortableSession.Enable": {
"t": "Personajes portátiles (juego portátil)",
"d": "Permite a los jugadores jugar en este reino con personajes portátiles guardados en su Manager."
},
"CharactersPerAccount": {
"t": "Personajes por cuenta",
"d": "Máximo de personajes que puede tener una cuenta entre todos los reinos."
+4
View File
@@ -380,6 +380,10 @@
"t": "Intervalle de sauvegarde automatique",
"d": "Fréquence de sauvegarde des personnages des joueurs pendant qu’ils sont en ligne."
},
"PortableSession.Enable": {
"t": "Personnages portables (jeu portable)",
"d": "Permet aux joueurs de jouer sur ce royaume avec des personnages portables enregistrés dans leur Manager."
},
"CharactersPerAccount": {
"t": "Personnages par compte",
"d": "Nombre maximal de personnages qu’un compte peut avoir sur tous les royaumes."
+4
View File
@@ -380,6 +380,10 @@
"t": "Интервал автосохранения",
"d": "Как часто персонажи игроков сохраняются, пока они в сети."
},
"PortableSession.Enable": {
"t": "Переносимые персонажи (переносимая игра)",
"d": "Разрешает игрокам заходить на этот сервер переносимыми персонажами, сохранёнными в их Менеджере."
},
"CharactersPerAccount": {
"t": "Персонажей на учётную запись",
"d": "Наибольшее число персонажей на учётной записи во всех мирах."
+4
View File
@@ -380,6 +380,10 @@
"t": "角色数据自动保存间隔",
"d": "在线玩家角色数据写入数据库的时间间隔。"
},
"PortableSession.Enable": {
"t": "便携式角色(跨服漫游)",
"d": "允许玩家使用保存在管理器中的便携式角色进入此服务器进行游玩。"
},
"CharactersPerAccount": {
"t": "每个账号最大角色数",
"d": "单个账号在所有服务器可创建的角色总数上限。"
+4 -2
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 }[];
@@ -439,6 +439,7 @@ export interface FriendsStatus {
auth_port: number;
world_port: number;
secondary_world_port?: number | null;
reborn_world_port?: number | null;
}
export interface InternetCheck {
@@ -482,6 +483,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"),
+4 -2
View File
@@ -77,8 +77,10 @@ add(scaling + "LFG.DefaultMode", "enum", ["Dungeon Finder group", "Группа
] });
add(scaling + "LFG.DefaultChallengeSize", "int", ["Challenge group size", "Размер группы для расчёта сложности", "Gruppengröße für die Schwierigkeit", "Taille du groupe pour la difficulté", "Tamaño del grupo para dificultad", "难度目标人数"], ["0 follows actual party size. 1–40 simulates that many players. Players can override with .lfgchallenge.", "0 — реальный размер группы. 1–40 — сложность как для указанного числа игроков. Игрок может изменить через .lfgchallenge.", "0 nutzt die tatsächliche Gruppe. 1–40 simuliert diese Spielerzahl. Mit .lfgchallenge änderbar.", "0 suit le groupe réel. 1–40 simule ce nombre de joueurs. Modifiable avec .lfgchallenge.", "0 usa el grupo real. 1–40 simula ese número de jugadores. Modificable con .lfgchallenge.", "0按实际人数,1–40模拟指定人数。玩家可通过 .lfgchallenge 更改。"], { min: 0, max: 40 });
add(scaling + "GroupScaling.LockOnEncounterStart", "bool", ["Lock scaling during combat", "Фиксировать скейлинг на время боя", "Skalierung im Kampf sperren", "Figer l’adaptation en combat", "Fijar ajuste durante combate", "战斗期间锁定缩放"], ["Joining or leaving during a boss fight does not change its scaling.", "Вход и выход игроков во время боя с боссом не меняют скейлинг.", "Beitreten oder Verlassen während eines Bosskampfs ändert die Skalierung nicht.", "Les arrivées et départs pendant un boss ne changent pas l’adaptation.", "Entrar o salir durante un jefe no cambia el ajuste.", "首领战期间玩家进出不会改变缩放。"], { advanced: true });
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic boundaries follow the level cap and enabled expansions. Custom uses the levels below.", "Автоматические границы зависят от максимального уровня и включённых дополнений. Ручные используют уровни ниже.", "Automatisch folgt der Maximalstufe und Erweiterungen. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique suit le niveau maximal et les extensions. Manuel utilise les niveaux ci-dessous.", "Automático sigue el nivel máximo y las expansiones. Manual usa los niveles siguientes.", "自动边界按等级上限和启用的资料片计算,自定义使用以下等级。"], { advanced: true, options: [
add(scaling + "Progression.Mode", "enum", ["Progression boundaries", "Границы прогрессии", "Fortschrittsgrenzen", "Limites de progression", "Límites de progresión", "进度边界"], ["Automatic splits the level cap between the expansions one after another. Parallel scales Classic over 1 to the level cap and TBC and WotLK over 45 to the level cap. Global scales every expansion over 1 to the level cap. Custom uses the levels below.", "Автоматически делит максимальный уровень между дополнениями по очереди. Параллельно: классика на уровнях 1 — максимум, TBC и WotLK на 45 — максимум. Глобально: все дополнения на 1 — максимум. Вручную использует уровни ниже.", "Automatisch teilt die Maximalstufe nacheinander auf die Erweiterungen auf. Parallel skaliert Classic über 1 bis zur Maximalstufe und TBC und WotLK über 45 bis zur Maximalstufe. Global skaliert alle Erweiterungen über 1 bis zur Maximalstufe. Benutzerdefiniert nutzt die folgenden Stufen.", "Automatique répartit le niveau maximal entre les extensions l'une après l'autre. Parallèle étend Classic de 1 au niveau maximal, TBC et WotLK de 45 au niveau maximal. Global étend toutes les extensions de 1 au niveau maximal. Manuel utilise les niveaux ci-dessous.", "Automático reparte el nivel máximo entre las expansiones una tras otra. Paralelo escala Classic de 1 al nivel máximo y TBC y WotLK de 45 al nivel máximo. Global escala todas las expansiones de 1 al nivel máximo. Manual usa los niveles siguientes.", "自动:按顺序在各资料片之间分配等级上限。并行:经典旧世为 1 至等级上限,TBC 和 WotLK 为 45 至等级上限。全局:所有资料片均为 1 至等级上限。自定义:使用以下等级。"], { advanced: true, options: [
{ value: "Auto", label: ["Automatic", "Автоматически", "Automatisch", "Automatique", "Automático", "自动"] },
{ value: "Parallel", label: ["Parallel (Classic 1-cap, TBC/WotLK 45-cap)", "Параллельно (классика 1–макс., TBC/WotLK 45–макс.)", "Parallel (Classic 1–Max., TBC/WotLK 45–Max.)", "Parallèle (Classic 1–max., TBC/WotLK 45–max.)", "Paralelo (Classic 1–máx., TBC/WotLK 45–máx.)", "并行(经典 1–上限,TBC/WotLK 45–上限)"] },
{ value: "Global", label: ["Global (everything 1-cap)", "Глобально (всё на 1–макс.)", "Global (alles 1–Max.)", "Global (tout 1–max.)", "Global (todo 1–máx.)", "全局(全部 1–上限)"] },
{ value: "Custom", label: ["Custom", "Вручную", "Benutzerdefiniert", "Manuel", "Manual", "自定义"] },
] });
for (const era of ["Classic", "Tbc"]) add(scaling + `Progression.${era}End`, "int", [`${era} last level`, `Последний уровень ${era}`, `${era}-Endstufe`, `Dernier niveau ${era}`, `Último nivel ${era}`, `${era} 最高等级`], ["Used in custom progression. 0 chooses automatically.", "Для ручной прогрессии. 0 — автоматически.", "Für benutzerdefinierten Fortschritt. 0 wählt automatisch.", "Pour la progression manuelle. 0 choisit automatiquement.", "Para progresión manual. 0 elige automáticamente.", "用于自定义进度,0为自动。"], { min: 0, max: 80, advanced: true });
@@ -213,6 +215,6 @@ export function canonicalModuleValue(key: string, value: string): string {
const v = value.trim().replace(/^"|"$/g, "");
if (key === scaling + "SoloAssist.Mode") return ({ "0": "None", "1": "Light", "2": "Full", none: "None", light: "Light", full: "Full" } as Record<string, string>)[v.toLowerCase()] ?? v;
if (key === scaling + "LFG.DefaultMode") return ({ "0": "Matchmaking", "1": "BotFill", "2": "CurrentParty", matchmaking: "Matchmaking", botfill: "BotFill", currentparty: "CurrentParty" } as Record<string, string>)[v.toLowerCase()] ?? v;
if (key === scaling + "Progression.Mode") return v.toLowerCase() === "auto" ? "Auto" : v.toLowerCase() === "custom" ? "Custom" : v;
if (key === scaling + "Progression.Mode") return ({ auto: "Auto", parallel: "Parallel", global: "Global", all: "Global", "1-60": "Global", custom: "Custom" } as Record<string, string>)[v.toLowerCase()] ?? v;
return v;
}
+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");
}
+2
View File
@@ -117,6 +117,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
<h2 className="truncate text-lg font-semibold" data-testid="drawer-title">{summary.display_name}</h2>
<p className="mt-0.5 text-sm text-muted"><Mode ruleset={summary.ruleset} /> · {t("browse.cap")} {summary.level_cap ?? "—"}</p>
<p className="text-sm"><Online p={summary.population} />{summary.population.capacity !== null && <span className="text-muted"> · {t("browse.capacity", { n: summary.population.capacity })}</span>}</p>
{!summary.online && <span className="mt-1 inline-block rounded bg-bad/15 px-2 py-0.5 text-xs font-medium text-bad">{t("browse.realmOffline")}</span>}
</div>
<button onClick={onClose} aria-label={t("portable.close")} className="cursor-pointer text-muted hover:text-ink"><X className="h-5 w-5" /></button>
</div>
@@ -180,6 +181,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:
<p className="font-medium">{blocked ? t("browse.cannotPlay") : t("browse.canPlay")}</p>
{pre.projection && <Projection from={pre.projection[0]} to={pre.projection[1]} cap={summary.level_cap} />}
<Notes notes={pre.notes} />
{!summary.online && <p className="mt-2 border-t border-line/40 pt-2 text-xs text-warn">{t("browse.offlineWarning")}</p>}
</div>}
</>}
</section>
+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>
);
}
+253
View File
@@ -0,0 +1,253 @@
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, api } 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 [portableEnabled, setPortableEnabled] = useState<boolean | null>(null);
const primaryRealm = !localId.includes(":");
const [ctl, setCtl] = useState<ControlStatus | null>(null);
const host = ctl?.hosting.find((h) => h.local_id === localId);
const link = host?.link;
useEffect(() => {
if (!primaryRealm) return;
let active = true;
void api.allSettings(localId.slice(4)).then((items) => {
const item = items.find((i) => i.key === "PortableSession.Enable");
if (active && item) setPortableEnabled(item.value === "1" || item.value.toLowerCase() === "true");
}).catch((e) => { if (active) setError(asUiError(e).technical); });
return () => { active = false; };
}, [localId, primaryRealm]);
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 {
if (primaryRealm && portableEnabled !== null) {
await api.allSettingsSave(localId.slice(4), {
"PortableSession.Enable": portableEnabled ? "1" : "0",
...(portableEnabled ? { "CharacterDatabase.WorkerThreads": "1" } : {}),
});
}
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>
{mine.state === "realm_stopped" && <p className="mt-2 text-xs text-warn">{t("registry.realmStoppedHint")}</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>
{primaryRealm && <label className="mt-3 flex items-start gap-2"><input type="checkbox" checked={portableEnabled ?? false} disabled={portableEnabled === null} onChange={(e) => setPortableEnabled(e.target.checked)} className="mt-1" data-testid="portable-enabled" /><span>{t("access.portableEnabled")}<span className="block text-xs text-muted">{t("access.portableEnabledHint")}</span></span></label>}
<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; };