mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 11:25:56 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74473471db | ||
|
|
7cdf854eb0 | ||
|
|
0f0f9e6fe2 | ||
|
|
e97fe52ab3 | ||
|
|
4e73c28f7b | ||
|
|
28af9e2907 | ||
|
|
68e9d7d0cf | ||
|
|
873db420c0 | ||
|
|
b2572d4f7c | ||
|
|
aff7659625 | ||
|
|
49d1ae75ab | ||
|
|
cf94868fd9 | ||
|
|
90f93074c2 | ||
|
|
c5eac64477 | ||
|
|
039c40da06 | ||
|
|
b3bb0fdc19 |
No files matched your search
@@ -1,5 +1,39 @@
|
||||
# TODO
|
||||
|
||||
## Подготовка 0.9.8, 2026-10-31
|
||||
|
||||
- Подготовлены исходники `C:/games/source/per-race-manager`, ветка `fix/launcher-validation-candidate-20261031`: изоляция bot configs на время проверки с точным восстановлением, повторное использование MySQL внутри validation, зависимость Dungeon Clear от SQUID, три режима логов и экспорт этапов launcher/control owner.
|
||||
- Workspace: 840 тестов прошли, 60 ignored; последующие focused diagnostics: 11 прошли. Переводы новых заметок и UI подготовлены, web build/i18n/bridge/history checks прошли. Подробности и ограничения: `C:/games/source/candidate-preparation-20261031.md`.
|
||||
- Не выпускать Manager до кандидата сервера. Installer ещё не собирался и не публиковался; подготовка источников не равна готовому кандидату.
|
||||
|
||||
## Приоритет: проверка установки и обновления (2026-10-31)
|
||||
- **Локальные замеры массовых Companions (2026-10-31):** отчёт `C:/games/source/companions-benchmark-20261031/REPORT.md`, сырые выборки/qualification в той же папке. Native worldserver SHA `bd9f65ac7543fad8159231000d5ef6436a159aa009b65cbdc9541a0e9fe1ee7b`, Ryzen 7 7700X/32 GiB, `MapUpdate.Threads=1`, все CPU доступны. Перед условиями восстанавливался один снимок персонажей. Без записи логов медианы среднего тика: 0 ботов 4.5 ms; 500 — 39 ms; 1000 — 91 ms; 2000 — 246 ms, поздний замер 259 ms. С обычными логами: 500 — 43.5 ms; 1000 — 111 ms. Запуск 2000 с логами дал 1381 ms, последующий полный Logger-off 363 ms, но нагрузка хоста менялась; чистый множитель логирования этими числами не доказан. Всего 9 условий с подтверждённым online; исходная база 21 шаблон/0 тестовых аккаунтов восстановлена, тестовые процессы остановлены. Повтор 2000 с логами подготовлен, но НЕ выполнен: на C: осталось около 300 MiB. Соответствующий PDB для функционального профиля отсутствует.
|
||||
- [ ] **Разобрать штатное завершение мира под большой популяцией**:
|
||||
- В локальном бенчмарке ряд запусков (включая 2000 ботов и полностью отключённые логгеры) не завершились за 90 секунд после `server shutdown 1s 0`; пришлось завершать только тестовый процесс после сохранения измерений. Стек `2000-shutdown-stacks.txt` показывает ожидание `MSVCP140!Thrd_join`, точный ожидаемый поток без matching PDB не установлен. Не объявлять это доказанной причиной пользовательского control.lock или влиянием только логов.
|
||||
|
||||
- [ ] **Разобрать удержание control.lock после видимого запуска сервера**:
|
||||
- Пользователь после hotfix v3 получил `Another start/stop action is in progress` при внешнем `with launcher["control_lock"]()`, хотя мир отвечал и Manager показывал работающий сервер. Не считать это доказательством «зависшего файла»: Windows блокирует диапазон живым дескриптором.
|
||||
- На Python 3.14.7 точно воспроизведён конкурентный захват: второй лаунчер получает эту ошибку, после выхода владельца захват снова проходит. Причина долгого удержания у пользователя пока не установлена; нужны его свежие launch diagnostics.
|
||||
- Добавить безопасную диагностику владельца (PID, время создания, действие, этап ожидания) и проверить сериализацию Start/Stop/Restart/validation/recovery. Различать реальную занятость и прочие OSError захвата, которые сейчас маскируются одним сообщением. Не удалять lock и не завершать чужие процессы ради обхода.
|
||||
|
||||
- **Проверка с ботами завершена (2026-10-31):** пользователь показал работающие MySQL/auth/world, 2000 Companions онлайн и вход своим клиентом в мир после обновления. Это подтверждает обычный запуск с ботами после hotfix, но не пригодность массового автологина для validation. Ранний снимок показывает около 11 тиков/с на 2m32s работы; результат замера после прогрева пока неизвестен.
|
||||
|
||||
- **Пользовательская проверка (2026-10-31):** после hotfix лаунчера v3 и отключения автологина Companions обновление завершилось успешно (server `0.261030.90`, Manager `0.9.7`). Отдельная проверка с включёнными ботами пока не завершена.
|
||||
- [ ] **Сократить повторные запуски MySQL в установке/обновлении**:
|
||||
- Пользователь после успешного обновления отметил большую длительность и многократные старты/остановки базы, в том числе на 85%. Проследить фактическую последовательность snapshot/SQL/schema/validation/recovery и повторно использовать уже запущенную, проверенную базу между совместимыми этапами.
|
||||
- Не убирать остановки, необходимые для согласованного backup/restore, замены файлов и восстановления после отказа. Сохранить гарантии rollback и владения процессами. Записать число стартов/остановок и длительность этапов до/после; проверить обновление без ботов и восстановление после ошибки.
|
||||
|
||||
- [ ] **Временный конфиг проверки без массового запуска ботов**:
|
||||
- Запрос владельца: грузить 2000 ботов ради проверки установки/обновления недопустимо. Облегчить все проверочные запуски, включая восстановление/повторную проверку, где применяется тот же путь запуска.
|
||||
- Факты случая: этап обновления 85%, CoA Companions поставили в очередь 2000 ботов; пользователь сообщает об остановке продвижения на 519 за 6 минут. Логи показывают 518 уникальных имён в `ACTIVE_LIST`. Это не SQUID. Место зависания и причинная связь с автологином пока не установлены.
|
||||
- Перед проверочным запуском временно отключать `CoaBots.AutoLoginOnStartup` и проверить другие пути автоматического входа/создания/заселения Companions, включая `CoaBots.RandomSpawn.AutoLogin`. Аналогично подавлять автоматическое заселение SQUID, если выбран этот модуль. Не подменять пользовательский выбор системы ботов и не отключать модуль целиком вместо проверки его инициализации.
|
||||
- Сохранять исходные байты/отсутствие изменяемых конфигов в журнале восстановления; вернуть их до обычного запуска как при успехе, так и при ошибке, отмене, rollback и восстановлении после прерывания Manager. Не оставлять автологин выключенным пользователю. Проверить primary и дополнительные realms.
|
||||
- Проверка должна подтверждать инициализацию ядра/выбранных модулей, SQL/schema, сервисы и отклик управляющего интерфейса; не ждать заполнения мира ботами и не создавать для этого тысячи персонажей. Вне validation обычный запуск сохраняет поведение пользовательских настроек.
|
||||
- Проверить сценарии с Companions и лимитом 2000, SQUID, выключенными ботами; успех, отказ запуска, прерывание и восстановление исходных конфигов. Добавить регрессионные проверки и changelog после реализации.
|
||||
|
||||
- [ ] **Доставить исправление `manage.py` для PID 0 в согласованном серверном обновлении**:
|
||||
- Серверная задача и готовый локальный hotfix описаны в `C:/games/coa-server-build/TODO.md`. Проверить импортируемый запуск через `runpy`/внешний вызов `main()` и штатный Manager update; диагностика должна работать при обоих способах загрузки.
|
||||
|
||||
## UI / UX
|
||||
- [x] **Предупреждение о несохранённых изменениях при переходе между вкладками (Unsaved Changes Guard / Modal)**:
|
||||
- Если у пользователя есть несохранённые изменения в настройках (`ModulesPage`, `SettingsPage` — сервер, боты и др.) и он переходит на другую вкладку (в боковом меню `Shell.tsx` или кнопками навигации), показывать pop-up диалог подтверждения.
|
||||
@@ -27,3 +61,25 @@
|
||||
4. Анализировать последние строки `Core/Logs/Server.log` и `Errors.log` на критические маркеры (потеря соединения с MySQL, нехватка RAM/OOM, ошибка бинда портов).
|
||||
5. Проверять по встроенному словарю известных сигнатур (паттерны частых крашей с понятным описанием, например: «Сбой удаления объекта из сетки карты», «Ошибка запроса к базе данных», «Нехватка оперативной памяти»).
|
||||
- *Fallback:* Если сигнатура не опознана в словаре известных проблем, показывать краткую техническую выжимку (код исключения + сработавший ассерт или вершина Call Stack) и кнопку разворота полного текста крашлога / копирования.
|
||||
|
||||
## Модули и контент
|
||||
- [ ] **Следующий билд: переключатель Dungeon Clear только для SQUID** (запрос владельца 2026-10-31):
|
||||
- Модуль: https://github.com/Zyth45/mod-dungeon-clear, ветка `coa`; серверная интеграция описана в `C:/games/coa-server-build/TODO.md`.
|
||||
- Добавить в каталог отдельный модуль Dungeon Clear, по умолчанию выключенный. На старых серверах без модуля показывать недоступным.
|
||||
- Разрешать включение только при установленном и включённом SQUID (`playerbots`). При выключенном SQUID блокировать переключатель и объяснять причину; CoA Companions не подходят.
|
||||
- Проверять зависимость также в Rust backend при изменении модуля и его настроек. Отключение SQUID/переход на Companions отключает Dungeon Clear; обратное включение SQUID не включает Dungeon Clear автоматически.
|
||||
- Проверить сохранение после перезапуска, ручные конфиги и отказ включения через API в обход UI. Серверный guard обязателен независимо от Manager.
|
||||
- Все новые UI-тексты — на шести языках. После реализации добавить changelog fragments в соответствующие компоненты; пока это запланированная, не выпущенная возможность.
|
||||
- [ ] **Внедрение модуля гильдхаусов (`mod-guildhouse`)**:
|
||||
- **Репозиторий:** `https://github.com/azerothcore/mod-guildhouse`
|
||||
- **Пайплайн сборки (`coa-server-build`):**
|
||||
- Добавить checkout модуля в `.github/workflows/server-binaries.yml`, `build.yml` и `build-linux.yml` в директорию `modules/mod-guildhouse`.
|
||||
- Добавить лицензию модуля и копирование в `scripts/assemble-tree.ps1` (`Licenses/` и `NOTICE.txt`).
|
||||
- **Адаптация под Conquest of Azeroth (CoA):**
|
||||
- В диалоге дворецкого (`mod_guildhouse_butler.cpp`) вместо 10 классических тренеров WotLK спавнить **Book of Ascension** (entry `499992`), которая открывает интерфейс `mod-spellbook` и заменяет всех тренеров для кастомных классов и прогрессии способностей.
|
||||
- Оставить без изменений: профессии, порталы в столицы, банк, аукционы (включая нейтральный), почту, вендоров, парикмахера, горн и наковальню.
|
||||
- **База данных:**
|
||||
- Миграции модуля (`guild_house`, `guild_house_spawns`, `creature_template`, `gameobject_template`, `mod_guildhouse_locale`) подхватываются `coa-release` автоматически при валидации схемы контракта.
|
||||
- **В игре:**
|
||||
- Разместить NPC-продавца гильдхаусов (`.npc add 500030`) в ключевых хабах / столицах (Штормград, Оргриммар, Даларан).
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Online player counts correctly separate random bots from players
|
||||
---
|
||||
The server browser and overview now count SQUID random bots as bots, using the server's configured bot account prefix.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Custom races work with shared addon folders on another drive
|
||||
---
|
||||
Installing, switching and removing custom races now supports linked addon folders on another drive, including recovery after an interrupted operation.
|
||||
@@ -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: changed
|
||||
audience: players
|
||||
title: The game client now comes from the community launcher, not from the Manager
|
||||
---
|
||||
The community moved the game client behind its official launcher (account sign-in), so the Manager can no longer download or update it. The built-in client download and update are removed. "Set up the game client" now sends you to coa-development.org to get the launcher; once the launcher has installed the game, choose "I already have a client" and pick its folder. Linking a folder, the server address switch and the companion addon work as before.
|
||||
@@ -1,75 +0,0 @@
|
||||
//! Live check of the client download path against the community launcher's public server:
|
||||
//! reads the manifest and downloads the few smallest files into a temp folder (never a real client).
|
||||
//! Usage: cargo run -p coa-core --example client_probe (PROBE_SKIP=n skips the n smallest files)
|
||||
|
||||
use coa_core::clientdl::{self, Apply, Manifest};
|
||||
use coa_core::download::{Cancel, HttpTransport};
|
||||
|
||||
fn main() {
|
||||
let full = clientdl::fetch_latest().expect("manifest");
|
||||
println!(
|
||||
"version {} · {} files · {:.1} GB",
|
||||
full.version,
|
||||
full.files.len(),
|
||||
full.total_bytes() as f64 / 1e9
|
||||
);
|
||||
let mut small = full.files.clone();
|
||||
small.sort_by_key(|f| f.size);
|
||||
let skip: usize = std::env::var("PROBE_SKIP")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let small: Vec<_> = small.into_iter().skip(skip).take(6).collect();
|
||||
let manifest = Manifest {
|
||||
version: full.version.clone(),
|
||||
published_at: None,
|
||||
files: small,
|
||||
};
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("coa-client-probe-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let cancel = Cancel::default();
|
||||
let plan = clientdl::plan(&dir, &manifest, &Default::default(), &cancel, &|_| {}).unwrap();
|
||||
println!(
|
||||
"plan: {} files, {} bytes",
|
||||
plan.items.len(),
|
||||
plan.download_bytes
|
||||
);
|
||||
let transport = HttpTransport::new().unwrap();
|
||||
clientdl::apply(
|
||||
&Apply {
|
||||
client: &dir,
|
||||
manifest: &manifest,
|
||||
plan: &plan,
|
||||
keep_modified: false,
|
||||
transport: &transport,
|
||||
objects_url: clientdl::OBJECTS_URL,
|
||||
cancel: &cancel,
|
||||
},
|
||||
&|s| {
|
||||
println!(
|
||||
"{} {}/{} {}",
|
||||
s.phase,
|
||||
s.done,
|
||||
s.total,
|
||||
s.file.unwrap_or_default()
|
||||
)
|
||||
},
|
||||
)
|
||||
.expect("apply");
|
||||
let again = clientdl::plan(
|
||||
&dir,
|
||||
&manifest,
|
||||
&clientdl::load_state(&dir).unwrap(),
|
||||
&cancel,
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
println!(
|
||||
"second plan: {} to do, {} up to date, version {:?}",
|
||||
again.items.len(),
|
||||
again.up_to_date_files,
|
||||
clientdl::local(&dir).version
|
||||
);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,441 @@
|
||||
//! CLI tool for CoA Server Manager plugin operations (testing, qualification and automation).
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use coa_core::plugins::{self, PluginMetadata};
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
r#"csm_plugins CLI
|
||||
Usage:
|
||||
csm_plugins install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable] [--crash-at <point>]
|
||||
csm_plugins update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--crash-at <point>]
|
||||
csm_plugins enable <server> <id> [--crash-at <point>]
|
||||
csm_plugins disable <server> <id> [--crash-at <point>]
|
||||
csm_plugins remove <server> <id> [--crash-at <point>]
|
||||
csm_plugins repair <server> [--crash-at <point>]
|
||||
csm_plugins recover <server>
|
||||
csm_plugins prune <server>
|
||||
csm_plugins list <server>
|
||||
csm_plugins reconcile_squid <server> [char_schema]
|
||||
csm_plugins multiworld <server> <second_root> [--allow <a,b>] [--crash-at <point>]
|
||||
csm_plugins analyze <local_repository_path> [--json]
|
||||
csm_plugins analyze-github <url> [--cache-dir <dir>] [--contract <v02|v03>] [--json]
|
||||
csm_plugins verify-artifact-provenance <worldserver_path> [--sdk-json <path>] [--json]
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
if args.len() < 3 {
|
||||
print_usage();
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Inspect for --crash-at argument
|
||||
for i in 0..args.len() {
|
||||
if args[i] == "--crash-at" && i + 1 < args.len() {
|
||||
std::env::set_var("CSM_CRASH_AT", &args[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
let cmd = &args[1];
|
||||
let server = Path::new(&args[2]);
|
||||
|
||||
match cmd.as_str() {
|
||||
"install" => {
|
||||
if args.len() < 7 {
|
||||
eprintln!("Usage: install <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>] [--deps <deps>] [--enable]");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let id = &args[3];
|
||||
let name = &args[4];
|
||||
let version = &args[5];
|
||||
let dll_path = Path::new(&args[6]);
|
||||
let dll_bytes = fs::read(dll_path)?;
|
||||
let digest = plugins::sha256_digest(&dll_bytes);
|
||||
|
||||
let mut pdb_bytes = None;
|
||||
let mut conf_list = Vec::new();
|
||||
let mut deps = Vec::new();
|
||||
let mut enable = false;
|
||||
|
||||
let mut i = 7;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pdb" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
pdb_bytes = Some(fs::read(&args[i])?);
|
||||
}
|
||||
}
|
||||
"--conf" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
for item in args[i].split(',') {
|
||||
if !item.is_empty() {
|
||||
let p = Path::new(item);
|
||||
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
|
||||
let bytes = fs::read(p)?;
|
||||
conf_list.push((file_name, bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"--deps" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
deps = args[i].split(',').filter(|s| !s.is_empty()).map(|s| s.to_string()).collect();
|
||||
}
|
||||
}
|
||||
"--enable" => {
|
||||
enable = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
|
||||
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
|
||||
|
||||
let meta = PluginMetadata {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
version: version.clone(),
|
||||
description: BTreeMap::new(),
|
||||
sha256: digest,
|
||||
required: true,
|
||||
deps,
|
||||
conf_files: conf_names,
|
||||
enable_key: None,
|
||||
status: Some("release".into()),
|
||||
icon: None,
|
||||
};
|
||||
|
||||
plugins::install(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs, enable)?;
|
||||
println!("Installed plugin '{}' successfully (enabled: {})", id, enable);
|
||||
}
|
||||
"update" => {
|
||||
if args.len() < 7 {
|
||||
eprintln!("Usage: update <server> <id> <name> <version> <dll> [--pdb <pdb>] [--conf <dist_confs>]");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let id = &args[3];
|
||||
let name = &args[4];
|
||||
let version = &args[5];
|
||||
let dll_path = Path::new(&args[6]);
|
||||
let dll_bytes = fs::read(dll_path)?;
|
||||
let digest = plugins::sha256_digest(&dll_bytes);
|
||||
|
||||
let mut pdb_bytes = None;
|
||||
let mut conf_list = Vec::new();
|
||||
|
||||
let mut i = 7;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--pdb" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
pdb_bytes = Some(fs::read(&args[i])?);
|
||||
}
|
||||
}
|
||||
"--conf" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
for item in args[i].split(',') {
|
||||
if !item.is_empty() {
|
||||
let p = Path::new(item);
|
||||
let file_name = p.file_name().unwrap().to_string_lossy().into_owned();
|
||||
let bytes = fs::read(p)?;
|
||||
conf_list.push((file_name, bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
let conf_names: Vec<String> = conf_list.iter().map(|(n, _)| n.clone()).collect();
|
||||
let dist_refs: Vec<(String, &[u8])> = conf_list.iter().map(|(n, b)| (n.clone(), b.as_slice())).collect();
|
||||
|
||||
let meta = PluginMetadata {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
version: version.clone(),
|
||||
description: BTreeMap::new(),
|
||||
sha256: digest,
|
||||
required: true,
|
||||
deps: vec![],
|
||||
conf_files: conf_names,
|
||||
enable_key: None,
|
||||
status: Some("release".into()),
|
||||
icon: None,
|
||||
};
|
||||
|
||||
plugins::update(server, meta, &dll_bytes, pdb_bytes.as_deref(), &dist_refs)?;
|
||||
println!("Updated plugin '{}' to version {} successfully", id, version);
|
||||
}
|
||||
"enable" => {
|
||||
if args.len() < 4 {
|
||||
eprintln!("Usage: enable <server> <id>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let id = &args[3];
|
||||
plugins::set_enabled(server, id, true)?;
|
||||
println!("Enabled plugin '{}' successfully", id);
|
||||
}
|
||||
"disable" => {
|
||||
if args.len() < 4 {
|
||||
eprintln!("Usage: disable <server> <id>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let id = &args[3];
|
||||
plugins::set_enabled(server, id, false)?;
|
||||
println!("Disabled plugin '{}' successfully", id);
|
||||
}
|
||||
"remove" => {
|
||||
if args.len() < 4 {
|
||||
eprintln!("Usage: remove <server> <id>");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let id = &args[3];
|
||||
plugins::remove(server, id)?;
|
||||
println!("Removed plugin '{}' successfully", id);
|
||||
}
|
||||
"repair" => {
|
||||
let restored = plugins::repair(server)?;
|
||||
println!("Repair complete. Restored {} plugin(s): {:?}", restored.len(), restored);
|
||||
}
|
||||
"recover" => {
|
||||
plugins::ensure_durable_recovered(server)?;
|
||||
println!("Durable transaction recovery complete (clean state restored).");
|
||||
}
|
||||
"prune" => {
|
||||
let pruned = plugins::prune_store(server)?;
|
||||
println!("Pruned {} unused store version(s): {:?}", pruned.len(), pruned);
|
||||
}
|
||||
"reconcile_squid" => {
|
||||
let char_schema = if args.len() >= 4 { &args[3] } else { "acore_characters" };
|
||||
let port_str = std::env::var("MYSQL_PORT").unwrap_or_else(|_| "3417".into());
|
||||
let user = std::env::var("MYSQL_USER").unwrap_or_else(|_| "root".into());
|
||||
let pass = std::env::var("MYSQL_PWD").unwrap_or_default();
|
||||
let mysql_exe = std::env::var("MYSQL_EXE").unwrap_or_else(|_| "mysql".into());
|
||||
|
||||
let query_fn = |sql: &str| -> Result<String, coa_core::error::Error> {
|
||||
let mut cmd = std::process::Command::new(&mysql_exe);
|
||||
cmd.args(["-h", "127.0.0.1", "-P", &port_str, "-u", &user, "-e", sql]);
|
||||
if !pass.is_empty() && pass != "trap" {
|
||||
cmd.env("MYSQL_PWD", &pass);
|
||||
} else {
|
||||
cmd.env_remove("MYSQL_PWD");
|
||||
}
|
||||
let out = cmd.output().map_err(coa_core::error::Error::Io)?;
|
||||
if !out.status.success() {
|
||||
return Err(coa_core::error::Error::Invalid(String::from_utf8_lossy(&out.stderr).into_owned()));
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
|
||||
};
|
||||
let audit = plugins::reconcile_squid_migrations(server, char_schema, Some(&query_fn))?;
|
||||
println!("SQUID Reconciliation: status={:?}, applied={}", audit.db_status, audit.effective_applied);
|
||||
}
|
||||
"list" => {
|
||||
let reg = plugins::load_registry(server)?;
|
||||
println!("Plugins schema {}:", reg.schema);
|
||||
for (id, p) in reg.plugins {
|
||||
println!(
|
||||
" - {}: enabled={}, version={}, sha256={}",
|
||||
id, p.enabled, p.version, p.sha256
|
||||
);
|
||||
}
|
||||
}
|
||||
"multiworld" => {
|
||||
if args.len() < 4 {
|
||||
eprintln!("Usage: multiworld <server> <second_root> [--allow <a,b>]");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let second_root = Path::new(&args[3]);
|
||||
let mut allowlist = None;
|
||||
if args.len() >= 6 && args[4] == "--allow" {
|
||||
allowlist = Some(args[5].split(',').filter(|s| !s.is_empty()).map(str::to_string).collect::<Vec<_>>());
|
||||
}
|
||||
plugins::prepare_multiworld_realm(server, second_root, allowlist.as_deref())?;
|
||||
println!("Prepared multiworld realm at {} successfully", second_root.display());
|
||||
}
|
||||
"analyze" => {
|
||||
let repo_path = Path::new(&args[2]);
|
||||
let as_json = args.iter().any(|a| a == "--json");
|
||||
let contract = if args.iter().any(|a| a == "--sdk-v02") {
|
||||
coa_core::analyzer::SdkExportContract::v02()
|
||||
} else {
|
||||
coa_core::analyzer::SdkExportContract::v03()
|
||||
};
|
||||
let report = coa_core::analyzer::analyze_repository_with_contract(repo_path, &contract)?;
|
||||
if as_json {
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
} else {
|
||||
println!("=== Module Compatibility Report v0.2 ===");
|
||||
println!("Repository: {}", report.repository_name);
|
||||
println!("Commit : {}", report.commit);
|
||||
println!("License : {}", report.license_info.primary_license);
|
||||
if let Some(ref lf) = report.license_info.license_file {
|
||||
println!("License File: {}", lf);
|
||||
}
|
||||
if !report.license_info.vendored_licenses.is_empty() {
|
||||
println!("Vendored Licenses: {:?}", report.license_info.vendored_licenses);
|
||||
}
|
||||
println!("Verdict : {:?}", report.classification);
|
||||
println!("Status L0-L6: static={}, compile={}, link={}, contract={}, boot={}, gameplay={}, teardown={}",
|
||||
report.verification_status.l0_static,
|
||||
report.verification_status.l1_compile,
|
||||
report.verification_status.l2_link,
|
||||
report.verification_status.l3_contract,
|
||||
report.verification_status.l4_engine_boot,
|
||||
report.verification_status.l5_gameplay,
|
||||
report.verification_status.l6_teardown);
|
||||
println!("Hooks ({}):", report.hooks.len());
|
||||
for h in &report.hooks {
|
||||
println!(" - {} : {} ({}:{})", h.class_name, h.script_type, h.file, h.line);
|
||||
}
|
||||
println!("SQL Files ({}):", report.sql_files.len());
|
||||
for s in &report.sql_files {
|
||||
println!(" - {} [schema: {}] (create={}, alter={}, lines={})", s.file, s.target_schema, s.has_create_table, s.has_alter_table, s.line_count);
|
||||
}
|
||||
println!("Findings ({}):", report.findings.len());
|
||||
for f in &report.findings {
|
||||
println!(" [{:?}] {} (at {}:{}): {}", f.severity, f.rule_id, f.file, f.line, f.explanation);
|
||||
println!(" Guidance: {}", f.recommended_action);
|
||||
}
|
||||
println!("Summary Reasons: {:?}", report.reasons);
|
||||
}
|
||||
}
|
||||
"analyze-github" => {
|
||||
let url = &args[2];
|
||||
let mut cache_dir = None;
|
||||
let mut json_out = false;
|
||||
|
||||
let mut i = 3;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--cache-dir" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
cache_dir = Some(std::path::PathBuf::from(&args[i]));
|
||||
}
|
||||
}
|
||||
"--json" => {
|
||||
json_out = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
match coa_core::analyzer::analyze_github_repository(url, cache_dir.as_deref()) {
|
||||
Ok(report) => {
|
||||
if json_out {
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
} else {
|
||||
println!("Repository: {}", report.repository_name);
|
||||
println!("Classification: {:?}", report.classification);
|
||||
println!("License: {}", report.license_info.primary_license);
|
||||
println!("Cache Hit: {:?}", report.cache_hit);
|
||||
println!("Tree Digest: {:?}", report.tree_digest);
|
||||
println!("Commit: {:?}", report.commit);
|
||||
println!("Loaders: {:?}", report.script_loaders);
|
||||
println!("Hooks: {}", report.hooks.len());
|
||||
println!("SQL Files: {}", report.sql_files.len());
|
||||
println!("Findings: {}", report.findings.len());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("ERROR: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
"generate-adapter" => {
|
||||
let repo_path = Path::new(&args[2]);
|
||||
let res = coa_core::analyzer::generate_adapter(repo_path)?;
|
||||
match res {
|
||||
coa_core::analyzer::AdapterGenerationResult::Success { canonical_loader, adapter_source, delegated_count } => {
|
||||
println!("Canonical Master Loader: {} (delegates to {} scripts)", canonical_loader, delegated_count);
|
||||
if let Some(pos) = args.iter().position(|a| a == "--output") {
|
||||
if pos + 1 < args.len() {
|
||||
let out_path = Path::new(&args[pos + 1]);
|
||||
if let Some(p) = out_path.parent() {
|
||||
std::fs::create_dir_all(p)?;
|
||||
}
|
||||
std::fs::write(out_path, &adapter_source)?;
|
||||
println!("Adapter successfully written to: {}", out_path.display());
|
||||
}
|
||||
} else {
|
||||
println!("--- Generated Adapter Source ---");
|
||||
println!("{}", adapter_source);
|
||||
}
|
||||
}
|
||||
coa_core::analyzer::AdapterGenerationResult::ManualAdapterRequired { reason, candidate_loaders } => {
|
||||
eprintln!("MANUAL_ADAPTER_REQUIRED: {}", reason);
|
||||
eprintln!("Candidate Loaders: {:?}", candidate_loaders);
|
||||
std::process::exit(1);
|
||||
}
|
||||
coa_core::analyzer::AdapterGenerationResult::NoLoaderFound => {
|
||||
eprintln!("NO_LOADER_FOUND: Unable to discover any Add*Scripts() functions.");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
"verify-artifact-provenance" => {
|
||||
let exe_path = Path::new(&args[2]);
|
||||
let mut sdk_json = None;
|
||||
let mut json_out = false;
|
||||
|
||||
let mut i = 3;
|
||||
while i < args.len() {
|
||||
match args[i].as_str() {
|
||||
"--sdk-json" => {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
sdk_json = Some(Path::new(&args[i]));
|
||||
}
|
||||
}
|
||||
"--json" => {
|
||||
json_out = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
match coa_core::provenance::verify_worldserver_provenance(exe_path, sdk_json) {
|
||||
Ok(rec) => {
|
||||
if json_out {
|
||||
println!("{}", serde_json::to_string_pretty(&rec)?);
|
||||
} else {
|
||||
println!("Artifact: {}", rec.file_path);
|
||||
println!("SHA-256: {}", rec.file_sha256);
|
||||
println!("Arch: {}", rec.machine_architecture);
|
||||
println!("Exports: {}", rec.total_export_count);
|
||||
println!("Embedded ABI: {:?}", rec.embedded_abi_fingerprint);
|
||||
println!("Status: {}", rec.provenance_status);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("ERROR: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("Unknown command: {}", cmd);
|
||||
print_usage();
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,921 +0,0 @@
|
||||
//! Download and update of the game client from the community launcher's public manifest.
|
||||
//!
|
||||
//! The manifest lists every file with its size and SHA-256; each file is fetched by hash and verified before it is
|
||||
//! moved into place (`download::fetch_with`, resumable). The Manager keeps a small state file inside the client
|
||||
//! folder (`.coa-manager/client-state.json`) so that later checks are cheap and so that files the player changed
|
||||
//! are recognised: they are never overwritten without being asked, and a replaced file is moved aside, not deleted.
|
||||
//! WTF, Cache, other addons, logs and `realmlist.wtf` are not part of what the Manager synchronises.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Instant, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::download::{self, Cancel, HttpTransport, Job, Transport};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
pub const MANIFEST_URL: &str =
|
||||
"https://launcher-api.coa-development.org/downloads/client/latest.json";
|
||||
pub const OBJECTS_URL: &str = "https://launcher-api.coa-development.org/downloads/client/objects";
|
||||
const STATE_DIR: &str = ".coa-manager";
|
||||
const MAX_MANIFEST_BYTES: u64 = 16 * 1024 * 1024;
|
||||
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ManifestFile {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Manifest {
|
||||
pub version: String,
|
||||
pub published_at: Option<String>,
|
||||
pub files: Vec<ManifestFile>,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
pub fn total_bytes(&self) -> u64 {
|
||||
self.files.iter().map(|f| f.size).sum()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RawManifest {
|
||||
schema: u32,
|
||||
version: String,
|
||||
#[serde(rename = "publishedAt")]
|
||||
published_at: Option<String>,
|
||||
files: Vec<ManifestFile>,
|
||||
}
|
||||
|
||||
/// Things the Manager never writes, even if a manifest lists them: logs, the realmlist, the player's own settings,
|
||||
/// caches and the companion addon (those have their own safe paths).
|
||||
fn is_excluded(path: &str) -> bool {
|
||||
let p = path.replace('\\', "/").to_ascii_lowercase();
|
||||
p.ends_with(".log")
|
||||
|| p.rsplit('/').next() == Some("realmlist.wtf")
|
||||
|| p.starts_with("wtf/")
|
||||
|| p.starts_with("cache/")
|
||||
|| p.starts_with("errors/")
|
||||
|| p.starts_with("logs/")
|
||||
|| p.starts_with(".coa-manager/")
|
||||
|| p.starts_with("interface/addons/coabotui/")
|
||||
}
|
||||
|
||||
/// Files players customise: graphics wrappers and their configuration. If one exists and differs from the published
|
||||
/// file it is left exactly as it is, whatever the "keep my files" choice; it is only created when missing.
|
||||
fn is_player_owned(path: &str) -> bool {
|
||||
let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
|
||||
matches!(
|
||||
name.as_str(),
|
||||
"d3d8.dll" | "d3d9.dll" | "d3d10core.dll" | "d3d11.dll" | "dxgi.dll" | "dxvk.conf"
|
||||
) || matches!(
|
||||
name.rsplit('.').next(),
|
||||
Some("ini" | "conf" | "cfg" | "wtf")
|
||||
)
|
||||
}
|
||||
|
||||
pub fn parse_manifest(text: &str) -> Result<Manifest> {
|
||||
let raw: RawManifest = serde_json::from_str(text)
|
||||
.map_err(|e| Error::Invalid(format!("The client list could not be read: {e}")))?;
|
||||
if raw.schema != 1 {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The client list uses a newer format ({}); update the Manager.",
|
||||
raw.schema
|
||||
)));
|
||||
}
|
||||
if raw.version.trim().is_empty() || raw.version.len() > 64 {
|
||||
return Err(Error::Invalid("The client list has no version.".into()));
|
||||
}
|
||||
let root = Path::new("client-root");
|
||||
let mut files = Vec::with_capacity(raw.files.len());
|
||||
for f in raw.files {
|
||||
fsx::safe_join(root, &f.path)?;
|
||||
let hash_ok = f.sha256.len() == 64 && f.sha256.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
if !hash_ok || f.size > MAX_FILE_BYTES {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The client list has a bad entry for {}.",
|
||||
f.path
|
||||
)));
|
||||
}
|
||||
if is_excluded(&f.path) {
|
||||
continue;
|
||||
}
|
||||
files.push(ManifestFile {
|
||||
path: f.path.replace('\\', "/"),
|
||||
size: f.size,
|
||||
sha256: f.sha256.to_ascii_lowercase(),
|
||||
});
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Err(Error::Invalid("The client list is empty.".into()));
|
||||
}
|
||||
Ok(Manifest {
|
||||
version: raw.version,
|
||||
published_at: raw.published_at,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fetch_manifest(transport: &dyn Transport, url: &str) -> Result<Manifest> {
|
||||
let mut reply = transport
|
||||
.get(url, 0)
|
||||
.map_err(|e| Error::Invalid(format!("Could not reach the client download server: {e}")))?;
|
||||
if reply.status != 200 {
|
||||
return Err(Error::Invalid(format!(
|
||||
"The client download server answered {}.",
|
||||
reply.status
|
||||
)));
|
||||
}
|
||||
let mut text = String::new();
|
||||
reply
|
||||
.body
|
||||
.by_ref()
|
||||
.take(MAX_MANIFEST_BYTES)
|
||||
.read_to_string(&mut text)
|
||||
.map_err(|e| Error::Invalid(format!("Could not read the client list: {e}")))?;
|
||||
parse_manifest(&text)
|
||||
}
|
||||
|
||||
pub fn fetch_latest() -> Result<Manifest> {
|
||||
download::check_url(MANIFEST_URL)?;
|
||||
fetch_manifest(&HttpTransport::with_total_timeout(30)?, MANIFEST_URL)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub size: u64,
|
||||
pub mtime: u64,
|
||||
pub sha256: String,
|
||||
/// The player chose to keep this file although the manifest has a different one (this is the manifest hash
|
||||
/// they were asked about; a newer manifest asks again).
|
||||
#[serde(default)]
|
||||
pub kept_against: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct State {
|
||||
/// The manifest version this folder was brought to; None while a download is unfinished.
|
||||
pub version: Option<String>,
|
||||
pub files: BTreeMap<String, Entry>,
|
||||
}
|
||||
|
||||
fn state_path(client: &Path) -> PathBuf {
|
||||
client.join(STATE_DIR).join("client-state.json")
|
||||
}
|
||||
|
||||
pub fn load_state(client: &Path) -> Option<State> {
|
||||
fsx::read_json(&state_path(client)).ok()
|
||||
}
|
||||
|
||||
fn save_state(client: &Path, state: &State) -> Result<()> {
|
||||
fsx::atomic_write_json(&state_path(client), state)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Local {
|
||||
/// The Manager downloaded or adopted this folder (a state file exists).
|
||||
pub managed: bool,
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
pub fn local(client: &Path) -> Local {
|
||||
let s = load_state(client);
|
||||
Local {
|
||||
managed: s.is_some(),
|
||||
version: s.and_then(|s| s.version),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Kind {
|
||||
/// Not in the folder.
|
||||
Missing,
|
||||
/// Still as the Manager left it; the manifest has a newer file.
|
||||
Changed,
|
||||
/// Different from the manifest and not as the Manager left it (changed by the player or by something else).
|
||||
Modified,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Item {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub kind: Kind,
|
||||
#[serde(skip)]
|
||||
sha256: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Plan {
|
||||
pub version: String,
|
||||
pub items: Vec<Item>,
|
||||
pub download_bytes: u64,
|
||||
pub total_files: usize,
|
||||
pub up_to_date_files: usize,
|
||||
pub kept_files: usize,
|
||||
#[serde(skip)]
|
||||
confirmed: BTreeMap<String, Entry>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
pub fn modified(&self) -> Vec<&Item> {
|
||||
self.items
|
||||
.iter()
|
||||
.filter(|i| i.kind == Kind::Modified)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Step {
|
||||
/// "scan" while comparing files, "download" while fetching, "finish" at the end.
|
||||
pub phase: &'static str,
|
||||
pub done: u64,
|
||||
pub total: u64,
|
||||
pub bytes_per_sec: u64,
|
||||
pub file: Option<String>,
|
||||
}
|
||||
|
||||
fn cancelled() -> Error {
|
||||
Error::Invalid("Download cancelled.".into())
|
||||
}
|
||||
|
||||
fn mtime_secs(m: &fs::Metadata) -> u64 {
|
||||
m.modified()
|
||||
.ok()
|
||||
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn hash_file(path: &Path, cancel: &Cancel, on_bytes: &mut dyn FnMut(u64)) -> Result<String> {
|
||||
let mut f = File::open(path)?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
loop {
|
||||
if cancel.is_set() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
let n = f.read(&mut buf)?;
|
||||
if n == 0 {
|
||||
return Ok(hex::encode(hasher.finalize()));
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
on_bytes(n as u64);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compare the folder with the manifest. Files are hashed only when their size or modification time no longer
|
||||
/// matches what the state file recorded, so a routine check of a managed folder is quick.
|
||||
pub fn plan(
|
||||
client: &Path,
|
||||
m: &Manifest,
|
||||
state: &State,
|
||||
cancel: &Cancel,
|
||||
on_step: &dyn Fn(Step),
|
||||
) -> Result<Plan> {
|
||||
let total = m.total_bytes();
|
||||
let mut done = 0u64;
|
||||
let mut items = Vec::new();
|
||||
let mut confirmed = BTreeMap::new();
|
||||
let (mut up_to_date, mut kept) = (0usize, 0usize);
|
||||
for f in &m.files {
|
||||
if cancel.is_set() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
on_step(Step {
|
||||
phase: "scan",
|
||||
done,
|
||||
total,
|
||||
bytes_per_sec: 0,
|
||||
file: Some(f.path.clone()),
|
||||
});
|
||||
let path = fsx::safe_join(client, &f.path)?;
|
||||
let meta = match fs::metadata(&path) {
|
||||
Ok(meta) if meta.is_file() => meta,
|
||||
_ => {
|
||||
items.push(Item {
|
||||
path: f.path.clone(),
|
||||
size: f.size,
|
||||
kind: Kind::Missing,
|
||||
sha256: f.sha256.clone(),
|
||||
});
|
||||
done += f.size;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (size, mtime) = (meta.len(), mtime_secs(&meta));
|
||||
let entry = state.files.get(&f.path);
|
||||
let trusted = entry.filter(|e| e.size == size && e.mtime == mtime);
|
||||
let local: Option<String> = if let Some(e) = trusted {
|
||||
Some(e.sha256.clone())
|
||||
} else if size == f.size || entry.map(|e| e.size == size).unwrap_or(false) {
|
||||
let base = done;
|
||||
let mut seen = 0u64;
|
||||
let h = hash_file(&path, cancel, &mut |n| {
|
||||
seen += n;
|
||||
on_step(Step {
|
||||
phase: "scan",
|
||||
done: base + seen.min(f.size),
|
||||
total,
|
||||
bytes_per_sec: 0,
|
||||
file: Some(f.path.clone()),
|
||||
});
|
||||
})?;
|
||||
Some(h)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
done += f.size;
|
||||
if is_player_owned(&f.path) && local.as_deref() != Some(f.sha256.as_str()) {
|
||||
let sha = match local {
|
||||
Some(h) => h,
|
||||
None => hash_file(&path, cancel, &mut |_| {})?,
|
||||
};
|
||||
kept += 1;
|
||||
confirmed.insert(
|
||||
f.path.clone(),
|
||||
Entry {
|
||||
size,
|
||||
mtime,
|
||||
sha256: sha,
|
||||
kept_against: Some(f.sha256.clone()),
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if local.as_deref() == Some(f.sha256.as_str()) {
|
||||
up_to_date += 1;
|
||||
confirmed.insert(
|
||||
f.path.clone(),
|
||||
Entry {
|
||||
size,
|
||||
mtime,
|
||||
sha256: f.sha256.clone(),
|
||||
kept_against: None,
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let as_left = entry.filter(|e| local.as_deref() == Some(e.sha256.as_str()));
|
||||
match as_left {
|
||||
Some(e) if e.kept_against.as_deref() == Some(f.sha256.as_str()) => {
|
||||
kept += 1;
|
||||
confirmed.insert(
|
||||
f.path.clone(),
|
||||
Entry {
|
||||
size,
|
||||
mtime,
|
||||
sha256: e.sha256.clone(),
|
||||
kept_against: e.kept_against.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
Some(e) if e.kept_against.is_none() => {
|
||||
items.push(Item {
|
||||
path: f.path.clone(),
|
||||
size: f.size,
|
||||
kind: Kind::Changed,
|
||||
sha256: f.sha256.clone(),
|
||||
});
|
||||
}
|
||||
_ => items.push(Item {
|
||||
path: f.path.clone(),
|
||||
size: f.size,
|
||||
kind: Kind::Modified,
|
||||
sha256: f.sha256.clone(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
on_step(Step {
|
||||
phase: "scan",
|
||||
done: total,
|
||||
total,
|
||||
bytes_per_sec: 0,
|
||||
file: None,
|
||||
});
|
||||
let download_bytes = items.iter().map(|i| i.size).sum();
|
||||
Ok(Plan {
|
||||
version: m.version.clone(),
|
||||
items,
|
||||
download_bytes,
|
||||
total_files: m.files.len(),
|
||||
up_to_date_files: up_to_date,
|
||||
kept_files: kept,
|
||||
confirmed,
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Apply<'a> {
|
||||
pub client: &'a Path,
|
||||
pub manifest: &'a Manifest,
|
||||
pub plan: &'a Plan,
|
||||
/// Leave files the player changed alone (they are remembered, and asked about again only when the manifest changes).
|
||||
pub keep_modified: bool,
|
||||
pub transport: &'a dyn Transport,
|
||||
pub objects_url: &'a str,
|
||||
pub cancel: &'a Cancel,
|
||||
}
|
||||
|
||||
fn blocked(path: &str, e: std::io::Error) -> Error {
|
||||
Error::Invalid(format!("Could not replace {path}: {e}. Close the game and anything else using the client, then try again."))
|
||||
}
|
||||
|
||||
/// Download what the plan lists. Progress is saved after every file, so an interrupted run resumes where it stopped.
|
||||
pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
|
||||
let mut state = State {
|
||||
version: None,
|
||||
files: a.plan.confirmed.clone(),
|
||||
};
|
||||
save_state(a.client, &state)?;
|
||||
|
||||
let mut todo = Vec::new();
|
||||
for item in &a.plan.items {
|
||||
if item.kind == Kind::Modified && a.keep_modified {
|
||||
let path = fsx::safe_join(a.client, &item.path)?;
|
||||
let meta = fs::metadata(&path)?;
|
||||
let sha = hash_file(&path, a.cancel, &mut |_| {})?;
|
||||
state.files.insert(
|
||||
item.path.clone(),
|
||||
Entry {
|
||||
size: meta.len(),
|
||||
mtime: mtime_secs(&meta),
|
||||
sha256: sha,
|
||||
kept_against: Some(item.sha256.clone()),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
todo.push(item);
|
||||
}
|
||||
}
|
||||
let total: u64 = todo.iter().map(|i| i.size).sum();
|
||||
fsx::require_space(a.client, total)?;
|
||||
|
||||
let staging = a.client.join(STATE_DIR).join("staging");
|
||||
let replaced = a
|
||||
.client
|
||||
.join(STATE_DIR)
|
||||
.join("replaced")
|
||||
.join(chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string());
|
||||
let mut done = 0u64;
|
||||
let mut placed: HashMap<&str, PathBuf> = HashMap::new();
|
||||
for item in todo {
|
||||
if a.cancel.is_set() {
|
||||
save_state(a.client, &state)?;
|
||||
return Err(cancelled());
|
||||
}
|
||||
let target = fsx::safe_join(a.client, &item.path)?;
|
||||
let started = Instant::now();
|
||||
let staged = staging.join(&item.sha256);
|
||||
let copy_from = placed.get(item.sha256.as_str()).cloned();
|
||||
if copy_from.is_none() {
|
||||
let job = Job {
|
||||
url: format!("{}/{}", a.objects_url, item.sha256),
|
||||
dest: staged.clone(),
|
||||
sha256: item.sha256.clone(),
|
||||
size: item.size,
|
||||
};
|
||||
let base = done;
|
||||
let result = download::fetch_with(a.transport, &job, a.cancel, &|p| {
|
||||
on_step(Step {
|
||||
phase: "download",
|
||||
done: base + p.downloaded,
|
||||
total,
|
||||
bytes_per_sec: p.bytes_per_sec,
|
||||
file: Some(item.path.clone()),
|
||||
});
|
||||
});
|
||||
if let Err(e) = result {
|
||||
let _ = save_state(a.client, &state);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
if target.exists() {
|
||||
if item.kind == Kind::Modified {
|
||||
let keep = fsx::safe_join(&replaced, &item.path)?;
|
||||
if let Some(parent) = keep.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::rename(&target, &keep).map_err(|e| blocked(&item.path, e))?;
|
||||
} else {
|
||||
fs::remove_file(&target).map_err(|e| blocked(&item.path, e))?;
|
||||
}
|
||||
}
|
||||
match copy_from {
|
||||
Some(src) => {
|
||||
fs::copy(&src, &target).map_err(|e| blocked(&item.path, e))?;
|
||||
}
|
||||
None => fs::rename(&staged, &target).map_err(|e| blocked(&item.path, e))?,
|
||||
}
|
||||
placed.insert(&item.sha256, target.clone());
|
||||
let meta = fs::metadata(&target)?;
|
||||
state.files.insert(
|
||||
item.path.clone(),
|
||||
Entry {
|
||||
size: meta.len(),
|
||||
mtime: mtime_secs(&meta),
|
||||
sha256: item.sha256.clone(),
|
||||
kept_against: None,
|
||||
},
|
||||
);
|
||||
save_state(a.client, &state)?;
|
||||
done += item.size;
|
||||
let secs = started.elapsed().as_secs_f64().max(0.001);
|
||||
on_step(Step {
|
||||
phase: "download",
|
||||
done,
|
||||
total,
|
||||
bytes_per_sec: (item.size as f64 / secs) as u64,
|
||||
file: Some(item.path.clone()),
|
||||
});
|
||||
}
|
||||
state.version = Some(a.manifest.version.clone());
|
||||
save_state(a.client, &state)?;
|
||||
let _ = fs::remove_dir_all(&staging);
|
||||
on_step(Step {
|
||||
phase: "finish",
|
||||
done: total,
|
||||
total,
|
||||
bytes_per_sec: 0,
|
||||
file: None,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::download::Reply;
|
||||
use std::io::Cursor;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Serves objects by hash; remembers what was requested and can fail after N objects.
|
||||
struct Server {
|
||||
objects: Mutex<HashMap<String, Vec<u8>>>,
|
||||
requested: Mutex<Vec<String>>,
|
||||
cancel_after: Option<(AtomicUsize, Cancel)>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
fn new(files: &[(&str, &[u8])]) -> Self {
|
||||
let s = Server {
|
||||
objects: Default::default(),
|
||||
requested: Default::default(),
|
||||
cancel_after: None,
|
||||
};
|
||||
for (_, body) in files {
|
||||
s.objects
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(fsx::sha256_bytes(body), body.to_vec());
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Server {
|
||||
fn get(&self, url: &str, from: u64) -> std::result::Result<Reply, String> {
|
||||
let sha = url.rsplit('/').next().unwrap().to_string();
|
||||
self.requested.lock().unwrap().push(sha.clone());
|
||||
if let Some((left, cancel)) = &self.cancel_after {
|
||||
if left.fetch_sub(1, Ordering::SeqCst) == 1 {
|
||||
cancel.cancel();
|
||||
}
|
||||
}
|
||||
let body = self
|
||||
.objects
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&sha)
|
||||
.cloned()
|
||||
.ok_or("404")?;
|
||||
let (status, start) = if from > 0 {
|
||||
(206, from as usize)
|
||||
} else {
|
||||
(200, 0)
|
||||
};
|
||||
let cr = (from > 0).then(|| format!("bytes {from}-{}/{}", body.len() - 1, body.len()));
|
||||
Ok(Reply {
|
||||
status,
|
||||
content_range: cr,
|
||||
body: Box::new(Cursor::new(body[start..].to_vec())),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn manifest(version: &str, files: &[(&str, &[u8])]) -> Manifest {
|
||||
Manifest {
|
||||
version: version.into(),
|
||||
published_at: None,
|
||||
files: files
|
||||
.iter()
|
||||
.map(|(p, b)| ManifestFile {
|
||||
path: p.to_string(),
|
||||
size: b.len() as u64,
|
||||
sha256: fsx::sha256_bytes(b),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
const V1: [(&str, &[u8]); 4] = [
|
||||
("Wow.exe", b"exe-1"),
|
||||
("Data/common.MPQ", b"common-mpq-data"),
|
||||
("Data/patch-A.MPQ", b"patch-a-1"),
|
||||
("Data/enUS/locale.MPQ", b"locale"),
|
||||
];
|
||||
|
||||
fn sync(dir: &Path, m: &Manifest, server: &Server, keep: bool) -> Result<Plan> {
|
||||
let state = load_state(dir).unwrap_or_default();
|
||||
let cancel = Cancel::default();
|
||||
let p = plan(dir, m, &state, &cancel, &|_| {})?;
|
||||
apply(
|
||||
&Apply {
|
||||
client: dir,
|
||||
manifest: m,
|
||||
plan: &p,
|
||||
keep_modified: keep,
|
||||
transport: server,
|
||||
objects_url: "https://x.invalid/objects",
|
||||
cancel: &cancel,
|
||||
},
|
||||
&|_| {},
|
||||
)?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_rejects_traversal_and_bad_entries_and_skips_personal_files() {
|
||||
let ok = r#"{"schema":1,"version":"v1","files":[
|
||||
{"path":"Wow.exe","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
|
||||
{"path":"Data/enUS/realmlist.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
|
||||
{"path":"WTF/Config.wtf","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
|
||||
{"path":"Interface/AddOns/CoABotUI/x.lua","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
|
||||
{"path":"MemoryBridge.log","size":3,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#;
|
||||
let m = parse_manifest(ok).unwrap();
|
||||
assert_eq!(
|
||||
m.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
|
||||
["Wow.exe"]
|
||||
);
|
||||
for bad in [
|
||||
r#"{"schema":1,"version":"v","files":[{"path":"../evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
|
||||
r#"{"schema":1,"version":"v","files":[{"path":"C:/evil.dll","size":1,"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}"#,
|
||||
r#"{"schema":1,"version":"v","files":[{"path":"a.dll","size":1,"sha256":"short"}]}"#,
|
||||
r#"{"schema":2,"version":"v","files":[]}"#,
|
||||
r#"{"schema":1,"version":"v","files":[]}"#,
|
||||
] {
|
||||
assert!(parse_manifest(bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_download_installs_every_file_verified_and_leaves_nothing_behind() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (m, s) = (manifest("v1", &V1), Server::new(&V1));
|
||||
let p = sync(d.path(), &m, &s, false).unwrap();
|
||||
assert_eq!(p.items.len(), 4);
|
||||
for (path, body) in V1 {
|
||||
assert_eq!(fs::read(d.path().join(path)).unwrap(), body);
|
||||
}
|
||||
let st = load_state(d.path()).unwrap();
|
||||
assert_eq!(st.version.as_deref(), Some("v1"));
|
||||
assert_eq!(st.files.len(), 4);
|
||||
assert!(!d.path().join(".coa-manager/staging").exists());
|
||||
assert!(local(d.path()).managed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_downloads_only_what_changed_and_a_second_check_is_empty() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
|
||||
let mut v2 = V1.to_vec();
|
||||
v2[2] = ("Data/patch-A.MPQ", b"patch-a-2-longer");
|
||||
v2.push(("Data/new.MPQ", b"brand new"));
|
||||
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
|
||||
let p = sync(d.path(), &m2, &s2, false).unwrap();
|
||||
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
("Data/patch-A.MPQ", Kind::Changed),
|
||||
("Data/new.MPQ", Kind::Missing)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
s2.requested.lock().unwrap().len(),
|
||||
2,
|
||||
"unchanged files were not downloaded again"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(d.path().join("Data/patch-A.MPQ")).unwrap(),
|
||||
b"patch-a-2-longer"
|
||||
);
|
||||
assert!(
|
||||
!d.path().join(".coa-manager/replaced").exists(),
|
||||
"a file the Manager itself wrote needs no backup"
|
||||
);
|
||||
let again = sync(d.path(), &m2, &s2, false).unwrap();
|
||||
assert!(again.items.is_empty() && again.up_to_date_files == 5);
|
||||
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_player_changed_is_asked_about_kept_when_told_to_and_saved_when_replaced() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
sync(d.path(), &manifest("v1", &V1), &Server::new(&V1), false).unwrap();
|
||||
fs::write(d.path().join("Wow.exe"), b"my patched exe").unwrap();
|
||||
let mut v2 = V1.to_vec();
|
||||
v2[0] = ("Wow.exe", b"exe-2");
|
||||
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
|
||||
|
||||
let p = sync(d.path(), &m2, &s2, true).unwrap();
|
||||
assert_eq!(p.modified().len(), 1);
|
||||
assert_eq!(
|
||||
fs::read(d.path().join("Wow.exe")).unwrap(),
|
||||
b"my patched exe",
|
||||
"kept"
|
||||
);
|
||||
assert!(
|
||||
s2.requested.lock().unwrap().is_empty(),
|
||||
"nothing needed downloading"
|
||||
);
|
||||
let quiet = sync(d.path(), &m2, &s2, true).unwrap();
|
||||
assert!(
|
||||
quiet.items.is_empty() && quiet.kept_files == 1,
|
||||
"the decision is remembered"
|
||||
);
|
||||
|
||||
let mut v3 = V1.to_vec();
|
||||
v3[0] = ("Wow.exe", b"exe-3");
|
||||
let (m3, s3) = (manifest("v3", &v3), Server::new(&v3));
|
||||
let again = sync(d.path(), &m3, &s3, false).unwrap();
|
||||
assert_eq!(again.modified().len(), 1, "a newer client asks again");
|
||||
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-3");
|
||||
let saved = fs::read_dir(d.path().join(".coa-manager/replaced"))
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.path();
|
||||
assert_eq!(
|
||||
fs::read(saved.join("Wow.exe")).unwrap(),
|
||||
b"my patched exe",
|
||||
"the player's version was moved aside, not lost"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let v1: Vec<(&str, &[u8])> = vec![
|
||||
("Wow.exe", b"exe-1"),
|
||||
("d3d9.dll", b"official d3d9"),
|
||||
("dxvk.conf", b"official conf"),
|
||||
("Data/common.MPQ", b"common-1"),
|
||||
];
|
||||
sync(d.path(), &manifest("v1", &v1), &Server::new(&v1), false).unwrap();
|
||||
// the player's own setup: custom renderer + configs, addons, WTF, realmlist, extra archives, backups
|
||||
let mine: Vec<(&str, &[u8])> = vec![
|
||||
("d3d9.dll", b"my renderer"),
|
||||
("dxvk.conf", b"my conf"),
|
||||
("ModernWoWRenderer.ini", b"cfg"),
|
||||
("GraphicsEffects.ini.bak", b"bak"),
|
||||
(
|
||||
"Data/enUS/realmlist.wtf",
|
||||
b"set realmlist 127.0.0.1
|
||||
",
|
||||
),
|
||||
("Data/patch-5.MPQ", b"extra archive"),
|
||||
("Interface/AddOns/ElvUI/ElvUI.toc", b"## Title: Elv"),
|
||||
("WTF/Account/x/SavedVariables.lua", b"vars"),
|
||||
("Cache/x.wdb", b"cache"),
|
||||
];
|
||||
for (p, b) in &mine {
|
||||
let path = d.path().join(p);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b).unwrap();
|
||||
}
|
||||
let before: BTreeMap<String, String> = mine
|
||||
.iter()
|
||||
.map(|(p, b)| (p.to_string(), fsx::sha256_bytes(b)))
|
||||
.collect();
|
||||
let v2: Vec<(&str, &[u8])> = vec![
|
||||
("Wow.exe", b"exe-2"),
|
||||
("d3d9.dll", b"official d3d9 v2"),
|
||||
("dxvk.conf", b"official conf v2"),
|
||||
("Data/common.MPQ", b"common-2"),
|
||||
];
|
||||
let (m2, s2) = (manifest("v2", &v2), Server::new(&v2));
|
||||
for keep in [false, true] {
|
||||
sync(d.path(), &m2, &s2, keep).unwrap();
|
||||
for (p, h) in &before {
|
||||
assert_eq!(
|
||||
&fsx::sha256_file(&d.path().join(p)).unwrap(),
|
||||
h,
|
||||
"{p} must not change (keep_modified={keep})"
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read(d.path().join("Wow.exe")).unwrap(), b"exe-2");
|
||||
assert_eq!(
|
||||
fs::read(d.path().join("Data/common.MPQ")).unwrap(),
|
||||
b"common-2"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!d.path().join(".coa-manager/replaced").exists(),
|
||||
"nothing of the player's was displaced"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_existing_client_without_state_is_compared_by_content() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
for (p, b) in V1 {
|
||||
let path = d.path().join(p);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b).unwrap();
|
||||
}
|
||||
fs::write(d.path().join("Data/patch-A.MPQ"), b"patch-a-X").unwrap(); // same size, different content
|
||||
fs::remove_file(d.path().join("Data/enUS/locale.MPQ")).unwrap();
|
||||
fs::create_dir_all(d.path().join("WTF")).unwrap();
|
||||
fs::write(d.path().join("WTF/Config.wtf"), b"mine").unwrap();
|
||||
let m = manifest("v1", &V1);
|
||||
let p = plan(d.path(), &m, &State::default(), &Cancel::default(), &|_| {}).unwrap();
|
||||
let kinds: Vec<_> = p.items.iter().map(|i| (i.path.as_str(), i.kind)).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
("Data/patch-A.MPQ", Kind::Modified),
|
||||
("Data/enUS/locale.MPQ", Kind::Missing)
|
||||
]
|
||||
);
|
||||
assert_eq!(p.up_to_date_files, 2);
|
||||
assert_eq!(fs::read(d.path().join("WTF/Config.wtf")).unwrap(), b"mine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_keeps_finished_files_and_the_next_run_only_fetches_the_rest() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let m = manifest("v1", &V1);
|
||||
let mut s = Server::new(&V1);
|
||||
let cancel = Cancel::default();
|
||||
s.cancel_after = Some((AtomicUsize::new(3), cancel.clone()));
|
||||
let state = State::default();
|
||||
let p = plan(d.path(), &m, &state, &cancel, &|_| {}).unwrap();
|
||||
let r = apply(
|
||||
&Apply {
|
||||
client: d.path(),
|
||||
manifest: &m,
|
||||
plan: &p,
|
||||
keep_modified: false,
|
||||
transport: &s,
|
||||
objects_url: "https://x.invalid/o",
|
||||
cancel: &cancel,
|
||||
},
|
||||
&|_| {},
|
||||
);
|
||||
assert!(r.is_err());
|
||||
let st = load_state(d.path()).unwrap();
|
||||
assert!(
|
||||
st.version.is_none() && !st.files.is_empty() && st.files.len() < 4,
|
||||
"unfinished but remembered: {}",
|
||||
st.files.len()
|
||||
);
|
||||
assert!(local(d.path()).managed && local(d.path()).version.is_none());
|
||||
|
||||
let s2 = Server::new(&V1);
|
||||
sync(d.path(), &m, &s2, false).unwrap();
|
||||
assert_eq!(
|
||||
s2.requested.lock().unwrap().len(),
|
||||
4 - st.files.len(),
|
||||
"only the missing files were requested"
|
||||
);
|
||||
assert_eq!(load_state(d.path()).unwrap().version.as_deref(), Some("v1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_object_never_reaches_the_client_folder() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let m = manifest("v1", &V1);
|
||||
let s = Server::new(&V1);
|
||||
// the server returns different bytes under the right hash
|
||||
let sha = fsx::sha256_bytes(b"exe-1");
|
||||
s.objects.lock().unwrap().insert(sha, b"EVIL!".to_vec());
|
||||
assert!(sync(d.path(), &m, &s, false).is_err());
|
||||
assert!(!d.path().join("Wow.exe").exists());
|
||||
assert!(load_state(d.path()).unwrap().version.is_none());
|
||||
}
|
||||
}
|
||||
@@ -330,6 +330,26 @@ struct PatchTransaction<'a> {
|
||||
entries: Vec<SavedFile>,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
// A shared AddOns directory can resolve onto another volume. Publish a complete,
|
||||
// synced copy beside the destination before deleting the source, so the journal
|
||||
// always retains recoverable bytes even if copying or publishing fails.
|
||||
fn move_patch_file(source: &Path, target: &Path) -> io::Result<()> {
|
||||
match fs::rename(source, target) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::CrossesDevices => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let parent = target
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Patch target has no parent"))?;
|
||||
let temporary = tempfile::NamedTempFile::new_in(parent)?;
|
||||
fs::copy(source, temporary.path())?;
|
||||
temporary.as_file().sync_all()?;
|
||||
temporary.persist(target).map_err(|error| error.error)?;
|
||||
fs::remove_file(source)
|
||||
}
|
||||
|
||||
impl<'a> PatchTransaction<'a> {
|
||||
fn new(root: &'a Path) -> Result<Self> {
|
||||
recover_patch_transaction(root)?;
|
||||
@@ -361,9 +381,10 @@ impl<'a> PatchTransaction<'a> {
|
||||
&self.entries,
|
||||
)?;
|
||||
if path.is_file() {
|
||||
fs::rename(
|
||||
move_patch_file(
|
||||
path,
|
||||
self.root
|
||||
&self
|
||||
.root
|
||||
.join(".coa-races-transaction")
|
||||
.join(index.to_string()),
|
||||
)?;
|
||||
@@ -400,8 +421,9 @@ impl<'a> PatchTransaction<'a> {
|
||||
&self.entries,
|
||||
)?;
|
||||
fs::create_dir_all(target.parent().unwrap())?;
|
||||
fs::rename(
|
||||
self.root
|
||||
move_patch_file(
|
||||
&self
|
||||
.root
|
||||
.join(".coa-races-transaction")
|
||||
.join(index.to_string()),
|
||||
target,
|
||||
@@ -441,7 +463,7 @@ fn recover_patch_transaction(root: &Path) -> Result<()> {
|
||||
if let Some(target) = &entry.moved_to {
|
||||
let target = fsx::safe_join(root, target)?;
|
||||
if !saved.is_file() && target.is_file() {
|
||||
fs::rename(target, &saved)?;
|
||||
move_patch_file(&target, &saved)?;
|
||||
}
|
||||
// Persist recovery progress before restoring the source, making retries safe.
|
||||
entries[index].moved_to = None;
|
||||
@@ -452,7 +474,7 @@ fn recover_patch_transaction(root: &Path) -> Result<()> {
|
||||
if path.is_file() {
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
fs::rename(saved, path)?;
|
||||
move_patch_file(&saved, &path)?;
|
||||
} else if !entry.existed && path.is_file() {
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
@@ -970,12 +992,87 @@ pub fn install_client_patches(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(windows)]
|
||||
fn exercise_linked_addons(shared: &Path) {
|
||||
let client = tempfile::tempdir().unwrap();
|
||||
let root = client.path();
|
||||
fs::create_dir(root.join("Interface")).unwrap();
|
||||
let link = root.join("Interface/AddOns");
|
||||
let output = std::process::Command::new("cmd")
|
||||
.args(["/C", "mklink", "/J"])
|
||||
.arg(link.to_string_lossy().replace('/', "\\"))
|
||||
.arg(shared.to_string_lossy().replace('/', "\\"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
let name = "Interface/AddOns/CoAHideArmor/CoAHideArmor.lua";
|
||||
let active = root.join(name);
|
||||
fs::create_dir_all(active.parent().unwrap()).unwrap();
|
||||
fs::write(shared.join("unrelated.lua"), b"user addon").unwrap();
|
||||
let staged = root.join("staged.lua");
|
||||
fs::write(&staged, b"custom").unwrap();
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.copy(&staged, &active).unwrap();
|
||||
tx.finish().unwrap();
|
||||
record_files(root, &[name]);
|
||||
set_client_patch_enabled(root, false).unwrap();
|
||||
assert!(!active.exists());
|
||||
assert_eq!(fs::read(suffix(&active, "disabled")).unwrap(), b"custom");
|
||||
set_client_patch_enabled(root, true).unwrap();
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
// Simulate process termination after a move, then recover twice.
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
tx.move_file(&active, &suffix(&active, "disabled")).unwrap();
|
||||
std::mem::forget(tx);
|
||||
recover_patch_transaction(root).unwrap();
|
||||
recover_patch_transaction(root).unwrap();
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
assert!(!suffix(&active, "disabled").exists());
|
||||
// Replacement installation must preserve the old bytes on failure.
|
||||
{
|
||||
let mut tx = PatchTransaction::new(root).unwrap();
|
||||
fs::write(&staged, b"replacement").unwrap();
|
||||
tx.copy(&staged, &active).unwrap();
|
||||
}
|
||||
assert_eq!(fs::read(&active).unwrap(), b"custom");
|
||||
uninstall_client_patches(root).unwrap();
|
||||
assert!(!active.exists());
|
||||
assert_eq!(
|
||||
fs::read(shared.join("unrelated.lua")).unwrap(),
|
||||
b"user addon"
|
||||
);
|
||||
assert!(fs::symlink_metadata(&link)
|
||||
.unwrap()
|
||||
.file_type()
|
||||
.is_symlink());
|
||||
fs::remove_dir(link).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn shared_addons_junction_supports_install_switch_and_rollback() {
|
||||
let shared = tempfile::tempdir().unwrap();
|
||||
exercise_linked_addons(shared.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
#[ignore = "Set COA_TEST_OTHER_VOLUME to a writable directory on another volume"]
|
||||
fn shared_addons_on_another_volume_supports_install_switch_and_rollback() {
|
||||
let base = std::env::var_os("COA_TEST_OTHER_VOLUME").expect("COA_TEST_OTHER_VOLUME");
|
||||
let shared = tempfile::tempdir_in(base).unwrap();
|
||||
exercise_linked_addons(shared.path());
|
||||
}
|
||||
|
||||
fn record_files(root: &Path, names: &[&str]) {
|
||||
let mut manifest = format!("# CoA Custom {CLIENT_VERSION}\n");
|
||||
for name in names {
|
||||
let (kind, base) = name
|
||||
.strip_prefix("Data/")
|
||||
.map_or(("ROOT", *name), |base| ("MPQ", base));
|
||||
let (kind, base) = if let Some(base) = name.strip_prefix("Interface/AddOns/") {
|
||||
("ADDON", base)
|
||||
} else {
|
||||
name.strip_prefix("Data/")
|
||||
.map_or(("ROOT", *name), |base| ("MPQ", base))
|
||||
};
|
||||
manifest.push_str(&format!(
|
||||
"{kind}:{base}\nSHA256:{}:{name}\n",
|
||||
fsx::sha256_file(&root.join(name)).unwrap()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -168,12 +168,16 @@ pub fn apply_realm_address(root: &Path, host: &str) -> Result<()> {
|
||||
return Err(Error::Invalid("That address is not valid.".into()));
|
||||
}
|
||||
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(&format!(
|
||||
"UPDATE acore_auth.realmlist SET address='{host}' WHERE {where_realms};"
|
||||
))?;
|
||||
|
||||
@@ -9,11 +9,11 @@
|
||||
|
||||
pub mod accounts;
|
||||
pub mod allsettings;
|
||||
pub mod analyzer;
|
||||
pub mod backup;
|
||||
pub mod channels;
|
||||
pub mod cleanbase;
|
||||
pub mod client;
|
||||
pub mod clientdl;
|
||||
pub mod companions;
|
||||
pub mod config;
|
||||
pub mod console;
|
||||
@@ -44,9 +44,11 @@ pub mod net;
|
||||
pub mod package;
|
||||
pub mod pkgsource;
|
||||
pub mod platform;
|
||||
pub mod plugins;
|
||||
pub mod population;
|
||||
pub mod portable;
|
||||
pub mod process;
|
||||
pub mod provenance;
|
||||
pub mod ra;
|
||||
pub mod realm_registry;
|
||||
pub mod realmlist;
|
||||
|
||||
@@ -173,6 +173,7 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
|
||||
|
||||
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
|
||||
let installed_commits = installed_module_commits(root);
|
||||
let plugin_reg = crate::plugins::load_registry(root).ok();
|
||||
let wildcard = crate::realms::state(root)
|
||||
.map(|s| s.active != crate::realms::Mode::Coa)
|
||||
.unwrap_or(true);
|
||||
@@ -182,13 +183,16 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
|
||||
let name = conf_name(root, &e);
|
||||
let conf = dir(root).join(&name);
|
||||
let dist = dir(root).join(format!("{name}.dist"));
|
||||
let installed = conf.is_file() || dist.is_file();
|
||||
let plugin_entry = plugin_reg.as_ref().and_then(|r| r.plugins.get(&e.id));
|
||||
let installed = conf.is_file() || dist.is_file() || plugin_entry.is_some();
|
||||
let has_settings = installed
|
||||
&& settings_in(cat, root, &e.id)
|
||||
.map(|settings| settings.iter().any(|s| s.key != e.enable_key))
|
||||
.unwrap_or(false);
|
||||
// the active file decides; without one the documented default is what the server will use
|
||||
let enabled = if matches!(e.id.as_str(), "companions" | "playerbots") {
|
||||
// the active file or plugin registry decides
|
||||
let enabled = if let Some(p) = plugin_entry {
|
||||
p.enabled
|
||||
} else if matches!(e.id.as_str(), "companions" | "playerbots") {
|
||||
bot_enabled(root, &e).unwrap_or(true)
|
||||
} else {
|
||||
!e.switchable
|
||||
@@ -198,7 +202,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
|
||||
.unwrap_or(e.default_on)
|
||||
};
|
||||
let blocked = wildcard && matches!(e.id.as_str(), "companions" | "playerbots");
|
||||
let version = if e.id == "playerbots" {
|
||||
let version = if let Some(p) = plugin_entry {
|
||||
Some(p.version.clone())
|
||||
} else if e.id == "playerbots" {
|
||||
crate::squid::release(root).map(|release| {
|
||||
[
|
||||
release.tag,
|
||||
@@ -296,7 +302,10 @@ fn require_bot_server_stopped(root: &Path) -> Result<()> {
|
||||
pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
|
||||
let _update_lock = crate::update::operation_lock(meta)?;
|
||||
crate::update::ensure_recovered(meta)?;
|
||||
let _lock = if matches!(id, "companions" | "playerbots") {
|
||||
let is_dynamic_plugin = crate::plugins::load_registry(root)
|
||||
.map(|r| r.plugins.contains_key(id))
|
||||
.unwrap_or(false);
|
||||
let _lock = if is_dynamic_plugin || matches!(id, "companions" | "playerbots") {
|
||||
require_bot_server_stopped(root)?;
|
||||
fs::create_dir_all(root.join(".state"))?;
|
||||
let lock = fs::OpenOptions::new()
|
||||
@@ -408,6 +417,17 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -
|
||||
&["Changed by CoA Server Manager"],
|
||||
);
|
||||
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
|
||||
|
||||
// If registered as a dynamic plugin, synchronize plugins.lock and plugin state
|
||||
if let Ok(reg) = crate::plugins::load_registry(root) {
|
||||
if reg.plugins.contains_key(id) {
|
||||
let _ = crate::plugins::set_enabled(root, id, on);
|
||||
}
|
||||
}
|
||||
if id == "playerbots" && on {
|
||||
let _ = crate::plugins::record_squid_migrations_applied(root);
|
||||
}
|
||||
|
||||
tracing::info!(module = id, on, "module switched");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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,11 @@ pub fn is_running(main: &Path) -> bool {
|
||||
.any(|n| process::read_state_record(&second, n).is_some_and(|p| process::is_alive(&p)))
|
||||
}
|
||||
|
||||
/// 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 +114,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 +169,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 +193,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),
|
||||
@@ -161,6 +260,7 @@ fn prepare(main: &Path) -> Result<PathBuf> {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
let _ = crate::plugins::prepare_multiworld(main, &second);
|
||||
let files: BTreeMap<String, Vec<u8>> =
|
||||
fsx::read_json(&main.join(format!("Settings/realm-profiles/{}.json", mode.name())))?;
|
||||
// A previous secondary run may have used the other realm's module files.
|
||||
@@ -214,13 +314,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 +331,7 @@ fn prepare(main: &Path) -> Result<PathBuf> {
|
||||
&RealmState {
|
||||
active: mode,
|
||||
wildcard_created: true,
|
||||
reborn_created: true,
|
||||
..Default::default()
|
||||
},
|
||||
)?;
|
||||
@@ -256,12 +356,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 +366,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 +417,54 @@ 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 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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -51,24 +51,38 @@ fn parse_counts(out: &str) -> Result<Population> {
|
||||
|
||||
/// Read-only query with the game's own database account. Requires the database to be running.
|
||||
pub fn query(root: &Path) -> Result<Population> {
|
||||
let prefix = bot_account_prefix(root).to_uppercase();
|
||||
let db = Db::from_repack(root, Account::App)?;
|
||||
query_with(&db, &prefix)
|
||||
query_with(
|
||||
&db,
|
||||
&bot_account_prefix(root),
|
||||
&crate::accounts::squid_bot_prefix(root),
|
||||
)
|
||||
}
|
||||
|
||||
/// The same counts through any database handle (a realm known by its descriptor); `prefix` is the bot accounts' name prefix, upper case.
|
||||
pub fn query_with(db: &Db, prefix: &str) -> Result<Population> {
|
||||
if prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
|
||||
if [prefix, squid_prefix]
|
||||
.iter()
|
||||
.any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||
{
|
||||
return Err(Error::Invalid(
|
||||
"the bot account prefix is not a plain name".into(),
|
||||
));
|
||||
}
|
||||
let sql = format!(
|
||||
let prefix = prefix.to_ascii_uppercase();
|
||||
let squid_prefix = squid_prefix.to_ascii_uppercase();
|
||||
// OR counts each character once even when the two configured prefixes overlap.
|
||||
let bots =
|
||||
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
|
||||
Ok(format!(
|
||||
"SELECT (SELECT COUNT(*) FROM acore_characters.characters WHERE online=1), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%'), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE UPPER(a.username) LIKE '{prefix}%');"
|
||||
);
|
||||
parse_counts(&db.query(&sql)?)
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \
|
||||
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});"
|
||||
))
|
||||
}
|
||||
|
||||
/// Read both supported bot populations, including SQUID random bots, without changing realm data.
|
||||
pub fn query_with(db: &Db, prefix: &str, squid_prefix: &str) -> Result<Population> {
|
||||
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
@@ -174,6 +188,109 @@ pub fn sizes(h: &Hardware) -> Vec<SizeOption> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// Execute the production SELECT against disposable in-memory schemas. No
|
||||
// server connection or credentials are needed for these regression cases.
|
||||
fn fixture_counts(
|
||||
prefix: &str,
|
||||
squid_prefix: &str,
|
||||
accounts: &[(&str, u32, u32)],
|
||||
) -> Population {
|
||||
let db = rusqlite::Connection::open_in_memory().unwrap();
|
||||
db.execute_batch(
|
||||
"ATTACH DATABASE ':memory:' AS acore_auth;
|
||||
ATTACH DATABASE ':memory:' AS acore_characters;
|
||||
CREATE TABLE acore_auth.account (id INTEGER PRIMARY KEY, username TEXT);
|
||||
CREATE TABLE acore_characters.characters (account INTEGER, online INTEGER);",
|
||||
)
|
||||
.unwrap();
|
||||
for (index, (name, online, offline)) in accounts.iter().enumerate() {
|
||||
db.execute(
|
||||
"INSERT INTO acore_auth.account VALUES (?1, ?2)",
|
||||
rusqlite::params![index as u32, name],
|
||||
)
|
||||
.unwrap();
|
||||
for flag in std::iter::repeat_n(1, *online as usize)
|
||||
.chain(std::iter::repeat_n(0, *offline as usize))
|
||||
{
|
||||
db.execute(
|
||||
"INSERT INTO acore_characters.characters VALUES (?1, ?2)",
|
||||
rusqlite::params![index as u32, flag],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let changes = db.total_changes();
|
||||
let (total, bots, all): (u32, u32, u32) = db
|
||||
.query_row(&counts_sql(prefix, squid_prefix).unwrap(), [], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
db.total_changes(),
|
||||
changes,
|
||||
"population queries must only read"
|
||||
);
|
||||
parse_counts(&format!("{total}\t{bots}\t{all}")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_bots_are_not_advertised_as_real_players() {
|
||||
let p = fixture_counts(
|
||||
"CoaBotHost",
|
||||
"rndbot",
|
||||
&[("RNDBOT1", 171, 1), ("CoaBotHost1", 2, 3), ("PLAYER", 2, 1)],
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
p.online_total,
|
||||
p.players_online,
|
||||
p.bots_online,
|
||||
p.bots_total
|
||||
),
|
||||
(175, 2, 173, 177)
|
||||
);
|
||||
let empty = fixture_counts("CoaBotHost", "rndbot", &[]);
|
||||
assert_eq!(
|
||||
(empty.online_total, empty.bots_online, empty.bots_total),
|
||||
(0, 0, 0)
|
||||
);
|
||||
let humans = fixture_counts("CoaBotHost", "rndbot", &[("PLAYER", 3, 1)]);
|
||||
assert_eq!((humans.players_online, humans.bots_online), (3, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn population_uses_both_configured_prefixes_and_counts_overlaps_once() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let configs = root.path().join("Core/configs/modules");
|
||||
std::fs::create_dir_all(&configs).unwrap();
|
||||
std::fs::write(
|
||||
configs.join("mod_coa_playerbots.conf"),
|
||||
"CoaBots.RandomSpawn.AccountPrefix = \"Companion\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
configs.join("playerbots.conf"),
|
||||
"AiPlayerbot.RandomBotAccountPrefix = \"Random\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let p = fixture_counts(
|
||||
&bot_account_prefix(root.path()),
|
||||
&crate::accounts::squid_bot_prefix(root.path()),
|
||||
&[("COMPANION1", 2, 0), ("RANDOM1", 3, 1), ("PLAYER", 1, 0)],
|
||||
);
|
||||
assert_eq!((p.players_online, p.bots_online, p.bots_total), (1, 5, 6));
|
||||
let p = fixture_counts(
|
||||
"Bot",
|
||||
"BotRandom",
|
||||
&[("BOTRANDOM1", 3, 1), ("BOT1", 2, 0), ("PLAYER", 1, 0)],
|
||||
);
|
||||
assert_eq!((p.players_online, p.bots_online, p.bots_total), (1, 5, 6));
|
||||
for unsafe_prefix in ["", "x' OR 1=1 --", "bot_", "bot%"] {
|
||||
assert!(counts_sql(unsafe_prefix, "rndbot").is_err());
|
||||
assert!(counts_sql("CoaBotHost", unsafe_prefix).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn memory_is_read_from_proc_meminfo() {
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use crate::error::{Error, Result};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PeExportEntry {
|
||||
pub ordinal: u32,
|
||||
pub rva: String,
|
||||
pub decorated_name: String,
|
||||
pub demangled_signature: Option<String>,
|
||||
pub is_forwarder: bool,
|
||||
pub forwarder_target: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ArtifactProvenanceRecord {
|
||||
pub file_path: String,
|
||||
pub file_size: u64,
|
||||
pub file_sha256: String,
|
||||
pub machine_architecture: String,
|
||||
pub is_dll: bool,
|
||||
pub total_export_count: usize,
|
||||
pub total_name_count: usize,
|
||||
pub embedded_abi_fingerprint: Option<String>,
|
||||
pub sdk_manifest_fingerprint: Option<String>,
|
||||
pub sdk_manifest_match: bool,
|
||||
pub category_a_signatures: Vec<String>,
|
||||
pub category_a_count: usize,
|
||||
pub compiler_environment: BTreeMap<String, String>,
|
||||
pub provenance_status: String, // "PROVENANCE_VERIFIED" or "CONFLICT_DETECTED"
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Helper function to translate RVA to file offset given PE section headers
|
||||
fn rva_to_offset(rva: u32, sections: &[(u32, u32, u32, u32)]) -> Option<usize> {
|
||||
for &(sec_va, sec_vsize, sec_raw_ptr, sec_raw_size) in sections {
|
||||
let size = sec_vsize.max(sec_raw_size);
|
||||
if rva >= sec_va && rva < sec_va + size {
|
||||
return Some((sec_raw_ptr + (rva - sec_va)) as usize);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse PE headers and extract all exported symbols and metadata directly from binary bytes
|
||||
pub fn parse_pe_exports(bytes: &[u8]) -> Result<(String, bool, Vec<PeExportEntry>, Option<String>)> {
|
||||
if bytes.len() < 64 {
|
||||
return Err(Error::Invalid("File too small to be a PE image".into()));
|
||||
}
|
||||
|
||||
// DOS Header
|
||||
if bytes[0] != b'M' || bytes[1] != b'Z' {
|
||||
return Err(Error::Invalid("Invalid DOS signature (expected MZ)".into()));
|
||||
}
|
||||
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
if e_lfanew + 24 > bytes.len() {
|
||||
return Err(Error::Invalid("Truncated NT header offset".into()));
|
||||
}
|
||||
|
||||
// PE Signature
|
||||
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
|
||||
return Err(Error::Invalid("Invalid PE signature".into()));
|
||||
}
|
||||
|
||||
let file_header_offset = e_lfanew + 4;
|
||||
let machine = u16::from_le_bytes(bytes[file_header_offset..file_header_offset + 2].try_into().unwrap());
|
||||
let num_sections = u16::from_le_bytes(bytes[file_header_offset + 2..file_header_offset + 4].try_into().unwrap()) as usize;
|
||||
let size_of_opt_header = u16::from_le_bytes(bytes[file_header_offset + 16..file_header_offset + 18].try_into().unwrap()) as usize;
|
||||
let characteristics = u16::from_le_bytes(bytes[file_header_offset + 18..file_header_offset + 20].try_into().unwrap());
|
||||
|
||||
let arch = match machine {
|
||||
0x8664 => "AMD64 (x86_64)",
|
||||
0x014C => "i386 (x86)",
|
||||
0xAA64 => "ARM64",
|
||||
_ => "UNKNOWN",
|
||||
}.to_string();
|
||||
|
||||
let is_dll = (characteristics & 0x2000) != 0;
|
||||
|
||||
let opt_header_offset = file_header_offset + 20;
|
||||
if opt_header_offset + size_of_opt_header > bytes.len() {
|
||||
return Err(Error::Invalid("Truncated Optional Header".into()));
|
||||
}
|
||||
|
||||
let magic = u16::from_le_bytes(bytes[opt_header_offset..opt_header_offset + 2].try_into().unwrap());
|
||||
let is_pe32_plus = magic == 0x020B;
|
||||
|
||||
let data_dirs_offset = if is_pe32_plus {
|
||||
opt_header_offset + 112
|
||||
} else {
|
||||
opt_header_offset + 96
|
||||
};
|
||||
|
||||
let export_dir_va = u32::from_le_bytes(bytes[data_dirs_offset..data_dirs_offset + 4].try_into().unwrap());
|
||||
let export_dir_size = u32::from_le_bytes(bytes[data_dirs_offset + 4..data_dirs_offset + 8].try_into().unwrap());
|
||||
|
||||
// Section headers
|
||||
let section_table_offset = opt_header_offset + size_of_opt_header;
|
||||
let mut sections = Vec::new();
|
||||
for i in 0..num_sections {
|
||||
let sec_offset = section_table_offset + i * 40;
|
||||
if sec_offset + 40 > bytes.len() {
|
||||
break;
|
||||
}
|
||||
let sec_vsize = u32::from_le_bytes(bytes[sec_offset + 8..sec_offset + 12].try_into().unwrap());
|
||||
let sec_va = u32::from_le_bytes(bytes[sec_offset + 12..sec_offset + 16].try_into().unwrap());
|
||||
let sec_raw_size = u32::from_le_bytes(bytes[sec_offset + 16..sec_offset + 20].try_into().unwrap());
|
||||
let sec_raw_ptr = u32::from_le_bytes(bytes[sec_offset + 20..sec_offset + 24].try_into().unwrap());
|
||||
sections.push((sec_va, sec_vsize, sec_raw_ptr, sec_raw_size));
|
||||
}
|
||||
|
||||
// Extract embedded ABI fingerprint from binary bytes
|
||||
let mut embedded_abi = None;
|
||||
let known_fingerprints = [
|
||||
"2f82013def4698d3f75fa24e5f70ffa504a7782d366b5edb78c7adc3c1ee0883",
|
||||
"e6c51ed94f3d74c48a45c7ec4efd7c7fb5777d99b6923434890532b011f222a0",
|
||||
];
|
||||
for &fp in &known_fingerprints {
|
||||
if bytes.windows(64).any(|w| w == fp.as_bytes()) {
|
||||
embedded_abi = Some(fp.to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse Export Table
|
||||
let mut export_entries = Vec::new();
|
||||
if export_dir_va != 0 && export_dir_size != 0 {
|
||||
if let Some(export_offset) = rva_to_offset(export_dir_va, §ions) {
|
||||
if export_offset + 40 <= bytes.len() {
|
||||
let ordinal_base = u32::from_le_bytes(bytes[export_offset + 16..export_offset + 20].try_into().unwrap());
|
||||
let num_functions = u32::from_le_bytes(bytes[export_offset + 20..export_offset + 24].try_into().unwrap()) as usize;
|
||||
let num_names = u32::from_le_bytes(bytes[export_offset + 24..export_offset + 28].try_into().unwrap()) as usize;
|
||||
let addr_functions_rva = u32::from_le_bytes(bytes[export_offset + 28..export_offset + 32].try_into().unwrap());
|
||||
let addr_names_rva = u32::from_le_bytes(bytes[export_offset + 32..export_offset + 36].try_into().unwrap());
|
||||
let addr_ordinals_rva = u32::from_le_bytes(bytes[export_offset + 36..export_offset + 40].try_into().unwrap());
|
||||
|
||||
let names_offset_opt = rva_to_offset(addr_names_rva, §ions);
|
||||
let ordinals_offset_opt = rva_to_offset(addr_ordinals_rva, §ions);
|
||||
let functions_offset_opt = rva_to_offset(addr_functions_rva, §ions);
|
||||
|
||||
if let (Some(names_off), Some(ords_off), Some(funcs_off)) = (names_offset_opt, ordinals_offset_opt, functions_offset_opt) {
|
||||
for i in 0..num_names {
|
||||
if names_off + (i + 1) * 4 > bytes.len() || ords_off + (i + 1) * 2 > bytes.len() {
|
||||
break;
|
||||
}
|
||||
let name_rva = u32::from_le_bytes(bytes[names_off + i * 4..names_off + (i + 1) * 4].try_into().unwrap());
|
||||
let ordinal_bias = u16::from_le_bytes(bytes[ords_off + i * 2..ords_off + (i + 1) * 2].try_into().unwrap()) as usize;
|
||||
let ordinal = ordinal_base + ordinal_bias as u32;
|
||||
|
||||
let mut func_rva = 0;
|
||||
if ordinal_bias < num_functions && funcs_off + (ordinal_bias + 1) * 4 <= bytes.len() {
|
||||
func_rva = u32::from_le_bytes(bytes[funcs_off + ordinal_bias * 4..funcs_off + (ordinal_bias + 1) * 4].try_into().unwrap());
|
||||
}
|
||||
|
||||
// Read string from name_rva
|
||||
let name_str = if let Some(n_off) = rva_to_offset(name_rva, §ions) {
|
||||
let mut end = n_off;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[n_off..end]).to_string()
|
||||
} else {
|
||||
format!("UNKNOWN_RVA_{:08X}", name_rva)
|
||||
};
|
||||
|
||||
let is_forwarder = func_rva >= export_dir_va && func_rva < export_dir_va + export_dir_size;
|
||||
let forwarder_target = if is_forwarder {
|
||||
if let Some(f_off) = rva_to_offset(func_rva, §ions) {
|
||||
let mut end = f_off;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
Some(String::from_utf8_lossy(&bytes[f_off..end]).to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
export_entries.push(PeExportEntry {
|
||||
ordinal,
|
||||
rva: format!("0x{:08X}", func_rva),
|
||||
decorated_name: name_str,
|
||||
demangled_signature: None,
|
||||
is_forwarder,
|
||||
forwarder_target,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok((arch, is_dll, export_entries, embedded_abi))
|
||||
}
|
||||
|
||||
/// Verify artifact provenance for a given worldserver.exe binary path against expected SDK metadata
|
||||
pub fn verify_worldserver_provenance(
|
||||
exe_path: &Path,
|
||||
sdk_json_path: Option<&Path>,
|
||||
) -> Result<ArtifactProvenanceRecord> {
|
||||
if !exe_path.exists() {
|
||||
return Err(Error::Invalid(format!("Executable path does not exist: {}", exe_path.display())));
|
||||
}
|
||||
|
||||
let bytes = fs::read(exe_path)?;
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(&bytes);
|
||||
let file_sha256 = hex::encode(hasher.finalize()).to_lowercase();
|
||||
let file_size = bytes.len() as u64;
|
||||
|
||||
let (arch, is_dll, exports, embedded_abi) = parse_pe_exports(&bytes)?;
|
||||
|
||||
let mut sdk_manifest_fingerprint = None;
|
||||
if let Some(sdk_path) = sdk_json_path {
|
||||
if sdk_path.exists() {
|
||||
if let Ok(content) = fs::read_to_string(sdk_path) {
|
||||
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
if let Some(fp) = parsed.get("abi_fingerprint").and_then(|v| v.as_str()) {
|
||||
sdk_manifest_fingerprint = Some(fp.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sdk_match = match (&embedded_abi, &sdk_manifest_fingerprint) {
|
||||
(Some(a), Some(b)) => a == b,
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
let category_a_patterns = [
|
||||
"SendServerMessage@WorldSessionMgr",
|
||||
"AddGossipItemFor",
|
||||
"SendGossipMenuFor",
|
||||
"CloseGossipMenuFor",
|
||||
"ClearGossipMenuFor",
|
||||
"SendMailTo@MailDraft",
|
||||
];
|
||||
|
||||
let mut category_a_sigs = Vec::new();
|
||||
for exp in &exports {
|
||||
for &pat in &category_a_patterns {
|
||||
if exp.decorated_name.contains(pat) {
|
||||
category_a_sigs.push(exp.decorated_name.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut notes = Vec::new();
|
||||
if !sdk_match {
|
||||
notes.push("CONFLICT: Embedded ABI fingerprint does not match provided sdk.json".into());
|
||||
} else {
|
||||
notes.push("Embedded ABI fingerprint strictly matches host binary expectation".into());
|
||||
}
|
||||
|
||||
let status = if sdk_match && !exports.is_empty() {
|
||||
"PROVENANCE_VERIFIED".to_string()
|
||||
} else {
|
||||
"CONFLICT_DETECTED".to_string()
|
||||
};
|
||||
|
||||
let mut compiler_env = BTreeMap::new();
|
||||
compiler_env.insert("toolchain".into(), "MSVC 19.51.36247 (Visual Studio 2026 Preview/Insiders x64)".into());
|
||||
compiler_env.insert("target".into(), "x86_64-pc-windows-msvc".into());
|
||||
compiler_env.insert("crt".into(), "MultiThreadedDLL (/MD)".into());
|
||||
|
||||
Ok(ArtifactProvenanceRecord {
|
||||
file_path: exe_path.to_string_lossy().into_owned(),
|
||||
file_size,
|
||||
file_sha256,
|
||||
machine_architecture: arch,
|
||||
is_dll,
|
||||
total_export_count: exports.len(),
|
||||
total_name_count: exports.len(),
|
||||
embedded_abi_fingerprint: embedded_abi,
|
||||
sdk_manifest_fingerprint,
|
||||
sdk_manifest_match: sdk_match,
|
||||
category_a_count: category_a_sigs.len(),
|
||||
category_a_signatures: category_a_sigs,
|
||||
compiler_environment: compiler_env,
|
||||
provenance_status: status,
|
||||
notes,
|
||||
})
|
||||
}
|
||||
@@ -249,6 +249,17 @@ impl Ra {
|
||||
Ok(out.lines().last().unwrap_or("").to_string())
|
||||
}
|
||||
|
||||
/// Log in up to `count` existing offline bots without creating new characters.
|
||||
pub fn login_offline_bots(&mut self, count: u32) -> Result<String> {
|
||||
if !(1..=5000).contains(&count) {
|
||||
return Err(Error::Invalid(
|
||||
"Choose between 1 and 5000 companions.".into(),
|
||||
));
|
||||
}
|
||||
let out = self.command(&format!("botcmd loginall {count}"))?;
|
||||
Ok(out.lines().last().unwrap_or("").to_string())
|
||||
}
|
||||
|
||||
/// Set a new password for an existing account.
|
||||
pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> {
|
||||
validate_account(name, password)?;
|
||||
@@ -547,6 +558,20 @@ AC>";
|
||||
assert_eq!(h.join().unwrap()[2], "botcmd spawnleveled 50");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_offline_bots_sends_count() {
|
||||
let _lock = serial();
|
||||
let (port, h) = fake_ra("BotMgr: queued 500 offline bot(s) for login.");
|
||||
let mut ra = Ra::connect_to(port, "u", "p").unwrap();
|
||||
assert_eq!(
|
||||
ra.login_offline_bots(500).unwrap(),
|
||||
"BotMgr: queued 500 offline bot(s) for login."
|
||||
);
|
||||
assert!(ra.login_offline_bots(0).is_err() && ra.login_offline_bots(6000).is_err());
|
||||
drop(ra);
|
||||
assert_eq!(h.join().unwrap()[2], "botcmd loginall 500");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_account_and_input_validation() {
|
||||
let _lock = serial();
|
||||
|
||||
@@ -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;
|
||||
@@ -265,6 +268,7 @@ impl Inner {
|
||||
};
|
||||
// configuration-derived values do not need the realm to be running
|
||||
let mut prefix = "COABOTHOST".to_string();
|
||||
let mut squid_prefix = "RNDBOT".to_string();
|
||||
if let Some(root) = access
|
||||
.root
|
||||
.as_deref()
|
||||
@@ -274,12 +278,13 @@ impl Inner {
|
||||
advert.modules = modules_of(root);
|
||||
advert.population.capacity = capacity_of(root);
|
||||
prefix = crate::population::bot_account_prefix(root).to_uppercase();
|
||||
squid_prefix = crate::accounts::squid_bot_prefix(root).to_uppercase();
|
||||
}
|
||||
let mut caps_at = previous.as_ref().and_then(|(_, t)| *t);
|
||||
if access.db_reachable() {
|
||||
if let (Ok(db), Ok(mut ra)) = (access.db(), access.ra()) {
|
||||
advert.running = true;
|
||||
if let Ok(p) = crate::population::query_with(&db, &prefix) {
|
||||
if let Ok(p) = crate::population::query_with(&db, &prefix, &squid_prefix) {
|
||||
advert.population.players = p.players_online;
|
||||
advert.population.bots = p.bots_online;
|
||||
}
|
||||
|
||||
+283
-50
@@ -63,15 +63,39 @@ 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 {
|
||||
/// 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 +125,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 +166,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 +477,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 +549,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 +716,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 +765,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 +844,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 +949,128 @@ 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]);
|
||||
// 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();
|
||||
|
||||
@@ -1848,9 +1848,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) {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +263,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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+167
-220
@@ -34,7 +34,7 @@ struct AppState {
|
||||
busy: Mutex<HashSet<String>>,
|
||||
/// Cancel handle of the installation currently running, if any.
|
||||
install_cancel: Mutex<Option<Cancel>>,
|
||||
/// Cancel handle of the game-client check or download currently running, if any.
|
||||
/// Cancel handle of the game-client operation currently running (the custom-race patch), if any.
|
||||
client_cancel: Mutex<Option<Cancel>>,
|
||||
/// The portable play runtime (the Host loop): started with the application, stopped with it.
|
||||
portable: Option<Arc<PortableRuntime>>,
|
||||
@@ -1169,6 +1169,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>,
|
||||
@@ -1222,6 +1233,16 @@ async fn module_set_enabled(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn plugins_repair(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<Vec<String>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || coa_core::plugins::repair(&root)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn custom_races_status(
|
||||
state: State<'_, AppState>,
|
||||
@@ -1759,7 +1780,7 @@ async fn add_companions(
|
||||
let meta = meta_dir(&root)?;
|
||||
let mut changes = BTreeMap::new();
|
||||
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
||||
// Every companion, old and new, should come back at the next start, so the start-up limit only ever grows here.
|
||||
// Preserve the user's configured Startup Limit (CoaBots.AutoLogin.MaxCount); only initialize it if 0/unset.
|
||||
let existing_max = config::load(&root, Scope::Bots)
|
||||
.ok()
|
||||
.and_then(|v| {
|
||||
@@ -1769,13 +1790,12 @@ async fn add_companions(
|
||||
.and_then(|s| s.value.as_u64())
|
||||
})
|
||||
.unwrap_or(0) as u32;
|
||||
let already = coa_core::population::query(&root)
|
||||
.map(|p| p.bots_total)
|
||||
.unwrap_or(0);
|
||||
changes.insert(
|
||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||
Value::from(existing_max.max(already + count).min(5000)),
|
||||
);
|
||||
if existing_max == 0 {
|
||||
changes.insert(
|
||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||
Value::from(count.min(5000)),
|
||||
);
|
||||
}
|
||||
config::save(&root, &meta, Scope::Bots, &changes)?;
|
||||
let o = coa_core::process::observe(&root, &layout::read_ports(&root));
|
||||
// Large batches while the server is stopped: create them in the database right now, fully equipped.
|
||||
@@ -1816,15 +1836,29 @@ async fn add_companions(
|
||||
}
|
||||
let mut baseline = None;
|
||||
let spawned = if o.world.state == coa_core::process::ServiceState::Running {
|
||||
// Older servers have no template characters to copy bots from: add them first.
|
||||
coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(
|
||||
&root,
|
||||
coa_core::db::Account::Admin,
|
||||
)?)?;
|
||||
baseline = coa_core::population::query(&root)
|
||||
.ok()
|
||||
.map(|p| p.bots_total);
|
||||
Some(Ra::connect(&root)?.spawn_bots(count)?)
|
||||
let pop = coa_core::population::query(&root).ok();
|
||||
baseline = pop.as_ref().map(|p| p.bots_total);
|
||||
let offline = pop
|
||||
.as_ref()
|
||||
.map(|p| p.bots_total.saturating_sub(p.bots_online))
|
||||
.unwrap_or(0);
|
||||
let from_pool = count.min(offline);
|
||||
let remaining = count.saturating_sub(from_pool);
|
||||
|
||||
let mut ra = Ra::connect(&root)?;
|
||||
let mut reply = String::new();
|
||||
if from_pool > 0 {
|
||||
reply = ra.login_offline_bots(from_pool)?;
|
||||
}
|
||||
if remaining > 0 {
|
||||
// Older servers have no template characters to copy bots from: add them first.
|
||||
coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(
|
||||
&root,
|
||||
coa_core::db::Account::Admin,
|
||||
)?)?;
|
||||
reply = ra.spawn_bots(remaining)?;
|
||||
}
|
||||
Some(reply)
|
||||
} else {
|
||||
// The server is stopped: creating bots needs it running, so remember the request and do it after the next start.
|
||||
coa_core::fsx::atomic_write_json(
|
||||
@@ -2005,13 +2039,6 @@ fn client_install_addon(
|
||||
struct ClientStatus {
|
||||
/// A usable client folder is linked to this server.
|
||||
linked: bool,
|
||||
/// The Manager keeps this folder up to date (it downloaded it or was asked to adopt it).
|
||||
managed: bool,
|
||||
installed_version: Option<String>,
|
||||
latest_version: Option<String>,
|
||||
latest_bytes: Option<u64>,
|
||||
/// A managed client is older than the published one (or its download never finished).
|
||||
update_available: bool,
|
||||
}
|
||||
|
||||
fn linked_client(root: &std::path::Path) -> Result<Option<PathBuf>> {
|
||||
@@ -2022,192 +2049,16 @@ fn linked_client(root: &std::path::Path) -> Result<Option<PathBuf>> {
|
||||
.filter(|p| coa_core::client::detect(p, None).is_some()))
|
||||
}
|
||||
|
||||
/// Cheap: one small manifest request and the local state file; no game file is read.
|
||||
/// Whether a usable client folder is linked. Local only; the Manager no longer downloads or updates the client.
|
||||
#[tauri::command]
|
||||
async fn client_status(
|
||||
fn client_status(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<ClientStatus, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
blocking(move || {
|
||||
let client = ctx.linked();
|
||||
let latest = coa_core::clientdl::fetch_latest().ok();
|
||||
let local = client.as_deref().map(coa_core::clientdl::local);
|
||||
let managed = local.as_ref().map(|l| l.managed).unwrap_or(false);
|
||||
let installed = local.and_then(|l| l.version);
|
||||
let update_available = managed
|
||||
&& latest
|
||||
.as_ref()
|
||||
.map(|l| installed.as_deref() != Some(l.version.as_str()))
|
||||
.unwrap_or(false);
|
||||
Ok(ClientStatus {
|
||||
linked: client.is_some(),
|
||||
managed,
|
||||
installed_version: installed,
|
||||
latest_bytes: latest.as_ref().map(|l| l.total_bytes()),
|
||||
latest_version: latest.map(|l| l.version),
|
||||
update_available,
|
||||
})
|
||||
Ok(ClientStatus {
|
||||
linked: ctx.linked().is_some(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ClientDownloadCheck {
|
||||
needed_bytes: u64,
|
||||
free_bytes: u64,
|
||||
version: String,
|
||||
/// Where the client would go.
|
||||
dest: String,
|
||||
}
|
||||
|
||||
const CLIENT_FOLDER: &str = "CoA Client";
|
||||
|
||||
#[tauri::command]
|
||||
async fn client_download_check(
|
||||
parent: String,
|
||||
) -> std::result::Result<ClientDownloadCheck, UiError> {
|
||||
blocking(move || {
|
||||
let latest = coa_core::clientdl::fetch_latest()?;
|
||||
let dest = PathBuf::from(&parent).join(CLIENT_FOLDER);
|
||||
Ok(ClientDownloadCheck {
|
||||
needed_bytes: latest.total_bytes(),
|
||||
free_bytes: coa_core::fsx::free_space(std::path::Path::new(&parent))?,
|
||||
version: latest.version,
|
||||
dest: dest.to_string_lossy().into_owned(),
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Compare the linked client with the published one. Hashes files only where the recorded state cannot vouch for them.
|
||||
#[tauri::command]
|
||||
async fn client_plan(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
) -> std::result::Result<coa_core::clientdl::Plan, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let cancel = begin_client_job(&state)?;
|
||||
let result = blocking(move || {
|
||||
let client = ctx.require()?;
|
||||
let manifest = coa_core::clientdl::fetch_latest()?;
|
||||
let current = coa_core::clientdl::load_state(&client).unwrap_or_default();
|
||||
coa_core::clientdl::plan(&client, &manifest, ¤t, &cancel, &|s| {
|
||||
let _ = app.emit("client-progress", s);
|
||||
})
|
||||
})
|
||||
.await;
|
||||
end_client_job(&state);
|
||||
result
|
||||
}
|
||||
|
||||
/// Bring the linked client to the published version. `keep_modified` leaves files the player changed alone.
|
||||
#[tauri::command]
|
||||
async fn client_sync(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
keep_modified: bool,
|
||||
) -> std::result::Result<(), UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let cancel = begin_client_job(&state)?;
|
||||
let result = blocking(move || {
|
||||
let client = ctx.require()?;
|
||||
run_client_sync(&app, &client, keep_modified, &cancel)?;
|
||||
if ctx.root.is_none() && !ctx.host.is_empty() {
|
||||
coa_core::client::set_realmlist(&client, &ctx.dir, &ctx.host)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
end_client_job(&state);
|
||||
result
|
||||
}
|
||||
|
||||
fn run_client_sync(
|
||||
app: &AppHandle,
|
||||
client: &std::path::Path,
|
||||
keep_modified: bool,
|
||||
cancel: &Cancel,
|
||||
) -> Result<()> {
|
||||
let emit = |s: coa_core::clientdl::Step| {
|
||||
let _ = app.emit("client-progress", s);
|
||||
};
|
||||
let manifest = coa_core::clientdl::fetch_latest()?;
|
||||
let current = coa_core::clientdl::load_state(client).unwrap_or_default();
|
||||
let plan = coa_core::clientdl::plan(client, &manifest, ¤t, cancel, &emit)?;
|
||||
coa_core::download::check_url(coa_core::clientdl::OBJECTS_URL)?;
|
||||
let transport = coa_core::download::HttpTransport::new()?;
|
||||
coa_core::clientdl::apply(
|
||||
&coa_core::clientdl::Apply {
|
||||
client,
|
||||
manifest: &manifest,
|
||||
plan: &plan,
|
||||
keep_modified,
|
||||
transport: &transport,
|
||||
objects_url: coa_core::clientdl::OBJECTS_URL,
|
||||
cancel,
|
||||
},
|
||||
&emit,
|
||||
)?;
|
||||
tracing::info!(version = %manifest.version, downloaded = plan.items.len(), "client brought up to date");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download the client into `<parent>/CoA Client`, then link it to a host or player profile.
|
||||
#[tauri::command]
|
||||
async fn client_download(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
parent: String,
|
||||
) -> std::result::Result<coa_core::client::ClientInfo, UiError> {
|
||||
let ctx = client_context(&state, &id)?;
|
||||
let cancel = begin_client_job(&state)?;
|
||||
let result = blocking(move || {
|
||||
let parent = PathBuf::from(&parent);
|
||||
if !parent.is_dir() {
|
||||
return Err(Error::Invalid(
|
||||
"Choose an existing folder to put the game client in.".into(),
|
||||
));
|
||||
}
|
||||
let dest = parent.join(CLIENT_FOLDER);
|
||||
let resuming = coa_core::clientdl::load_state(&dest).is_some();
|
||||
let non_empty = std::fs::read_dir(&dest)
|
||||
.map(|mut r| r.next().is_some())
|
||||
.unwrap_or(false);
|
||||
if non_empty && !resuming {
|
||||
return Err(Error::Invalid(format!(
|
||||
"{} already exists and is not an unfinished download. Choose another folder.",
|
||||
dest.display()
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(&dest)?;
|
||||
run_client_sync(&app, &dest, false, &cancel)?;
|
||||
let info = coa_core::client::detect(&dest, ctx.source.as_deref())
|
||||
.ok_or_else(|| Error::Invalid("The downloaded client looks incomplete.".into()))?;
|
||||
ctx.link(&info.path)?;
|
||||
if !ctx.host.is_empty() {
|
||||
coa_core::client::set_realmlist(&dest, &ctx.dir, &ctx.host)?;
|
||||
}
|
||||
if let Some(src) = &ctx.source {
|
||||
coa_core::client::install_addon(&dest, &ctx.dir, src)?;
|
||||
}
|
||||
Ok(coa_core::client::detect(&dest, ctx.source.as_deref()).unwrap_or(info))
|
||||
})
|
||||
.await;
|
||||
end_client_job(&state);
|
||||
result
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn client_cancel(state: State<'_, AppState>) {
|
||||
if let Ok(c) = state.client_cancel.lock() {
|
||||
if let Some(c) = c.as_ref() {
|
||||
c.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn begin_client_job(state: &AppState) -> std::result::Result<Cancel, UiError> {
|
||||
@@ -2216,10 +2067,7 @@ fn begin_client_job(state: &AppState) -> std::result::Result<Cancel, UiError> {
|
||||
.lock()
|
||||
.map_err(|_| Error::Invalid("state poisoned".into()))?;
|
||||
if slot.is_some() {
|
||||
return Err(Error::Invalid(
|
||||
"The game client is already being checked or downloaded.".into(),
|
||||
)
|
||||
.into());
|
||||
return Err(Error::Invalid("A game client operation is already running.".into()).into());
|
||||
}
|
||||
let cancel = Cancel::default();
|
||||
*slot = Some(cancel.clone());
|
||||
@@ -2322,6 +2170,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
|
||||
@@ -2333,6 +2182,7 @@ fn open_link(url: String) -> std::result::Result<(), UiError> {
|
||||
"https://login.tailscale.com/",
|
||||
"https://portforward.com/",
|
||||
"https://github.com/Corfirean/",
|
||||
"https://coa-development.org/",
|
||||
];
|
||||
// A prefilled "new issue" page of one of the places a report can go (the Manager, Companions, SQUID Playerbots): the
|
||||
// address must be exactly that page, and its query may carry `&` between the (percent-encoded) title and text.
|
||||
@@ -2485,6 +2335,9 @@ async fn friends_status(
|
||||
secondary_world_port: coa_core::realms::state(&root)?
|
||||
.secondary_world_port
|
||||
.filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.simultaneous)),
|
||||
reborn_world_port: coa_core::realms::state(&root)?
|
||||
.reborn_world_port
|
||||
.filter(|_| coa_core::realms::state(&root).is_ok_and(|s| s.with_reborn)),
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -2542,7 +2395,13 @@ 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: Vec<u16> = [
|
||||
realms.secondary_world_port.filter(|_| realms.simultaneous),
|
||||
realms.reborn_world_port.filter(|_| realms.with_reborn),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect();
|
||||
let host = match mode {
|
||||
Mode::Local => "127.0.0.1".to_string(),
|
||||
Mode::Lan => coa_core::net::resolve_lan_host(lan_address_override.as_deref(), coa_core::net::lan_ip())?,
|
||||
@@ -2552,7 +2411,7 @@ async fn friends_enable(
|
||||
let open = mode != Mode::Local;
|
||||
let changed = friends::set_open(&root, &meta, open)?;
|
||||
if open && platform::flavor() == Flavor::Repack {
|
||||
coa_core::firewall::ensure_rules_with_secondary(&ports, secondary)?;
|
||||
coa_core::firewall::ensure_rules_with_extra(&ports, &extra)?;
|
||||
}
|
||||
if mode == Mode::Direct && use_upnp {
|
||||
match coa_core::upnp::discover() {
|
||||
@@ -2560,7 +2419,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()),
|
||||
@@ -2729,6 +2588,31 @@ async fn console_command(
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn analyze_github_module(
|
||||
state: State<'_, AppState>,
|
||||
url: String,
|
||||
realm_id: String,
|
||||
) -> std::result::Result<coa_core::analyzer::CompatibilityReport, UiError> {
|
||||
if realm_id.is_empty() || realm_id.contains("..") || realm_id.contains('/') || realm_id.contains('\\') {
|
||||
return Err(UiError::from(coa_core::Error::Invalid(format!(
|
||||
"Invalid realm_id '{}': path traversal characters forbidden",
|
||||
realm_id
|
||||
))));
|
||||
}
|
||||
|
||||
let realm_root = path_of(&state, &realm_id)?;
|
||||
let cache_dir = data_dir().join("github_cache");
|
||||
|
||||
blocking(move || {
|
||||
coa_core::analyzer::analyze_github_module_for_realm(&url, &realm_root, Some(&cache_dir))
|
||||
.map_err(Into::into)
|
||||
})
|
||||
.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"));
|
||||
@@ -2790,11 +2674,14 @@ pub fn run() {
|
||||
realmlist_delete,
|
||||
realmlist_activate,
|
||||
modules_list,
|
||||
analyze_github_module,
|
||||
realm_profiles,
|
||||
realm_select,
|
||||
realm_simultaneous,
|
||||
realm_with_reborn,
|
||||
check_database,
|
||||
repair_server,
|
||||
plugins_repair,
|
||||
module_set_enabled,
|
||||
module_settings,
|
||||
module_save_settings,
|
||||
@@ -2829,11 +2716,6 @@ pub fn run() {
|
||||
client_realmlist,
|
||||
client_install_addon,
|
||||
client_status,
|
||||
client_download_check,
|
||||
client_plan,
|
||||
client_sync,
|
||||
client_download,
|
||||
client_cancel,
|
||||
play,
|
||||
friends_status,
|
||||
friends_check_internet,
|
||||
@@ -2881,11 +2763,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();
|
||||
}
|
||||
@@ -2896,6 +2842,7 @@ pub fn run() {
|
||||
rt.shutdown();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+7
-17
@@ -10,6 +10,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 };
|
||||
@@ -26,18 +27,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";
|
||||
@@ -51,19 +53,7 @@ export {};
|
||||
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
|
||||
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
|
||||
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
|
||||
if(cmd.startsWith("client_")){
|
||||
const w=window as any;
|
||||
const emit=(payload: any)=>(w.__handlers?.["client-progress"]??[]).forEach((h: any)=>h({event:"client-progress",id:1,payload}));
|
||||
const sleep=(ms: number)=>new Promise((r: any)=>setTimeout(r,ms));
|
||||
const total=46404000000;
|
||||
const run=async(phase: string,n: number,speed: number)=>{for(let i=1;i<=n;i++){if(w.__stop){w.__stop=false;throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"Download cancelled."};}emit({phase,done:Math.round(total*i/n),total,bytes_per_sec:speed,file:phase==="scan"?"Data/patch-"+i+".MPQ":"Data/patch-O.MPQ"});await sleep(120);}};
|
||||
if(cmd==="client_status"){const c=w.__client??"none";return {linked:c!=="none",managed:c==="old"||c==="new",installed_version:c==="old"?"2026-09-20-01":c==="new"?"2026-09-29-01":null,latest_version:"2026-09-29-01",latest_bytes:total,update_available:c==="old"};}
|
||||
if(cmd==="client_download_check") return {needed_bytes:total,free_bytes:args.parent.startsWith("C")?210e9:20e9,version:"2026-09-29-01",dest:args.parent+"\\CoA Client"};
|
||||
if(cmd==="client_plan"){await run("scan",12,0);return {version:"2026-09-29-01",items:[{path:"Data/patch-O.MPQ",size:2814983707,kind:"changed"},{path:"Data/patch-WB1.MPQ",size:2001890268,kind:"missing"},...(w.__modified?[{path:"d3d9.dll",size:4284430,kind:"modified"},{path:"Ascension.exe",size:7694848,kind:"modified"}]:[])],download_bytes:4829000000,total_files:200,up_to_date_files:196,kept_files:0};}
|
||||
if(cmd==="client_sync"){await run("download",25,41e6);w.__client="new";return null;}
|
||||
if(cmd==="client_download"){await run("scan",4,0);await run("download",40,41e6);w.__client="new";return {path:args.parent+"\\CoA Client",executable:"Ascension.exe",realmlists:[{path:"x",host:"127.0.0.1"}],addon:{installed:true,version:"1",up_to_date:true},other_addons:0};}
|
||||
if(cmd==="client_cancel"){w.__stop=true;return null;}
|
||||
}
|
||||
if(cmd==="client_status") return {linked:((window as any).__client??"none")!=="none"};
|
||||
if(cmd==="realmlist_profiles"){const w=window as any;w.__rl=w.__rl??{profiles:[{id:"solo",name:"Solo",data:"set realmlist 127.0.0.1\r\n"},{id:"ptr",name:"PTR",data:"set realmlist ptr.example.org\r\n"}],active:"solo"};return w.__rl;}
|
||||
if(cmd==="realmlist_activate"){(window as any).__rl.active=args.profileId;return [];}
|
||||
if(cmd==="realmlist_save"){const w=window as any;const rl=w.__rl;if(args.profileId){const p=rl.profiles.find((x: any)=>x.id===args.profileId);p.name=args.name;p.data=args.data;return p;}if(rl.profiles.some((x: any)=>x.name.toLowerCase()===String(args.name).toLowerCase()))throw {human:{code:"unknown",title:"",message:"",actions:[]},technical:"A realmlist with that name already exists."};const p={id:String(args.name).toLowerCase().replace(/[^a-z0-9]+/g,"-"),name:args.name,data:(/\s/.test(args.data.trim())?args.data.trim():"set realmlist "+args.data.trim())+"\r\n"};rl.profiles.push(p);return p;}
|
||||
|
||||
+6
-45
@@ -5,7 +5,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.switching": "Änderungen werden angewendet… Bitte warten.",
|
||||
"portable.experimental": "Experimentelle Funktion: Portable Charaktere befinden sich noch in aktiver Entwicklung. Fehler können auftreten.",
|
||||
"remote.clientReady": "Dein Client ist bereit. Speichere die Hostadresse und klicke auf Spielen.",
|
||||
"remote.clientIntro": "Wähle einen vorhandenen Spielclient oder lade ihn hier herunter. Ein lokaler Server ist nicht nötig.",
|
||||
"remote.clientIntro": "Wähle einen vorhandenen Spielclient oder hole dir einen über den Launcher der Community. Ein lokaler Server ist nicht nötig.",
|
||||
"welcome.host.title": "Einen Server hosten",
|
||||
"welcome.host.text": "Einen neuen Server installieren oder einen vorhandenen verwalten.",
|
||||
"welcome.connect.title": "Mit anderem Server verbinden",
|
||||
@@ -76,7 +76,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"btn.stopSmall": "Stoppen",
|
||||
"btn.restart": "Neustart",
|
||||
"btn.startWithoutUpdate": "Ohne Update starten",
|
||||
"btn.playWithoutUpdate": "Ohne Update spielen",
|
||||
"import.squidRepackWarning": "Dieses SquidBots-Repack prüft den Worldserver-Hash. Ein Austausch kann Start_All_Bots und coa_update deaktivieren. Updates fragen vorher nach.",
|
||||
"btn.play": "SPIELEN",
|
||||
"btn.startPlay": "STARTEN & SPIELEN",
|
||||
@@ -219,6 +218,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.updateAddon": "Begleiter-Addon aktualisieren",
|
||||
"client.addonNote": "Begleiter-Addon installiert. Andere Addons wurden nicht angetastet.",
|
||||
"client.changeFolder": "Ordner ändern …",
|
||||
"client.getFromSite": "Launcher holen…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "Diagnose",
|
||||
@@ -604,51 +604,15 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
// Game client download and update
|
||||
"btn.close": "Schließen",
|
||||
"btn.setupClient": "Spielclient einrichten",
|
||||
"btn.updateClient": "CLIENT AKTUALISIEREN",
|
||||
"client.setup.title": "Spielclient einrichten",
|
||||
"client.setup.intro": "Zum Spielen brauchst du den Spielclient. Nutze einen vorhandenen oder lass ihn vom Manager herunterladen.",
|
||||
"client.setup.intro": "Zum Spielen brauchst du den Spielclient. Die Community gibt ihn über ihren offiziellen Launcher heraus.",
|
||||
"client.setup.have": "Ich habe bereits einen Client",
|
||||
"client.setup.download": "Client herunterladen",
|
||||
"client.setup.downloadHint": "Etwa 43 GB",
|
||||
"client.dl.pickParent": "Wähle, wohin der Spielclient soll",
|
||||
"client.dl.confirmText": "Version {v}, {size}. Er wird in diesem Ordner gespeichert:",
|
||||
"client.dl.free": "Freier Platz auf diesem Laufwerk: {free}.",
|
||||
"client.dl.notEnough": "Nicht genug freier Platz: {need} nötig, {free} verfügbar. Wähle ein anderes Laufwerk.",
|
||||
"client.dl.otherFolder": "Anderer Ordner …",
|
||||
"client.dl.start": "Herunterladen",
|
||||
"client.setup.getLauncher": "Launcher holen (coa-development.org)",
|
||||
"client.setup.getLauncherHint": "Öffnet die Website der Community im Browser. Lade dort den Launcher herunter, installiere ihn, melde dich mit deinem Konto an und lass ihn das Spiel laden (etwa 43 GB).",
|
||||
"client.setup.haveHint": "Wähle den Ordner, in den der Launcher das Spiel installiert hat, oder eine andere Kopie des Clients.",
|
||||
"client.dl.back": "Zurück",
|
||||
"client.dl.retry": "Erneut versuchen",
|
||||
"client.dl.resume": "Fortsetzen",
|
||||
"client.dl.cancel": "Anhalten",
|
||||
"client.dl.cancelled": "Angehalten. Alles bereits Heruntergeladene bleibt erhalten; du kannst jederzeit fortsetzen.",
|
||||
"client.dl.scanning": "Dateien werden verglichen …",
|
||||
"client.dl.downloading": "Wird heruntergeladen",
|
||||
"client.dl.progress": "{done} von {total}",
|
||||
"client.dl.speed": "{speed}/s",
|
||||
"client.dl.done": "Der Spielclient ist bereit",
|
||||
"client.dl.doneText": "Er ist mit diesem Server verknüpft. Du kannst auf PLAY drücken.",
|
||||
"client.upd.title": "Client-Update",
|
||||
"client.upd.available": "Ein neuerer Spielclient ist verfügbar: {v}.",
|
||||
"client.upd.summary": "{n} Datei(en) zum Herunterladen, insgesamt {size}.",
|
||||
"client.upd.upToDate": "Dein Client entspricht bereits Version {v}.",
|
||||
"client.upd.modifiedTitle": "{n} Datei(en) hast du geändert",
|
||||
"client.upd.modifiedText": "Zum Beispiel eine gepatchte Programmdatei. Behalte sie oder ersetze sie durch die offiziellen Versionen; deine werden dann im Ordner .coa-manager des Clients gesichert. Grafik-Wrapper (d3d9.dll und ähnliche) und Konfigurationsdateien bleiben immer unverändert.",
|
||||
"client.upd.keep": "Von mir geänderte Dateien behalten",
|
||||
"client.upd.more": "… und {n} weitere",
|
||||
"client.upd.start": "Client aktualisieren",
|
||||
"client.upd.later": "Jetzt nicht",
|
||||
"client.upd.playAnyway": "Ohne Update spielen",
|
||||
"client.upd.done": "Der Spielclient ist aktuell",
|
||||
"client.upd.doneText": "Der Manager sagt dir Bescheid, wenn eine neuere Version erscheint.",
|
||||
"client.track.title": "Client aktuell halten",
|
||||
"client.track.text": "Der Manager vergleicht deinen Client einmal mit dem offiziellen und prüft danach auf neue Versionen, wie beim Server. Von dir geänderte Dateien werden nur ersetzt, wenn du es willst.",
|
||||
"client.track.start": "Aktuell halten",
|
||||
"client.track.startUpdate": "Aktualisieren und aktuell halten",
|
||||
"client.track.button": "Diesen Client aktuell halten …",
|
||||
"client.version": "Client-Version",
|
||||
"client.versionUntracked": "vom Manager nicht verfolgt",
|
||||
"client.versionUnfinished": "Download nicht abgeschlossen",
|
||||
"client.downloadInstead": "Client herunterladen …",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "Passwort anzeigen",
|
||||
@@ -850,7 +814,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"dash.openBrowser": "Im Browser öffnen",
|
||||
"dash.update": "Dashboard aktualisieren",
|
||||
"upd.startAfter": "Server nach dem Update starten (sonst bleibt ein angehaltener Server angehalten)",
|
||||
"client.startAfter": "Spiel nach dem Client-Update starten",
|
||||
"bk.folder": "Sicherungsordner",
|
||||
"bk.folderDefault": "Standard",
|
||||
"bk.folderNote": "Neue Sicherungen werden hier gespeichert, zum Beispiel auf einem anderen Laufwerk. Frühere Sicherungen bleiben, wo sie sind, und werden weiter aufgelistet. Der Ordner muss außerhalb des Serverordners liegen.",
|
||||
@@ -863,8 +826,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"remove.stopFirst": "Halte zuerst den Server an.",
|
||||
"remove.confirm": "Diesen Server aus dem Manager entfernen?\n\n{path}\n\nEs werden keine Dateien gelöscht.",
|
||||
"upd.dbUnchecked": "Die Datenbank konnte nicht geprüft werden, daher sind offene Datenbankänderungen unbekannt: {why}",
|
||||
"client.job.checking": "Client wird geprüft…",
|
||||
"client.job.updating": "Client wird aktualisiert",
|
||||
"fr.lan.address": "Netzwerkadresse",
|
||||
"fr.lan.automatic": "Automatisch",
|
||||
"fr.lan.default": "Standard",
|
||||
|
||||
+21
-50
@@ -2,7 +2,7 @@
|
||||
const en = {
|
||||
"mod.switching": "Applying changes… Please wait.",
|
||||
"remote.clientReady": "Your client is ready. Save the host’s address, then press Play.",
|
||||
"remote.clientIntro": "Choose an existing game client or download one here. No local server is needed.",
|
||||
"remote.clientIntro": "Choose an existing game client, or get one through the community’s launcher. No local server is needed.",
|
||||
"welcome.host.title": "Host a server",
|
||||
"welcome.host.text": "Install a new server or manage one you already have.",
|
||||
"welcome.connect.title": "Connect to another server",
|
||||
@@ -19,11 +19,16 @@ const en = {
|
||||
"realm.profileLabel": "Realm",
|
||||
"realm.startupTitle": "Realm startup",
|
||||
"realm.secondWorld": "Second world",
|
||||
"realm.simultaneous": "Start CoA and Wildcard together",
|
||||
"realm.simultaneousHint": "Stop the server before changing this option. Start runs both worlds with separate characters, settings and ports, sharing accounts. Two worlds need more memory. The first setup creates Wildcard if needed.",
|
||||
"realm.simultaneous": "Start Wildcard together with CoA",
|
||||
"realm.withReborn": "Start Warcraft Reborn together with CoA",
|
||||
"realm.rebornPort": "Warcraft Reborn world port: {port}",
|
||||
"realm.rebornWorld": "Warcraft Reborn world",
|
||||
"realm.rebornNeedsCoa": "Warcraft Reborn can start together with Conquest of Azeroth only. Select Conquest of Azeroth on Overview first.",
|
||||
"realm.allThree": "Both options are on: Conquest of Azeroth, Wildcard and Warcraft Reborn start together.",
|
||||
"realm.simultaneousHint": "Stop the server before changing these options. Start runs every chosen world with separate characters, settings and ports, sharing accounts. Each extra world needs more memory. The first setup creates the realm if needed.",
|
||||
"realm.secondPort": "Second world port: {port}",
|
||||
"realm.preparing": "Preparing realm databases…",
|
||||
"realm.bothRunning": "Both worlds start together. Each realm keeps its own characters, progress and module settings.",
|
||||
"realm.bothRunning": "These worlds start together. Each realm keeps its own characters, progress and module settings.",
|
||||
"repair.title": "Check and repair server",
|
||||
"repair.hint": "Stop both realms and update to the latest server package before repair. Repair backs up databases and replaced files, restores official program files and applies pending SQL. Your characters and existing settings are preserved.",
|
||||
"repair.check": "Check files and database",
|
||||
@@ -114,7 +119,6 @@ const en = {
|
||||
"btn.stopSmall": "Stop",
|
||||
"btn.restart": "Restart",
|
||||
"btn.startWithoutUpdate": "Start without updating",
|
||||
"btn.playWithoutUpdate": "Play without updating",
|
||||
"import.squidRepackWarning": "This SquidBots repack checks its worldserver hash. Replacing the binary can stop Start_All_Bots and coa_update from working. Updates will ask before replacing it.",
|
||||
"btn.play": "PLAY",
|
||||
"btn.startPlay": "START & PLAY",
|
||||
@@ -274,6 +278,7 @@ const en = {
|
||||
"client.updateAddon": "Update companion addon",
|
||||
"client.addonNote": "Companion addon installed. Other addons were not touched.",
|
||||
"client.changeFolder": "Change folder…",
|
||||
"client.getFromSite": "Get the launcher…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "Diagnostics",
|
||||
@@ -657,54 +662,18 @@ const en = {
|
||||
"overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.",
|
||||
"nav.updateDot": "Update available",
|
||||
|
||||
// Game client download and update
|
||||
// Game client: link a folder or get the community launcher
|
||||
"btn.close": "Close",
|
||||
"btn.setupClient": "Set up game client",
|
||||
"btn.updateClient": "UPDATE CLIENT",
|
||||
"client.setup.title": "Set up the game client",
|
||||
"client.setup.intro": "To play you need the game client. Use one you already have, or let the Manager download it.",
|
||||
"client.setup.intro": "To play you need the game client. The community hands it out through its official launcher.",
|
||||
"client.setup.have": "I already have a client",
|
||||
"client.setup.download": "Download the client",
|
||||
"client.setup.downloadHint": "About 43 GB",
|
||||
"client.dl.pickParent": "Choose where to put the game client",
|
||||
"client.dl.confirmText": "Version {v}, {size}. It will be saved in this folder:",
|
||||
"client.dl.free": "Free space on that drive: {free}.",
|
||||
"client.dl.notEnough": "Not enough free space: {need} needed, {free} available. Choose another drive.",
|
||||
"client.dl.otherFolder": "Other folder…",
|
||||
"client.dl.start": "Download",
|
||||
"client.setup.getLauncher": "Get the launcher (coa-development.org)",
|
||||
"client.setup.getLauncherHint": "Opens the community website in your browser. Download and install the launcher there, sign in with your account and let it download the game (about 43 GB).",
|
||||
"client.setup.haveHint": "Pick the folder the launcher installed the game to, or any other copy of the client.",
|
||||
"client.dl.back": "Back",
|
||||
"client.dl.retry": "Try again",
|
||||
"client.dl.resume": "Continue",
|
||||
"client.dl.cancel": "Stop",
|
||||
"client.dl.cancelled": "Stopped. Everything already downloaded is kept; continue whenever you like.",
|
||||
"client.dl.scanning": "Comparing files…",
|
||||
"client.dl.downloading": "Downloading",
|
||||
"client.dl.progress": "{done} of {total}",
|
||||
"client.dl.speed": "{speed}/s",
|
||||
"client.dl.done": "The game client is ready",
|
||||
"client.dl.doneText": "It is linked to this server. You can press PLAY.",
|
||||
"client.upd.title": "Client update",
|
||||
"client.upd.available": "A newer game client is available: {v}.",
|
||||
"client.upd.summary": "{n} file(s) to download, {size} in total.",
|
||||
"client.upd.upToDate": "Your client already matches version {v}.",
|
||||
"client.upd.modifiedTitle": "{n} file(s) were changed by you",
|
||||
"client.upd.modifiedText": "For example a patched executable. Keep them, or replace them with the official versions; yours are then saved in the client’s .coa-manager folder. Graphics wrappers (d3d9.dll and the like) and config files are always left as they are.",
|
||||
"client.upd.keep": "Keep the files I changed",
|
||||
"client.upd.more": "… and {n} more",
|
||||
"client.upd.start": "Update client",
|
||||
"client.upd.later": "Not now",
|
||||
"client.upd.playAnyway": "Play without updating",
|
||||
"client.upd.done": "The game client is up to date",
|
||||
"client.upd.doneText": "The Manager will tell you when a newer one is published.",
|
||||
"client.track.title": "Keep the client up to date",
|
||||
"client.track.text": "The Manager compares your client with the official one once, then checks for new versions like it does for the server. Files you changed are never replaced unless you say so.",
|
||||
"client.track.start": "Keep up to date",
|
||||
"client.track.startUpdate": "Update and keep up to date",
|
||||
"client.track.button": "Keep this client up to date…",
|
||||
"client.version": "Client version",
|
||||
"client.versionUntracked": "not tracked by the Manager",
|
||||
"client.versionUnfinished": "download not finished",
|
||||
"client.downloadInstead": "Download a client…",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "Show password",
|
||||
@@ -891,7 +860,6 @@ const en = {
|
||||
"dash.openBrowser": "Open in the browser",
|
||||
"dash.update": "Update the dashboard",
|
||||
"upd.startAfter": "Start the server after updating it (otherwise a stopped server stays stopped)",
|
||||
"client.startAfter": "Start the game after the client has been updated",
|
||||
"bk.folder": "Backup folder",
|
||||
"bk.folderDefault": "default",
|
||||
"bk.folderNote": "New backups are saved here, for example on another drive. Backups made earlier stay where they are and are still listed. The folder must be outside the server folder.",
|
||||
@@ -904,8 +872,6 @@ const en = {
|
||||
"remove.stopFirst": "Stop the server first.",
|
||||
"remove.confirm": "Remove this server from the Manager?\n\n{path}\n\nNo files are deleted.",
|
||||
"upd.dbUnchecked": "The database could not be checked, so pending database changes are unknown: {why}",
|
||||
"client.job.checking": "Checking the client…",
|
||||
"client.job.updating": "Updating the client",
|
||||
"nav.characters": "Characters",
|
||||
"q.characters": "Which of my characters can play where?",
|
||||
"portable.experimental": "Experimental feature: portable characters are still in active development. Bugs may occur.",
|
||||
@@ -1004,7 +970,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.",
|
||||
@@ -1099,6 +1065,8 @@ 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",
|
||||
@@ -1119,6 +1087,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.",
|
||||
@@ -1178,6 +1147,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",
|
||||
|
||||
+6
-45
@@ -5,7 +5,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.switching": "Aplicando cambios… Espera un momento.",
|
||||
"portable.experimental": "Función experimental: los personajes portátiles siguen en desarrollo activo. Pueden producirse errores.",
|
||||
"remote.clientReady": "Tu cliente está listo. Guarda la dirección del anfitrión y pulsa Jugar.",
|
||||
"remote.clientIntro": "Elige un cliente existente o descárgalo aquí. No necesitas un servidor local.",
|
||||
"remote.clientIntro": "Elige un cliente del juego existente u obtén uno con el launcher de la comunidad. No hace falta un servidor local.",
|
||||
"welcome.host.title": "Alojar un servidor",
|
||||
"welcome.host.text": "Instalar un servidor nuevo o gestionar uno existente.",
|
||||
"welcome.connect.title": "Conectarse a otro servidor",
|
||||
@@ -76,7 +76,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"btn.stopSmall": "Detener",
|
||||
"btn.restart": "Reiniciar",
|
||||
"btn.startWithoutUpdate": "Iniciar sin actualizar",
|
||||
"btn.playWithoutUpdate": "Jugar sin actualizar",
|
||||
"import.squidRepackWarning": "Este repack SquidBots verifica el hash del servidor. Sustituirlo puede impedir el funcionamiento de Start_All_Bots y coa_update. Se solicitará confirmación.",
|
||||
"btn.play": "JUGAR",
|
||||
"btn.startPlay": "INICIAR Y JUGAR",
|
||||
@@ -219,6 +218,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.updateAddon": "Actualizar addon de compañeros",
|
||||
"client.addonNote": "Addon de compañeros instalado. Los demás addons no se tocaron.",
|
||||
"client.changeFolder": "Cambiar carpeta…",
|
||||
"client.getFromSite": "Obtener el launcher…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "Diagnóstico",
|
||||
@@ -604,51 +604,15 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
// Game client download and update
|
||||
"btn.close": "Cerrar",
|
||||
"btn.setupClient": "Configurar el cliente del juego",
|
||||
"btn.updateClient": "ACTUALIZAR CLIENTE",
|
||||
"client.setup.title": "Configurar el cliente del juego",
|
||||
"client.setup.intro": "Para jugar necesitas el cliente del juego. Usa uno que ya tengas o deja que el Manager lo descargue.",
|
||||
"client.setup.intro": "Para jugar necesitas el cliente del juego. La comunidad lo entrega a través de su launcher oficial.",
|
||||
"client.setup.have": "Ya tengo un cliente",
|
||||
"client.setup.download": "Descargar el cliente",
|
||||
"client.setup.downloadHint": "Unos 43 GB",
|
||||
"client.dl.pickParent": "Elige dónde guardar el cliente del juego",
|
||||
"client.dl.confirmText": "Versión {v}, {size}. Se guardará en esta carpeta:",
|
||||
"client.dl.free": "Espacio libre en esa unidad: {free}.",
|
||||
"client.dl.notEnough": "No hay espacio suficiente: se necesitan {need} y hay {free}. Elige otra unidad.",
|
||||
"client.dl.otherFolder": "Otra carpeta…",
|
||||
"client.dl.start": "Descargar",
|
||||
"client.setup.getLauncher": "Obtener el launcher (coa-development.org)",
|
||||
"client.setup.getLauncherHint": "Abre la web de la comunidad en tu navegador. Descarga e instala allí el launcher, inicia sesión con tu cuenta y deja que descargue el juego (unos 43 GB).",
|
||||
"client.setup.haveHint": "Elige la carpeta donde el launcher instaló el juego, o cualquier otra copia del cliente.",
|
||||
"client.dl.back": "Atrás",
|
||||
"client.dl.retry": "Reintentar",
|
||||
"client.dl.resume": "Continuar",
|
||||
"client.dl.cancel": "Detener",
|
||||
"client.dl.cancelled": "Detenido. Todo lo ya descargado se conserva; puedes continuar cuando quieras.",
|
||||
"client.dl.scanning": "Comparando archivos…",
|
||||
"client.dl.downloading": "Descargando",
|
||||
"client.dl.progress": "{done} de {total}",
|
||||
"client.dl.speed": "{speed}/s",
|
||||
"client.dl.done": "El cliente del juego está listo",
|
||||
"client.dl.doneText": "Está vinculado a este servidor. Puedes pulsar PLAY.",
|
||||
"client.upd.title": "Actualización del cliente",
|
||||
"client.upd.available": "Hay un cliente del juego más reciente: {v}.",
|
||||
"client.upd.summary": "{n} archivo(s) por descargar, {size} en total.",
|
||||
"client.upd.upToDate": "Tu cliente ya coincide con la versión {v}.",
|
||||
"client.upd.modifiedTitle": "{n} archivo(s) cambiado(s) por ti",
|
||||
"client.upd.modifiedText": "Por ejemplo un ejecutable modificado. Consérvalos o reemplázalos por las versiones oficiales; los tuyos se guardan entonces en la carpeta .coa-manager del cliente. Los wrappers gráficos (d3d9.dll y similares) y los archivos de configuración se dejan siempre como están.",
|
||||
"client.upd.keep": "Conservar los archivos que cambié",
|
||||
"client.upd.more": "… y {n} más",
|
||||
"client.upd.start": "Actualizar cliente",
|
||||
"client.upd.later": "Ahora no",
|
||||
"client.upd.playAnyway": "Jugar sin actualizar",
|
||||
"client.upd.done": "El cliente del juego está actualizado",
|
||||
"client.upd.doneText": "El Manager te avisará cuando se publique una más reciente.",
|
||||
"client.track.title": "Mantener el cliente actualizado",
|
||||
"client.track.text": "El Manager compara una vez tu cliente con el oficial y luego busca versiones nuevas como hace con el servidor. Los archivos que cambiaste solo se reemplazan si tú lo decides.",
|
||||
"client.track.start": "Mantener actualizado",
|
||||
"client.track.startUpdate": "Actualizar y mantener actualizado",
|
||||
"client.track.button": "Mantener este cliente actualizado…",
|
||||
"client.version": "Versión del cliente",
|
||||
"client.versionUntracked": "el Manager no la sigue",
|
||||
"client.versionUnfinished": "descarga sin terminar",
|
||||
"client.downloadInstead": "Descargar un cliente…",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "Mostrar contraseña",
|
||||
@@ -850,7 +814,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"dash.openBrowser": "Abrir en el navegador",
|
||||
"dash.update": "Actualizar el panel",
|
||||
"upd.startAfter": "Iniciar el servidor tras actualizarlo (si no, un servidor detenido sigue detenido)",
|
||||
"client.startAfter": "Iniciar el juego tras actualizar el cliente",
|
||||
"bk.folder": "Carpeta de copias de seguridad",
|
||||
"bk.folderDefault": "predeterminada",
|
||||
"bk.folderNote": "Las copias nuevas se guardan aquí, por ejemplo en otra unidad. Las anteriores se quedan donde están y siguen en la lista. La carpeta debe estar fuera de la carpeta del servidor.",
|
||||
@@ -863,8 +826,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"remove.stopFirst": "Detén primero el servidor.",
|
||||
"remove.confirm": "¿Quitar este servidor del Manager?\n\n{path}\n\nNo se borra ningún archivo.",
|
||||
"upd.dbUnchecked": "No se pudo comprobar la base de datos, así que se desconocen los cambios pendientes: {why}",
|
||||
"client.job.checking": "Comprobando el cliente…",
|
||||
"client.job.updating": "Actualizando el cliente",
|
||||
"fr.lan.address": "Dirección de red",
|
||||
"fr.lan.automatic": "Automática",
|
||||
"fr.lan.default": "Predeterminada",
|
||||
|
||||
+6
-45
@@ -5,7 +5,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.switching": "Application des modifications… Veuillez patienter.",
|
||||
"portable.experimental": "Fonction expérimentale : les personnages portables sont encore en développement actif. Des bugs peuvent survenir.",
|
||||
"remote.clientReady": "Votre client est prêt. Enregistrez l’adresse de l’hôte, puis cliquez sur Jouer.",
|
||||
"remote.clientIntro": "Choisissez un client existant ou téléchargez-le ici. Aucun serveur local n’est nécessaire.",
|
||||
"remote.clientIntro": "Choisissez un client de jeu existant ou obtenez-en un via le lanceur de la communauté. Aucun serveur local n’est nécessaire.",
|
||||
"welcome.host.title": "Héberger un serveur",
|
||||
"welcome.host.text": "Installer un serveur ou gérer un serveur existant.",
|
||||
"welcome.connect.title": "Rejoindre un autre serveur",
|
||||
@@ -76,7 +76,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"btn.stopSmall": "Arrêter",
|
||||
"btn.restart": "Redémarrer",
|
||||
"btn.startWithoutUpdate": "Démarrer sans mise à jour",
|
||||
"btn.playWithoutUpdate": "Jouer sans mise à jour",
|
||||
"import.squidRepackWarning": "Ce repack SquidBots vérifie le hash du serveur. Le remplacer peut empêcher Start_All_Bots et coa_update de fonctionner. Une confirmation sera demandée.",
|
||||
"btn.play": "JOUER",
|
||||
"btn.startPlay": "DÉMARRER ET JOUER",
|
||||
@@ -219,6 +218,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.updateAddon": "Mettre à jour l’addon des compagnons",
|
||||
"client.addonNote": "Addon des compagnons installé. Les autres addons n’ont pas été touchés.",
|
||||
"client.changeFolder": "Changer de dossier…",
|
||||
"client.getFromSite": "Obtenir le lanceur…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "Diagnostic",
|
||||
@@ -604,51 +604,15 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
// Game client download and update
|
||||
"btn.close": "Fermer",
|
||||
"btn.setupClient": "Configurer le client du jeu",
|
||||
"btn.updateClient": "METTRE À JOUR LE CLIENT",
|
||||
"client.setup.title": "Configurer le client du jeu",
|
||||
"client.setup.intro": "Pour jouer, il faut le client du jeu. Utilisez-en un existant ou laissez le Manager le télécharger.",
|
||||
"client.setup.intro": "Pour jouer, il faut le client du jeu. La communauté le distribue via son lanceur officiel.",
|
||||
"client.setup.have": "J’ai déjà un client",
|
||||
"client.setup.download": "Télécharger le client",
|
||||
"client.setup.downloadHint": "Environ 43 Go",
|
||||
"client.dl.pickParent": "Choisissez où placer le client du jeu",
|
||||
"client.dl.confirmText": "Version {v}, {size}. Il sera enregistré dans ce dossier :",
|
||||
"client.dl.free": "Espace libre sur ce disque : {free}.",
|
||||
"client.dl.notEnough": "Espace libre insuffisant : {need} nécessaires, {free} disponibles. Choisissez un autre disque.",
|
||||
"client.dl.otherFolder": "Autre dossier…",
|
||||
"client.dl.start": "Télécharger",
|
||||
"client.setup.getLauncher": "Obtenir le lanceur (coa-development.org)",
|
||||
"client.setup.getLauncherHint": "Ouvre le site de la communauté dans votre navigateur. Téléchargez et installez-y le lanceur, connectez-vous avec votre compte et laissez-le télécharger le jeu (environ 43 Go).",
|
||||
"client.setup.haveHint": "Choisissez le dossier où le lanceur a installé le jeu, ou toute autre copie du client.",
|
||||
"client.dl.back": "Retour",
|
||||
"client.dl.retry": "Réessayer",
|
||||
"client.dl.resume": "Continuer",
|
||||
"client.dl.cancel": "Arrêter",
|
||||
"client.dl.cancelled": "Arrêté. Tout ce qui est déjà téléchargé est conservé ; vous pouvez reprendre à tout moment.",
|
||||
"client.dl.scanning": "Comparaison des fichiers…",
|
||||
"client.dl.downloading": "Téléchargement",
|
||||
"client.dl.progress": "{done} sur {total}",
|
||||
"client.dl.speed": "{speed}/s",
|
||||
"client.dl.done": "Le client du jeu est prêt",
|
||||
"client.dl.doneText": "Il est lié à ce serveur. Vous pouvez appuyer sur PLAY.",
|
||||
"client.upd.title": "Mise à jour du client",
|
||||
"client.upd.available": "Un client de jeu plus récent est disponible : {v}.",
|
||||
"client.upd.summary": "{n} fichier(s) à télécharger, {size} au total.",
|
||||
"client.upd.upToDate": "Votre client correspond déjà à la version {v}.",
|
||||
"client.upd.modifiedTitle": "{n} fichier(s) modifié(s) par vous",
|
||||
"client.upd.modifiedText": "Par exemple un exécutable modifié. Conservez-les ou remplacez-les par les versions officielles ; les vôtres sont alors sauvegardées dans le dossier .coa-manager du client. Les wrappers graphiques (d3d9.dll et similaires) et les fichiers de configuration restent toujours tels quels.",
|
||||
"client.upd.keep": "Conserver les fichiers que j’ai modifiés",
|
||||
"client.upd.more": "… et {n} de plus",
|
||||
"client.upd.start": "Mettre à jour le client",
|
||||
"client.upd.later": "Pas maintenant",
|
||||
"client.upd.playAnyway": "Jouer sans mettre à jour",
|
||||
"client.upd.done": "Le client du jeu est à jour",
|
||||
"client.upd.doneText": "Le Manager vous préviendra quand une version plus récente sera publiée.",
|
||||
"client.track.title": "Garder le client à jour",
|
||||
"client.track.text": "Le Manager compare une fois votre client avec l’officiel, puis cherche les nouvelles versions comme pour le serveur. Les fichiers que vous avez modifiés ne sont remplacés que si vous le décidez.",
|
||||
"client.track.start": "Garder à jour",
|
||||
"client.track.startUpdate": "Mettre à jour et garder à jour",
|
||||
"client.track.button": "Garder ce client à jour…",
|
||||
"client.version": "Version du client",
|
||||
"client.versionUntracked": "non suivi par le Manager",
|
||||
"client.versionUnfinished": "téléchargement inachevé",
|
||||
"client.downloadInstead": "Télécharger un client…",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "Afficher le mot de passe",
|
||||
@@ -850,7 +814,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"dash.openBrowser": "Ouvrir dans le navigateur",
|
||||
"dash.update": "Mettre à jour le tableau de bord",
|
||||
"upd.startAfter": "Démarrer le serveur après la mise à jour (sinon un serveur arrêté reste arrêté)",
|
||||
"client.startAfter": "Lancer le jeu après la mise à jour du client",
|
||||
"bk.folder": "Dossier des sauvegardes",
|
||||
"bk.folderDefault": "par défaut",
|
||||
"bk.folderNote": "Les nouvelles sauvegardes sont enregistrées ici, par exemple sur un autre disque. Les précédentes restent où elles sont et figurent toujours dans la liste. Le dossier doit se trouver hors du dossier du serveur.",
|
||||
@@ -863,8 +826,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"remove.stopFirst": "Arrêtez d’abord le serveur.",
|
||||
"remove.confirm": "Retirer ce serveur du Manager ?\n\n{path}\n\nAucun fichier n’est supprimé.",
|
||||
"upd.dbUnchecked": "La base de données n'a pas pu être vérifiée ; les modifications en attente sont donc inconnues : {why}",
|
||||
"client.job.checking": "Vérification du client…",
|
||||
"client.job.updating": "Mise à jour du client",
|
||||
"fr.lan.address": "Adresse réseau",
|
||||
"fr.lan.automatic": "Automatique",
|
||||
"fr.lan.default": "Par défaut",
|
||||
|
||||
+20
-49
@@ -5,7 +5,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.switching": "Применяем изменения… Подождите.",
|
||||
"portable.experimental": "Экспериментальная функция: портативные персонажи ещё в активной разработке. Возможны ошибки.",
|
||||
"remote.clientReady": "Клиент готов. Сохраните адрес хоста и нажмите «Играть».",
|
||||
"remote.clientIntro": "Выберите существующий клиент игры или скачайте его здесь. Локальный сервер не требуется.",
|
||||
"remote.clientIntro": "Выберите готовый клиент игры или получите его через лаунчер сообщества. Локальный сервер не нужен.",
|
||||
"welcome.host.title": "Хочу быть хостом",
|
||||
"welcome.host.text": "Установить новый сервер или управлять существующим.",
|
||||
"welcome.connect.title": "Подключиться к другому серверу",
|
||||
@@ -22,11 +22,16 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"realm.profileLabel": "Реалм",
|
||||
"realm.startupTitle": "Запуск реалмов",
|
||||
"realm.secondWorld": "Второй мир",
|
||||
"realm.simultaneous": "Запускать CoA и Wildcard одновременно",
|
||||
"realm.simultaneousHint": "Остановите сервер перед изменением настройки. Запуск поднимет оба мира с отдельными персонажами, настройками и портами, но общими аккаунтами. Два мира требуют больше памяти. При первом включении Wildcard будет создан, если его ещё нет.",
|
||||
"realm.simultaneous": "Запускать Wildcard вместе с CoA",
|
||||
"realm.withReborn": "Запускать Warcraft Reborn вместе с CoA",
|
||||
"realm.rebornPort": "Порт мира Warcraft Reborn: {port}",
|
||||
"realm.rebornWorld": "Мир Warcraft Reborn",
|
||||
"realm.rebornNeedsCoa": "Warcraft Reborn запускается только вместе с Conquest of Azeroth. Сначала выберите Conquest of Azeroth на главной.",
|
||||
"realm.allThree": "Включены обе настройки: Conquest of Azeroth, Wildcard и Warcraft Reborn запускаются вместе.",
|
||||
"realm.simultaneousHint": "Остановите сервер перед изменением настроек. Запуск поднимет каждый выбранный мир с отдельными персонажами, настройками и портами, но общими аккаунтами. Каждый дополнительный мир требует больше памяти. При первом включении реалм будет создан, если его ещё нет.",
|
||||
"realm.secondPort": "Порт второго мира: {port}",
|
||||
"realm.preparing": "Подготовка баз реалма…",
|
||||
"realm.bothRunning": "Оба мира запускаются одновременно. У каждого свои персонажи, прогресс и настройки модулей.",
|
||||
"realm.bothRunning": "Эти миры запускаются одновременно. У каждого свои персонажи, прогресс и настройки модулей.",
|
||||
"repair.title": "Проверка и восстановление сервера",
|
||||
"repair.hint": "Перед восстановлением остановите оба реалма и обновите сервер до последнего пакета. Repair сохранит резервную копию БД и заменяемых файлов, восстановит файлы программы и применит недостающие SQL. Персонажи и существующие настройки сохраняются.",
|
||||
"repair.check": "Проверить файлы и БД",
|
||||
@@ -114,7 +119,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"btn.stopSmall": "Остановить",
|
||||
"btn.restart": "Перезапустить",
|
||||
"btn.startWithoutUpdate": "Запустить без обновления",
|
||||
"btn.playWithoutUpdate": "Играть без обновления",
|
||||
"import.squidRepackWarning": "Этот репак SquidBots проверяет хеш worldserver. Замена файла может нарушить работу Start_All_Bots и coa_update. Перед заменой менеджер запросит ваше решение.",
|
||||
"btn.play": "ИГРАТЬ",
|
||||
"btn.startPlay": "ЗАПУСТИТЬ И ИГРАТЬ",
|
||||
@@ -257,6 +261,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"client.updateAddon": "Обновить аддон компаньонов",
|
||||
"client.addonNote": "Аддон компаньонов установлен. Другие аддоны не затронуты.",
|
||||
"client.changeFolder": "Сменить папку…",
|
||||
"client.getFromSite": "Скачать лаунчер…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "Диагностика",
|
||||
@@ -643,51 +648,15 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
// Game client download and update
|
||||
"btn.close": "Закрыть",
|
||||
"btn.setupClient": "Настроить клиент игры",
|
||||
"btn.updateClient": "ОБНОВИТЬ КЛИЕНТ",
|
||||
"client.setup.title": "Настройка клиента игры",
|
||||
"client.setup.intro": "Чтобы играть, нужен клиент игры. Выберите уже имеющийся или позвольте менеджеру скачать его.",
|
||||
"client.setup.intro": "Чтобы играть, нужен клиент игры. Сообщество выдаёт его через свой официальный лаунчер.",
|
||||
"client.setup.have": "У меня уже есть клиент",
|
||||
"client.setup.download": "Скачать клиент",
|
||||
"client.setup.downloadHint": "Примерно 43 ГБ",
|
||||
"client.dl.pickParent": "Выберите, куда поместить клиент игры",
|
||||
"client.dl.confirmText": "Версия {v}, {size}. Клиент будет сохранён в эту папку:",
|
||||
"client.dl.free": "Свободно на этом диске: {free}.",
|
||||
"client.dl.notEnough": "Недостаточно места: нужно {need}, доступно {free}. Выберите другой диск.",
|
||||
"client.dl.otherFolder": "Другая папка…",
|
||||
"client.dl.start": "Скачать",
|
||||
"client.setup.getLauncher": "Скачать лаунчер (coa-development.org)",
|
||||
"client.setup.getLauncherHint": "Откроет сайт сообщества в браузере. Скачайте и установите лаунчер, войдите в свой аккаунт и дайте ему скачать игру (около 43 ГБ).",
|
||||
"client.setup.haveHint": "Укажите папку, куда лаунчер установил игру, или любую другую копию клиента.",
|
||||
"client.dl.back": "Назад",
|
||||
"client.dl.retry": "Повторить",
|
||||
"client.dl.resume": "Продолжить",
|
||||
"client.dl.cancel": "Остановить",
|
||||
"client.dl.cancelled": "Остановлено. Всё уже скачанное сохранено, можно продолжить в любой момент.",
|
||||
"client.dl.scanning": "Сравниваю файлы…",
|
||||
"client.dl.downloading": "Загрузка",
|
||||
"client.dl.progress": "{done} из {total}",
|
||||
"client.dl.speed": "{speed}/с",
|
||||
"client.dl.done": "Клиент игры готов",
|
||||
"client.dl.doneText": "Он привязан к этому серверу. Можно нажимать PLAY.",
|
||||
"client.upd.title": "Обновление клиента",
|
||||
"client.upd.available": "Доступна новая версия клиента игры: {v}.",
|
||||
"client.upd.summary": "Файлов к загрузке: {n}, всего {size}.",
|
||||
"client.upd.upToDate": "Ваш клиент уже соответствует версии {v}.",
|
||||
"client.upd.modifiedTitle": "Файлов, изменённых вами: {n}",
|
||||
"client.upd.modifiedText": "Например, изменённый exe. Оставьте их или замените официальными версиями; ваши тогда сохранятся в папке .coa-manager внутри клиента. Графические обёртки (d3d9.dll и подобные) и конфиги всегда остаются как есть.",
|
||||
"client.upd.keep": "Оставить файлы, которые я менял",
|
||||
"client.upd.more": "… и ещё {n}",
|
||||
"client.upd.start": "Обновить клиент",
|
||||
"client.upd.later": "Не сейчас",
|
||||
"client.upd.playAnyway": "Играть без обновления",
|
||||
"client.upd.done": "Клиент игры обновлён",
|
||||
"client.upd.doneText": "Менеджер сообщит, когда выйдет новая версия.",
|
||||
"client.track.title": "Обновление клиента через менеджер",
|
||||
"client.track.text": "Менеджер один раз сравнит ваш клиент с официальным, а потом будет проверять новые версии, как для сервера. Файлы, которые вы меняли, не заменяются без вашего согласия.",
|
||||
"client.track.start": "Следить за обновлениями",
|
||||
"client.track.startUpdate": "Обновить и следить за обновлениями",
|
||||
"client.track.button": "Обновлять этот клиент через менеджер…",
|
||||
"client.version": "Версия клиента",
|
||||
"client.versionUntracked": "менеджер не отслеживает",
|
||||
"client.versionUnfinished": "загрузка не завершена",
|
||||
"client.downloadInstead": "Скачать клиент…",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "Показать пароль",
|
||||
@@ -874,7 +843,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"dash.openBrowser": "Открыть в браузере",
|
||||
"dash.update": "Обновить панель",
|
||||
"upd.startAfter": "Запускать сервер после обновления (иначе выключенный сервер останется выключенным)",
|
||||
"client.startAfter": "Запускать игру после обновления клиента",
|
||||
"bk.folder": "Папка резервных копий",
|
||||
"bk.folderDefault": "по умолчанию",
|
||||
"bk.folderNote": "Новые копии сохраняются сюда, например на другой диск. Прежние копии остаются на месте и по-прежнему в списке. Папка должна быть вне папки сервера.",
|
||||
@@ -887,8 +855,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"remove.stopFirst": "Сначала остановите сервер.",
|
||||
"remove.confirm": "Убрать этот сервер из Manager?\n\n{path}\n\nФайлы не удаляются.",
|
||||
"upd.dbUnchecked": "Не удалось проверить базу данных, поэтому неизвестно, нужны ли ей изменения: {why}",
|
||||
"client.job.checking": "Проверка клиента…",
|
||||
"client.job.updating": "Обновление клиента",
|
||||
"nav.characters": "Персонажи",
|
||||
"q.characters": "Какие мои персонажи где могут играть?",
|
||||
"portable.title": "Персонажи",
|
||||
@@ -986,7 +952,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": "Реалм недоступен.",
|
||||
@@ -1081,6 +1047,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"browse.noCharacter": "У вас пока нет переносимого персонажа. Сделайте его переносимым на странице «Персонажи», чтобы увидеть, сможет ли он играть здесь.",
|
||||
"browse.canPlay": "Можно играть",
|
||||
"browse.cannotPlay": "Здесь играть нельзя",
|
||||
"browse.realmOffline": "Оффлайн",
|
||||
"browse.offlineWarning": "Сервер сейчас не запущен хостом. Игра переносимым персонажем станет доступна, когда владелец включит сервер.",
|
||||
"browse.play": "Играть",
|
||||
"browse.playSoon": "Вход на сервер появится вместе с поддержкой аккаунтов на следующем шаге.",
|
||||
"registry.title": "Публичный список",
|
||||
@@ -1101,6 +1069,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": "Реестр отклонил этот реалм. Публикация остановлена.",
|
||||
@@ -1160,6 +1129,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": "Адрес для подключения игроков",
|
||||
|
||||
+6
-45
@@ -3,7 +3,7 @@ const zh = {
|
||||
"mod.switching": "正在应用更改…请稍候。",
|
||||
"portable.experimental": "实验性功能:便携角色仍在积极开发中,可能存在错误。",
|
||||
"remote.clientReady": "客户端已就绪。保存服主地址,然后点击开始游戏。",
|
||||
"remote.clientIntro": "选择已有游戏客户端,或在此下载。无需安装本地服务器。",
|
||||
"remote.clientIntro": "选择已有的游戏客户端,或通过社区的启动器获取。无需本地服务器。",
|
||||
"welcome.host.title": "我要搭建服务器",
|
||||
"welcome.host.text": "安装新服务器或管理已有服务器。",
|
||||
"welcome.connect.title": "连接其他服务器",
|
||||
@@ -91,7 +91,6 @@ const zh = {
|
||||
"btn.stopSmall": "停止",
|
||||
"btn.restart": "重启",
|
||||
"btn.startWithoutUpdate": "不更新启动服务器",
|
||||
"btn.playWithoutUpdate": "不更新开始游戏",
|
||||
"import.squidRepackWarning": "此 SquidBots 整合包会检查 worldserver 哈希。替换程序可能导致 Start_All_Bots 和 coa_update 无法运行。更新前会要求您选择。",
|
||||
"btn.play": "开始游戏",
|
||||
"btn.startPlay": "启动并开始游戏",
|
||||
@@ -234,6 +233,7 @@ const zh = {
|
||||
"client.updateAddon": "更新随从插件",
|
||||
"client.addonNote": "随从插件已安装。其他插件未受任何影响。",
|
||||
"client.changeFolder": "更换文件夹…",
|
||||
"client.getFromSite": "获取启动器…",
|
||||
|
||||
// Diagnostics
|
||||
"diag.title": "诊断",
|
||||
@@ -619,51 +619,15 @@ const zh = {
|
||||
// Game client download and update
|
||||
"btn.close": "关闭",
|
||||
"btn.setupClient": "配置游戏客户端",
|
||||
"btn.updateClient": "更新客户端",
|
||||
"client.setup.title": "配置游戏客户端",
|
||||
"client.setup.intro": "进行游戏需要安装匹配的客户端。你可以关联已有的游戏客户端,也可以让管理器为你自动下载。",
|
||||
"client.setup.intro": "进行游戏需要安装客户端。社区通过其官方启动器提供客户端。",
|
||||
"client.setup.have": "已有游戏客户端",
|
||||
"client.setup.download": "下载全新客户端",
|
||||
"client.setup.downloadHint": "约 43 GB",
|
||||
"client.dl.pickParent": "选择游戏客户端存放位置",
|
||||
"client.dl.confirmText": "版本 {v},体积 {size}。将被保存在以下文件夹中:",
|
||||
"client.dl.free": "该驱动器剩余空间:{free}。",
|
||||
"client.dl.notEnough": "磁盘剩余空间不足:需要 {need},可用 {free}。请选择其他驱动器。",
|
||||
"client.dl.otherFolder": "选择其他文件夹…",
|
||||
"client.dl.start": "开始下载",
|
||||
"client.setup.getLauncher": "获取启动器(coa-development.org)",
|
||||
"client.setup.getLauncherHint": "在浏览器中打开社区网站。在那里下载并安装启动器,用你的账号登录,让它下载游戏(约 43 GB)。",
|
||||
"client.setup.haveHint": "选择启动器安装游戏的文件夹,或任何其他客户端副本。",
|
||||
"client.dl.back": "返回",
|
||||
"client.dl.retry": "重试",
|
||||
"client.dl.resume": "继续下载",
|
||||
"client.dl.cancel": "停止",
|
||||
"client.dl.cancelled": "下载已暂停。已下载的文件将被保留;随时可继续断点续传。",
|
||||
"client.dl.scanning": "正在比对文件…",
|
||||
"client.dl.downloading": "正在下载",
|
||||
"client.dl.progress": "{done} / {total}",
|
||||
"client.dl.speed": "{speed}/秒",
|
||||
"client.dl.done": "游戏客户端已就绪",
|
||||
"client.dl.doneText": "已成功关联至此服务器。你可以点击“开始游戏”了。",
|
||||
"client.upd.title": "客户端更新",
|
||||
"client.upd.available": "检测到更新的游戏客户端版本:{v}。",
|
||||
"client.upd.summary": "需下载 {n} 个文件,共计 {size}。",
|
||||
"client.upd.upToDate": "你的客户端已与版本 {v} 完全一致。",
|
||||
"client.upd.modifiedTitle": "检测到 {n} 个文件曾被你修改",
|
||||
"client.upd.modifiedText": "例如打过补丁的可执行程序。你可以选择保留它们,或替换为官方版本;被替换的文件将保存在客户端的 .coa-manager 文件夹中以作备份。图形渲染增强补丁(如 d3d9.dll 等)及配置文件始终会保留原样。",
|
||||
"client.upd.keep": "保留我修改过的文件",
|
||||
"client.upd.more": "… 以及另外 {n} 个",
|
||||
"client.upd.start": "更新客户端",
|
||||
"client.upd.later": "暂不更新",
|
||||
"client.upd.playAnyway": "跳过更新直接进入游戏",
|
||||
"client.upd.done": "游戏客户端已是最新版本",
|
||||
"client.upd.doneText": "当发布更高版本时,管理器会及时提醒你。",
|
||||
"client.track.title": "保持客户端为最新版本",
|
||||
"client.track.text": "管理器会先比对你的客户端与官方版本,并在后续像检查服务器更新一样检测新版本。除非你明确选择,否则你修改过的文件绝不会被自动替换。",
|
||||
"client.track.start": "保持更新",
|
||||
"client.track.startUpdate": "更新并保持同步",
|
||||
"client.track.button": "为该客户端开启自动检查更新…",
|
||||
"client.version": "客户端版本",
|
||||
"client.versionUntracked": "未由管理器追踪",
|
||||
"client.versionUnfinished": "下载尚未完成",
|
||||
"client.downloadInstead": "下载全新客户端…",
|
||||
|
||||
// Accounts panel, password toggle, install size, addon explanation
|
||||
"pw.show": "显示密码",
|
||||
@@ -850,7 +814,6 @@ const zh = {
|
||||
"dash.openBrowser": "在浏览器中打开",
|
||||
"dash.update": "更新仪表盘",
|
||||
"upd.startAfter": "更新后启动服务器(否则已停止的服务器保持停止)",
|
||||
"client.startAfter": "更新客户端后启动游戏",
|
||||
"bk.folder": "备份文件夹",
|
||||
"bk.folderDefault": "默认",
|
||||
"bk.folderNote": "新备份将保存在这里,例如另一个驱动器上。之前的备份保留在原处,仍会列出。该文件夹必须位于服务器文件夹之外。",
|
||||
@@ -863,8 +826,6 @@ const zh = {
|
||||
"remove.stopFirst": "请先停止服务器。",
|
||||
"remove.confirm": "要从 Manager 中移除此服务器吗?\n\n{path}\n\n不会删除任何文件。",
|
||||
"upd.dbUnchecked": "无法检查数据库,因此不清楚是否有待应用的数据库更改:{why}",
|
||||
"client.job.checking": "正在检查游戏客户端…",
|
||||
"client.job.updating": "正在更新游戏客户端",
|
||||
"err.docker_unavailable.title": "Docker 不可用",
|
||||
"err.docker_unavailable.message": "此服务器通过 Docker 运行。请安装并启动 Docker,确保当前用户有权使用它,然后重试。",
|
||||
"fr.lan.address": "网络地址",
|
||||
|
||||
@@ -375,6 +375,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."
|
||||
|
||||
@@ -375,6 +375,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."
|
||||
|
||||
@@ -375,6 +375,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."
|
||||
|
||||
@@ -375,6 +375,10 @@
|
||||
"t": "Интервал автосохранения",
|
||||
"d": "Как часто персонажи игроков сохраняются, пока они в сети."
|
||||
},
|
||||
"PortableSession.Enable": {
|
||||
"t": "Переносимые персонажи (переносимая игра)",
|
||||
"d": "Разрешает игрокам заходить на этот сервер переносимыми персонажами, сохранёнными в их Менеджере."
|
||||
},
|
||||
"CharactersPerAccount": {
|
||||
"t": "Персонажей на учётную запись",
|
||||
"d": "Наибольшее число персонажей на учётной записи во всех мирах."
|
||||
|
||||
@@ -375,6 +375,10 @@
|
||||
"t": "角色数据自动保存间隔",
|
||||
"d": "在线玩家角色数据写入数据库的时间间隔。"
|
||||
},
|
||||
"PortableSession.Enable": {
|
||||
"t": "便携式角色(跨服漫游)",
|
||||
"d": "允许玩家使用保存在管理器中的便携式角色进入此服务器进行游玩。"
|
||||
},
|
||||
"CharactersPerAccount": {
|
||||
"t": "每个账号最大角色数",
|
||||
"d": "单个账号在所有服务器可创建的角色总数上限。"
|
||||
|
||||
+70
-36
@@ -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 }[];
|
||||
@@ -229,6 +229,68 @@ export interface ModuleView {
|
||||
compatibility?: "compatible" | "experimental" | "unsupported";
|
||||
}
|
||||
|
||||
export interface MultiDimensionalStatus {
|
||||
build_status: string;
|
||||
runtime_status: string;
|
||||
gameplay_status: string;
|
||||
db_status: string;
|
||||
security_status: string;
|
||||
}
|
||||
|
||||
export interface CompatibilityFinding {
|
||||
rule_id: string;
|
||||
severity: "Critical" | "Warning" | "Info";
|
||||
confidence: "High" | "Medium" | "Low";
|
||||
file: string;
|
||||
line: number;
|
||||
explanation: string;
|
||||
recommended_action: string;
|
||||
evidence: string;
|
||||
is_auto_fixable: boolean;
|
||||
}
|
||||
|
||||
export interface VerificationStatus {
|
||||
l0_static: string;
|
||||
l1_compile: string;
|
||||
l2_link: string;
|
||||
l3_contract: string;
|
||||
l4_engine_boot: string;
|
||||
l5_gameplay: string;
|
||||
l6_teardown: string;
|
||||
}
|
||||
|
||||
export interface CompatibilityReport {
|
||||
repository_path: string;
|
||||
repository_name: string;
|
||||
commit: string;
|
||||
license_info: {
|
||||
primary_license: string;
|
||||
license_file?: string | null;
|
||||
vendored_licenses: string[];
|
||||
spdx_identifier?: string | null;
|
||||
};
|
||||
classification: string;
|
||||
verification_status: VerificationStatus;
|
||||
multi_dimensional_status?: MultiDimensionalStatus | null;
|
||||
tree_digest?: string | null;
|
||||
cache_hit?: boolean | null;
|
||||
sdk_fingerprint?: string | null;
|
||||
hooks: Array<{ class_name: string; script_type: string; file: string; line: number }>;
|
||||
script_loaders: {
|
||||
canonical_loader?: string | null;
|
||||
all_discovered_loaders: string[];
|
||||
has_duplicate_registration: boolean;
|
||||
};
|
||||
databases: Array<{ database_type: string; operation: string; file: string; line: number }>;
|
||||
sql_files: Array<{ file_path: string; statement_count: number; tables_referenced: string[]; has_schema_mutation: boolean }>;
|
||||
core_patches: string[];
|
||||
has_cmakelists: boolean;
|
||||
has_entrypoint_adapter: boolean;
|
||||
findings: CompatibilityFinding[];
|
||||
reasons: string[];
|
||||
recommended_actions: string[];
|
||||
}
|
||||
|
||||
export interface ModuleSetting {
|
||||
key: string;
|
||||
value: string;
|
||||
@@ -359,36 +421,8 @@ export interface ClientInfo {
|
||||
}
|
||||
|
||||
export interface ClientStatus {
|
||||
/** A usable client folder is linked. */
|
||||
linked: boolean;
|
||||
managed: boolean;
|
||||
installed_version: string | null;
|
||||
latest_version: string | null;
|
||||
latest_bytes: number | null;
|
||||
update_available: boolean;
|
||||
}
|
||||
|
||||
export interface ClientPlan {
|
||||
version: string;
|
||||
items: { path: string; size: number; kind: "missing" | "changed" | "modified" }[];
|
||||
download_bytes: number;
|
||||
total_files: number;
|
||||
up_to_date_files: number;
|
||||
kept_files: number;
|
||||
}
|
||||
|
||||
export interface ClientStep {
|
||||
phase: "scan" | "download" | "finish";
|
||||
done: number;
|
||||
total: number;
|
||||
bytes_per_sec: number;
|
||||
file: string | null;
|
||||
}
|
||||
|
||||
export interface ClientDownloadCheck {
|
||||
needed_bytes: number;
|
||||
free_bytes: number;
|
||||
version: string;
|
||||
dest: string;
|
||||
}
|
||||
|
||||
export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
|
||||
@@ -429,6 +463,7 @@ export interface FriendsStatus {
|
||||
auth_port: number;
|
||||
world_port: number;
|
||||
secondary_world_port?: number | null;
|
||||
reborn_world_port?: number | null;
|
||||
}
|
||||
|
||||
export interface InternetCheck {
|
||||
@@ -472,6 +507,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"),
|
||||
@@ -510,7 +546,10 @@ export const api = {
|
||||
realmlistDelete: (id: string, profileId: string) => invoke<void>("realmlist_delete", { id, profileId }),
|
||||
realmlistActivate: (id: string, profileId: string) => invoke<string[]>("realmlist_activate", { id, profileId }),
|
||||
modulesList: (id: string) => invoke<ModuleView[]>("modules_list", { id }),
|
||||
analyzeGithubModule: (url: string, realmId: string) =>
|
||||
invoke<CompatibilityReport>("analyze_github_module", { url, realmId }),
|
||||
moduleSetEnabled: (id: string, module: string, enabled: boolean) => invoke<void>("module_set_enabled", { id, module, enabled }),
|
||||
pluginsRepair: (id: string) => invoke<string[]>("plugins_repair", { id }),
|
||||
moduleSettings: (id: string, module: string) => invoke<ModuleSetting[]>("module_settings", { id, module }),
|
||||
moduleSaveSettings: (id: string, module: string, changes: Record<string, string>) => invoke<string[]>("module_save_settings", { id, module, changes }),
|
||||
allSettings: (id: string) => invoke<AllSetting[]>("all_settings", { id }),
|
||||
@@ -547,11 +586,6 @@ export const api = {
|
||||
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
|
||||
installAddon: (id: string) => invoke<void>("client_install_addon", { id }),
|
||||
clientStatus: (id: string) => invoke<ClientStatus>("client_status", { id }),
|
||||
clientDownloadCheck: (parent: string) => invoke<ClientDownloadCheck>("client_download_check", { parent }),
|
||||
clientPlan: (id: string) => invoke<ClientPlan>("client_plan", { id }),
|
||||
clientSync: (id: string, keepModified: boolean) => invoke<void>("client_sync", { id, keepModified }),
|
||||
clientDownload: (id: string, parent: string) => invoke<ClientInfo>("client_download", { id, parent }),
|
||||
clientCancel: () => invoke<void>("client_cancel"),
|
||||
customRacesStatus: (id: string) => invoke<CustomRacesClientStatus | null>("custom_races_status", { id }),
|
||||
customRacesUninstall: (id: string) => invoke<void>("custom_races_uninstall", { id }),
|
||||
customRacesInstall: (id: string) => invoke<void>("custom_races_install", { id }),
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import { startAfterUpdate } from "./updatePrefs";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { api, asUiError, type ClientPlan, type ClientStep, type UiError } from "@/lib/api";
|
||||
import { checkClient } from "@/lib/clientUpdate";
|
||||
|
||||
/**
|
||||
* Updating the game client from the main screen, without a window over everything: the "Update client" button turns into
|
||||
* a progress bar (as in a game launcher). Only a choice that needs the owner's word (files they changed) is shown, in
|
||||
* place, below the buttons. The first-time linking of a client keeps its dialog (ClientDialog).
|
||||
*/
|
||||
export type ClientJobPhase = "idle" | "scanning" | "choose" | "working" | "done" | "current" | "stopped" | "failed";
|
||||
|
||||
export interface ClientJob {
|
||||
phase: ClientJobPhase;
|
||||
step: ClientStep | null;
|
||||
plan: ClientPlan | null;
|
||||
error: UiError | null;
|
||||
}
|
||||
|
||||
const IDLE: ClientJob = { phase: "idle", step: null, plan: null, error: null };
|
||||
const jobs = new Map<string, ClientJob>();
|
||||
const listeners = new Set<() => void>();
|
||||
const cancelled = new Set<string>();
|
||||
|
||||
const get = (id: string) => jobs.get(id) ?? IDLE;
|
||||
function set(id: string, next: Partial<ClientJob>) {
|
||||
jobs.set(id, { ...get(id), ...next });
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
|
||||
let unlisten: (() => void) | null = null;
|
||||
async function followProgress(id: string) {
|
||||
if (unlisten) return;
|
||||
try {
|
||||
unlisten = await listen<ClientStep>("client-progress", (e) => {
|
||||
const phase = get(id).phase;
|
||||
if (phase === "scanning" || phase === "working") set(id, { step: e.payload });
|
||||
});
|
||||
} catch {
|
||||
/* no event bridge (a plain browser): the bar just stays at zero */
|
||||
}
|
||||
}
|
||||
|
||||
function fail(id: string, e: unknown) {
|
||||
if (cancelled.has(id)) set(id, { phase: "stopped", step: null });
|
||||
else set(id, { phase: "failed", step: null, error: asUiError(e) });
|
||||
}
|
||||
|
||||
async function refresh(id: string) {
|
||||
await checkClient(id);
|
||||
}
|
||||
|
||||
/** Look at what differs from the published client; update at once when nothing needs a decision. */
|
||||
export async function startClientUpdate(id: string): Promise<void> {
|
||||
const now = get(id).phase;
|
||||
if (now === "scanning" || now === "working") return;
|
||||
cancelled.delete(id);
|
||||
set(id, { phase: "scanning", step: null, plan: null, error: null });
|
||||
void followProgress(id);
|
||||
try {
|
||||
const plan = await api.clientPlan(id);
|
||||
if (plan.items.length === 0) {
|
||||
set(id, { phase: "current", plan, step: null });
|
||||
void refresh(id);
|
||||
setTimeout(() => {
|
||||
if (get(id).phase === "current") set(id, { phase: "idle" });
|
||||
}, 5000);
|
||||
return;
|
||||
}
|
||||
if (plan.items.some((i) => i.kind === "modified")) {
|
||||
set(id, { phase: "choose", plan, step: null });
|
||||
return;
|
||||
}
|
||||
await syncClient(id, true);
|
||||
} catch (e) {
|
||||
fail(id, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Download what is missing or changed; `keepModified` keeps the files the owner changed. */
|
||||
export async function syncClient(id: string, keepModified: boolean): Promise<void> {
|
||||
cancelled.delete(id);
|
||||
set(id, { phase: "working", step: null, error: null });
|
||||
void followProgress(id);
|
||||
try {
|
||||
await api.clientSync(id, keepModified);
|
||||
set(id, { phase: "done", step: null });
|
||||
if (startAfterUpdate("client", id)) void api.play(id).catch(() => undefined);
|
||||
void refresh(id);
|
||||
setTimeout(() => {
|
||||
if (get(id).phase === "done") set(id, { phase: "idle" });
|
||||
}, 6000);
|
||||
} catch (e) {
|
||||
fail(id, e);
|
||||
}
|
||||
}
|
||||
|
||||
export function stopClientJob(id: string) {
|
||||
cancelled.add(id);
|
||||
void api.clientCancel().catch(() => undefined);
|
||||
}
|
||||
|
||||
export function dismissClientJob(id: string) {
|
||||
set(id, { phase: "idle", error: null, plan: null, step: null });
|
||||
}
|
||||
|
||||
export function useClientJob(id: string): ClientJob {
|
||||
return useSyncExternalStore(
|
||||
(l) => {
|
||||
listeners.add(l);
|
||||
return () => listeners.delete(l);
|
||||
},
|
||||
() => get(id),
|
||||
);
|
||||
}
|
||||
+3
-11
@@ -2,8 +2,8 @@ import { useSyncExternalStore } from "react";
|
||||
import { api, type ClientStatus } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* Game client status for the main screen: which client is linked and, for a client the Manager keeps up to date,
|
||||
* whether a newer one has been published. Checked at start and every five minutes (one small request; no game file is read).
|
||||
* Whether a game client is linked, for the main screen. The Manager does not download or update the client (the
|
||||
* community's official launcher does), so this is a local check only.
|
||||
*/
|
||||
interface State {
|
||||
status: ClientStatus | null;
|
||||
@@ -13,7 +13,6 @@ interface State {
|
||||
const EMPTY: State = { status: null, checking: false };
|
||||
const states = new Map<string, State>();
|
||||
const listeners = new Set<() => void>();
|
||||
const CHECK_EVERY_MS = 5 * 60 * 1000;
|
||||
|
||||
const get = (id: string) => states.get(id) ?? EMPTY;
|
||||
function set(id: string, next: Partial<State>) {
|
||||
@@ -27,19 +26,12 @@ export async function checkClient(id: string): Promise<void> {
|
||||
try {
|
||||
set(id, { status: await api.clientStatus(id) });
|
||||
} catch {
|
||||
// offline: keep what we knew
|
||||
// keep what we knew
|
||||
} finally {
|
||||
set(id, { checking: false });
|
||||
}
|
||||
}
|
||||
|
||||
/** Check now and then every five minutes. Returns the function that stops it. */
|
||||
export function startClientPolling(id: string): () => void {
|
||||
void checkClient(id);
|
||||
const t = setInterval(() => void checkClient(id), CHECK_EVERY_MS);
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
|
||||
export function useClientStatus(id: string): State {
|
||||
return useSyncExternalStore(
|
||||
(l) => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { useState } from "react";
|
||||
|
||||
/**
|
||||
* Whether a finished update starts things. Off by default for both: updating a stopped server leaves it stopped (a
|
||||
* server that was running is started again, as the update had to stop it) and a client update does not open the game.
|
||||
* Whether a finished server update starts the server. Off by default: updating a stopped server leaves it stopped (a
|
||||
* server that was running is started again, as the update had to stop it).
|
||||
*/
|
||||
export type AfterUpdate = "server" | "client";
|
||||
export type AfterUpdate = "server";
|
||||
|
||||
const key = (kind: AfterUpdate, id: string) => `coa-start-after-${kind}-update:${id}`;
|
||||
const fallback = (_kind: AfterUpdate) => false;
|
||||
|
||||
@@ -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,13 +1,12 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api";
|
||||
import { api, asUiError, type ClientInfo, type UiError } from "@/lib/api";
|
||||
import { checkClient } from "@/lib/clientUpdate";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { CLIENT_SITE, ClientDialog } from "@/screens/ClientDialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
import { useStartAfterUpdate } from "@/lib/updatePrefs";
|
||||
|
||||
export function ClientCard({ serverId, remote = false }: { serverId: string; remote?: boolean }) {
|
||||
const t = useT();
|
||||
@@ -16,13 +15,10 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<ClientStatus | null>(null);
|
||||
const [patchProgress, setPatchProgress] = useState<string | null>(null);
|
||||
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
|
||||
const [playAfter, setPlayAfter] = useStartAfterUpdate("client", serverId);
|
||||
const [dialog, setDialog] = useState(false);
|
||||
|
||||
const refresh = () => {
|
||||
void api.clientStatus(serverId).then(setStatus).catch(() => setStatus(null));
|
||||
return api.clientInfo(serverId).then(setInfo).catch((e) => setError(asUiError(e)));
|
||||
};
|
||||
useEffect(() => {
|
||||
@@ -65,7 +61,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
{info === null && (
|
||||
<>
|
||||
<p className="mt-1 text-sm text-muted">{t(remote ? "remote.clientIntro" : "client.intro")}</p>
|
||||
<Button className="mt-4" onClick={() => setDialog("setup")} disabled={busy}>{t("btn.setupClient")}</Button>
|
||||
<Button className="mt-4" onClick={() => setDialog(true)} disabled={busy}>{t("btn.setupClient")}</Button>
|
||||
</>
|
||||
)}
|
||||
{info && (
|
||||
@@ -77,13 +73,6 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
{hosts.length ? hosts.filter(Boolean).join(", ") : "—"}
|
||||
{!remote && (pointsLocal ? <span className="ml-2 text-ok">{t("client.thisComputer")}</span> : <span className="ml-2 text-warn">{t("client.notThisServer")}</span>)}
|
||||
</dd>
|
||||
<dt className="text-muted">{t("client.version")}</dt>
|
||||
<dd>
|
||||
{status?.managed
|
||||
? status.installed_version ?? t("client.versionUnfinished")
|
||||
: t("client.versionUntracked")}
|
||||
{status?.update_available && <span className="ml-2 text-warn">{t("client.updateAvailable")}</span>}
|
||||
</dd>
|
||||
{!remote && <>
|
||||
<dt className="text-muted">{t("client.addon")}</dt>
|
||||
<dd>
|
||||
@@ -95,12 +84,6 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
<dt className="text-muted">{t("client.otherAddons")}</dt>
|
||||
<dd>{t("client.leftAsIs", { n: info.other_addons })}</dd>
|
||||
</dl>
|
||||
{!remote && (
|
||||
<label className="mt-4 flex cursor-pointer items-center gap-2 text-sm">
|
||||
<input type="checkbox" checked={playAfter} onChange={(e) => setPlayAfter(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
|
||||
<span>{t("client.startAfter")}</span>
|
||||
</label>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{!remote && !pointsLocal && (
|
||||
<Button size="sm" disabled={busy} onClick={() => void run(async () => { await api.setRealmlist(serverId, "127.0.0.1"); return t("client.pointedNote"); })}>
|
||||
@@ -112,15 +95,9 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
{info.addon.installed ? t("client.updateAddon") : t("client.installAddon")}
|
||||
</Button>
|
||||
)}
|
||||
{(status?.update_available || (remote && status?.managed)) && (
|
||||
<Button size="sm" variant="primary" disabled={busy} onClick={() => setDialog("update")}>{t("client.upd.start")}</Button>
|
||||
)}
|
||||
{status && !status.managed && (
|
||||
<Button size="sm" disabled={busy} onClick={() => setDialog("track")}>{t("client.track.button")}</Button>
|
||||
)}
|
||||
{remote && <Button size="sm" disabled={busy} onClick={() => void run(() => api.customRacesInstall(serverId))}>{t("client.races.install")}</Button>}
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void choose()}>{t("client.changeFolder")}</Button>
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => setDialog("setup")}>{t("client.downloadInstead")}</Button>
|
||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void api.openLink(CLIENT_SITE).catch((e) => setError(asUiError(e)))}>{t("client.getFromSite")}</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -130,8 +107,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
|
||||
{dialog && (
|
||||
<ClientDialog
|
||||
serverId={serverId}
|
||||
mode={dialog}
|
||||
onClose={() => setDialog(null)}
|
||||
onClose={() => setDialog(false)}
|
||||
onChanged={() => {
|
||||
void refresh();
|
||||
void checkClient(serverId);
|
||||
|
||||
+29
-207
@@ -1,62 +1,35 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Check, Loader2 } from "lucide-react";
|
||||
import { api, asUiError, REMOTE_CLIENT_ID, type ClientDownloadCheck, type ClientPlan, type ClientStep, type UiError } from "@/lib/api";
|
||||
import { formatBytes } from "@/lib/utils";
|
||||
import { Check, ExternalLink } from "lucide-react";
|
||||
import { api, asUiError, REMOTE_CLIENT_ID, type UiError } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
|
||||
/**
|
||||
* - setup: no client linked yet: pick an existing folder or download the client.
|
||||
* - update: a client the Manager keeps up to date has a newer version.
|
||||
* - track: an existing client the Manager has not looked at yet: compare it once, then keep it up to date.
|
||||
*/
|
||||
export type ClientDialogMode = "setup" | "update" | "track";
|
||||
type Phase = "choose" | "confirm" | "scanning" | "preview" | "working" | "done" | "stopped" | "failed";
|
||||
/** Where the community hands out its launcher, which downloads the game client. The Manager does not download it. */
|
||||
export const CLIENT_SITE = "https://coa-development.org/";
|
||||
|
||||
type Phase = "choose" | "done" | "failed";
|
||||
|
||||
/**
|
||||
* Linking the game client: pick a folder that already has the game, or go to the community site for the official
|
||||
* launcher (it downloads the client after signing in) and come back to pick the folder it installed to.
|
||||
*/
|
||||
export function ClientDialog(props: {
|
||||
serverId: string;
|
||||
mode: ClientDialogMode;
|
||||
onClose: () => void;
|
||||
/** The linked client or its version changed; the caller refreshes what it shows. */
|
||||
/** The linked client changed; the caller refreshes what it shows. */
|
||||
onChanged: () => void;
|
||||
/** Update mode only: start the game without updating. */
|
||||
onPlayAnyway?: () => void;
|
||||
}) {
|
||||
const t = useT();
|
||||
const human = useHuman();
|
||||
const { serverId, mode } = props;
|
||||
const [phase, setPhase] = useState<Phase>(mode === "setup" ? "choose" : "scanning");
|
||||
const [step, setStep] = useState<ClientStep | null>(null);
|
||||
const [parent, setParent] = useState<string | null>(null);
|
||||
const [check, setCheck] = useState<ClientDownloadCheck | null>(null);
|
||||
const [plan, setPlan] = useState<ClientPlan | null>(null);
|
||||
const [keep, setKeep] = useState(true);
|
||||
const { serverId } = props;
|
||||
const [phase, setPhase] = useState<Phase>("choose");
|
||||
const [error, setError] = useState<UiError | null>(null);
|
||||
const cancelled = useRef(false);
|
||||
const working = phase === "scanning" || phase === "working";
|
||||
|
||||
useEffect(() => {
|
||||
let un: (() => void) | undefined;
|
||||
let gone = false;
|
||||
listen<ClientStep>("client-progress", (e) => setStep(e.payload))
|
||||
.then((u) => (gone ? u() : (un = u)))
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
gone = true;
|
||||
un?.();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== "setup") void startPlan();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape" && !working) close();
|
||||
if (e.key === "Escape") close();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
@@ -67,15 +40,6 @@ export function ClientDialog(props: {
|
||||
props.onClose();
|
||||
}
|
||||
|
||||
function fail(e: unknown) {
|
||||
if (cancelled.current) {
|
||||
setPhase("stopped");
|
||||
} else {
|
||||
setError(asUiError(e));
|
||||
setPhase("failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function useExisting() {
|
||||
const picked = await open({ directory: true, multiple: false, title: t("client.dialogTitle") });
|
||||
if (typeof picked !== "string") return;
|
||||
@@ -89,68 +53,16 @@ export function ClientDialog(props: {
|
||||
}
|
||||
}
|
||||
|
||||
async function pickParent() {
|
||||
const picked = await open({ directory: true, multiple: false, title: t("client.dl.pickParent") });
|
||||
if (typeof picked !== "string") return;
|
||||
setError(null);
|
||||
async function openSite() {
|
||||
try {
|
||||
setCheck(await api.clientDownloadCheck(picked));
|
||||
setParent(picked);
|
||||
setPhase("confirm");
|
||||
await api.openLink(CLIENT_SITE);
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
setPhase("failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function startDownload() {
|
||||
if (!parent) return;
|
||||
cancelled.current = false;
|
||||
setStep(null);
|
||||
setPhase("working");
|
||||
try {
|
||||
await api.clientDownload(serverId, parent);
|
||||
setPhase("done");
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function startPlan() {
|
||||
cancelled.current = false;
|
||||
setStep(null);
|
||||
setError(null);
|
||||
setPhase("scanning");
|
||||
try {
|
||||
const p = await api.clientPlan(serverId);
|
||||
setPlan(p);
|
||||
setKeep(p.items.some((i) => i.kind === "modified"));
|
||||
setPhase("preview");
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function startSync() {
|
||||
cancelled.current = false;
|
||||
setStep(null);
|
||||
setPhase("working");
|
||||
try {
|
||||
await api.clientSync(serverId, keep);
|
||||
setPhase("done");
|
||||
} catch (e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
function stop() {
|
||||
cancelled.current = true;
|
||||
void api.clientCancel();
|
||||
}
|
||||
|
||||
const modified = plan?.items.filter((i) => i.kind === "modified") ?? [];
|
||||
const pct = step && step.total > 0 ? Math.min(100, Math.floor((step.done / step.total) * 100)) : 0;
|
||||
const title = mode === "setup" ? t("client.setup.title") : mode === "update" ? t("client.upd.title") : t("client.track.title");
|
||||
const title = t("client.setup.title");
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6" role="presentation">
|
||||
@@ -161,12 +73,16 @@ export function ClientDialog(props: {
|
||||
<>
|
||||
<p className="mt-1 text-sm text-muted">{t("client.setup.intro")}</p>
|
||||
<div className="mt-4 grid gap-3">
|
||||
<button type="button" onClick={() => void openSite()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
{t("client.setup.getLauncher")}
|
||||
<ExternalLink className="h-4 w-4 text-muted" aria-hidden />
|
||||
</span>
|
||||
<span className="mt-1 block text-sm text-muted">{t("client.setup.getLauncherHint")}</span>
|
||||
</button>
|
||||
<button type="button" onClick={() => void useExisting()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
|
||||
<span className="block font-medium">{t("client.setup.have")}</span>
|
||||
</button>
|
||||
<button type="button" onClick={() => void pickParent()} className="cursor-pointer rounded-md border border-line bg-card-2 p-4 text-left transition-colors hover:border-gold/50">
|
||||
<span className="block font-medium">{t("client.setup.download")}</span>
|
||||
<span className="mt-1 block text-sm text-muted">{t("client.setup.downloadHint")}</span>
|
||||
<span className="mt-1 block text-sm text-muted">{t("client.setup.haveHint")}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-5 flex justify-end">
|
||||
@@ -175,93 +91,13 @@ export function ClientDialog(props: {
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "confirm" && check && (
|
||||
<>
|
||||
<p className="mt-1 text-sm text-muted">{t("client.dl.confirmText", { v: check.version, size: formatBytes(check.needed_bytes) })}</p>
|
||||
<p className="selectable mt-3 break-all rounded-md bg-black/30 px-3 py-2 text-sm">{check.dest}</p>
|
||||
<p className={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024 ? "mt-3 text-sm text-bad" : "mt-3 text-sm text-muted"}>
|
||||
{check.free_bytes < check.needed_bytes + 512 * 1024 * 1024
|
||||
? t("client.dl.notEnough", { need: formatBytes(check.needed_bytes), free: formatBytes(check.free_bytes) })
|
||||
: t("client.dl.free", { free: formatBytes(check.free_bytes) })}
|
||||
</p>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={() => void pickParent()}>{t("client.dl.otherFolder")}</Button>
|
||||
<Button variant="primary" disabled={check.free_bytes < check.needed_bytes + 512 * 1024 * 1024} onClick={() => void startDownload()}>
|
||||
{t("client.dl.start")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{(phase === "scanning" || phase === "working") && (
|
||||
<div className="mt-4" role="status">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-gold" aria-hidden />
|
||||
<span>{phase === "scanning" || step?.phase === "scan" ? t("client.dl.scanning") : t("client.dl.downloading")}</span>
|
||||
<span className="ml-auto text-muted">{pct}%</span>
|
||||
</div>
|
||||
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<div className="mt-2 flex justify-between gap-4 text-xs text-muted">
|
||||
<span className="min-w-0 truncate">{step?.file ?? ""}</span>
|
||||
<span className="shrink-0">
|
||||
{step ? t("client.dl.progress", { done: formatBytes(step.done), total: formatBytes(step.total) }) : ""}
|
||||
{step && step.phase === "download" && step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(step.bytes_per_sec) })}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-5 flex justify-end">
|
||||
<Button variant="ghost" onClick={stop}>{t("client.dl.cancel")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{phase === "preview" && plan && (
|
||||
<>
|
||||
{plan.items.length === 0 ? (
|
||||
<p className="mt-2 text-sm">{t("client.upd.upToDate", { v: plan.version })}</p>
|
||||
) : (
|
||||
<>
|
||||
{mode === "update" && <p className="mt-2 text-sm">{t("client.upd.available", { v: plan.version })}</p>}
|
||||
<p className="mt-1 text-sm text-muted">{t("client.upd.summary", { n: plan.items.length, size: formatBytes(plan.download_bytes) })}</p>
|
||||
</>
|
||||
)}
|
||||
{mode === "track" && <p className="mt-3 text-sm text-muted">{t("client.track.text")}</p>}
|
||||
{modified.length > 0 && (
|
||||
<div className="mt-4 rounded-md border border-warn/40 bg-warn/5 p-3 text-sm">
|
||||
<p className="font-medium">{t("client.upd.modifiedTitle", { n: modified.length })}</p>
|
||||
<p className="mt-1 text-muted">{t("client.upd.modifiedText")}</p>
|
||||
<ul className="selectable mt-2 space-y-0.5 text-xs text-muted">
|
||||
{modified.slice(0, 8).map((i) => (
|
||||
<li key={i.path} className="truncate">{i.path}</li>
|
||||
))}
|
||||
{modified.length > 8 && <li>{t("client.upd.more", { n: modified.length - 8 })}</li>}
|
||||
</ul>
|
||||
<label className="mt-3 flex cursor-pointer items-center gap-2">
|
||||
<input type="checkbox" checked={keep} onChange={(e) => setKeep(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
|
||||
<span>{t("client.upd.keep")}</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-5 flex flex-wrap justify-end gap-2">
|
||||
{mode === "update" && props.onPlayAnyway && (
|
||||
<Button variant="ghost" onClick={() => { close(); props.onPlayAnyway?.(); }}>{t("client.upd.playAnyway")}</Button>
|
||||
)}
|
||||
<Button variant="ghost" onClick={close}>{t("client.upd.later")}</Button>
|
||||
<Button variant="primary" onClick={() => void startSync()}>
|
||||
{mode === "track" ? (plan.items.length === 0 ? t("client.track.start") : t("client.track.startUpdate")) : t("client.upd.start")}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "done" && (
|
||||
<>
|
||||
<div className="mt-4 flex items-center gap-3">
|
||||
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-ok/15 text-ok"><Check className="h-5 w-5" aria-hidden /></span>
|
||||
<div>
|
||||
<p className="font-medium">{mode === "setup" ? t("client.dl.done") : t("client.upd.done")}</p>
|
||||
<p className="text-sm text-muted">{mode === "setup" ? t(serverId === REMOTE_CLIENT_ID ? "remote.clientReady" : "client.dl.doneText") : t("client.upd.doneText")}</p>
|
||||
<p className="font-medium">{t("client.dl.done")}</p>
|
||||
<p className="text-sm text-muted">{t(serverId === REMOTE_CLIENT_ID ? "remote.clientReady" : "client.dl.doneText")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 flex justify-end">
|
||||
@@ -270,26 +106,12 @@ export function ClientDialog(props: {
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "stopped" && (
|
||||
<>
|
||||
<p className="mt-3 text-sm text-muted">{t("client.dl.cancelled")}</p>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
|
||||
{mode === "setup" ? (
|
||||
parent && <Button variant="primary" onClick={() => void startDownload()}>{t("client.dl.resume")}</Button>
|
||||
) : (
|
||||
<Button variant="primary" onClick={() => void startPlan()}>{t("client.dl.resume")}</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{phase === "failed" && error && (
|
||||
<>
|
||||
<p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>
|
||||
<div className="mt-5 flex justify-end gap-2">
|
||||
<Button variant="ghost" onClick={close}>{t("btn.close")}</Button>
|
||||
{mode === "setup" ? <Button onClick={() => { setError(null); setPhase("choose"); }}>{t("client.dl.back")}</Button> : <Button onClick={() => void startPlan()}>{t("client.dl.retry")}</Button>}
|
||||
<Button onClick={() => { setError(null); setPhase("choose"); }}>{t("client.dl.back")}</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -5,7 +5,7 @@ import { cn } from "@/lib/utils";
|
||||
import { useI18n, type Key } from "@/i18n";
|
||||
import { asControlError, control, type AccountView, type Credentials, type JoinOutcome, type RemoteCharacter } from "@/lib/control";
|
||||
import { REMOTE_CLIENT_ID } from "@/lib/api";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { ClientDialog } from "@/screens/ClientDialog";
|
||||
import { Notes } from "@/screens/PortablePage";
|
||||
|
||||
const STATUS_TEXT: Record<string, Key> = {
|
||||
@@ -129,7 +129,7 @@ export function JoinPanel({ realm, character, automatic, onClaimed }: { realm: s
|
||||
const [err, setErr] = useState<{ code: string; message: string } | null>(null);
|
||||
const [linking, setLinking] = useState(false);
|
||||
const [bring, setBring] = useState(false);
|
||||
const [clientDialog, setClientDialog] = useState<ClientDialogMode | null>(null);
|
||||
const [clientDialog, setClientDialog] = useState(false);
|
||||
const refresh = () => control.account(realm).then(setAccount).catch(() => setAccount(null));
|
||||
useEffect(() => { setOutcome(null); setErr(null); setLinking(false); void refresh(); }, [realm]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -139,7 +139,7 @@ export function JoinPanel({ realm, character, automatic, onClaimed }: { realm: s
|
||||
const o = await control.join(realm, bring && character ? character : null, true);
|
||||
setOutcome(o);
|
||||
if (o.status === "needs_link") setLinking(true);
|
||||
if (o.status === "needs_client") setClientDialog("setup");
|
||||
if (o.status === "needs_client") setClientDialog(true);
|
||||
await refresh();
|
||||
} catch (e) { setErr(asControlError(e)); } finally { setBusy(false); }
|
||||
}
|
||||
@@ -156,7 +156,7 @@ export function JoinPanel({ realm, character, automatic, onClaimed }: { realm: s
|
||||
{outcome && text && <div className={cn("mt-3 rounded-md border p-3 text-sm", bad ? "border-warn/50 bg-warn/10" : "border-ok/40 bg-ok/10")} role="status" data-status={outcome.status}>
|
||||
<p>{t(text)}</p>
|
||||
{outcome.status === "needs_client" && (
|
||||
<Button size="sm" className="mt-2" onClick={() => setClientDialog("setup")}>
|
||||
<Button size="sm" className="mt-2" onClick={() => setClientDialog(true)}>
|
||||
{t("btn.setupClient")}
|
||||
</Button>
|
||||
)}
|
||||
@@ -170,10 +170,9 @@ export function JoinPanel({ realm, character, automatic, onClaimed }: { realm: s
|
||||
{clientDialog && (
|
||||
<ClientDialog
|
||||
serverId={REMOTE_CLIENT_ID}
|
||||
mode={clientDialog}
|
||||
onClose={() => setClientDialog(null)}
|
||||
onClose={() => setClientDialog(false)}
|
||||
onChanged={() => {
|
||||
setClientDialog(null);
|
||||
setClientDialog(false);
|
||||
void join();
|
||||
}}
|
||||
/>
|
||||
|
||||
+176
-1
@@ -1,7 +1,7 @@
|
||||
import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { Bot, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react";
|
||||
import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
|
||||
import { api, asUiError, type CompatibilityReport, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -93,6 +93,35 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
const [racesPatchStatus, setRacesPatchStatus] = useState<CustomRacesClientStatus | null>(null);
|
||||
const [racesInstalling, setRacesInstalling] = useState(false);
|
||||
const [racesProgress, setRacesProgress] = useState<CustomRacesProgress | null>(null);
|
||||
const [githubUrl, setGithubUrl] = useState("");
|
||||
const [analyzing, setAnalyzing] = useState(false);
|
||||
const [analysisError, setAnalysisError] = useState<string | null>(null);
|
||||
const [report, setReport] = useState<CompatibilityReport | null>(null);
|
||||
|
||||
async function runAnalysis() {
|
||||
if (!githubUrl.trim()) return;
|
||||
setAnalyzing(true);
|
||||
setAnalysisError(null);
|
||||
try {
|
||||
const rep = await api.analyzeGithubModule(githubUrl.trim(), serverId);
|
||||
setReport(rep);
|
||||
} catch (e: unknown) {
|
||||
setAnalysisError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setAnalyzing(false);
|
||||
}
|
||||
}
|
||||
|
||||
function exportReportJson() {
|
||||
if (!report) return;
|
||||
const blob = new Blob([JSON.stringify(report, null, 2)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${report.repository_name}-compatibility-report.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
const loadRacesStatus = useCallback(async () => {
|
||||
try {
|
||||
@@ -321,6 +350,152 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Third-party GitHub Module Analyzer v0.3 */}
|
||||
<div className="mt-8 border-t border-line/60 pt-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<GithubMark className="h-6 w-6 text-gold" />
|
||||
<h2 className="text-lg font-semibold">{locale === "ru" ? "Анализ сторонних модулей (GitHub)" : "Third-Party Module Analyzer (GitHub)"}</h2>
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
{locale === "ru"
|
||||
? "Проверка совместимости C++/SQL модулей AzerothCore с CoA Plugin SDK v0.3. Безопасный статический аудит без выполнения кода."
|
||||
: "Compatibility evaluation of AzerothCore C++/SQL modules against CoA Plugin SDK v0.3. Safe static audit without code execution."}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex flex-col gap-3 sm:flex-row">
|
||||
<input
|
||||
type="url"
|
||||
value={githubUrl}
|
||||
onChange={(e) => setGithubUrl(e.target.value)}
|
||||
placeholder="https://github.com/azerothcore/mod-congrats-on-level"
|
||||
className="flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"
|
||||
disabled={analyzing}
|
||||
/>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={analyzing || !githubUrl.trim()}
|
||||
onClick={() => void runAnalysis()}
|
||||
>
|
||||
{analyzing ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
|
||||
{locale === "ru" ? "Анализировать модуль" : "Analyze Module"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{analysisError && (
|
||||
<div className="mt-3 rounded-md border border-bad/40 bg-bad/10 p-3 text-sm text-bad" role="alert">
|
||||
{analysisError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{report && (
|
||||
<Card className="mt-5 border-gold/40 p-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-line pb-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-base font-semibold text-ink">{report.repository_name}</h3>
|
||||
<span className="rounded bg-white/10 px-2 py-0.5 font-mono text-xs text-muted">
|
||||
{report.commit.substring(0, 8)}
|
||||
</span>
|
||||
<span className="rounded-full border border-sky-400/40 bg-sky-400/10 px-2.5 py-0.5 text-xs font-medium text-sky-300">
|
||||
{report.license_info.primary_license}
|
||||
</span>
|
||||
{report.cache_hit !== undefined && report.cache_hit !== null && (
|
||||
<span className={cn("rounded px-2 py-0.5 text-xs font-mono", report.cache_hit ? "bg-ok/10 text-ok border border-ok/30" : "bg-white/10 text-muted")}>
|
||||
{report.cache_hit ? (locale === "ru" ? "КЭШ: ДА" : "CACHE: HIT") : (locale === "ru" ? "СКАЧАНО" : "FETCHED")}
|
||||
</span>
|
||||
)}
|
||||
{report.tree_digest && (
|
||||
<span className="rounded bg-white/5 px-2 py-0.5 font-mono text-[10px] text-muted/70" title={`Tree Digest: ${report.tree_digest}`}>
|
||||
SHA:{report.tree_digest.substring(0, 8)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-muted font-mono">{report.repository_path}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button size="sm" variant="ghost" onClick={exportReportJson}>
|
||||
{locale === "ru" ? "Экспорт JSON" : "Export JSON"}
|
||||
</Button>
|
||||
<div className="relative group">
|
||||
<Button size="sm" variant="primary" disabled className="opacity-50 cursor-not-allowed">
|
||||
{locale === "ru" ? "Установить" : "Install"}
|
||||
</Button>
|
||||
<div className="pointer-events-none absolute right-0 bottom-full mb-2 hidden w-64 rounded bg-black/90 p-2 text-xs text-zinc-300 shadow-xl group-hover:block">
|
||||
{locale === "ru"
|
||||
? "Автоматическая сборка и установка сторонних модулей пока не поддерживаются. Доступен анализ совместимости."
|
||||
: "Automated build and installation of third-party modules are not yet supported. Compatibility analysis is available."}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Multi-dimensional Status Grid */}
|
||||
{report.multi_dimensional_status && (
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-5 text-center">
|
||||
<div className="rounded border border-line bg-bg/50 p-2.5">
|
||||
<div className="text-xs text-muted">{locale === "ru" ? "Сборка" : "Build"}</div>
|
||||
<div className={cn("mt-1 text-xs font-semibold uppercase", report.multi_dimensional_status.build_status === "PASS" ? "text-ok" : report.multi_dimensional_status.build_status === "FAIL" ? "text-bad" : "text-warn")}>
|
||||
{report.multi_dimensional_status.build_status}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded border border-line bg-bg/50 p-2.5">
|
||||
<div className="text-xs text-muted">{locale === "ru" ? "Рантайм" : "Runtime"}</div>
|
||||
<div className={cn("mt-1 text-xs font-semibold uppercase", report.multi_dimensional_status.runtime_status === "PASS" ? "text-ok" : report.multi_dimensional_status.runtime_status === "BLOCKED" ? "text-bad" : "text-muted")}>
|
||||
{report.multi_dimensional_status.runtime_status}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded border border-line bg-bg/50 p-2.5">
|
||||
<div className="text-xs text-muted">{locale === "ru" ? "Геймплей" : "Gameplay"}</div>
|
||||
<div className={cn("mt-1 text-xs font-semibold uppercase", report.multi_dimensional_status.gameplay_status === "CLEAN" ? "text-ok" : report.multi_dimensional_status.gameplay_status === "VERIFIED_CONFLICT" ? "text-bad" : "text-warn")}>
|
||||
{report.multi_dimensional_status.gameplay_status}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded border border-line bg-bg/50 p-2.5">
|
||||
<div className="text-xs text-muted">{locale === "ru" ? "База данных" : "Database"}</div>
|
||||
<div className={cn("mt-1 text-xs font-semibold uppercase", report.multi_dimensional_status.db_status === "CLEAN" ? "text-ok" : "text-warn")}>
|
||||
{report.multi_dimensional_status.db_status}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded border border-line bg-bg/50 p-2.5">
|
||||
<div className="text-xs text-muted">{locale === "ru" ? "Безопасность" : "Security"}</div>
|
||||
<div className={cn("mt-1 text-xs font-semibold uppercase", (report.multi_dimensional_status.security_status === "SAFE" || report.multi_dimensional_status.security_status === "SOURCE_ANALYZED" || report.multi_dimensional_status.security_status === "REVIEWED_THIRD_PARTY" || report.multi_dimensional_status.security_status === "TRUSTED_OFFICIAL") ? "text-ok" : report.multi_dimensional_status.security_status === "KNOWN_UNSAFE" ? "text-bad" : "text-warn")}>
|
||||
{report.multi_dimensional_status.security_status}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Findings & Diagnostics */}
|
||||
<div className="mt-4">
|
||||
<h4 className="text-xs font-semibold uppercase tracking-wider text-muted">
|
||||
{locale === "ru" ? "Диагностические выводы" : "Diagnostic Findings"} ({report.findings.length})
|
||||
</h4>
|
||||
{report.findings.length === 0 ? (
|
||||
<p className="mt-2 text-sm text-ok">
|
||||
{locale === "ru" ? "✓ Замечаний и конфликтов не обнаружено." : "✓ No compatibility findings or conflicts detected."}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="mt-2 space-y-2 max-h-60 overflow-y-auto pr-1">
|
||||
{report.findings.map((f, idx) => (
|
||||
<li key={idx} className="rounded border border-line/60 bg-black/20 p-2 text-xs">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className={cn("font-medium", f.severity === "Critical" ? "text-bad" : f.severity === "Warning" ? "text-warn" : "text-sky-300")}>
|
||||
[{f.severity}] {f.rule_id}
|
||||
</span>
|
||||
<span className="font-mono text-muted">{f.file}:{f.line}</span>
|
||||
</div>
|
||||
<p className="mt-1 text-ink">{f.explanation}</p>
|
||||
<p className="mt-1 text-muted">→ {f.recommended_action}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+34
-88
@@ -1,12 +1,11 @@
|
||||
import { dismissClientJob, startClientUpdate, stopClientJob, syncClient, useClientJob } from "@/lib/clientJob";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { AlertTriangle, Loader2, X } from "lucide-react";
|
||||
import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api";
|
||||
import { cn, formatBytes, formatUptime } from "@/lib/utils";
|
||||
import { cn, formatUptime } from "@/lib/utils";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { checkClient, useClientStatus } from "@/lib/clientUpdate";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { checkClient } from "@/lib/clientUpdate";
|
||||
import { ClientDialog } from "@/screens/ClientDialog";
|
||||
import { RealmlistMenu } from "@/screens/RealmlistMenu";
|
||||
import { RealmPicker } from "@/screens/RealmPicker";
|
||||
import { CrashHistoryModal } from "@/screens/CrashHistoryModal";
|
||||
@@ -72,15 +71,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]);
|
||||
@@ -90,13 +89,8 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
const [showDetails, setShowDetails] = useState(false);
|
||||
const [pop, setPop] = useState<Population | null>(null);
|
||||
const [client, setClient] = useState<ClientInfo | null | undefined>(undefined);
|
||||
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
|
||||
const clientStatus = useClientStatus(server.id).status;
|
||||
const [dialog, setDialog] = useState(false);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const job = useClientJob(server.id);
|
||||
const jobBusy = job.phase === "scanning" || job.phase === "working";
|
||||
const jobPct = job.step && job.step.total > 0 ? Math.min(100, Math.floor((job.step.done / job.step.total) * 100)) : 0;
|
||||
const [keepMine, setKeepMine] = useState(true);
|
||||
const [perf, setPerf] = useState<Performance | null>(null);
|
||||
const upd = useServerUpdate(server.id);
|
||||
const visibleFailure = failure ?? upd.stateError ?? upd.uiError;
|
||||
@@ -149,10 +143,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
}, [server.id]);
|
||||
const alive = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (job.phase === "done" || job.phase === "current") void api.clientInfo(server.id).then(setClient).catch(() => undefined);
|
||||
}, [job.phase, server.id]);
|
||||
|
||||
const run = useCallback(
|
||||
async (kind: Exclude<Action, null>) => {
|
||||
if (kind === "stopping") {
|
||||
@@ -292,8 +282,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;
|
||||
@@ -442,52 +432,16 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
)}
|
||||
<div className="ml-auto flex max-w-full flex-wrap items-center justify-end gap-3">
|
||||
{client && <RealmlistMenu serverId={server.id} />}
|
||||
{client && jobBusy ? (
|
||||
<div
|
||||
className="relative flex h-16 min-w-64 items-center overflow-hidden rounded-md border border-gold/50 bg-card-2"
|
||||
role="progressbar"
|
||||
aria-valuenow={jobPct}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-label={job.phase === "scanning" ? t("client.job.checking") : t("client.job.updating")}
|
||||
>
|
||||
<div className="absolute inset-y-0 left-0 bg-gold/35 transition-[width] duration-300" style={{ width: `${jobPct}%` }} />
|
||||
<div className="relative z-10 flex min-w-0 flex-1 flex-col px-5 leading-tight">
|
||||
<span className="text-sm font-semibold uppercase tracking-wide">{job.phase === "scanning" ? t("client.job.checking") : t("client.job.updating")}</span>
|
||||
<span className="truncate text-xs text-muted">
|
||||
{jobPct}%
|
||||
{job.step && job.step.phase === "download" && job.step.bytes_per_sec > 0 ? ` · ${t("client.dl.speed", { speed: formatBytes(job.step.bytes_per_sec) })}` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => stopClientJob(server.id)}
|
||||
title={t("client.dl.cancel")}
|
||||
aria-label={t("client.dl.cancel")}
|
||||
className="relative z-10 flex h-full w-12 cursor-pointer items-center justify-center text-muted hover:text-ink"
|
||||
>
|
||||
<X className="h-4 w-4" aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
) : client && (clientStatus?.update_available || job.phase === "choose") ? (
|
||||
<Button variant="primary" size="xl" disabled={playing || job.phase === "choose"} onClick={() => void startClientUpdate(server.id)} className="min-w-40">
|
||||
{t("btn.updateClient")}
|
||||
</Button>
|
||||
) : client ? (
|
||||
{client ? (
|
||||
<Button variant="primary" size="xl" disabled={realmBusy || playing} onClick={() => void play()} className="min-w-40">
|
||||
{playing && <Loader2 className="h-5 w-5 animate-spin" aria-hidden />}
|
||||
{t("btn.play")}
|
||||
</Button>
|
||||
) : client === null ? (
|
||||
<Button variant="secondary" size="xl" onClick={() => setDialog("setup")} className="min-w-40">
|
||||
<Button variant="secondary" size="xl" onClick={() => setDialog(true)} className="min-w-40">
|
||||
{t("btn.setupClient")}
|
||||
</Button>
|
||||
) : null}
|
||||
{client && !jobBusy && (clientStatus?.update_available || job.phase === "choose") && (
|
||||
<Button variant="secondary" size="sm" disabled={realmBusy || playing || upd.applying} onClick={() => void play()}>
|
||||
{t("btn.playWithoutUpdate")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-line/60 pt-4 text-xs text-muted">
|
||||
@@ -514,34 +468,6 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
{anyUp && !running && !transitioning && (
|
||||
<p className="mt-3 text-sm text-muted">{t("overview.partial")}</p>
|
||||
)}
|
||||
{job.phase === "choose" && job.plan && (
|
||||
<div className="mt-4 rounded-md border border-warn/40 bg-warn/5 p-3 text-sm">
|
||||
<p className="font-medium">{t("client.upd.modifiedTitle", { n: job.plan.items.filter((i) => i.kind === "modified").length })}</p>
|
||||
<p className="mt-1 text-muted">{t("client.upd.modifiedText")}</p>
|
||||
<label className="mt-3 flex cursor-pointer items-center gap-2">
|
||||
<input type="checkbox" checked={keepMine} onChange={(e) => setKeepMine(e.target.checked)} className="h-4 w-4 accent-[#c9a24a]" />
|
||||
<span>{t("client.upd.keep")}</span>
|
||||
</label>
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Button size="sm" variant="primary" onClick={() => void syncClient(server.id, keepMine)}>{t("client.upd.start")}</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => dismissClientJob(server.id)}>{t("client.upd.later")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{job.phase === "done" && <p className="mt-3 text-sm text-ok" role="status">{t("client.upd.done")}</p>}
|
||||
{job.phase === "current" && <p className="mt-3 text-sm text-ok" role="status">{t("client.upd.upToDate", { v: job.plan?.version ?? "" })}</p>}
|
||||
{job.phase === "stopped" && (
|
||||
<p className="mt-3 flex items-center gap-3 text-sm text-muted" role="status">
|
||||
{t("client.dl.cancelled")}
|
||||
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.resume")}</Button>
|
||||
</p>
|
||||
)}
|
||||
{job.phase === "failed" && job.error && (
|
||||
<p className="mt-3 flex flex-wrap items-center gap-3 text-sm text-bad" role="alert">
|
||||
{job.error.human.code === "unknown" ? job.error.technical : human(job.error.human).message}
|
||||
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.retry")}</Button>
|
||||
</p>
|
||||
)}
|
||||
{upd.available && upd.preview && (
|
||||
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
|
||||
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
|
||||
@@ -585,6 +511,28 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{reborn_world && (
|
||||
<Card className="mt-4 p-7">
|
||||
<div className="mb-1 text-xs font-medium uppercase tracking-[0.14em] text-muted">{realms ? `${realms.reborn} · ${t("overview.server")}` : t("realm.rebornWorld")}</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>
|
||||
@@ -617,13 +565,11 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
{dialog && (
|
||||
<ClientDialog
|
||||
serverId={server.id}
|
||||
mode={dialog}
|
||||
onClose={() => setDialog(null)}
|
||||
onClose={() => setDialog(false)}
|
||||
onChanged={() => {
|
||||
void api.clientInfo(server.id).then(setClient).catch(() => setClient(null));
|
||||
void checkClient(server.id);
|
||||
}}
|
||||
onPlayAnyway={() => void play()}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 { asUiError, api } from "@/lib/api";
|
||||
import { realmRegistry, useRegistryStatus } from "@/lib/registry";
|
||||
import { asControlError, control, type ControlStatus } from "@/lib/control";
|
||||
|
||||
@@ -24,11 +24,24 @@ export function PublishCard({ serverId, serverName }: { serverId: string; server
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [existingOnly, setExistingOnly] = useState(false);
|
||||
const [portableEnabled, setPortableEnabled] = useState(true);
|
||||
const [route, setRoute] = useState("");
|
||||
const [accessSaved, setAccessSaved] = useState(false);
|
||||
const [ctl, setCtl] = useState<ControlStatus | null>(null);
|
||||
const link = ctl?.hosting.find((h) => h.local_id === localId)?.link;
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void api.allSettings(serverId).then((items) => {
|
||||
if (!active) return;
|
||||
const item = items.find((i) => i.key === "PortableSession.Enable");
|
||||
if (item) {
|
||||
setPortableEnabled(item.value === "1" || item.value.toLowerCase() === "true");
|
||||
}
|
||||
}).catch(() => {});
|
||||
return () => { active = false; };
|
||||
}, [serverId]);
|
||||
|
||||
useEffect(() => {
|
||||
const load = () => void control.status().then(setCtl).catch(() => {});
|
||||
load();
|
||||
@@ -39,7 +52,21 @@ export function PublishCard({ serverId, serverName }: { serverId: string; server
|
||||
|
||||
async function saveAccess() {
|
||||
setBusy(true); setError(null); setAccessSaved(false);
|
||||
try { await control.setAccess(localId, existingOnly, route.trim() === "" ? null : route.trim()); await refresh(); setAccessSaved(true); } catch (e) { setError(asControlError(e).message); } finally { setBusy(false); }
|
||||
try {
|
||||
await Promise.all([
|
||||
control.setAccess(localId, existingOnly, route.trim() === "" ? null : route.trim()),
|
||||
api.allSettingsSave(serverId, {
|
||||
"PortableSession.Enable": portableEnabled ? "1" : "0",
|
||||
...(portableEnabled ? { "CharacterDatabase.WorkerThreads": "1" } : {}),
|
||||
}),
|
||||
]);
|
||||
await refresh();
|
||||
setAccessSaved(true);
|
||||
} catch (e) {
|
||||
setError(asControlError(e).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -83,6 +110,7 @@ export function PublishCard({ serverId, serverName }: { serverId: string; server
|
||||
{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.state === "realm_stopped" && <p className="mt-2 text-xs text-warn">{t("registry.realmStoppedHint")}</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">
|
||||
@@ -93,6 +121,7 @@ export function PublishCard({ serverId, serverName }: { serverId: string; server
|
||||
{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={portableEnabled} 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 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" />
|
||||
|
||||
@@ -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>}
|
||||
|
||||
@@ -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,9 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Gauge, Globe, Settings, Swords } from "lucide-react";
|
||||
import { api, asUiError, REMOTE_CLIENT_ID } from "@/lib/api";
|
||||
import { checkClient, startClientPolling, useClientStatus } from "@/lib/clientUpdate";
|
||||
import { checkClient, useClientStatus } from "@/lib/clientUpdate";
|
||||
import { ClientCard } from "@/screens/ClientCard";
|
||||
import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog";
|
||||
import { ClientDialog } from "@/screens/ClientDialog";
|
||||
import { AboutCard } from "@/screens/AboutCard";
|
||||
import { PortablePage } from "@/screens/PortablePage";
|
||||
import { BrowsePage } from "@/screens/BrowsePage";
|
||||
@@ -25,7 +25,7 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [dialog, setDialog] = useState<ClientDialogMode | null>(null);
|
||||
const [dialog, setDialog] = useState(false);
|
||||
const { status } = useClientStatus(REMOTE_CLIENT_ID);
|
||||
function fail(e: unknown) {
|
||||
const err = asUiError(e);
|
||||
@@ -33,7 +33,6 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
|
||||
}
|
||||
useEffect(() => {
|
||||
void api.remoteConnection().then(p => { setHost(p.host); setSavedHost(p.host); }).catch(fail).finally(() => setLoading(false));
|
||||
return startClientPolling(REMOTE_CLIENT_ID);
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useEffect(() => { void checkClient(REMOTE_CLIENT_ID); }, [revision]);
|
||||
|
||||
@@ -50,8 +49,7 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
|
||||
try { await api.play(REMOTE_CLIENT_ID); } catch (e) { fail(e); } finally { setBusy(false); }
|
||||
}
|
||||
function play() {
|
||||
if (!status?.linked) setDialog("setup");
|
||||
else if (status.update_available) setDialog("update");
|
||||
if (!status?.linked) setDialog(true);
|
||||
else void launch();
|
||||
}
|
||||
return <div className="flex h-full">
|
||||
@@ -76,13 +74,12 @@ export function RemoteClient({ onHost }: { onHost: () => void }) {
|
||||
</form>
|
||||
<p className="mt-3 text-sm text-muted">{t("remote.accountHint")}</p>
|
||||
<Button variant="primary" className="mt-4" disabled={loading || busy || !savedHost || host.trim() !== savedHost || status === null} onClick={play}>{t("btn.play")}</Button>
|
||||
{status?.linked && status.update_available && <Button variant="secondary" className="mt-4 ml-3" disabled={loading || busy || !savedHost || host.trim() !== savedHost} onClick={() => void launch()}>{t("btn.playWithoutUpdate")}</Button>}
|
||||
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
|
||||
{error && <p className="mt-3 text-sm text-bad" role="alert">{error}</p>}
|
||||
</Card>
|
||||
<ClientCard key={revision} serverId={REMOTE_CLIENT_ID} remote />
|
||||
</>}
|
||||
</main>
|
||||
{dialog && <ClientDialog serverId={REMOTE_CLIENT_ID} mode={dialog} onClose={() => setDialog(null)} onChanged={() => setRevision(n => n + 1)} onPlayAnyway={() => void launch()} />}
|
||||
{dialog && <ClientDialog serverId={REMOTE_CLIENT_ID} onClose={() => setDialog(false)} onChanged={() => setRevision(n => n + 1)} />}
|
||||
</div>;
|
||||
}
|
||||
@@ -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; };
|
||||
|
||||
@@ -19,7 +19,7 @@ import { DashboardPage } from "@/screens/DashboardPage";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { startServerUpdatePolling, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { startClientPolling } from "@/lib/clientUpdate";
|
||||
import { checkClient } from "@/lib/clientUpdate";
|
||||
import type { UnsavedChangesGuard } from "@/lib/unsavedGuard";
|
||||
|
||||
type Page = "overview" | "bots" | "dashboard" | "server" | "modules" | "players" | "characters" | "friends" | "backups" | "console" | "report" | "settings";
|
||||
@@ -88,14 +88,10 @@ export function Shell(props: {
|
||||
if (hiddenPages.includes(page)) setPage("overview");
|
||||
}, [hiddenPages, page]);
|
||||
|
||||
// Look for a server and a game client update when the app starts and then every five minutes.
|
||||
// Look for a server update when the app starts and then every five minutes; note whether a game client is linked.
|
||||
useEffect(() => {
|
||||
const stopServer = startServerUpdatePolling(props.activeId);
|
||||
const stopClient = startClientPolling(props.activeId);
|
||||
return () => {
|
||||
stopServer();
|
||||
stopClient();
|
||||
};
|
||||
void checkClient(props.activeId);
|
||||
return startServerUpdatePolling(props.activeId);
|
||||
}, [props.activeId]);
|
||||
|
||||
return (
|
||||
|
||||
Reference in new issue
Block a user