Compare commits

...
Author SHA1 Message Date
ДмитрийandClaude Sonnet 5.5 1974ff54e3 Prepare Manager 0.9.16 with reviewed notes in six languages
Version 0.9.16 (Manager only; no server release). Reviewed notes: the client download now comes from
the community launcher, HD graphics hint and translated Custom Races patch card, companions startup
limit creates the missing ones, weekly world restart, server log auto-cleanup. Translations in ru,
de, fr, es and zh for these five notes and for the 0.9.15 note, which the history test requires.
Bundled server history stays at 0.261115.110; notes of later server releases show in English until
a Manager refreshes and translates them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:57:49 +05:00
Corfirean de3af82e5d Merge pull request #231 from Corfirean/feat/weekly-restart-log-cleanup-on-master
Settings: weekly world restart and server log auto-cleanup
2026-11-20 21:43:38 +05:00
Corfirean 802bde220c Merge pull request #230 from Corfirean/feat/startup-fleet-top-up
Companions: the startup limit creates the missing ones
2026-11-20 21:43:30 +05:00
Corfirean dfe7ac656b Merge pull request #229 from Corfirean/fix/client-download-launcher-on-master
Remove the dead built-in client download; point players to the launcher
2026-11-20 21:43:21 +05:00
Corfirean cee5139879 Merge pull request #232 from Corfirean/fix/changelog-fragment-length
Changelog: shorten the Custom Races 2.0.2 fragment to the 300-character limit
2026-11-20 21:43:12 +05:00
ДмитрийandClaude Sonnet 5.5 1ea2c8318b docs(changelog): shorten the Custom Races 2.0.2 fragment to the 300-character limit
Its body was 375 characters, so `changelog.py check` over the whole directory failed. The title is
unchanged, so the published 0.9.15 note is the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:43:02 +05:00
ДмитрийandClaude Sonnet 5.5 2b7dbf8e1e feat(settings): translations and changelog for weekly restart and log auto-cleanup
The weekly restart schedule and the server log auto-cleanup (previous commit) had strings only in
en and ru and no changelog fragments. Adds de/es/fr/zh for the weekday names, the weekly toggle
and the log settings, and one fragment per change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:37:01 +05:00
Дмитрий 4ff190f6d1 feat(settings): add weekly restart schedule and server log auto-cleanup 2026-11-20 21:34:23 +05:00
ДмитрийandClaude Sonnet 5.5 bff5248591 feat(companions): the startup limit is a fleet size, so missing companions are created
CoaBots.AutoLogin.MaxCount only makes the server log in companions that already exist: with 50
companions and a limit of 300, 50 came online. The Manager now creates the difference.

- coa-core: fleet_shortfall / queue_fleet_top_up queue one durable pending job per realm for
  limit - existing (at most 2000 per job, the most one server command takes). Nothing is queued
  when the fleet is complete or an unfinished job exists for the realm.
- start_server: after the world is up, each realm whose auto-login is on is topped up before its
  pending job runs (shared reconcile_realm_companions helper). If the existing count cannot be
  read, nothing is created.
- Saving the startup settings of a running server tops up right away (new top_up_startup_fleet
  command); a shortfall above 200 asks for confirmation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:31:32 +05:00
ДмитрийandClaude Sonnet 5.5 f5205662a9 feat(client): say where HD graphics is switched, translate the Custom Races patch card
The community launcher owns the Standard/HD choice (Settings -> "HD graphics"; its setup
also offers it), so the Manager cannot toggle it. The client setup dialog now points players
there. The Custom Races client patch status badges, hints and Install/Repair/Uninstall
buttons were English/Russian ternaries; they are now i18n keys in all six locales.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:08:55 +05:00
ДмитрийandClaude Sonnet 5.5 169d8b8977 feat(client): drop built-in client download, point players to the community launcher
The community moved the game client behind its official launcher (account
sign-in, signed manifest, its own CDN), so the public manifest now answers 404
and the Manager must not pose as the launcher. Remove the client download and
update path (clientdl, plan/sync/download/cancel commands, update job and
progress UI, version tracking) and reduce "Set up the game client" to: open
coa-development.org for the launcher, or pick a folder that already has the
game. Linking a folder, realmlist switch, companion addon and the custom-race
patch are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 21:08:50 +05:00
ДмитрийandClaude Sonnet 5.5 41977442e9 Merge master into integrate/manager-0.9.15
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 13:12:54 +05:00
github-actions[bot] c75785d13e Update published Manager changelog 2026-11-19 07:59:40 +00:00
ДмитрийandClaude Sonnet 5.5 2b9021ce07 Manager 0.9.15: Custom Races client 2.0.2
Installs the 2.0.2 client set (retail body cache, subclass and HD patches, current
CoACustomRace.exe, newer subclass addon without the Skinshifter collection),
with the 2.0 inventory kept for installs that still carry that manifest.
Archive sizes and hashes verified against the real release archives.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-18 21:38:11 +05:00
Corfirean b9e663079e Merge integrate/manager-0.9.14: Manager 0.9.14 (Rust launcher, fast races switch, ports, realm names, addons, companions on Wildcard/Reborn) 2026-11-16 18:14:10 +05:00
github-actions[bot] d7693b0878 Update published Manager changelog 2026-11-16 10:21:01 +00:00
ДмитрийandClaude Opus 5.5 1f64da3ae0 Prepare Manager 0.9.14 with reviewed notes in six languages
Version 0.9.14; reviewed Manager (12) and server (6) records with translations in all
five languages; server components from the lock of build run 43758471036; bundled server
history through 0.261115.110 from build main 45c013be9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:00:33 +05:00
ДмитрийandClaude Opus 5.5 1aec8e5394 Release note title the collector keeps (no technical word)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 02:18:18 +05:00
Дмитрий 326a4fe3d3 Merge feat/companions-realms: companion bots on Wildcard and Warcraft Reborn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	crates/coa-core/src/ra.rs
2026-11-16 00:52:15 +05:00
ДмитрийandClaude Opus 5.5 f9839ba369 Custom races off: count the characters kept out, delete their companion bots
A client without the races patch crashes on a unit of race 12+, so the server now keeps
those characters out while custom races are off. The Custom Races card shows how many
player characters and bots that are (active realm, read only while the database runs) and
offers botcmd purgecustomraces for the companion bots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:36:18 +05:00
ДмитрийandClaude Opus 5.5 e951eb134b Companions open on Wildcard and Reborn when the server build plays them
The module list blocked Companions on every realm but Conquest of Azeroth, so the
multi-realm bot work could not be switched on. It is allowed (as experimental) when the
world server or its bots plugin carries the standard-class bot profiles of the multi-realm
bots build; SQUID and Dungeon Clear stay CoA-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:27:54 +05:00
ДмитрийandClaude Opus 5.5 6cbf007d72 Companions on Wildcard/Reborn: pending bot jobs survive crashes, validated spawn requests
The uncommitted RC hardening of the multirealm Manager branch: a per-realm pending job
state machine reconciled against the database (no duplicate bots after a crash or an RA
timeout), cancelled by Stop spawning / Delete all bots, legacy file migrated; spawn
requests and build ids validated; tests JOB-01..JOB-14.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:20:50 +05:00
Дмитрий 07e9bc497d feat(manager): dynamic wildcard archetypes, realm-isolated pending jobs, and hardened bot deployment 2026-11-16 00:17:08 +05:00
Дмитрий e4edb7cbdd feat(manager): multi-realm character database routing, RA dispatch & extended bot manager UI 2026-11-16 00:16:51 +05:00
Дмитрий ca2514c790 feat(manager): expand multi-realm bot fleet controls, DB routing, and compatibility guards 2026-11-16 00:16:15 +05:00
Дмитрий 69c9938aba feat(manager): enable multi-realm playerbots support across CoA, Wildcard, and Reborn 2026-11-16 00:16:15 +05:00
ДмитрийandClaude Opus 5.5 2fd42f2acd Custom races hold their V2 parts; the addon list shows every addon
- Subclasses/Hero Races and the /dev menu are parts of Custom Races (catalog part_of,
  hidden from the grid): their switch and settings sit inside the Custom Races settings.
- The companion bots addon (CoABotUI) moves from the client facts into the addon list,
  with install/update from the server package; the /dev menu addon of the V2 patch is
  listed as installed by the patch, without its own buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 00:07:54 +05:00
ДмитрийandClaude Opus 5.5 05630ec9eb Addon catalog in the game client card
addons/catalog.json pins SquidBots Lite, DragonUI (+Options), IncahootsCoA and CoACombat
to a commit and lists every file with its git blob SHA-1 and size. Install downloads
GitHub's archive of that commit, verifies each file (archives are not byte-stable, their
contents are), stages next to AddOns and moves the folders in; a foreign folder of the
same name goes to AddOns/.coa-addons-backup. .coa-addons.json records what the Manager
installed; update and remove touch only that. CoA_DevMenu ships with Custom Races V2, so
the separate dev menu addon is not in the catalog. Checked against the real GitHub
archives of the three small addons (ignored test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:58:29 +05:00
ДмитрийandClaude Opus 5.5 d64fdb51be Client: clear the game cache on Play, remember the friend's server login
- clear_game_cache removes Cache/WDB/<locale>/*.wdb before every Play (own server and
  friend's), on by default, switch in the client card; nothing else in Cache or Data.
- The connection profile keeps the listed realm it was joined through; Play fills that
  realm's saved account into GlueConfig.json every time. A host typed by hand drops it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:51:40 +05:00
ДмитрийandClaude Opus 5.5 260d10b729 Scheduled daily restart of the world (#202)
Settings/restart-schedule.json (Settings, Startup) holds a local time and a countdown.
The Rust world supervisor asks the world for 'server restart <seconds>' once that time has
passed (by at most 15 minutes, for a world that ran before it), and starts the world
again when it exits with RESTART_EXIT_CODE; the database and auth keep running. While it
is under way (.state/scheduled-restart) the status says so and the Manager does not take
the down world for a crash. Extra worlds follow their server's schedule. Repacks with the
Python supervisor do not run the schedule; the card says the server needs an update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:26:14 +05:00
ДмитрийandClaude Opus 5.5 20657df203 MySQL options of the owner kept across starts (#103)
Settings, Service edits Settings/mysql-custom.ini. Every start adds its name = value lines
(outside a section or in [mysqld]) to the rendered my.ini, after the defaults so they
win; the port, addresses, data and log paths, sockets and !include stay managed. Nothing
changes for a server without the file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:21:24 +05:00
ДмитрийandClaude Opus 5.5 f08ae1c76b Modules: switches for the Custom Races V2 subclasses and the /dev menu
mod-subclass (Subclass.Enable, the Thin Twins and Two-Headed Ogre races, two players per
character, levels) and mod-ilusixn-devmenu (DevMenu.Enable, who may use it) were shipped
with V2 but had no place in the Manager. They are catalog modules now, with translated
controls for their main settings; the rest stays under the advanced settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:17:04 +05:00
ДмитрийandClaude Opus 5.5 4fc133c35e Race restriction survives a catalog that only adds races
The worldserver ignores DisabledRaceIds saved against another ChrRaces catalog and with
it CoACustomRaces.Enable, so every server that had a restriction from 1.9.2 lost custom
races after the V2 update. Before a start the Manager binds the restriction to the new
catalog when every disabled race keeps its RaceID and name, judged by the server's own
snapshot (written by every save) or the table of every catalog a build has shipped
(race_catalogs.json, generated from the core history). Renamed races (1.9.1 reused 32/33)
and unknown catalogs still wait for the owner's review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:14:59 +05:00
ДмитрийandClaude Opus 5.5 de38e60444 Merge fix/races-fast-toggle: custom races switch in seconds
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:10:50 +05:00
ДмитрийandClaude Opus 5.5 3c26004e04 Custom races: switch in seconds (append-only journal, entry points only, hash cache)
V2 has 7,220 files. Switching rewrote the whole transaction journal with fsync after
every file (quadratic: minutes on fast disks, far longer with antivirus) and renamed
every file. Now:
- the journal is append-only JSON lines; recovery replays it, ignores a torn last
  line and still reads the old journal.json of 0.9.13;
- only what the stock client loads is hidden (Data/*.MPQ, root dll/exe/bat, addons,
  any file that replaced the player's own); Data/Retail, VulkanShaders and the
  Esteria data stay in place, and a client disabled by 0.9.13 is recognised;
- payload hashes are remembered for the run, keyed by name, size and times.
Real V2 archives, release build: disable 1.9 s, enable 2.2 s, 224 of 7,220 files moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:10:43 +05:00
ДмитрийandClaude Opus 5.5 d1534ebc92 Realm names chosen in the Manager (#61, #209)
Settings, Startup lists every realm of the server with its name. The choice is kept in
Settings/realm-names.json of the main folder; the launcher, the realm-list setup and the
client's Config.wtf use it, and a running database gets it at once. Names are 1-32
characters without quotation marks or control characters, written as escaped SQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:08:48 +05:00
ДмитрийandClaude Opus 5.5 20d4c3351e Ports: name Windows reservations at once, move the database to a free port
A reserved or taken database port no longer fails the start after 30 seconds: the
launcher recognises Windows excluded ranges (netsh), moves MySQL to a free port and
records it in Settings/repack.json. Only the server's own services use that port.
The database connection of with_database is rebuilt after the start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:59:20 +05:00
ДмитрийandClaude Opus 5.5 8a313b83b8 Cargo.lock: coa-launcher follows the workspace version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:55:40 +05:00
ДмитрийandClaude Opus 5.5 7eea72c415 Merge feat/rust-launcher: the Manager starts and stops servers through the Rust launcher
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:54:21 +05:00
Corfirean e8ffa6efe3 Merge feat/custom-races-v2: Manager 0.9.13 with Custom Races V2 2026-11-15 08:14:40 +05:00
github-actions[bot] baeecd2ddf Update published Manager changelog 2026-11-15 02:08:39 +00:00
ДмитрийandClaude Opus 5.5 d352731280 Prepare Manager 0.9.13 with reviewed notes in six languages
Manager 0.9.13 carries the Custom Races V2 client. Its reviewed note and the 213 notes of the upcoming
server record (Custom Races V2: subclasses, Two-Players, the new races; collected with the pipeline's own
rules from the frozen sources of candidate run 43641984449) have Russian, German, French, Spanish and
Simplified Chinese translations. Bundled server history refreshed through 0.261114.106 from
coa-server-build 3308e3a.

Checks: release-history tests 5/5, check-i18n, npm run build, cargo check --locked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:27:37 +05:00
ДмитрийandClaude Opus 5.5 a0545286ee Install the Custom Races V2 client
The client update now takes ilusixn/CustomRacesCoa coa-custom-2.0: nine client archives plus the server
archive's client addons (subclass interface, dev menu, teleports, spell activation overlay), 76 race
archives and 7220 verified files in all, among them CoACustomRace.exe and its Vulkan renderer.

- The game starts CoACustomRace.exe when it is there; Ascension.exe is left alone, and a disabled V2
  falls back to it.
- Updating from 1.9.2 retires its patched Ascension.exe and puts the player's own back (1.9.2 replaced
  it; V2 does not ship one). Earlier installs keep their own hash lists, 1.9.2's included.
- Four V2 archives are byte-identical to 1.9.2's: a verified 1.9.2 copy in the cache or in Downloads
  is used instead of downloading it again.

Verified: unit tests (800 passed); against the real archives, every bundled hash, a full install,
disable, enable and uninstall in a disposable client, and an update of a client that Manager 0.9.12
had put 1.9.2 on (its own Ascension.exe comes back, and again after uninstalling).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:59:43 +05:00
ДмитрийandClaude Opus 5.5 6f8ed793a7 Merge integrate/release-0.9.12 (release 2026-11-14)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:56:41 +05:00
github-actions[bot] b3c88ce2a6 Update published Manager changelog 2026-11-14 04:41:00 +00:00
CorfireanandClaude Opus 5.5 d71c5635e3 Translate the auction house bot note of the upcoming server release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:15:27 +05:00
CorfireanandClaude Opus 5.5 755761d0de Prepare Manager 0.9.12 with reviewed notes in six languages
Bundled server history refreshed through 0.261108.95 from coa-server-build ca04f96.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:05:14 +05:00
Corfirean 550e475962 Merge remote-tracking branch 'origin/feat/bot-scaling-settings' into integrate/release-0.9.12 2026-11-13 23:54:41 +05:00
ДмитрийandClaude Opus 5.5 2e6fcceb05 CI: drop the launcher bridge test (the bridge was removed)
tools/test_launcher_bridge.py tested crates/coa-core/src/launcher_bridge.py,
which the Rust launcher replaced; check.yml and release.yml still ran it, so
the release build failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:48:17 +05:00
ДмитрийandClaude Opus 5.5 abcc816581 Stop: ask the world again when a shutdown request is lost
A console shutdown request is sometimes lost, and the world then keeps
running until the stop times out. While the world still runs and its
console still answers after 15 s, the launcher asks again (twice at most);
asking twice is harmless. Verified on a disposable repack with the first
World::ShutdownServ call suppressed in a debugger: the second request
stopped the world.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:07:54 +05:00
ДмитрийandClaude Opus 5.5 8353b791fb The Manager no longer edits Scripts/manage.py
Repacks ship no .bat files, and the Manager starts servers with
coa-core::launcher, so the realm-profile patch it wrote into manage.py
served no one. It is no longer applied (realm creation, realm switching and
start).

Recognising the edits older Managers made (realm patch, bridge import fix)
moves into legacy_launcher, so updates and file checks still treat such a
file as unmodified. Nothing there writes a file.

manage.py itself stays complete in the repack: Managers up to 0.9.10 run it
through their bridge and patch its text, so it cannot become a thin wrapper
until those Managers are no longer supported.

Verified: coa-core unit tests; examples/manager_launcher_e2e on a disposable
repack (manage.py unchanged after a start with a realm profile).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:07:41 +05:00
ДмитрийandClaude Opus 5.5 b81227b0ea Bug-report relay in Rust (coa-launcher relay-worker)
launcher::relay does what BugReport/relay.py and manage.py relay-worker do,
with the same spool: the <key>.status files the world reads, the journal
relay.sqlite3 (deliveries, settings), relay.lock (byte 0) and the
relay-ready record. Service answers map to the same states and retry times;
a post interrupted mid-flight stays uncertain and is never resent.

When coa-launcher.exe supervises a world it runs the relay itself; the
Python supervisor still runs relay.py.

Verified:
- examples/relay_equivalence: the same reports and scripted service answers
  through relay.py and the Rust relay give identical statuses, journal rows
  (including retry times) and posts, and each continues the other's journal.
- examples/manager_launcher_e2e on a disposable repack: supervisor and relay
  are coa-launcher.exe, start/stop interoperates with manage.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:00:40 +05:00
ДмитрийandClaude Opus 5.5 a9fb982ab0 Console shutdown request reads the reply before closing
send_without_answer closed the socket right after writing "server shutdown".
With the reply still unread, Windows resets the connection, and the world
can drop the command: a world supervised by coa-launcher.exe ignored the
shutdown and the stop timed out after 90 seconds. The reply is now read up
to the next prompt, the end of the connection or 10 seconds.

The E2E also checks which supervisor runs the world and that manage.py
stops a world the Manager started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 09:38:59 +05:00
ДмитрийandClaude Opus 5.5 a822bfc99b Manager starts and stops servers through the Rust launcher
driver::run now calls coa-core::launcher::ops::run in-process instead of
running Scripts/manage.py through launcher_bridge.py. Failures carry a typed
code (Error::Service) instead of being guessed from stderr text.

Moved into the launcher: realm profiles (realm id, name and databases from
Settings/realm-profile.json), extra worlds sharing the main database,
the shared world startup deadline and console readiness check, the owned-world
check on shutdown, force-stop-all, and an environment block without
AC_REALM_SERVER_PORT for update validation.

The world supervisor is Scripts/coa-launcher.exe when the repack ships it,
otherwise manage.py watch-world. Extra worlds get an unmodified manage.py.
The realm patch of manage.py stays for the repack's own .bat files.

Verified with examples/manager_launcher_e2e on a disposable repack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 08:45:08 +05:00
ДмитрийandClaude Opus 5.5 1211de5a77 launcher (Rust): services inherit only their log and NUL; MySQL errors carry the server's text
std::process::Command lets a Windows child inherit every inheritable handle of the parent: a
MySQL started by the launcher kept the caller's files and pipes open (found by the SQUID test,
whose log stayed locked). Services now start through CreateProcessW with
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = [log, NUL], as Python's subprocess does. The MySQL client's
outputs are read while it runs (a full pipe stopped it) and its last error line is reported.

E2E on a disposable repack: launcher_e2e PASS again; squid_equivalence PASS: Rust and
squid_playerbots.py leave identical journals, acore_playerbots tables (row counts) and
playerbots.conf (4106 lines), and a second run of either changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:48:04 +05:00
ДмитрийandClaude Opus 5.5 ee36692db7 launcher (Rust): services, world supervisor, SQUID provisioning, coa-launcher.exe
- services: exclusive-bind port check, readiness by listener row or the server side of a
  loopback connection, MySQL client, start MySQL/auth, stop-all (world through its console,
  database last), status.
- world: start-world through a supervisor process (coa-launcher watch-world) that keeps the
  bug-report relay (still BugReport/relay.py via the repack's Python) alive; detailed logging.
- squid: squid_playerbots.py in Rust with the same journals (coa_squid_migrations,
  coa_squid_pending, coa_bots_installed).
- coa-launcher.exe: the manage.py commands and error texts (the Manager reads them).
- Services no longer inherit the launcher's stdin/stdout/stderr: a server holding the
  output pipe kept whoever read the launcher's output waiting.

E2E (examples/launcher_e2e, disposable stable repack on free ports): coa-launcher start-all ->
manage.py sees and stops it; manage.py start-all -> coa-launcher sees and stops it; a second
Rust-only cycle leaves nothing running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 07:29:55 +05:00
ДмитрийandClaude Opus 5.5 ee43522019 launcher (Rust): settings, state records, control lock, prepare
First part of moving Scripts/manage.py into coa-core (plan §17, PY-1). Same formats on disk as
manage.py so both can run on one server: .state records, the byte-0 control lock msvcrt.locking
takes, configuration.json. prepare renders byte-for-byte what manage.py renders (checked against
the real script, COA_MANAGE_PY). State files are flushed to disk before they replace the old ones,
and a damaged record counts as no process instead of failing every later start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 06:58:16 +05:00
github-actions[bot] b4dc30b84a Update published Manager changelog 2026-11-08 10:21:07 +00:00
Дмитрий 73a6cca753 Integrate the qualified November release sources [skip ci] 2026-11-08 15:09:20 +05:00
Corfirean 705bee7d56 Merge verified Custom Races download recovery [skip ci]
Recover interrupted Custom Races patch downloads
2026-11-08 01:44:09 +05:00
Corfirean 5aa9b32283 Merge release cold-cache preparation fix [skip ci]
release: build the frontend before the tests
2026-11-08 01:44:05 +05:00
Дмитрий 711f378ae8 Bind translated release notes to the exact candidate sources [skip ci] 2026-11-08 01:23:56 +05:00
Corfirean c29d56e2b3 Register local installer preparation workflow [skip ci] 2026-11-08 01:21:16 +05:00
Дмитрий d63e85bb18 Prepare Manager 0.9.10 with reviewed notes and signing of local installers [skip ci] 2026-11-08 01:20:32 +05:00
Дмитрий c513649beb Merge remote-tracking branch 'origin/fix/recover-client-patch-downloads' into release/20261108-manager 2026-11-08 01:09:43 +05:00
ДмитрийandClaude Sonnet 5.5 d2e6fef188 feat(bots): settings for bot strength scaling in dungeons and raids
Adds the CoaBots.Scaling.* keys (Enable, Dungeons, Raids, Battlegrounds,
World, DamageDone, HealingDone, DamageTaken, TankThreat, BossTuning) to the
bots schema under Combat, with defaults that change nothing (all multipliers 1,
boss tuning off), translations in five languages and a changelog fragment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:22:47 +05:00
Дмитрий 1a1976d9ad Recover interrupted Custom Races patch downloads 2026-10-31 07:55:15 +05:00
121 changed files with 35941 additions and 3435 deletions

No files matched your search

-1
View File
@@ -26,5 +26,4 @@ jobs:
- run: node tools/check-i18n.mjs - run: node tools/check-i18n.mjs
- run: npm run build - run: npm run build
- run: node --experimental-strip-types --test tools/*.test.mjs - run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- run: cargo test --workspace --locked - run: cargo test --workspace --locked
-1
View File
@@ -74,7 +74,6 @@ jobs:
- name: Tests - name: Tests
run: cargo test --workspace --locked -- --test-threads=1 run: cargo test --workspace --locked -- --test-threads=1
- run: node --experimental-strip-types --test tools/*.test.mjs - run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- name: Build and sign (publish only when requested) - name: Build and sign (publish only when requested)
id: tauri id: tauri
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@v0
@@ -0,0 +1,72 @@
name: sign-local-installer
on:
push:
branches: [release/20261108-manager]
workflow_dispatch:
inputs:
build_run_id:
description: Successful manager-local run in coa-server-build
required: true
permissions:
contents: read
actions: read
jobs:
sign:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Verify local build provenance
env:
GH_TOKEN: ${{ github.token }}
BUILD_RUN: ${{ inputs.build_run_id }}
run: |
python3 - <<'PY'
import json, os, subprocess
run = os.environ['BUILD_RUN']
if not run.isdigit():
raise RuntimeError('Invalid build run')
data = json.loads(subprocess.check_output(['gh', 'api', f'repos/Corfirean/coa-server-build/actions/runs/{run}']))
if data['conclusion'] != 'success' or data['path'] != '.github/workflows/manager-local.yml':
raise RuntimeError('Not a successful local Manager build')
subprocess.run(['gh', 'run', 'download', run, '-R', 'Corfirean/coa-server-build', '-n', 'unsigned-manager-windows', '-D', '_prepared-manager'], check=True)
from pathlib import Path
import hashlib
root = Path('_prepared-manager')
meta = json.loads((root / 'prepared-source.json').read_text())
version = json.loads(Path('package.json').read_text())['version']
name = meta['installer']
if Path(name).name != name or meta['source'] != os.environ['GITHUB_SHA'] or meta['version'] != version or str(meta['run']) != run:
raise RuntimeError('Installer identity differs')
if hashlib.sha256((root / name).read_bytes()).hexdigest() != meta['sha256']:
raise RuntimeError('Installer hash differs')
PY
- run: npm ci
- name: Sign exact locally compiled bytes
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
node --input-type=module <<'JS'
import { readFileSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
const root = '_prepared-manager/';
const meta = JSON.parse(readFileSync(root + 'prepared-source.json'));
execFileSync('node_modules/.bin/tauri', ['signer', 'sign', '--app-version', meta.version, root + meta.installer], {stdio: 'inherit'});
if (createHash('sha256').update(readFileSync(root + meta.installer)).digest('hex') !== meta.sha256) throw new Error('Signed bytes changed');
const signature = readFileSync(root + meta.installer + '.sig', 'utf8').trim();
const url = `https://github.com/Corfirean/coa-server-manager/releases/download/v${meta.version}/${encodeURIComponent(meta.installer)}`;
writeFileSync(root + 'latest.json', JSON.stringify({version: meta.version, notes: 'See the release notes.', pub_date: new Date().toISOString(), platforms: {'windows-x86_64': {signature, url}}}, null, 2) + '\n');
meta.signingRun = process.env.GITHUB_RUN_ID;
writeFileSync(root + 'prepared-source.json', JSON.stringify(meta, null, 2) + '\n');
JS
- uses: actions/upload-artifact@v4
with:
name: prepared-manager-windows
path: _prepared-manager/*
retention-days: 14
if-no-files-found: error
+41
View File
@@ -8,6 +8,47 @@ Published releases and previews. Pre-release entries do not change the stable up
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first. Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.9.15 — 2026-11-19
- The Custom Races client update brings version 2.0.2.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.15) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.14...v0.9.15)
## 0.9.14 — 2026-11-16
- Install community addons from the Manager.
- Old item and creature data is cleared before every Play.
- Turning the custom races client patch on or off takes seconds again.
- The database moves to a free port when Windows reserves or another program takes 3307.
- Your own MySQL settings survive restarts and updates.
- Disabled custom races stay disabled after a server update that adds races.
- Rename your realms in the Manager.
- The account for a friend's server is in the login box at every Play.
- Restart the world every day at a chosen time.
- Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu.
- Companion bots on Wildcard and Warcraft Reborn.
- The Custom Races card tells which characters stay out while races are off.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.14) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.13...v0.9.14)
## 0.9.13 — 2026-11-15
- The custom races client is updated to Custom Races V2.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13)
## 0.9.12 — 2026-11-14
- Settings for how much help bots get in dungeons and raids.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12)
## 0.9.10 — 2026-11-08
- Custom Races patch installation recovers from interrupted downloads.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10)
## 0.9.9 — 2026-11-04 ## 0.9.9 — 2026-11-04
- Update and recovery checks use the temporary login port even with a Windows override. - Update and recovery checks use the temporary login port even with a Windows override.
Generated
+14 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-core" name = "coa-core"
version = "0.9.9" version = "0.9.16"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"chrono", "chrono",
@@ -606,6 +606,7 @@ dependencies = [
"serde_json", "serde_json",
"sha1", "sha1",
"sha2", "sha2",
"socket2",
"tar", "tar",
"tempfile", "tempfile",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -618,6 +619,15 @@ dependencies = [
"zstd", "zstd",
] ]
[[package]]
name = "coa-launcher"
version = "0.9.16"
dependencies = [
"coa-core",
"serde_json",
"windows-sys 0.60.2",
]
[[package]] [[package]]
name = "coa-registry-proto" name = "coa-registry-proto"
version = "0.1.0" version = "0.1.0"
@@ -634,7 +644,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-release" name = "coa-release"
version = "0.9.9" version = "0.9.16"
dependencies = [ dependencies = [
"chrono", "chrono",
"coa-core", "coa-core",
@@ -643,7 +653,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-server-manager" name = "coa-server-manager"
version = "0.9.9" version = "0.9.16"
dependencies = [ dependencies = [
"coa-control-proto", "coa-control-proto",
"coa-core", "coa-core",
@@ -658,6 +668,7 @@ dependencies = [
"tauri-plugin-single-instance", "tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"tracing", "tracing",
"uuid",
] ]
[[package]] [[package]]
+2 -2
View File
@@ -1,10 +1,10 @@
[workspace] [workspace]
resolver = "2" resolver = "2"
members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"] members = ["crates/coa-core", "crates/coa-launcher", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"] exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package] [workspace.package]
version = "0.9.9" version = "0.9.16"
edition = "2021" edition = "2021"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
+7247
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Custom Races patch installation recovers from interrupted downloads
---
Unfinished downloads resume automatically. Invalid archives in Downloads are skipped without changing them, and damaged cached archives are downloaded again.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Settings for how much help bots get in dungeons and raids
---
Bot damage, healing, damage taken and tank threat can now be tuned under Bots, Combat. Everything defaults to 1 (no change); a switch turns the extra help for four hard bosses on.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: players
title: Install community addons from the Manager
---
The game client card lists SquidBots Lite, DragonUI, IncahootsCoA and CoACombat. Each comes from its author's GitHub at a pinned version, every file is checked before it goes into Interface/AddOns, and the Manager updates or removes only what it installed.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: players
title: Old item and creature data is cleared before every Play
---
After a server update the game showed old names and stats from its own cache (Cache/WDB). Play now clears that cache first; it fills again within seconds. A switch next to the client graphics settings turns it off.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: players
title: Turning the custom races client patch on or off takes seconds again
---
V2 has over 7,000 files and switching it could run for many minutes. Now only the files the game itself loads are hidden, and the rest stays in place. A switch that was cut short is undone safely.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The custom races client is updated to Custom Races V2
---
The client update installs V2 and starts its own CoACustomRace.exe; Ascension.exe is left as it was. Four archives are the same as in 1.9.2, so a game folder that already had 1.9.2 downloads only the rest.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: The database moves to a free port when Windows reserves or another program takes 3307
---
Hyper-V, WSL and Docker can reserve a range that includes the database port; the start then waited 30 seconds and failed. The database now picks a free port and records it, and a reserved game port is named as such at once.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Your own MySQL settings survive restarts and updates
---
Settings, Service has a MySQL settings box. Its options are added to my.ini at every start of the database; before, my.ini was rewritten and hand edits were lost. Port, addresses and data paths stay managed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Disabled custom races stay disabled after a server update that adds races
---
A race list saved before Custom Races V2 no longer matched V2's race catalog, and the server then ignored it and turned custom races off. Before a start the Manager now keeps the list when every disabled race kept its ID and name.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Rename your realms in the Manager
---
Settings, Startup has a name for every realm. A running server shows it at once, the game client picks it on the next Play, and it stays after restarts and updates. Before, the launcher wrote the default name back at every start.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: players
title: The account for a friend's server is in the login box at every Play
---
The account the Manager made on a listed server was filled in only when joining. Play now fills it in every time, also after another server's account was used.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Restart the world every day at a chosen time
---
Settings, Startup, Scheduled restart: at that local time the world restarts with an in-game countdown and comes back by itself; the database keeps running. It works without the Manager open and needs a server with the new launcher.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu
---
The Custom Races settings now hold Subclasses and Hero Races (subclasses, the Thin Twins, the Two-Headed Ogre, two players per character) and the GM /dev menu, each with its own switch.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Companion bots on Wildcard and Warcraft Reborn
---
With a server build that supports it, Companions can be switched on for Wildcard and Warcraft Reborn: bots get whole Wildcard archetypes or Reborn abilities by level, and bot creation survives a crash without duplicates.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: The Custom Races card tells which characters stay out while races are off
---
With custom races off, the card shows how many player characters and bots of custom races cannot enter the world, and offers to delete the companion bots of those races.
@@ -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 client download moved behind the community launcher's sign-in, so the Manager's built-in download and update are removed. Get the launcher at coa-development.org, then choose your game folder in the Manager.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The Custom Races client update brings version 2.0.2
---
Updating the Custom Races client installs 2.0.2, including the retail body models, subclass and HD patches and the Two-Players bar. About 4.4 GB of new files are fetched. Update the Manager before the server.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: Client setup says where to switch HD graphics; Custom Races patch card is translated
---
HD or standard graphics is a launcher setting; the client setup dialog now says so. The Custom Races client patch status and buttons are now translated into every language the Manager offers.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Clean server logs by hand or automatically when they grow too big
---
Server logging settings show how much the logs take and clean them with one button. Optionally the Manager cleans them above a size you choose; logs the running server uses are kept.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The startup limit for companions now creates the ones that are missing
---
With 50 companions and a startup limit of 300, the Manager now creates the missing 250 instead of logging in only 50. Companions that exist are never created again. Up to 2000 are created at a time.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Restart the world every week on a chosen day and time
---
Next to the daily restart, pick a weekday, a time and the in-game countdown in the scheduled restart settings. Existing daily schedules keep working.
+83 -1
View File
@@ -172,10 +172,26 @@
"Corfirean/coa-server-manager:20261030-window-lifecycle.md", "Corfirean/coa-server-manager:20261030-window-lifecycle.md",
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md", "Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md",
"Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md", "Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md",
"Corfirean/coa-server-manager:20261031-recover-client-patch-downloads.md",
"Corfirean/coa-server-manager:20261031-server-logging-controls.md", "Corfirean/coa-server-manager:20261031-server-logging-controls.md",
"Corfirean/coa-server-manager:20261031-validation-bot-population.md", "Corfirean/coa-server-manager:20261031-validation-bot-population.md",
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md", "Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
"Corfirean/coa-server-manager:20261103-isolated-login-port.md" "Corfirean/coa-server-manager:20261103-isolated-login-port.md",
"Corfirean/coa-server-manager:20261107-bot-strength-scaling-settings.md",
"Corfirean/coa-server-manager:20261115-addon-catalog.md",
"Corfirean/coa-server-manager:20261115-clear-game-cache.md",
"Corfirean/coa-server-manager:20261115-custom-races-fast-toggle.md",
"Corfirean/coa-server-manager:20261115-custom-races-v2-client.md",
"Corfirean/coa-server-manager:20261115-database-port-relocation.md",
"Corfirean/coa-server-manager:20261115-mysql-custom-options.md",
"Corfirean/coa-server-manager:20261115-race-restriction-kept.md",
"Corfirean/coa-server-manager:20261115-realm-names.md",
"Corfirean/coa-server-manager:20261115-remembered-friend-login.md",
"Corfirean/coa-server-manager:20261115-scheduled-restart.md",
"Corfirean/coa-server-manager:20261115-v2-feature-switches.md",
"Corfirean/coa-server-manager:20261116-companions-wildcard-reborn.md",
"Corfirean/coa-server-manager:20261116-custom-race-characters-off.md",
"Corfirean/coa-server-manager:20261118-custom-races-2-0-2-client.md"
], ],
"releases": [ "releases": [
{ {
@@ -900,6 +916,72 @@
], ],
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7", "commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9" "compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9"
},
{
"tag": "v0.9.10",
"version": "0.9.10",
"date": "2026-11-08",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10",
"notes": [
"Custom Races patch installation recovers from interrupted downloads"
],
"commit": "711f378ae82f75d3fc64368c042889c773315c54",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10"
},
{
"tag": "v0.9.12",
"version": "0.9.12",
"date": "2026-11-14",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12",
"notes": [
"Settings for how much help bots get in dungeons and raids"
],
"commit": "d71c5635e3262a775b400a1c90ac81d7bddcbeaf",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12"
},
{
"tag": "v0.9.13",
"version": "0.9.13",
"date": "2026-11-15",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13",
"notes": [
"The custom races client is updated to Custom Races V2"
],
"commit": "d3527312803fb5a3e1cd48e01496645a8bbc9dcf",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13"
},
{
"tag": "v0.9.14",
"version": "0.9.14",
"date": "2026-11-16",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.14",
"notes": [
"Install community addons from the Manager",
"Old item and creature data is cleared before every Play",
"Turning the custom races client patch on or off takes seconds again",
"The database moves to a free port when Windows reserves or another program takes 3307",
"Your own MySQL settings survive restarts and updates",
"Disabled custom races stay disabled after a server update that adds races",
"Rename your realms in the Manager",
"The account for a friend's server is in the login box at every Play",
"Restart the world every day at a chosen time",
"Switches for the Custom Races V2 subclasses, Hero Races and the /dev menu",
"Companion bots on Wildcard and Warcraft Reborn",
"The Custom Races card tells which characters stay out while races are off"
],
"commit": "1f64da3ae064b3f02d2bb11d818c44d26a557045",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.13...v0.9.14"
},
{
"tag": "v0.9.15",
"version": "0.9.15",
"date": "2026-11-19",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.15",
"notes": [
"The Custom Races client update brings version 2.0.2"
],
"commit": "2b9021ce072e3b6c7e9c8106f8a54f59f1b37424",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.14...v0.9.15"
} }
] ]
} }
+2 -1
View File
@@ -5,6 +5,7 @@ edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
socket2 = "0.6"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
sha2 = "0.10" sha2 = "0.10"
@@ -37,7 +38,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
ed25519-dalek = { version = "2", features = ["rand_core"] } ed25519-dalek = { version = "2", features = ["rand_core"] }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] } windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
[features] [features]
testkit = [] testkit = []
-75
View File
@@ -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();
}
+114
View File
@@ -0,0 +1,114 @@
//! The Rust launcher on a DISPOSABLE repack, side by side with Scripts/manage.py:
//!
//! 1. install the stable server into a new folder on unused ports;
//! 2. coa-launcher start-all, then manage.py status-json must see every service;
//! 3. manage.py stop-all stops what coa-launcher started;
//! 4. manage.py start-all, coa-launcher status-json sees it, coa-launcher stop-all stops it;
//! 5. both stop-alls leave nothing of the repack running.
//!
//! usage: launcher_e2e <new folder ending in -fixture> <coa-launcher.exe>
use std::path::Path;
use std::process::Command;
use coa_core::install::{install_base, Params};
use coa_core::registry::Registry;
fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
fn run(exe: &Path, args: &[&str]) -> (bool, String) {
let out = Command::new(exe).args(args).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
(out.status.success(), text)
}
fn launcher(root: &Path, exe: &Path, action: &str) -> (bool, String) {
let r = root.to_string_lossy().into_owned();
let t = std::time::Instant::now();
let out = run(exe, &["--root", &r, action]);
println!("[coa-launcher {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
out
}
fn manage(root: &Path, action: &str) -> (bool, String) {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
let t = std::time::Instant::now();
let out = run(&python, &["-B", &script, action]);
println!("[manage.py {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
out
}
fn indent(s: &str) -> String {
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
}
fn status(out: &str) -> serde_json::Value {
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
serde_json::from_str(line).unwrap()
}
fn all(v: &serde_json::Value, running: bool) -> bool {
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
let exe = Path::new(&a[1]);
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
if root.join("Core/worldserver.exe").is_file() {
println!("reusing the installed fixture");
} else {
install(root);
}
test(root, exe);
}
fn install(root: &Path) {
assert!(!root.exists(), "a new folder is required");
let reg_dir = std::env::temp_dir().join("coa-launcher-e2e-registry");
let _ = std::fs::remove_dir_all(&reg_dir);
let reg = Registry::at(reg_dir.join("installs.json"));
// what the Manager installs: the stable release's installation image
let image = coa_core::install::Source::Installation(Box::new(coa_core::channels::resolve("stable").expect("stable channel")));
let installed = install_base(
&Params { source: image, dest: root.into(), trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, registry: &reg, cancel: Default::default() },
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
)
.expect("install");
println!("installed {}", installed.version);
let repack = root.join("Settings/repack.json");
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack).unwrap()).unwrap();
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
cfg[k] = free_port().into();
}
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg).unwrap()).unwrap();
}
fn test(root: &Path, exe: &Path) {
// 2. Rust starts, Python sees it
assert!(launcher(root, exe, "start-all").0, "coa-launcher start-all");
let seen = status(&manage(root, "status-json").1);
assert!(all(&seen, true), "manage.py must see the services coa-launcher started: {seen}");
// 3. Python stops what Rust started
assert!(manage(root, "stop-all").0, "manage.py stop-all");
assert!(all(&status(&launcher(root, exe, "status-json").1), false));
// 4. Python starts, Rust sees and stops it
assert!(manage(root, "start-all").0, "manage.py start-all");
let seen = status(&launcher(root, exe, "status-json").1);
assert!(all(&seen, true), "coa-launcher must see the services manage.py started: {seen}");
assert!(launcher(root, exe, "stop-all").0, "coa-launcher stop-all");
assert!(all(&status(&manage(root, "status-json").1), false));
// 5. Rust alone, a second time (start on a server it stopped)
assert!(launcher(root, exe, "start-all").0);
assert!(launcher(root, exe, "stop-all").0);
let left = coa_core::process::find_by_exe(&root.join("mysql/bin/mysqld.exe")).len()
+ coa_core::process::find_by_exe(&root.join("Core/worldserver.exe")).len()
+ coa_core::process::find_by_exe(&root.join("Core/authserver.exe")).len();
assert_eq!(left, 0, "nothing of the repack may be left running");
println!("LAUNCHER E2E PASS");
}
@@ -0,0 +1,149 @@
//! The Manager's start/stop (`driver`) on the Rust launcher, on a DISPOSABLE repack:
//!
//! 1. driver start-all: every service runs, the console answers, manage.py is not touched and sees the services;
//! 2. driver stop-all stops everything;
//! 3. manage.py start-all, then driver stop-all stops what Python started;
//! 4. a taken world port fails with the typed "port in use" code (no stderr parsing), then stop-all;
//! 5. driver start-all, then the forced stop;
//! 6. with a realm profile: the realm row gets the profile's name, manage.py is still not edited;
//! 7. nothing of the repack is left running.
//!
//! usage: manager_launcher_e2e <existing folder ending in -fixture>
use std::path::Path;
use std::process::Command;
use std::time::Instant;
use coa_core::driver::{self, Verb};
use coa_core::error::ErrorCode;
use coa_core::launcher::{services, settings::Settings, state};
fn indent(s: &str) -> String {
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
}
fn drive(root: &Path, verb: Verb) -> driver::DriverOutcome {
let t = Instant::now();
let out = driver::run(root, verb).expect("driver");
println!("[driver {verb:?}] ok={} code={:?} in {:?}\n{}", out.ok, out.code, t.elapsed(), indent(&out.output));
out
}
fn manage(root: &Path, action: &str) -> (bool, String) {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
let t = Instant::now();
let out = Command::new(python).args(["-B", &script, action]).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
println!("[manage.py {action}] ok={} in {:?}\n{}", out.status.success(), t.elapsed(), indent(&text));
(out.status.success(), text)
}
fn python_status(root: &Path) -> serde_json::Value {
let (ok, out) = manage(root, "status-json");
assert!(ok);
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
serde_json::from_str(line).unwrap()
}
fn all(v: &serde_json::Value, running: bool) -> bool {
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
}
fn nothing_running(root: &Path) -> bool {
["mysql", "auth", "world", "supervisor", "relay"].iter().all(|n| state::running(root, n).is_none())
&& ["mysql/bin/mysqld.exe", "Core/authserver.exe", "Core/worldserver.exe"]
.iter()
.all(|exe| coa_core::process::find_by_exe(&root.join(exe)).is_empty())
}
fn console(root: &Path) -> String {
let cfg = Settings::load(root, 0).unwrap();
let mut ra = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).unwrap();
ra.run("server info").unwrap()
}
fn realm_name(root: &Path) -> String {
services::mysql(root, Some("SELECT name FROM acore_auth.realmlist WHERE id=1;"), None).unwrap()
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
assert!(nothing_running(root), "the fixture must be stopped before the test");
let manage_py = root.join("Scripts/manage.py");
let original = std::fs::read(&manage_py).unwrap();
let profile = root.join("Settings/realm-profile.json");
assert!(!profile.exists(), "the fixture starts without a realm profile");
// 1
let started = drive(root, Verb::StartAll);
assert!(started.ok, "start-all");
assert!(all(&python_status(root), true), "manage.py sees what the Manager started");
let info = console(root);
println!("[console] {}", info.lines().next().unwrap_or(""));
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not rewritten");
assert_eq!(realm_name(root), "AzerothCore", "no profile: the launcher's own realm name");
let shipped = root.join("Scripts/coa-launcher.exe");
let supervisor = state::running(root, "supervisor").expect("a supervisor");
println!("[supervisor] {}", supervisor.exe);
let expected = if shipped.is_file() { "coa-launcher.exe" } else { "python.exe" };
assert!(supervisor.exe.to_lowercase().ends_with(expected), "the world is supervised by {expected}");
let relay = state::running(root, "relay").expect("a bug-report relay");
println!("[relay] {}", relay.exe);
assert!(relay.exe.to_lowercase().ends_with(expected), "the relay is run by {expected}");
assert!(state::running(root, "relay-ready").is_some_and(|r| r.pid == relay.pid), "the relay reported ready");
// 2
assert!(drive(root, Verb::StopAll).ok, "stop-all");
assert!(nothing_running(root), "1-2 left something running");
// 2b: the repack's Python launcher stops a world the Manager started
assert!(drive(root, Verb::StartAll).ok);
assert!(manage(root, "stop-all").0, "manage.py stops what the Manager started");
assert!(nothing_running(root), "2b left something running");
// 3
assert!(manage(root, "start-all").0);
assert!(drive(root, Verb::StopAll).ok, "driver stops what manage.py started");
assert!(nothing_running(root), "3 left something running");
// 4
let cfg = Settings::load(root, 0).unwrap();
let blocker = std::net::TcpListener::bind(("127.0.0.1", cfg.world_port)).unwrap();
let refused = drive(root, Verb::StartAll);
assert!(!refused.ok);
assert_eq!(refused.code, Some(ErrorCode::PortInUse), "typed port error");
assert!(refused.output.contains(&format!("Port {}", cfg.world_port)));
drop(blocker);
assert!(drive(root, Verb::StopAll).ok);
assert!(nothing_running(root), "4 left something running");
// 5
assert!(drive(root, Verb::StartAll).ok);
let t = Instant::now();
let forced = driver::force_stop(root).expect("force stop");
println!("[driver force_stop] ok={} in {:?}\n{}", forced.ok, t.elapsed(), indent(&forced.output));
assert!(forced.ok && forced.output.contains("Force-stopped"));
assert!(nothing_running(root), "5 left something running");
// 6
std::fs::write(&profile, br#"{"active":"coa","wildcard_created":false}"#).unwrap();
let result = std::panic::catch_unwind(|| {
assert!(drive(root, Verb::StartAll).ok, "start-all with a realm profile");
assert_eq!(realm_name(root), "Conquest of Azeroth");
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not edited for a realm profile either");
assert!(drive(root, Verb::StopAll).ok);
});
std::fs::remove_file(&profile).unwrap();
std::fs::write(&manage_py, &original).unwrap();
if result.is_err() {
let _ = driver::run(root, Verb::StopAll);
panic!("step 6 failed");
}
// 7
assert!(nothing_running(root), "something of the repack is still running");
println!("PASS: the Manager starts and stops through the Rust launcher, interoperates with manage.py, typed errors");
}
@@ -0,0 +1,170 @@
//! The Rust bug-report relay against the repack's `BugReport/relay.py`, offline (a scripted service, no network):
//!
//! 1. the same reports and the same service answers give the same `.status` files and journal rows;
//! 2. each relay continues the other's journal: what one delivered is never sent again by the other, and a post the
//! other left in progress is uncertain.
//!
//! usage: relay_equivalence <repack folder with Runtime/python and BugReport/relay.py>
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Arc, Mutex};
use coa_core::launcher::relay::{Failure, Relay, Service};
const REPORTS: [(&str, &str); 5] = [
("1-00000000000000a1", "COABUG1\r\nQuest broken\r\nThe NPC is gone.\r\n"),
("9-00000000000000b2", "COABUG1\nRate limited\nBody text\n"),
("3-00000000000000c3", "COABUG1\nRejected\nBody\n"),
("4-00000000000000d4", "COABUG1\nxy\nTitle too short\n"),
("5-00000000000000e5", "COABUG1\nUnknown outcome\nBody\n"),
];
/// The answers per title, in the vocabulary of both relays.
fn answer(title: &str) -> std::result::Result<u64, Failure> {
match title {
"Quest broken" => Ok(101),
"Rate limited" => Err(Failure::Limited(60)),
"Rejected" => Err(Failure::Invalid),
_ => Err(Failure::Uncertain),
}
}
const PYTHON: &str = r#"
import importlib.util, sys, json
from pathlib import Path
spec = importlib.util.spec_from_file_location("relay", sys.argv[1]); relay = importlib.util.module_from_spec(spec); spec.loader.exec_module(relay)
spool = Path(sys.argv[2]); calls = []
class Fake:
def create(self, title, body):
calls.append(title)
if title == "Quest broken": return 101
if title == "Rate limited": raise relay.DeliveryError("limited", 60)
if title == "Rejected": raise relay.DeliveryError("invalid")
raise relay.DeliveryError("uncertain")
t = [float(sys.argv[3])]
def clock():
t[0] += 3
return t[0]
r = relay.Relay(spool, Fake(), clock=clock)
for path in sorted(spool.glob("*.report")):
r.process(path)
r.close()
print(json.dumps(calls))
"#;
struct Scripted(Arc<Mutex<Vec<String>>>);
impl Service for Scripted {
fn create(&self, title: &str, _: &str) -> std::result::Result<u64, Failure> {
self.0.lock().unwrap().push(title.into());
answer(title)
}
}
fn spool(dir: &Path) -> PathBuf {
std::fs::create_dir_all(dir).unwrap();
for (key, text) in REPORTS {
std::fs::write(dir.join(format!("{key}.report")), text).unwrap();
}
dir.into()
}
fn python(repack: &Path, spool: &Path, start: f64) -> Vec<String> {
let out = Command::new(repack.join("Runtime/python/python.exe"))
.args(["-I", "-B", "-c", PYTHON])
.arg(repack.join("BugReport/relay.py"))
.arg(spool)
.arg(start.to_string())
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
serde_json::from_slice(&out.stdout).unwrap()
}
/// The clock of both relays: `start`, then 3 seconds later at every reading.
fn rust(spool: &Path, start: f64) -> Vec<String> {
let calls = Arc::new(Mutex::new(Vec::new()));
let t = Mutex::new(start);
let clock = move || {
let mut v = t.lock().unwrap();
*v += 3.0;
*v
};
let relay = Relay::with_clock(spool, Scripted(calls.clone()), Box::new(clock)).unwrap();
relay.pass().unwrap();
drop(relay);
let c = calls.lock().unwrap().clone();
c
}
/// `.status` files and journal rows (without the post time).
fn snapshot(spool: &Path) -> (Vec<(String, String)>, Vec<String>) {
let mut statuses: Vec<(String, String)> = std::fs::read_dir(spool)
.unwrap()
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "status"))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read_to_string(e.path()).unwrap()))
.collect();
statuses.sort();
let db = rusqlite::Connection::open(spool.join("relay.sqlite3")).unwrap();
let mut q = db.prepare("SELECT key, digest, marker, state, number, next_try FROM deliveries ORDER BY key").unwrap();
let rows = q
.query_map([], |r| {
Ok(format!(
"{}|{}|{}|{}|{:?}|{}",
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, String>(3)?,
r.get::<_, Option<i64>>(4)?,
r.get::<_, f64>(5)?
))
})
.unwrap()
.map(Result::unwrap)
.collect();
(statuses, rows)
}
fn main() {
let repack = PathBuf::from(std::env::args().nth(1).expect("repack folder"));
let work = tempfile::tempdir().unwrap();
// 1
let (a, b) = (spool(&work.path().join("python")), spool(&work.path().join("rust")));
let py_calls = python(&repack, &a, 1000.0);
let rs_calls = rust(&b, 1000.0);
println!("python posted {py_calls:?}\nrust posted {rs_calls:?}");
assert_eq!(py_calls, rs_calls, "the same reports are posted");
let (pa, pb) = (snapshot(&a), snapshot(&b));
for s in &pa.0 {
println!(" {} = {}", s.0, s.1.trim());
}
assert_eq!(pa, pb, "the same statuses and journal");
// 2: each continues the other's journal. Before the retry times nothing is sent again; after them only the
// rate-limited report is (created, rejected and uncertain ones never are).
assert!(python(&repack, &b, 1000.0).is_empty(), "Python does not resend what Rust handled");
assert!(rust(&a, 1000.0).is_empty(), "Rust does not resend what Python handled");
// Later passes: the queued reports go out, a refused or uncertain one never again.
for start in [5000.0, 6000.0, 7000.0] {
let (p, r) = (python(&repack, &b, start), rust(&a, start));
println!("at {start}: python on rust's journal posted {p:?}, rust on python's posted {r:?}");
assert_eq!(p, r, "the same retries");
assert!(!p.iter().any(|t| t == "Quest broken" || t == "Unknown outcome"), "created and uncertain are final");
}
assert_eq!(snapshot(&a), snapshot(&b), "the same after a retry by the other relay");
for dir in [&a, &b] {
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
db.execute("UPDATE deliveries SET state='posting' WHERE key='9-00000000000000b2'", []).unwrap();
}
python(&repack, &b, 9000.0);
rust(&a, 9000.0);
for dir in [&a, &b] {
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
let state: String = db.query_row("SELECT state FROM deliveries WHERE key='9-00000000000000b2'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "uncertain", "an interrupted post is not retried ({})", dir.display());
}
assert_eq!(snapshot(&a), snapshot(&b), "still the same after the crossover");
println!("PASS: relay journals, statuses and posts are the same in Python and Rust");
}
@@ -0,0 +1,103 @@
//! SQUID database provisioning in Rust gives exactly what Scripts/squid_playerbots.py gives, on a DISPOSABLE repack:
//! the same journals (coa_squid_migrations, coa_squid_pending) in every schema, the same acore_playerbots tables
//! with the same row counts, the same playerbots.conf. Each side starts from the same state (SQUID never
//! provisioned), and a second run of each must change nothing.
//!
//! usage: squid_equivalence <fixture ending in -fixture> <coa-launcher.exe>
use std::path::Path;
use std::process::Command;
use coa_core::launcher::{services, squid};
fn sql(root: &Path, q: &str) -> String {
services::mysql(root, Some(q), None).unwrap_or_else(|e| panic!("{q}: {e}"))
}
/// What provisioning leaves behind, comparable between runs.
fn snapshot(root: &Path) -> String {
let mut out = Vec::new();
for schema in ["acore_characters", "acore_world", "acore_playerbots"] {
let tables = sql(root, &format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}' ORDER BY TABLE_NAME;"));
for t in tables.lines() {
if schema != "acore_playerbots" && !t.starts_with("coa_squid") {
continue;
}
let n = sql(root, &format!("SELECT COUNT(*) FROM `{schema}`.`{t}`;"));
out.push(format!("{schema}.{t} rows={n}"));
if t == "coa_squid_migrations" || t == "coa_squid_pending" {
for row in sql(root, &format!("SELECT path, sha256 FROM `{schema}`.`{t}` ORDER BY path;")).lines() {
out.push(format!(" {row}"));
}
}
}
}
let conf = std::fs::read_to_string(root.join("Core/configs/modules/playerbots.conf")).unwrap();
out.push(format!("playerbots.conf:\n{}", conf.replace("\r\n", "\n")));
out.join("\n")
}
fn reset(root: &Path, conf: &[u8]) {
sql(root, "DROP DATABASE IF EXISTS acore_playerbots;");
for schema in ["acore_characters", "acore_world"] {
sql(root, &format!("DROP TABLE IF EXISTS `{schema}`.coa_squid_migrations, `{schema}`.coa_squid_pending;"));
}
std::fs::write(root.join("Core/configs/modules/playerbots.conf"), conf).unwrap();
}
fn python(root: &Path) {
let harness = root.join(".state/squid_harness.py");
std::fs::write(
&harness,
"import sys, pathlib\nroot = pathlib.Path(sys.argv[1])\nsys.path.insert(0, str(root / 'Scripts'))\nsys.argv = ['manage.py']\nimport manage\nfrom squid_playerbots import prepare_playerbots\nprepare_playerbots(manage.ROOT, manage.settings(), manage.mysql)\n",
)
.unwrap();
let out = Command::new(root.join("Runtime/python/python.exe")).arg("-B").arg(&harness).arg(root).output().unwrap();
assert!(out.status.success(), "python: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
print!("{}", String::from_utf8_lossy(&out.stdout));
}
fn rust(root: &Path) {
let cfg = coa_core::launcher::Settings::load(root, 0).unwrap();
squid::prepare_playerbots(root, cfg.mysql_port, &|q| services::mysql(root, Some(q), None), &|m| println!("{m}")).unwrap();
}
fn main() {
let a: Vec<String> = std::env::args().skip(1).collect();
let root = Path::new(&a[0]);
let exe = Path::new(&a[1]);
assert!(a[0].ends_with("-fixture"));
let modules = root.join("Core/configs/modules");
// SQUID on, Companions off
let companions = std::fs::read_to_string(modules.join("mod_coa_playerbots.conf")).unwrap();
std::fs::write(modules.join("mod_coa_playerbots.conf"), companions.replace("CoaBots.Enable = 1", "CoaBots.Enable = 0")).unwrap();
let squid_conf = std::fs::read_to_string(modules.join("playerbots.conf")).unwrap().replace("AiPlayerbot.Enabled = 0", "AiPlayerbot.Enabled = 1");
let r = root.to_string_lossy().into_owned();
let started = Command::new(exe).args(["--root", &r, "start-mysql"]).output().unwrap();
assert!(started.status.success(), "{}", String::from_utf8_lossy(&started.stderr));
reset(root, squid_conf.as_bytes());
let t = std::time::Instant::now();
python(root);
println!("python provisioned in {:?}", t.elapsed());
let by_python = snapshot(root);
python(root);
assert_eq!(snapshot(root), by_python, "a second Python run changed something");
reset(root, squid_conf.as_bytes());
let t = std::time::Instant::now();
rust(root);
println!("rust provisioned in {:?}", t.elapsed());
let by_rust = snapshot(root);
rust(root);
assert_eq!(snapshot(root), by_rust, "a second Rust run changed something");
if by_python != by_rust {
std::fs::write(root.join(".state/squid-python.txt"), &by_python).unwrap();
std::fs::write(root.join(".state/squid-rust.txt"), &by_rust).unwrap();
panic!("Rust and Python differ: see .state/squid-python.txt and squid-rust.txt");
}
println!("{} lines of journal/table/config state are identical", by_rust.lines().count());
let stopped = Command::new(exe).args(["--root", &r, "stop-all"]).output().unwrap();
assert!(stopped.status.success());
println!("SQUID EQUIVALENCE PASS");
}
+494
View File
@@ -0,0 +1,494 @@
//! A catalog of game addons the Manager can install into a client's `Interface/AddOns`.
//!
//! Every addon is pinned to a commit of its GitHub repository; the catalog lists each file it installs with its
//! git blob SHA-1 and size, which are checked after download (GitHub's archives are not byte-stable, their
//! contents are). The Manager records what it installed in `Interface/AddOns/.coa-addons.json` and only ever
//! removes or replaces those folders; a folder of the same name that someone else put there is moved to
//! `Interface/AddOns/.coa-addons-backup` first.
use std::collections::BTreeMap;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use sha1::{Digest, Sha1};
use crate::download::{Cancel, Transport};
use crate::error::{Error, Result};
use crate::fsx;
static CATALOG: &str = include_str!("../../../addons/catalog.json");
const STATE: &str = ".coa-addons.json";
const BACKUP: &str = ".coa-addons-backup";
/// No addon archive is anywhere near this; a larger answer is not what the catalog describes.
const MAX_ARCHIVE: u64 = 1 << 30;
#[derive(Debug, Clone, Deserialize)]
struct AddonFile {
path: String,
from: String,
sha1: String,
size: u64,
}
#[derive(Debug, Clone, Deserialize)]
struct Entry {
id: String,
name: String,
description: BTreeMap<String, String>,
author: String,
license: String,
#[serde(default)]
needs: Option<String>,
repo: String,
commit: String,
archive: String,
folders: Vec<String>,
files: Vec<AddonFile>,
}
#[derive(Deserialize)]
struct Catalog {
addons: Vec<Entry>,
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
struct Installed {
commit: String,
folders: Vec<String>,
}
/// One addon of the catalog as the Manager shows it for a client.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddonView {
pub id: String,
pub name: String,
pub description: BTreeMap<String, String>,
pub author: String,
pub license: String,
/// A server module the addon is made for (`playerbots`), shown as a hint.
pub needs: Option<String>,
pub repo: String,
pub size: u64,
pub installed: bool,
pub update_available: bool,
/// Folders of this addon that are in the client but were not installed by the Manager.
pub foreign_folders: Vec<String>,
/// Installed by something else, shown so nobody looks for it twice: `custom-races` (the client patch).
pub bundled: Option<String>,
}
fn catalog() -> Result<Vec<Entry>> {
let catalog: Catalog = serde_json::from_str(CATALOG)?;
for entry in &catalog.addons {
for folder in &entry.folders {
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
return Err(Error::Invalid(format!("Invalid addon folder in the catalog: {folder}")));
}
}
}
Ok(catalog.addons)
}
fn addons_dir(client: &Path) -> PathBuf {
client.join("Interface").join("AddOns")
}
fn read_state(client: &Path) -> BTreeMap<String, Installed> {
fsx::read_json(&addons_dir(client).join(STATE)).unwrap_or_default()
}
fn write_state(client: &Path, state: &BTreeMap<String, Installed>) -> Result<()> {
fsx::atomic_write_json(&addons_dir(client).join(STATE), state)
}
/// The catalog with what is installed in `client`.
pub fn list(client: &Path) -> Result<Vec<AddonView>> {
let state = read_state(client);
let dir = addons_dir(client);
let owned: Vec<&String> = state.values().flat_map(|i| i.folders.iter()).collect();
Ok(catalog()?
.into_iter()
.map(|entry| {
let installed = state.get(&entry.id);
AddonView {
foreign_folders: entry
.folders
.iter()
.filter(|f| dir.join(f).exists() && !owned.contains(f))
.cloned()
.collect(),
size: entry.files.iter().map(|f| f.size).sum(),
installed: installed.is_some(),
update_available: installed.is_some_and(|i| i.commit != entry.commit),
id: entry.id,
name: entry.name,
description: entry.description,
author: entry.author,
license: entry.license,
needs: entry.needs,
repo: entry.repo,
bundled: None,
}
})
.chain(std::iter::once(dev_menu(&dir)))
.collect())
}
/// The /dev menu addon of Custom Races V2: the client patch installs it and switches it with the patch.
fn dev_menu(dir: &Path) -> AddonView {
let mut description = BTreeMap::new();
for (lang, text) in [
("en", "The in-game /dev editor for game masters. It comes with the Custom Races V2 client patch and is switched with it."),
("ru", "Внутриигровой редактор /dev для гейм-мастеров. Ставится вместе с клиентским патчем Custom Races V2 и включается вместе с ним."),
("de", "Der /dev-Editor im Spiel für Spielleiter. Er kommt mit dem Client-Patch Custom Races V2 und wird mit ihm geschaltet."),
("fr", "L'éditeur /dev en jeu pour les maîtres du jeu. Il vient avec le patch client Custom Races V2 et s'active avec lui."),
("es", "El editor /dev del juego para los máster. Viene con el parche de cliente Custom Races V2 y se activa con él."),
("zh", "供游戏管理员使用的游戏内 /dev 编辑器。随 Custom Races V2 客户端补丁安装,并随补丁一起开关。"),
] {
description.insert(lang.to_string(), text.to_string());
}
AddonView {
id: "coa-dev-menu".into(),
name: "CoA Dev Menu".into(),
description,
author: "ilusixn".into(),
license: "see repository".into(),
needs: None,
repo: "https://github.com/ilusixn/ilusixn-dev-menu".into(),
size: 0,
installed: dir.join("CoA_DevMenu/CoA_DevMenu.toc").is_file(),
update_available: false,
foreign_folders: Vec::new(),
bundled: Some("custom-races".into()),
}
}
/// The git blob id of `bytes` (what the catalog records for each file).
fn git_blob_sha1(bytes: &[u8]) -> String {
let mut hasher = Sha1::new();
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
hasher.update(bytes);
hex::encode(hasher.finalize())
}
fn download(transport: &dyn Transport, url: &str, dest: &Path, cancel: &Cancel) -> Result<()> {
crate::download::check_url(url)?;
let reply = transport.get(url, 0).map_err(Error::Invalid)?;
if reply.status != 200 {
return Err(Error::Invalid(format!("The addon download answered HTTP {}.", reply.status)));
}
let mut body = reply.body.take(MAX_ARCHIVE + 1);
let mut file = fs::File::create(dest)?;
let mut buf = vec![0u8; 1 << 20];
let mut total = 0u64;
loop {
if cancel.is_set() {
return Err(Error::Invalid("Operation cancelled.".into()));
}
let n = body.read(&mut buf)?;
if n == 0 {
break;
}
total += n as u64;
if total > MAX_ARCHIVE {
return Err(Error::Invalid("The addon download is larger than any catalog addon.".into()));
}
file.write_all(&buf[..n])?;
}
file.sync_all()?;
Ok(())
}
/// Unpack the catalog's files of `entry` from `archive` into `staging`, checking every one.
fn unpack(entry: &Entry, archive: &Path, staging: &Path) -> Result<()> {
let mut zip = zip::ZipArchive::new(fs::File::open(archive)?)
.map_err(|e| Error::Invalid(format!("The addon download is not a zip archive: {e}")))?;
// GitHub archives hold everything under one top folder (`<repo>-<commit>/`).
let mut by_path = BTreeMap::new();
for index in 0..zip.len() {
let name = zip
.by_index(index)
.map_err(|e| Error::Invalid(e.to_string()))?
.name()
.replace('\\', "/");
if let Some((_, inner)) = name.split_once('/') {
by_path.insert(inner.to_string(), index);
}
}
for file in &entry.files {
let index = *by_path
.get(&file.from)
.ok_or_else(|| Error::Invalid(format!("The addon download lacks {}.", file.from)))?;
let mut zipped = zip.by_index(index).map_err(|e| Error::Invalid(e.to_string()))?;
let mut bytes = Vec::with_capacity(file.size as usize);
zipped.by_ref().take(file.size + 1).read_to_end(&mut bytes)?;
if bytes.len() as u64 != file.size || git_blob_sha1(&bytes) != file.sha1 {
return Err(Error::Invalid(format!("{} failed verification.", file.from)));
}
let target = fsx::safe_join(staging, &file.path)?;
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
fs::write(target, bytes)?;
}
Ok(())
}
fn stamp() -> String {
chrono::Local::now().format("%Y%m%d-%H%M%S").to_string()
}
/// Install or update `id` in `client` from `transport`.
pub fn install_with(transport: &dyn Transport, client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
if crate::client::is_running(client) {
return Err(Error::Invalid("Close the game before installing addons.".into()));
}
let entry = catalog()?
.into_iter()
.find(|e| e.id == id)
.ok_or_else(|| Error::Invalid(format!("Unknown addon {id}.")))?;
install_entry(transport, client, &entry, cancel)?;
list(client)
}
fn install_entry(transport: &dyn Transport, client: &Path, entry: &Entry, cancel: &Cancel) -> Result<()> {
let dir = addons_dir(client);
fs::create_dir_all(&dir)?;
// Staged next to AddOns' own folders, so the final moves stay on one volume even for a linked AddOns.
let staging = tempfile::Builder::new().prefix(".coa-addon-").tempdir_in(&dir)?;
let archive = staging.path().join("archive.zip");
download(transport, &entry.archive, &archive, cancel)?;
let unpacked = staging.path().join("files");
unpack(entry, &archive, &unpacked)?;
if cancel.is_set() {
return Err(Error::Invalid("Operation cancelled.".into()));
}
let mut state = read_state(client);
let ours: Vec<String> = state.values().flat_map(|i| i.folders.clone()).collect();
// Move what is in the way out first, so a failed move leaves the client as it was.
let mut moved: Vec<(PathBuf, PathBuf)> = Vec::new();
let undo = |moved: &[(PathBuf, PathBuf)]| {
for (from, to) in moved.iter().rev() {
let _ = fs::rename(to, from);
}
};
for folder in &entry.folders {
let target = dir.join(folder);
if !target.exists() {
continue;
}
let aside = if ours.contains(folder) {
staging.path().join("old").join(folder)
} else {
dir.join(BACKUP).join(format!("{folder}-{}", stamp()))
};
if let Some(parent) = aside.parent() {
fs::create_dir_all(parent)?;
}
if let Err(e) = fs::rename(&target, &aside) {
undo(&moved);
return Err(Error::Invalid(format!("{folder} is in use and could not be replaced: {e}")));
}
moved.push((target, aside));
}
let mut placed: Vec<PathBuf> = Vec::new();
for folder in &entry.folders {
let target = dir.join(folder);
if let Err(e) = fs::rename(unpacked.join(folder), &target) {
for p in &placed {
let _ = fs::remove_dir_all(p);
}
undo(&moved);
return Err(Error::Invalid(format!("{folder} could not be installed: {e}")));
}
placed.push(target);
}
state.insert(
entry.id.clone(),
Installed {
commit: entry.commit.clone(),
folders: entry.folders.clone(),
},
);
write_state(client, &state)?;
tracing::info!(addon = %entry.id, commit = %entry.commit, "addon installed");
Ok(())
}
pub fn install(client: &Path, id: &str, cancel: &Cancel) -> Result<Vec<AddonView>> {
install_with(&crate::download::HttpTransport::with_total_timeout(1800)?, client, id, cancel)
}
/// Remove an addon the Manager installed (only its recorded folders).
pub fn remove(client: &Path, id: &str) -> Result<Vec<AddonView>> {
if crate::client::is_running(client) {
return Err(Error::Invalid("Close the game before removing addons.".into()));
}
let mut state = read_state(client);
let Some(installed) = state.remove(id) else {
return list(client);
};
let dir = addons_dir(client);
for folder in &installed.folders {
if folder.is_empty() || folder.contains(['/', '\\']) || folder.starts_with('.') {
continue;
}
let target = dir.join(folder);
if target.exists() {
fs::remove_dir_all(&target)?;
}
}
write_state(client, &state)?;
list(client)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::download::Reply;
struct Serve(Vec<u8>);
impl Transport for Serve {
fn get(&self, _: &str, _: u64) -> std::result::Result<Reply, String> {
Ok(Reply { status: 200, content_range: None, body: Box::new(std::io::Cursor::new(self.0.clone())) })
}
}
/// A GitHub-like archive of the catalog entry `id` with the given file bodies (path in repo -> bytes).
fn archive(entry: &Entry, body: &dyn Fn(&AddonFile) -> Vec<u8>) -> Vec<u8> {
let mut out = std::io::Cursor::new(Vec::new());
let mut zip = zip::ZipWriter::new(&mut out);
for file in &entry.files {
zip.start_file(format!("repo-{}/{}", entry.commit, file.from), zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(&body(file)).unwrap();
}
zip.finish().unwrap();
out.into_inner()
}
/// A small catalog entry whose files hash to what the archive will hold.
fn small_entry() -> Entry {
let bytes = b"## Interface: 30300\n".to_vec();
Entry {
id: "t".into(),
name: "T".into(),
description: BTreeMap::new(),
author: "a".into(),
license: "x".into(),
needs: None,
repo: "r".into(),
commit: "c1".into(),
archive: "https://example.invalid/a.zip".into(),
folders: vec!["TestAddon".into()],
files: vec![AddonFile {
path: "TestAddon/TestAddon.toc".into(),
from: "TestAddon/TestAddon.toc".into(),
sha1: git_blob_sha1(&bytes),
size: bytes.len() as u64,
}],
}
}
#[test]
fn the_catalog_is_valid_and_pins_every_addon() {
let entries = catalog().unwrap();
assert!(entries.len() >= 4);
let views = list(Path::new("C:/no-such-client")).unwrap();
assert_eq!(views.iter().filter(|v| v.bundled.is_some()).count(), 1, "the dev menu is shown, not installable");
for e in &entries {
assert_eq!(e.commit.len(), 40, "{}", e.id);
assert!(e.archive.starts_with("https://codeload.github.com/") && e.archive.ends_with(&e.commit));
assert!(e.description.contains_key("en") && e.description.contains_key("ru"));
for folder in &e.folders {
assert!(e.files.iter().any(|f| f.path.eq_ignore_ascii_case(&format!("{folder}/{folder}.toc"))
|| f.path.starts_with(&format!("{folder}/")) && f.path.ends_with(".toc")), "{folder} has no toc");
}
for f in &e.files {
fsx::safe_join(Path::new("C:/x"), &f.path).unwrap();
assert!(e.folders.iter().any(|folder| f.path.starts_with(&format!("{folder}/"))));
}
}
}
#[test]
#[ignore = "Downloads the catalog's small addons from GitHub"]
fn the_real_catalog_installs_from_github() {
let client = tempfile::tempdir().unwrap();
for id in ["incahoots", "coacombat", "squidbots-lite"] {
let views = install(client.path(), id, &Cancel::default()).unwrap();
let view = views.iter().find(|v| v.id == id).unwrap();
assert!(view.installed && !view.update_available, "{id}");
}
assert!(addons_dir(client.path()).join("IncahootsCoA/IncahootsCoA.toc").is_file());
assert!(addons_dir(client.path()).join("SquidBotsLite/SquidBotsLite.toc").is_file());
}
#[test]
fn git_blob_ids_match_git() {
// `printf 'hello\n' | git hash-object --stdin`
assert_eq!(git_blob_sha1(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
}
fn unpack_and_place(entry: &Entry, client: &Path, bytes: Vec<u8>) -> Result<()> {
let dir = addons_dir(client);
fs::create_dir_all(&dir)?;
let staging = tempfile::tempdir_in(&dir)?;
let archive = staging.path().join("a.zip");
download(&Serve(bytes), &entry.archive, &archive, &Cancel::default())?;
unpack(entry, &archive, &staging.path().join("files"))
}
#[test]
fn a_tampered_or_incomplete_download_is_refused() {
let client = tempfile::tempdir().unwrap();
let entry = small_entry();
let good = archive(&entry, &|_| b"## Interface: 30300\n".to_vec());
unpack_and_place(&entry, client.path(), good).unwrap();
let bad = archive(&entry, &|_| b"## Interface: 30300 evil\n".to_vec());
assert!(unpack_and_place(&entry, client.path(), bad).unwrap_err().to_string().contains("verification"));
let empty = {
let mut out = std::io::Cursor::new(Vec::new());
zip::ZipWriter::new(&mut out).finish().unwrap();
out.into_inner()
};
assert!(unpack_and_place(&entry, client.path(), empty).unwrap_err().to_string().contains("lacks"));
}
#[test]
fn install_update_and_remove_keep_other_folders() {
let client = tempfile::tempdir().unwrap();
let mut entry = small_entry();
let dir = addons_dir(client.path());
fs::create_dir_all(dir.join("TestAddon")).unwrap();
fs::write(dir.join("TestAddon/mine.lua"), b"player's own").unwrap();
fs::create_dir_all(dir.join("Other")).unwrap();
let serve = Serve(archive(&entry, &|_| b"## Interface: 30300
".to_vec()));
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
assert!(!dir.join("TestAddon/mine.lua").exists(), "the player's folder was set aside");
let backups: Vec<_> = fs::read_dir(dir.join(BACKUP)).unwrap().flatten().collect();
assert_eq!(backups.len(), 1);
assert!(backups[0].path().join("mine.lua").is_file());
assert_eq!(read_state(client.path())["t"].commit, "c1");
// An update replaces the Manager's own folder without another backup.
entry.commit = "c2".into();
install_entry(&serve, client.path(), &entry, &Cancel::default()).unwrap();
assert_eq!(read_state(client.path())["t"].commit, "c2");
assert_eq!(fs::read_dir(dir.join(BACKUP)).unwrap().count(), 1);
// A failed download changes nothing.
let broken = Serve(archive(&entry, &|_| b"tampered".to_vec()));
assert!(install_entry(&broken, client.path(), &entry, &Cancel::default()).is_err());
assert!(dir.join("TestAddon/TestAddon.toc").is_file());
remove(client.path(), "t").unwrap();
assert!(!dir.join("TestAddon").exists());
assert!(dir.join("Other").is_dir());
assert!(!read_state(client.path()).contains_key("t"));
// No leftover staging folders.
assert!(fs::read_dir(&dir).unwrap().flatten().all(|e| !e.file_name().to_string_lossy().starts_with(".coa-addon-")));
}
}
+6 -2
View File
@@ -308,7 +308,9 @@ pub fn with_database<T>(root: &Path, f: impl FnOnce(&Db) -> Result<T>) -> Result
let db = Db::from_repack(root, Account::Admin)?; let db = Db::from_repack(root, Account::Admin)?;
let observed = process::observe(root, &read_ports(root)); let observed = process::observe(root, &read_ports(root));
let mysql_was_up = observed.mysql.state == ServiceState::Running && db.ping(); let mysql_was_up = observed.mysql.state == ServiceState::Running && db.ping();
if !mysql_was_up { let db = if mysql_was_up {
db
} else {
let out = driver::run(root, Verb::StartMysql)?; let out = driver::run(root, Verb::StartMysql)?;
if !out.ok { if !out.ok {
// Keep the launcher's own last lines: the title alone ("Something went wrong") hides the cause. // Keep the launcher's own last lines: the title alone ("Something went wrong") hides the cause.
@@ -317,7 +319,9 @@ pub fn with_database<T>(root: &Path, f: impl FnOnce(&Db) -> Result<T>) -> Result
driver::startup_failure(root, &out) driver::startup_failure(root, &out)
))); )));
} }
} // The start may have moved the database to another port (a reserved or taken one).
Db::from_repack(root, Account::Admin)?
};
let result = f(&db); let result = f(&db);
if !mysql_was_up { if !mysql_was_up {
let now = process::observe(root, &read_ports(root)); let now = process::observe(root, &read_ports(root));
+65 -10
View File
@@ -15,7 +15,8 @@ use crate::fsx;
pub use crate::glue_config; pub use crate::glue_config;
pub const ADDON_NAME: &str = "CoABotUI"; pub const ADDON_NAME: &str = "CoABotUI";
const EXECUTABLES: [&str; 3] = ["Ascension.exe", "Wow.exe", "WoW.exe"]; // CoA Custom Races V2 ships its own client (CoACustomRace.exe) next to Ascension.exe and must be started instead.
const EXECUTABLES: [&str; 4] = ["CoACustomRace.exe", "Ascension.exe", "Wow.exe", "WoW.exe"];
pub fn is_running(client: &Path) -> bool { pub fn is_running(client: &Path) -> bool {
if crate::platform::flavor() == crate::platform::Flavor::Docker { if crate::platform::flavor() == crate::platform::Flavor::Docker {
@@ -71,13 +72,23 @@ fn realm_config(old: &[u8], realm: &str) -> Vec<u8> {
} }
pub fn sync_realm(client: &Path, meta: &Path, mode: crate::realms::Mode) -> Result<bool> { pub fn sync_realm(client: &Path, meta: &Path, mode: crate::realms::Mode) -> Result<bool> {
sync_realm_when_closed(client, meta, mode, is_running(client)) let realm = match mode {
crate::realms::Mode::Coa => "Conquest of Azeroth",
crate::realms::Mode::Wildcard => "Wildcard",
crate::realms::Mode::Reborn => "Warcraft Reborn",
};
sync_realm_when_closed(client, meta, realm, is_running(client))
}
/// [`sync_realm`] with the realm's name as the server shows it (the owner may have renamed it).
pub fn sync_realm_named(client: &Path, meta: &Path, realm: &str) -> Result<bool> {
sync_realm_when_closed(client, meta, realm, is_running(client))
} }
fn sync_realm_when_closed( fn sync_realm_when_closed(
client: &Path, client: &Path,
meta: &Path, meta: &Path,
mode: crate::realms::Mode, realm: &str,
running: bool, running: bool,
) -> Result<bool> { ) -> Result<bool> {
if running { if running {
@@ -89,11 +100,6 @@ fn sync_realm_when_closed(
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
Err(e) => return Err(e.into()), Err(e) => return Err(e.into()),
}; };
let realm = match mode {
crate::realms::Mode::Coa => "Conquest of Azeroth",
crate::realms::Mode::Wildcard => "Wildcard",
crate::realms::Mode::Reborn => "Warcraft Reborn",
};
let new = realm_config(&old, realm); let new = realm_config(&old, realm);
if new == old { if new == old {
return Ok(true); return Ok(true);
@@ -409,6 +415,38 @@ pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
Ok(()) Ok(())
} }
/// Remove the game's cache of server data (`Cache/WDB/<locale>/*.wdb`: creatures, items, quests, pages). The client
/// keeps answers it got from a server; after the server's data changes they show old names and stats until the
/// cache is gone. Only `.wdb` files under `Cache/WDB` are removed. Returns how many.
pub fn clear_game_cache(client: &Path) -> Result<usize> {
if is_running(client) {
return Ok(0);
}
let root = client.join("Cache").join("WDB");
let mut removed = 0;
let Ok(locales) = fs::read_dir(&root) else {
return Ok(0);
};
for locale in locales.flatten() {
if !locale.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let Ok(files) = fs::read_dir(locale.path()) else {
continue;
};
for file in files.flatten() {
let path = file.path();
let is_wdb = path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("wdb"));
if is_wdb && file.file_type().is_ok_and(|t| t.is_file()) && fs::remove_file(&path).is_ok() {
removed += 1;
}
}
}
Ok(removed)
}
/// Start the game client. The caller is responsible for making sure the server is ready first. /// Start the game client. The caller is responsible for making sure the server is ready first.
pub fn launch(client: &Path) -> Result<u32> { pub fn launch(client: &Path) -> Result<u32> {
let exe = let exe =
@@ -607,6 +645,23 @@ pub fn recover_all_realmlist_overrides(meta_roots: &[PathBuf]) -> usize {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn only_the_server_data_cache_is_cleared() {
let d = tempfile::tempdir().unwrap();
let wdb = d.path().join("Cache/WDB/enUS");
fs::create_dir_all(&wdb).unwrap();
fs::write(wdb.join("creaturecache.wdb"), b"x").unwrap();
fs::write(wdb.join("itemcache.WDB"), b"x").unwrap();
fs::write(wdb.join("notes.txt"), b"keep").unwrap();
fs::create_dir_all(d.path().join("Data/Retail/Cache")).unwrap();
fs::write(d.path().join("Data/Retail/Cache/id-1.bin"), b"keep").unwrap();
assert_eq!(clear_game_cache(d.path()).unwrap(), 2);
assert!(wdb.join("notes.txt").is_file());
assert!(d.path().join("Data/Retail/Cache/id-1.bin").is_file());
assert_eq!(clear_game_cache(d.path()).unwrap(), 0);
assert_eq!(clear_game_cache(&d.path().join("missing")).unwrap(), 0);
}
#[cfg(windows)] #[cfg(windows)]
#[test] #[test]
@@ -677,10 +732,10 @@ mod tests {
let meta = d.path().join("meta"); let meta = d.path().join("meta");
let original = b"SET realmName \"Wildcard\"\n"; let original = b"SET realmName \"Wildcard\"\n";
fs::write(c.join("WTF/Config.wtf"), original).unwrap(); fs::write(c.join("WTF/Config.wtf"), original).unwrap();
assert!(!sync_realm_when_closed(&c, &meta, crate::realms::Mode::Coa, true).unwrap()); assert!(!sync_realm_when_closed(&c, &meta, "Conquest of Azeroth", true).unwrap());
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original); assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
assert!(!backup_dir(&meta).exists()); assert!(!backup_dir(&meta).exists());
assert!(sync_realm_when_closed(&c, &meta, crate::realms::Mode::Coa, false).unwrap()); assert!(sync_realm_when_closed(&c, &meta, "Conquest of Azeroth", false).unwrap());
assert_eq!( assert_eq!(
fs::read(c.join("WTF/Config.wtf")).unwrap(), fs::read(c.join("WTF/Config.wtf")).unwrap(),
b"SET realmName \"Conquest of Azeroth\"\n" b"SET realmName \"Conquest of Azeroth\"\n"
-975
View File
@@ -1,975 +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()),
});
if crate::client_graphics::disabled(client, &f.path)? {
kept += 1;
done += f.size;
continue;
}
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 crate::client_graphics::disabled(a.client, &item.path)? {
continue;
}
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 disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() {
let dir = tempfile::tempdir().unwrap();
let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")];
let manifest = manifest("v1", &files);
let cancel = Cancel::default();
let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap();
fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap();
crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap();
let server = Server::new(&files);
apply(
&Apply {
client: dir.path(),
manifest: &manifest,
plan: &old_plan,
keep_modified: false,
transport: &server,
objects_url: "https://x.invalid/objects",
cancel: &cancel,
},
&|_| {},
)
.unwrap();
assert!(server.requested.lock().unwrap().is_empty());
assert!(!dir.path().join("d3d9.dll").exists());
assert!(!dir.path().join("dxgi.dll").exists());
assert_eq!(
fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(),
b"custom disabled"
);
let after = plan(
dir.path(),
&manifest,
&load_state(dir.path()).unwrap(),
&cancel,
&|_| {},
)
.unwrap();
assert!(after.items.is_empty());
crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap();
assert_eq!(
fs::read(dir.path().join("d3d9.dll")).unwrap(),
b"custom disabled"
);
}
#[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());
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,116 @@
{
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
"Data/Retail/Assets/EquipmentFitting/1068-1.bin": "332d2c38b037a118f262bbb3096a01ebfb33c5347e96bbfb64157437b300281b",
"Data/Retail/Assets/EquipmentFitting/60-0.bin": "ffbf6efc9ea09b0c442f048c5bc7b4c5975258045cfddedd9a77a93363312b5e",
"Data/Retail/Assets/EquipmentFitting/60-1.bin": "36ceed2a55756f3322e018938809acea5124351161405058ef27d100173778da",
"Data/Retail/Assets/EquipmentFitting/61-0.bin": "3b302a4055d1e795c451b02e38dfe8007527ee1bc5f926ebcd6ef17f433cd232",
"Data/Retail/Assets/EquipmentFitting/61-1.bin": "c42df399ed99be3c7ce1b5fdb95a873711011713a4cd867bc226a14b1ce0e8ca",
"Data/Retail/Assets/EquipmentFitting/65-0.bin": "8ce3f884ae197d14dff0f955c2cf05abb716742c8aff79f7af1cec5cf7225f04",
"Data/Retail/Assets/EquipmentFitting/68-0.bin": "f1d878f0f943cbdb8025af8daac4a38c1d1e159bd961d9d76f225931c11648ac",
"Data/Retail/Assets/EquipmentFitting/68-1.bin": "2ccbae634384200340c0cc3dca36a7a014a8ddad110598e4470ff1b266576465",
"Data/Retail/Assets/EquipmentFitting/73-0.bin": "5530882678f677ad47987ce906e851338a35f7d9737e3f9d829938027b8af67f",
"Data/Retail/Assets/EquipmentFitting/74-0.bin": "53a7be86b3bfdd6995406c706df3ca091484206d8141cebb39113c714500384a",
"Data/Retail/Assets/EquipmentFitting/74-1.bin": "e688c55a355231978d42480a003c26d379460f5931c2469c119ecb073ea153e1",
"Data/Retail/Assets/EquipmentFitting/75-0.bin": "289abc71c6df0e031a64d62a40e658eaefd37e45373a062ca52f08fbe803500c",
"Data/Retail/Assets/EquipmentFitting/76-0.bin": "63a493e70b91f59ff49f1942d959df986062bd267fe2ba589f344963df771021",
"Data/Retail/Assets/EquipmentFitting/77-0.bin": "b1366ce0dc4f31cb8c8c9705be2da565df4b905224af04b6b88f8c8e9c87e3c9",
"Data/Retail/Assets/EquipmentFitting/78-0.bin": "7b0031fb12ab19020005bdccacca2dd3991349c36949a58b035992585b4134db",
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
"Data/patch-ZK.MPQ": "444d0ecb72c1e990509d53e3cfa5b7634c816733533e8a97e5d7f5653ee32cce",
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
"Data/patch-ZZT.MPQ": "e60dab63fe5650fdf5f0846ea6d4136219293bcfdad46d9b796697faeff9ab4c",
"Data/patch-ZZU.MPQ": "0311de8f034eae7dec1bd2c92b1fe6c741cbaf53da62c7609cd12b6c37908e47",
"Data/patch-ZZV.MPQ": "3b04008905e7185d165827d68f7ca228dda8272816364f7d71874ecc83b64f0e",
"Data/patch-ZZW.MPQ": "3bbbc72901fd2d662113036485c380701e693f5a39ba9479af306bf2fa2030bd",
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"Data/patch-ZZZA.MPQ": "57ccbdc0a66000767554ffd194088df6d602ddd8341a141bca8201e7d5435889",
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
"Data/patch-ZZZD.MPQ": "ca893cf8129f6fd442a63f0697a8ddea88546e3ce71bde713be2cc832b892bc9",
"Data/patch-ZZZE.MPQ": "2e245ee0fe3b913087eed399062fda5843d98b04afac38024f7c64ac3bf43e18",
"Data/patch-ZZZF.MPQ": "40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3",
"Data/patch-ZZZZ.MPQ": "860c990db3b4185fdc36e1a001d3ca3507a68253a4506793a115f86eb0892a15",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "88e268d3be9eca3b0644f543d823f4bdcc04a9700a6e8ed73fd2a1260ad191af",
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaBanshee.bin": "d3fe66caa6a0ecba96bddb07ac1cbdb915694e87fc1608da0fdabecdf9ffea4d",
"EsteriaBansheeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCentaur.bin": "d63f0b7d21cee67d234d134e832fe6d55c398f2b63f9f6c191dcfa9671637185",
"EsteriaCentaurTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
"EsteriaEthereal.bin": "ada3b7588511a847dd5154d91e3041e9f7f193998b06bfede5e0afc32570b48c",
"EsteriaEtherealTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaFaceless.bin": "1c5a1d7a6b1db6984a8e41bc4804e9f7c50d65dcdbb8c0a9d1a9e8af8c91bd8f",
"EsteriaFacelessTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
"EsteriaHozen.bin": "739bc3775388976f5c09bcbf3a98b62d804dff78d545e25a41d07dd99b5fddc5",
"EsteriaHozenTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaKvItems.bin": "fc5f9d86114234b38dbb0e14a6a5ec16249eaa92a73411a7fc371a950549dcce",
"EsteriaKvSkins.bin": "60b2b899f5f83137368514928f92f3b04c0fae058f534c487ddbe913ee4bec18",
"EsteriaKyrian.bin": "9329147f08805ff4003f9e062fea7c6ea8fdd8c4d6a40de63a6d228ebe1b7c9a",
"EsteriaKyrianTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaMantid.bin": "71536dee6c2abd0b0e13f33bc73cad7e6fb1b0fc1f6912a95c55d57bc7ee1787",
"EsteriaMantidTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
"EsteriaSlime.bin": "491e942ceb6abda83c0249afebae7c9c43af3897b35e45fa33d6f9177ecbc177",
"EsteriaSlimeTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaThinHuman.bin": "bc12e5ca2c087ca0a8642ff6cd8e78fe2e1f85928518b12c19b4245a8320585d",
"EsteriaThinHumanTextures.bin": "27488a7494fa9733b53118d1d0f4acef50a9e19004f81f9c8a614b10f4c3fd5e",
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
"EsteriaVenthyr.bin": "5bcf7804363e59b3c922830d06de17bbd348b9967307f39b7d72bc09f58814eb",
"EsteriaVenthyrTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVorkai.bin": "d6d2088c7e867b5db437e9afc2d323c22d830c6f84a3598415eedcaa27e2461f",
"EsteriaVorkaiTextures.bin": "837774377ca055e6a5c79c1a4cfd8151e7c1f7ce2c16990b00fd445281137433",
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.lua": "062de55c91228971553f482fd2c8753f4752993b4e8e49d4ded04fa18b98bde7",
"Interface/AddOns/CoAQuestSafe/CoAQuestSafe.toc": "890bb9d1087e236f4823603f5df3ab0e316dbb65c28feebbda08fb0ab53a408f",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.toc": "16298c04af68e68d6445e7a11f42aee525dd4145f85d2771ff434fb7c6e95a85",
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
}
File diff suppressed because it is too large. Load diff
+54 -304
View File
@@ -1,11 +1,10 @@
//! Start/stop of a repack-shaped installation by delegating to the repack's own supervisor //! Start/stop of a repack-shaped installation through the repack launcher in this crate
//! (`Runtime\python\python.exe Scripts\manage.py <verb>`), which already implements config rendering, the //! ([`crate::launcher`]): config rendering, the services, the world supervisor, graceful shutdown and readiness.
//! bug-report relay, RA graceful shutdown and readiness. Observation stays native (see `process`). //! It writes the same `.state` records as the repack's `Scripts/manage.py`, so the repack's own launcher and
//! this Manager can be used on the same folder. Observation stays native (see `process`).
use std::io::Read; use std::path::Path;
use std::path::{Path, PathBuf}; use std::sync::Mutex;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use serde::Serialize; use serde::Serialize;
@@ -22,22 +21,13 @@ pub enum Verb {
} }
impl Verb { impl Verb {
fn arg(self) -> &'static str { fn action(self) -> crate::launcher::ops::Action {
use crate::launcher::ops::Action;
match self { match self {
Verb::StartAll => "start-all", Verb::StartAll => Action::StartAll,
Verb::StartMysql => "start-mysql", Verb::StartMysql => Action::StartMysql,
Verb::StartWorld => "start-world", Verb::StartWorld => Action::StartWorld,
Verb::StopAll => "stop-all", Verb::StopAll => Action::StopAll,
}
}
fn timeout(self, _root: &Path) -> Duration {
match self {
// Includes database startup, optional bot provisioning and the shared 25-minute
// world/console wait in launcher_bridge.py, even for older installed scripts.
Verb::StartAll | Verb::StartWorld => Duration::from_secs(3600),
Verb::StartMysql => Duration::from_secs(360),
Verb::StopAll => Duration::from_secs(240),
} }
} }
} }
@@ -52,41 +42,14 @@ pub struct DriverOutcome {
pub output: String, pub output: String,
} }
/// Map the launcher's own messages onto stable error codes. Unknown text stays `Unknown` (details remain visible). fn has_launcher_settings(root: &Path) -> Result<()> {
pub fn translate(output: &str) -> ErrorCode { if !root.join("Settings/repack.json").is_file() {
let o = output.to_lowercase();
if o.contains("is already used") {
ErrorCode::PortInUse
} else if o.contains("another start/stop action is in progress")
|| o.contains("shutdown is still finishing")
{
ErrorCode::OperationInProgress
} else if o.contains("packaged database is missing")
|| o.contains("extract the complete repack")
{
ErrorCode::ServerFilesIncomplete
} else if o.contains("stopped during startup")
|| o.contains("is still starting")
|| o.contains("world startup failed")
{
ErrorCode::StartupFailed
} else if o.contains("invalid port") || o.contains("unresolved placeholder") {
ErrorCode::InvalidConfigValue
} else {
ErrorCode::Unknown
}
}
fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
let python = root.join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py");
if !python.is_file() || !script.is_file() {
return Err(Error::Invalid( return Err(Error::Invalid(
"This server has no CoA Repack launcher; start/stop is not available for it yet." "This server has no CoA Repack launcher; start/stop is not available for it yet."
.into(), .into(),
)); ));
} }
Ok((python, script)) Ok(())
} }
/// Run a launcher verb to completion (blocking; call from a worker thread). /// Run a launcher verb to completion (blocking; call from a worker thread).
@@ -181,6 +144,10 @@ fn run_inner_mode(
} }
if matches!(verb, Verb::StartAll | Verb::StartWorld) { if matches!(verb, Verb::StartAll | Verb::StartWorld) {
crate::modules::ensure_bot_exclusivity(&root)?; crate::modules::ensure_bot_exclusivity(&root)?;
// A server update that only added races keeps the owner's race restriction (and custom races on).
if let Err(error) = crate::race_availability::rebind_unchanged(&root) {
tracing::warn!(%error, "the race restriction could not be checked against the race catalog");
}
} }
if crate::docker::is_docker(&root) { if crate::docker::is_docker(&root) {
prepare_headless_world(&root, verb)?; prepare_headless_world(&root, verb)?;
@@ -205,108 +172,51 @@ fn run_inner_mode(
if matches!(verb, Verb::StartAll | Verb::StartWorld) { if matches!(verb, Verb::StartAll | Verb::StartWorld) {
crate::modules::ensure_bot_exclusivity(&root)?; crate::modules::ensure_bot_exclusivity(&root)?;
} }
let (python, script) = launcher(&root)?; has_launcher_settings(&root)?;
prepare_headless_world(&root, verb)?; prepare_headless_world(&root, verb)?;
let original = std::fs::read_to_string(&script)?;
let patched = patch_launcher_imports(&original)?;
if original != patched {
fsx::atomic_write(&script, patched.as_bytes())?;
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
if meta.original_hashes.get("Scripts/manage.py")
== Some(&fsx::sha256_bytes(original.as_bytes()))
{
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(patched.as_bytes()),
);
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
}
}
}
}
discard_damaged_launcher_state(&root);
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) { if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?; recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
} }
if force { if force {
recover_world_for_forced_stop(&root)?; recover_world_for_forced_stop(&root)?;
} }
let mut cmd = Command::new(&python); let action = if force {
crate::launcher::ops::Action::ForceStopAll
} else {
verb.action()
};
tracing::info!(?verb, root = %root.display(), "driver: starting launcher action");
let lines = Mutex::new(Vec::<String>::new());
let progress = |line: &str| {
tracing::info!(?verb, "launcher: {line}");
lines.lock().unwrap_or_else(|e| e.into_inner()).push(line.to_string());
};
let result = crate::launcher::Settings::load(&root, 0).and_then(|mut cfg| {
if validating_update { if validating_update {
// Isolated startup must use the port from its temporary auth config. // Isolated startup must use the port from its temporary auth config.
cmd.env_remove("AC_REALM_SERVER_PORT"); cfg.env_remove.push("AC_REALM_SERVER_PORT".into());
} }
cmd.arg("-B") crate::launcher::ops::run(&root, &cfg, 0, action, None, &progress)
.arg("-c")
.arg(LAUNCH_SCRIPT)
.arg(&script)
.arg(if force { "force-stop-all" } else { verb.arg() })
.current_dir(&root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
tracing::info!(?verb, root = %root.display(), "driver: starting launcher verb");
let mut child = cmd.spawn()?;
let mut stdout = child.stdout.take().expect("piped");
let mut stderr = child.stderr.take().expect("piped");
let out_t = std::thread::spawn(move || {
let mut s = String::new();
let _ = stdout.read_to_string(&mut s);
s
}); });
let err_t = std::thread::spawn(move || { let mut output = lines.into_inner().unwrap_or_else(|e| e.into_inner()).join("\n");
let mut s = String::new(); let ok = result.is_ok();
let _ = stderr.read_to_string(&mut s); let code = match &result {
s Ok(()) => None,
}); Err(error) => {
let deadline = Instant::now() + verb.timeout(&root); if !output.is_empty() {
let status = loop { output.push('\n');
if let Some(st) = child.try_wait()? {
break Some(st);
}
if Instant::now() > deadline {
// Never kill the servers themselves: only abandon the launcher process we spawned.
let _ = child.kill();
break None;
}
std::thread::sleep(Duration::from_millis(200));
};
let mut output = out_t.join().unwrap_or_default();
output.push_str(&err_t.join().unwrap_or_default());
let mut output = output.trim().to_string();
if status.is_none() {
output.push_str(&format!(
"\nLauncher {} exceeded its {} second deadline; check the server logs.",
verb.arg(),
verb.timeout(&root).as_secs()
));
}
let (ok, exit_code) = match status {
Some(st) => (st.success(), st.code()),
None => (false, None),
};
let code = if ok {
None
} else {
// Log evidence beats the launcher's generic "stopped during startup" message.
let base = if status.is_none() {
ErrorCode::StartupFailed
} else {
translate(&output)
};
match base {
ErrorCode::StartupFailed | ErrorCode::Unknown => {
Some(crate::health::diagnose_installation(&root).unwrap_or(base))
} }
output.push_str(&format!("ERROR: {error}"));
// Log evidence beats a generic "stopped during startup".
match error.code() {
ErrorCode::StartupFailed | ErrorCode::Unknown => Some(
crate::health::diagnose_installation(&root).unwrap_or(error.code()),
),
other => Some(other), other => Some(other),
} }
}
}; };
let exit_code = Some(if ok { 0 } else { 1 });
if code == Some(ErrorCode::PortInUse) { if code == Some(ErrorCode::PortInUse) {
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root)); let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
for service in [&observed.mysql, &observed.auth, &observed.world] for service in [&observed.mysql, &observed.auth, &observed.world]
@@ -374,35 +284,6 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
Ok(()) Ok(())
} }
/// The launcher keeps one JSON record per service in `.state`. A crash or power loss while it writes one can leave
/// a file of the right length that holds only zero bytes (NTFS keeps the length but not the data), and the launcher
/// then dies on every start with an unreadable record. Such a file carries no information, so remove it: the
/// launcher treats a missing record as "not running". Only empty or all-zero `*.json` files are touched.
pub(crate) fn discard_damaged_launcher_state(root: &Path) -> Vec<PathBuf> {
let mut removed = Vec::new();
let Ok(entries) = std::fs::read_dir(root.join(".state")) else {
return removed;
};
for entry in entries.flatten() {
let path = entry.path();
if path
.extension()
.is_none_or(|e| !e.eq_ignore_ascii_case("json"))
|| !path.is_file()
{
continue;
}
let Ok(bytes) = std::fs::read(&path) else {
continue;
};
if bytes.iter().all(|b| *b == 0) && std::fs::remove_file(&path).is_ok() {
tracing::warn!(file = %path.display(), bytes = bytes.len(), "driver: removed a launcher state file damaged by an interrupted write");
removed.push(path);
}
}
removed
}
/// A lost launcher record must not hide this installation's running MySQL from /// A lost launcher record must not hide this installation's running MySQL from
/// graceful shutdown. Adopt only the exact executable owning its configured port. /// graceful shutdown. Adopt only the exact executable owning its configured port.
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> { fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
@@ -453,60 +334,6 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
Ok(()) Ok(())
} }
const LAUNCH_SCRIPT: &str = include_str!("launcher_bridge.py");
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
if !text.contains("from squid_playerbots import") || text.contains(line) {
return Ok(text.into());
}
let root = "ROOT = Path(__file__).resolve().parents[1]";
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
return Err(Error::Invalid(
"The server launcher cannot load its integration scripts. Repair its program files."
.into(),
));
}
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
}
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
if signed.as_bytes() == actual {
return true;
}
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) {
return true;
}
crate::realms::patch_launcher(signed).is_ok_and(|s| {
s.as_bytes() == actual || patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual)
})
}
/// Recover legacy metadata only when undoing supported Manager edits reproduces the recorded hash.
pub(crate) fn launcher_matches_recorded(recorded: &str, actual: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(actual) else {
return false;
};
let without_import = text.replacen(
"ROOT = Path(__file__).resolve().parents[1]\nsys.path.insert(0, str(Path(__file__).resolve().parent))",
"ROOT = Path(__file__).resolve().parents[1]", 1,
);
for candidate in [
Some(without_import.clone()),
crate::realms::unpatch_launcher(&without_import),
]
.into_iter()
.flatten()
{
if crate::fsx::sha256_bytes(candidate.as_bytes()).eq_ignore_ascii_case(recorded)
&& launcher_matches(&candidate, actual)
{
return true;
}
}
false
}
pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String { pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
let code = started let code = started
.code .code
@@ -608,7 +435,7 @@ mod tests {
text.contains("launcher request failed before completion") text.contains("launcher request failed before completion")
&& text.contains("in progress") && text.contains("in progress")
); );
assert!(!text.contains("starting launcher verb")); assert!(!text.contains("starting launcher action"));
} }
#[test] #[test]
@@ -665,78 +492,10 @@ mod tests {
} }
#[test] #[test]
fn slow_world_startup_has_time_with_either_bot_system_without_extending_shutdown() { fn launcher_failures_carry_their_error_code() {
let folder = tempfile::tempdir().unwrap(); let e = Error::Service(ErrorCode::PortInUse, "Port 8085 is already used (PID 4).".into());
let modules = folder.path().join("Core/configs/modules"); assert_eq!(e.code(), ErrorCode::PortInUse);
std::fs::create_dir_all(&modules).unwrap(); assert_eq!(e.to_string(), "Port 8085 is already used (PID 4).");
std::fs::write(
modules.join("playerbots.conf.dist"),
"AiPlayerbot.Enabled = 1\n",
)
.unwrap();
assert_eq!(
Verb::StartAll.timeout(folder.path()),
Duration::from_secs(3600)
);
assert_eq!(
Verb::StopAll.timeout(folder.path()),
Duration::from_secs(240)
);
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
assert_eq!(
Verb::StartWorld.timeout(folder.path()),
Duration::from_secs(3600)
);
assert_eq!(
Verb::StartMysql.timeout(folder.path()),
Duration::from_secs(360)
);
}
#[test]
fn zero_filled_launcher_state_is_discarded_and_valid_state_is_kept() {
let folder = tempfile::tempdir().unwrap();
let state = folder.path().join(".state");
std::fs::create_dir_all(&state).unwrap();
std::fs::write(state.join("mysql.json"), vec![0u8; 116]).unwrap();
std::fs::write(state.join("configuration.json"), Vec::<u8>::new()).unwrap();
std::fs::write(state.join("world.json"), "{\"pid\": 4}\n").unwrap();
std::fs::write(state.join("stop-relay"), Vec::<u8>::new()).unwrap();
std::fs::write(state.join("auth.json"), "{\"pid\": 0}").unwrap();
let mut removed: Vec<_> = discard_damaged_launcher_state(folder.path())
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
removed.sort();
assert_eq!(removed, ["configuration.json", "mysql.json"]);
assert!(
state.join("world.json").exists()
&& state.join("auth.json").exists()
&& state.join("stop-relay").exists()
);
assert!(discard_damaged_launcher_state(folder.path()).is_empty());
assert!(discard_damaged_launcher_state(&folder.path().join("missing")).is_empty());
}
#[test]
fn translates_known_launcher_messages() {
assert_eq!(
translate("RuntimeError: Port 8085 is already used. Stop the other server"),
ErrorCode::PortInUse
);
assert_eq!(
translate("Another start/stop action is in progress."),
ErrorCode::OperationInProgress
);
assert_eq!(
translate("The packaged database is missing. Extract the complete repack."),
ErrorCode::ServerFilesIncomplete
);
assert_eq!(
translate("world stopped during startup. Check its log."),
ErrorCode::StartupFailed
);
assert_eq!(translate("Exit code -1073741819"), ErrorCode::Unknown);
} }
#[test] #[test]
@@ -779,13 +538,4 @@ mod tests {
assert!(!reason.contains("private")); assert!(!reason.contains("private"));
assert!(!reason.contains("Something went wrong")); assert!(!reason.contains("Something went wrong"));
} }
#[test]
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
let fixed = patch_launcher_imports(text).unwrap();
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
assert!(fixed.ends_with("custom = 42\n"));
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
}
} }
+4
View File
@@ -24,6 +24,9 @@ pub enum Error {
UnknownInstallation(String), UnknownInstallation(String),
#[error("{0}")] #[error("{0}")]
Invalid(String), Invalid(String),
/// A server start or stop failed for a reason the UI can explain (the repack launcher's own errors).
#[error("{1}")]
Service(ErrorCode, String),
#[error("package not published: {0}")] #[error("package not published: {0}")]
PackageNotPublished(String), PackageNotPublished(String),
#[error("download server unreachable: {0}")] #[error("download server unreachable: {0}")]
@@ -199,6 +202,7 @@ impl Error {
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished, Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable, Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
Error::BotModulesConflict => ErrorCode::BotModulesConflict, Error::BotModulesConflict => ErrorCode::BotModulesConflict,
Error::Service(code, _) => *code,
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing, Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported, Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
_ => ErrorCode::Unknown, _ => ErrorCode::Unknown,
+25
View File
@@ -0,0 +1,25 @@
//! The repack launcher in Rust: what `Scripts/manage.py` does, without Python.
//!
//! Formats on disk stay exactly those of `manage.py`, so the two can be used on the same server during the move
//! (an old `.bat` and a new Manager, or the other way round):
//!
//! * `.state/<service>.json` process records `{pid, exe, created}` (see [`crate::process::ProcessIdentity`]);
//! * `.state/control.lock` one start/stop action at a time: byte 0 locked, as `msvcrt.locking` does;
//! * `.state/control-owner.json`, `.state/configuration.json`, `.state/debug-logs.json`;
//! * the rendered configs (`Core/configs/*.conf`, `mysql/my.ini`, `mysql/admin-client.ini`) byte for byte.
//!
//! State files are written with a flush to disk before they replace the old ones (`manage.py` did not, and a
//! power cut could leave a zero-filled record that stopped every later start).
pub mod ops;
pub mod relay;
pub mod render;
pub mod schedule;
pub mod services;
pub mod settings;
pub mod spawn;
pub mod squid;
pub mod state;
pub mod world;
pub use settings::Settings;
+103
View File
@@ -0,0 +1,103 @@
//! One start/stop action of a repack, with the control lock held (`manage.py main()`): the entry point of both
//! `coa-launcher.exe` and the Manager.
use std::path::Path;
use std::time::Duration;
use crate::error::Result;
use crate::launcher::services::{self, Progress};
use crate::launcher::world::{self, Supervisor};
use crate::launcher::{render, settings::Settings, squid, state};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
StartAll,
StartMysql,
StartAuth,
StartWorld,
StopAll,
/// Stop the world without its console first (unsaved progress is lost), then everything else.
ForceStopAll,
Prepare,
}
impl Action {
/// The command name, as the `.bat` files and `manage.py` call it.
pub fn name(self) -> &'static str {
match self {
Action::StartAll => "start-all",
Action::StartMysql => "start-mysql",
Action::StartAuth => "start-auth",
Action::StartWorld => "start-world",
Action::StopAll => "stop-all",
Action::ForceStopAll => "force-stop-all",
Action::Prepare => "prepare",
}
}
pub fn parse(name: &str) -> Option<Action> {
[
Action::StartAll,
Action::StartMysql,
Action::StartAuth,
Action::StartWorld,
Action::StopAll,
Action::ForceStopAll,
Action::Prepare,
]
.into_iter()
.find(|a| a.name() == name)
}
}
/// Run `action`. A started world is supervised by `supervisor`, or by what the repack ships when it is `None`.
pub fn run(root: &Path, cfg: &Settings, offset: i32, action: Action, supervisor: Option<&Supervisor>, progress: Progress) -> Result<()> {
let _lock = state::ControlLock::acquire(root, action.name(), Duration::from_secs(30), progress)?;
match action {
// Shutdown uses the existing client and console settings: the templates may be exactly what a recovery
// needs to replace, so nothing is rendered.
Action::StopAll => return services::stop_all(root, cfg, progress),
Action::ForceStopAll => return services::force_stop_all(root, cfg, progress),
_ => {}
}
if matches!(action, Action::StartAll | Action::StartWorld) {
squid::validate_bots(root)?;
}
let relocated;
let cfg = match action {
Action::StartAll | Action::StartMysql | Action::StartAuth | Action::StartWorld => {
match services::relocate_database_port(root, cfg, offset, progress)? {
Some(_) => {
let mut moved = Settings::load(root, offset)?;
moved.env_remove = cfg.env_remove.clone();
relocated = moved;
&relocated
}
None => cfg,
}
}
_ => cfg,
};
render::prepare(root, cfg)?;
if action == Action::Prepare {
return Ok(());
}
if matches!(action, Action::StartAll | Action::StartMysql) {
services::start_mysql(root, cfg, progress)?;
}
if matches!(action, Action::StartAll | Action::StartAuth) {
services::start_auth(root, cfg, progress)?;
}
if matches!(action, Action::StartAll | Action::StartWorld) {
let shipped;
let supervisor = match supervisor {
Some(s) => s,
None => {
shipped = Supervisor::of(root)?;
&shipped
}
};
world::start_world(root, cfg, offset, supervisor, progress)?;
}
Ok(())
}
+493
View File
@@ -0,0 +1,493 @@
//! The bug-report relay (`BugReport/relay.py` and `manage.py relay-worker`): delivers the reports the world
//! writes to `BugReport/reports/*.report` through the CoA report service.
//!
//! On disk everything stays as the Python relay keeps it, so either can take over a spool: the `<key>.status`
//! files the world reads back, the delivery journal `relay.sqlite3` (tables `deliveries` and `settings`), and
//! `relay.lock` (byte 0 locked while a worker runs). A delivery interrupted while it was posting becomes
//! `uncertain` and is never sent again (the service's duplicate filter may have been reset in the meantime).
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use rusqlite::{params, Connection, OptionalExtension};
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
use crate::launcher::state;
const REPOSITORY: &str = "jealous-sound/azerothcore-wotlk-coa";
pub const SERVICE_URL: &str = "https://coa-bug-report.up.railway.app";
/// Distribution credential for this narrow intake API (the same as relay.py's); not a GitHub token.
pub const DEFAULT_API_KEY: &str = "coa_zRatxUHShOn-HEkoreKGME6sd3DdMG7eKTTKlj2JCK4";
const MAX_FILE: u64 = 16000;
const MAX_RESPONSE: usize = 64 * 1024;
/// `[1-9][0-9]{0,9}-[0-9a-f]{16,48}`: the name of a report file (without `.report`).
pub fn valid_key(key: &str) -> bool {
let Some((id, hex)) = key.split_once('-') else { return false };
(1..=10).contains(&id.len())
&& !id.starts_with('0')
&& id.bytes().all(|b| b.is_ascii_digit())
&& (16..=48).contains(&hex.len())
&& hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
/// Why a delivery did not create an issue. Only fixed local codes: never service bodies, credentials or report
/// content.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
/// 202 pending: the service is still creating it.
Pending(u64),
/// 429: try again later.
Limited(u64),
/// The report itself was refused.
Invalid,
/// The service refused this relay (redirect, auth, missing endpoint, GitHub access).
Blocked(u64),
/// The outcome is unknown (network, timeout, unexpected answer).
Uncertain,
}
/// Where reports go.
pub trait Service {
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure>;
}
/// The CoA report service over HTTPS.
pub struct ReportService {
api: String,
key: String,
client: reqwest::blocking::Client,
}
impl ReportService {
pub fn new(base_url: &str, api_key: &str) -> Result<ReportService> {
if api_key.is_empty() || !api_key.is_ascii() || api_key.chars().any(char::is_whitespace) {
return Err(Error::Invalid("Configure a valid report-service intake key.".into()));
}
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(30))
// One report every few seconds at most: a fresh connection each time, never a stale pooled one.
.pool_max_idle_per_host(0)
.user_agent("CoA-InGame-BugReport/1")
.build()
.map_err(|e| Error::Invalid(format!("The report client could not start: {e}")))?;
Ok(ReportService { api: format!("{base_url}/v1/reports"), key: api_key.into(), client })
}
}
/// `Retry-After` in seconds, kept within 1 s .. 1 day; `default` when absent or not a number.
fn retry_delay(retry_after: Option<&str>, default: u64) -> u64 {
retry_after.and_then(|v| v.trim().parse::<i64>().ok()).map_or(default, |v| v.clamp(1, 86400) as u64)
}
/// A JSON object of at most 64 KiB, or nothing.
fn json_object(raw: Option<&[u8]>) -> Option<serde_json::Map<String, serde_json::Value>> {
let raw = raw?;
if raw.len() > MAX_RESPONSE {
return None;
}
match serde_json::from_slice(raw).ok()? {
serde_json::Value::Object(map) => Some(map),
_ => None,
}
}
fn issue_number(data: &serde_json::Map<String, serde_json::Value>) -> std::result::Result<u64, Failure> {
let number = data.get("issue_number").and_then(|n| if n.is_u64() { n.as_u64() } else { None });
match number {
Some(n)
if data.get("status").and_then(|s| s.as_str()) == Some("created")
&& (1..=4294967295).contains(&n)
&& data.get("issue_url").and_then(|u| u.as_str())
== Some(format!("https://github.com/{REPOSITORY}/issues/{n}").as_str()) =>
{
Ok(n)
}
_ => Err(Failure::Uncertain),
}
}
/// What a service answer means (relay.py's `create`): the status, its `Retry-After` and its body (`None` when it
/// could not be read or was longer than 64 KiB).
pub fn classify(status: u16, retry_after: Option<&str>, body: Option<&[u8]>) -> std::result::Result<u64, Failure> {
let field = |data: &serde_json::Map<String, serde_json::Value>, k: &str| data.get(k).and_then(|v| v.as_str()).map(str::to_owned);
match status {
200..=202 => {
let data = json_object(body).ok_or(Failure::Uncertain)?;
match status {
202 if field(&data, "status").as_deref() == Some("pending") => Err(Failure::Pending(retry_delay(retry_after, 2))),
202 => Err(Failure::Uncertain),
_ => issue_number(&data),
}
}
429 => Err(Failure::Limited(retry_delay(retry_after, 300))),
400 | 413 | 415 | 422 => Err(Failure::Invalid),
301 | 302 | 303 | 307 | 308 | 401 | 403 | 404 | 405 => Err(Failure::Blocked(300)),
503 => {
let data = json_object(body).unwrap_or_default();
if field(&data, "status").as_deref() == Some("failed") && field(&data, "error").as_deref() == Some("github_access_denied") {
Err(Failure::Blocked(retry_delay(retry_after, 300)))
} else {
Err(Failure::Uncertain)
}
}
_ => Err(Failure::Uncertain),
}
}
impl Service for ReportService {
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure> {
use std::io::Read;
let sent = self
.client
.post(&self.api)
.header("Authorization", format!("Bearer {}", self.key))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.body(serde_json::json!({ "title": title, "body": body }).to_string())
.send();
let response = sent.map_err(|_| Failure::Uncertain)?;
let status = response.status().as_u16();
let retry_after = response.headers().get("Retry-After").and_then(|v| v.to_str().ok()).map(str::to_owned);
let mut raw = Vec::new();
let read = response.take(MAX_RESPONSE as u64 + 1).read_to_end(&mut raw).is_ok() && raw.len() <= MAX_RESPONSE;
classify(status, retry_after.as_deref(), read.then_some(raw.as_slice()))
}
}
/// A report: `COABUG1\n<title>\n<body>`, checked as the world writes it.
pub struct Report {
pub digest: String,
pub marker: String,
pub title: String,
pub body: String,
}
pub fn read_report(path: &Path) -> Result<Report> {
let bad = || Error::Invalid("Invalid report file".into());
let key = path.file_stem().and_then(|s| s.to_str()).ok_or_else(bad)?;
let meta = std::fs::symlink_metadata(path)?;
if !valid_key(key) || meta.file_type().is_symlink() || meta.len() > MAX_FILE {
return Err(bad());
}
let raw = std::fs::read(path)?;
let text = String::from_utf8(raw.clone()).map_err(|_| bad())?.replace("\r\n", "\n");
let rest = text.strip_prefix("COABUG1\n").ok_or_else(|| Error::Invalid("Unsupported report format".into()))?;
let invalid = || Error::Invalid("Invalid report content".into());
let (title, body) = rest.split_once('\n').ok_or_else(invalid)?;
if !(3..=200).contains(&title.len())
|| body.trim().is_empty()
|| title.chars().any(|c| (c as u32) < 32)
|| body.chars().any(|c| (c as u32) < 32 && !matches!(c, '\r' | '\n' | '\t'))
{
return Err(invalid());
}
let digest = hex(&Sha256::digest(&raw));
let id = hex(&Sha256::digest(format!("{key}:{digest}").as_bytes()));
Ok(Report { digest, marker: format!("<!-- coa-report:{id} -->"), title: title.into(), body: body.into() })
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// `<key>.status`: what the world shows the player (`queued`, `created|<issue>`, `failed`, ...).
pub fn write_status(spool: &Path, key: &str, state: &str, number: Option<u64>) -> Result<()> {
let value = match (state, number) {
("created", Some(n)) => format!("created|{n}"),
("created", None) => "created|None".into(),
_ => state.to_string(),
};
let data = format!("{value}\n");
let destination = spool.join(format!("{key}.status"));
if std::fs::read(&destination).is_ok_and(|d| d == data.as_bytes()) {
return Ok(());
}
crate::fsx::atomic_write(&destination, data.as_bytes())
}
fn now() -> f64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
}
/// The delivery journal of one spool.
pub struct Relay<S: Service> {
spool: PathBuf,
service: S,
db: Connection,
clock: Box<dyn Fn() -> f64 + Send>,
}
impl<S: Service> Relay<S> {
pub fn open(spool: &Path, service: S) -> Result<Relay<S>> {
Self::with_clock(spool, service, Box::new(now))
}
pub fn with_clock(spool: &Path, service: S, clock: Box<dyn Fn() -> f64 + Send>) -> Result<Relay<S>> {
let db = Connection::open(spool.join("relay.sqlite3")).map_err(sql)?;
db.execute_batch(
"PRAGMA synchronous=FULL;
CREATE TABLE IF NOT EXISTS deliveries (
key TEXT PRIMARY KEY, digest TEXT NOT NULL, marker TEXT NOT NULL, state TEXT NOT NULL,
number INTEGER, attempted REAL NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value REAL NOT NULL);
UPDATE deliveries SET state='uncertain' WHERE state='posting';",
)
.map_err(sql)?;
Ok(Relay { spool: spool.into(), service, db, clock })
}
fn set_state(&self, key: &str, state: &str, number: Option<u64>, delay: u64) -> Result<()> {
self.db
.execute(
"UPDATE deliveries SET state=?1, number=?2, next_try=?3 WHERE key=?4",
params![state, number.map(|n| n as i64), (self.clock)() + delay as f64, key],
)
.map_err(sql)?;
write_status(&self.spool, key, state, number)
}
fn set_network_gate(&self, delay: u64) -> Result<()> {
self.db
.execute("INSERT OR REPLACE INTO settings VALUES('next_network',?1)", params![(self.clock)() + delay as f64])
.map_err(sql)?;
Ok(())
}
/// Handle one report file; returns its delivery state.
pub fn process(&self, path: &Path) -> Result<String> {
let Some(key) = path.file_stem().and_then(|s| s.to_str()).filter(|k| valid_key(k)) else {
return Ok("ignored".into());
};
let report = match read_report(path) {
Ok(r) => r,
Err(_) => {
write_status(&self.spool, key, "failed", None)?;
return Ok("failed".into());
}
};
self.db
.execute(
"INSERT OR IGNORE INTO deliveries(key,digest,marker,state) VALUES(?1,?2,?3,'queued')",
params![key, report.digest, report.marker],
)
.map_err(sql)?;
let (digest, row_state, number, next_try): (String, String, Option<i64>, f64) = self
.db
.query_row("SELECT digest, state, number, next_try FROM deliveries WHERE key=?1", params![key], |r| {
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
})
.map_err(sql)?;
let number = number.map(|n| n as u64);
if digest != report.digest {
// Never replace an existing delivery or publish edited content under the same ID.
write_status(&self.spool, key, "failed", None)?;
return Ok("changed".into());
}
if matches!(row_state.as_str(), "created" | "failed" | "uncertain") {
write_status(&self.spool, key, &row_state, number)?;
return Ok(row_state);
}
if next_try > (self.clock)() {
write_status(&self.spool, key, &row_state, None)?;
return Ok(row_state);
}
let gate: Option<f64> = self
.db
.query_row("SELECT value FROM settings WHERE key='next_network'", [], |r| r.get(0))
.optional()
.map_err(sql)?;
if gate.is_some_and(|g| g > (self.clock)()) {
write_status(&self.spool, key, &row_state, None)?;
return Ok(row_state);
}
self.set_network_gate(5)?;
// A crash after this point needs review: the service's duplicate cache can reset on deploy.
self.db
.execute("UPDATE deliveries SET state='posting', attempted=?1 WHERE key=?2", params![(self.clock)(), key])
.map_err(sql)?;
match self.service.create(&report.title, &report.body) {
Ok(n) => {
self.set_state(key, "created", Some(n), 0)?;
Ok("created".into())
}
Err(failure) => {
let (state, delay) = match failure {
Failure::Limited(d) | Failure::Pending(d) => ("queued", d),
Failure::Blocked(d) => ("blocked", d),
Failure::Invalid => ("failed", 300),
Failure::Uncertain => ("uncertain", 300),
};
self.set_state(key, state, None, delay)?;
if let Failure::Limited(d) | Failure::Blocked(d) = failure {
self.set_network_gate(d)?;
}
Ok(state.into())
}
}
}
/// One pass over the spool, in name order.
pub fn pass(&self) -> Result<()> {
let mut reports: Vec<PathBuf> = std::fs::read_dir(&self.spool)?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x == "report"))
.collect();
reports.sort();
for path in reports {
self.process(&path)?;
}
Ok(())
}
}
fn sql(e: rusqlite::Error) -> Error {
Error::Invalid(format!("The bug-report journal failed ({e})."))
}
/// `relay-worker`: deliver reports until the supervisor asks the relay to stop (`.state/stop-relay`).
pub fn worker(root: &Path) -> Result<()> {
let spool = root.join("BugReport/reports");
std::fs::create_dir_all(&spool)?;
let _lock = state::FileLock::try_acquire(&spool.join("relay.lock"))?
.ok_or_else(|| Error::Invalid("Another bug-report relay is already using this spool.".into()))?;
let key = std::env::var("COA_BUGREPORT_API_KEY").unwrap_or_else(|_| DEFAULT_API_KEY.into());
let relay = Relay::open(&spool, ReportService::new(SERVICE_URL, &key)?)?;
state::record(root, "relay-ready", std::process::id())?;
println!("Bug-report relay ready. Waiting for in-game reports.");
let stop = state::dir(root).join("stop-relay");
while !stop.exists() {
relay.pass()?;
for _ in 0..10 {
if stop.exists() {
return Ok(());
}
std::thread::sleep(Duration::from_millis(500));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
type Answers = Arc<Mutex<Vec<std::result::Result<u64, Failure>>>>;
struct Fake(Answers, Arc<Mutex<u32>>);
impl Service for Fake {
fn create(&self, _: &str, _: &str) -> std::result::Result<u64, Failure> {
*self.1.lock().unwrap() += 1;
self.0.lock().unwrap().remove(0)
}
}
fn report(spool: &Path, key: &str, text: &str) -> PathBuf {
let p = spool.join(format!("{key}.report"));
std::fs::write(&p, text).unwrap();
p
}
#[test]
fn keys_follow_the_world_format() {
assert!(valid_key("1-0123456789abcdef"));
assert!(valid_key("4294967295-0123456789abcdef0123456789abcdef0123456789abcdef"));
for bad in ["0-0123456789abcdef", "1-0123456789abcde", "1-0123456789ABCDEF", "12345678901-0123456789abcdef", "x"] {
assert!(!valid_key(bad), "{bad}");
}
}
#[test]
fn service_answers_map_like_relay_py() {
let ok = format!(r#"{{"status":"created","issue_number":12,"issue_url":"https://github.com/{REPOSITORY}/issues/12"}}"#);
let cases: Vec<(u16, Option<&str>, Option<&[u8]>, std::result::Result<u64, Failure>)> = vec![
(201, None, Some(ok.as_bytes()), Ok(12)),
(200, None, Some(ok.as_bytes()), Ok(12)),
(201, None, Some(br#"{"status":"created","issue_number":12,"issue_url":"https://evil/12"}"#), Err(Failure::Uncertain)),
(201, None, Some(br#"{"status":"created","issue_number":0,"issue_url":"x"}"#), Err(Failure::Uncertain)),
(201, None, Some(b"[1]"), Err(Failure::Uncertain)),
(201, None, None, Err(Failure::Uncertain)),
(202, Some("7"), Some(br#"{"status":"pending"}"#), Err(Failure::Pending(7))),
(202, None, Some(br#"{"status":"pending"}"#), Err(Failure::Pending(2))),
(202, None, Some(br#"{"status":"other"}"#), Err(Failure::Uncertain)),
(429, Some("999999"), None, Err(Failure::Limited(86400))),
(429, Some("0"), None, Err(Failure::Limited(1))),
(429, Some("soon"), None, Err(Failure::Limited(300))),
(422, None, None, Err(Failure::Invalid)),
(302, None, None, Err(Failure::Blocked(300))),
(401, None, None, Err(Failure::Blocked(300))),
(503, Some("30"), Some(br#"{"status":"failed","error":"github_access_denied"}"#), Err(Failure::Blocked(30))),
(503, None, Some(b"{}"), Err(Failure::Uncertain)),
(500, None, None, Err(Failure::Uncertain)),
];
for (i, (status, retry, body, expected)) in cases.into_iter().enumerate() {
assert_eq!(classify(status, retry, body), expected, "case {i}");
}
assert!(json_object(Some(&vec![b' '; MAX_RESPONSE + 1])).is_none(), "oversized answers are refused");
assert!(ReportService::new(SERVICE_URL, "has space").is_err());
assert!(ReportService::new(SERVICE_URL, "coa_key").is_ok());
}
#[test]
fn a_report_is_checked_and_identified_like_relay_py() {
let d = tempfile::tempdir().unwrap();
let p = report(d.path(), "7-0123456789abcdef", "COABUG1\r\nBroken quest\r\nThe NPC is missing.\r\n");
let r = read_report(&p).unwrap();
assert_eq!(r.title, "Broken quest");
assert_eq!(r.body, "The NPC is missing.\n");
assert_eq!(r.digest, hex(&Sha256::digest(std::fs::read(&p).unwrap())));
assert!(r.marker.starts_with("<!-- coa-report:") && r.marker.len() == 16 + 64 + 4);
for bad in ["COABUG2\nTitle\nBody", "COABUG1\nab\nBody", "COABUG1\nTitle\n \n", "COABUG1\nTi\u{7}tle\nBody", "COABUG1\nTitle"] {
std::fs::write(&p, bad).unwrap();
assert!(read_report(&p).is_err(), "{bad:?}");
}
}
#[test]
fn deliveries_follow_the_journal() {
let d = tempfile::tempdir().unwrap();
let spool = d.path();
let t = Arc::new(Mutex::new(1000.0f64));
let calls = Arc::new(Mutex::new(0));
let answers: Answers = Arc::new(Mutex::new(vec![Err(Failure::Limited(60)), Ok(42)]));
let clock = t.clone();
let relay = Relay::with_clock(spool, Fake(answers, calls.clone()), Box::new(move || *clock.lock().unwrap())).unwrap();
let p = report(spool, "7-0123456789abcdef", "COABUG1\nBroken quest\nThe NPC is missing.\n");
let status = || std::fs::read_to_string(spool.join("7-0123456789abcdef.status")).unwrap();
assert_eq!(relay.process(&p).unwrap(), "queued", "429 keeps it queued");
assert_eq!(status(), "queued\n");
assert_eq!(relay.process(&p).unwrap(), "queued", "not before its retry time");
assert_eq!(*calls.lock().unwrap(), 1);
*t.lock().unwrap() += 61.0;
assert_eq!(relay.process(&p).unwrap(), "created");
assert_eq!(status(), "created|42\n");
assert_eq!(relay.process(&p).unwrap(), "created", "never sent twice");
assert_eq!(*calls.lock().unwrap(), 2);
std::fs::write(&p, "COABUG1\nBroken quest\nEdited.\n").unwrap();
assert_eq!(relay.process(&p).unwrap(), "changed");
relay
.db
.execute("INSERT INTO deliveries(key,digest,marker,state) VALUES('8-0123456789abcdef','x','m','posting')", [])
.unwrap();
drop(relay);
let reopened = Relay::open(spool, Fake(Arc::new(Mutex::new(vec![])), calls.clone())).unwrap();
let state: String =
reopened.db.query_row("SELECT state FROM deliveries WHERE key='8-0123456789abcdef'", [], |r| r.get(0)).unwrap();
assert_eq!(state, "uncertain", "an interrupted post is never retried");
}
#[test]
fn a_second_worker_cannot_take_the_spool() {
let d = tempfile::tempdir().unwrap();
let first = state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap();
assert!(first.is_some());
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_none());
drop(first);
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_some());
}
}
+367
View File
@@ -0,0 +1,367 @@
//! `prepare`: the configuration files a repack runs with, rendered from `Settings/*.template` and
//! `Settings/repack.json` (`manage.py prepare()`), byte for byte the same.
use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
use crate::launcher::{settings::Settings, state};
/// Services whose running process blocks moving the folder or changing ports.
const SERVICES: [&str; 5] = ["mysql", "auth", "world", "supervisor", "relay"];
/// The root as the servers see it: forward slashes, and the short (8.3) form when the real one has non-Latin
/// letters, which MySQL and the servers do not read reliably from their config files.
pub fn native_root(root: &Path) -> Result<String> {
let mut value = root.to_string_lossy().into_owned();
if !value.is_ascii() {
if let Some(short) = sys::short_path(root) {
value = short;
}
}
if !value.is_ascii() {
return Err(Error::Invalid(
"Extract the repack to a path with Latin letters, such as C:\\Games\\CoA-Repack.".into(),
));
}
Ok(value.replace('\\', "/"))
}
/// Text as Python's text mode reads it: strict UTF-8, Windows and old Mac line ends turned into "\n".
fn read_text(path: &Path) -> Result<String> {
let bytes = std::fs::read(path)?;
let text = String::from_utf8(bytes).map_err(|_| Error::Invalid(format!("{} is not UTF-8 text.", path.display())))?;
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
}
/// Text written as Python's text mode writes it on Windows: "\n" becomes "\r\n".
fn windows_text(text: &str) -> Vec<u8> {
if cfg!(windows) {
text.replace('\n', "\r\n").into_bytes()
} else {
text.as_bytes().to_vec()
}
}
fn placeholders(line: &str) -> Vec<String> {
let mut out = Vec::new();
let bytes = line.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'@' {
let mut j = i + 1;
while j < bytes.len() && (bytes[j].is_ascii_alphabetic() || bytes[j] == b'_') {
j += 1;
}
if j < bytes.len() && j > i + 1 && bytes[j] == b'@' {
out.push(line[i..=j].to_string());
i = j + 1;
continue;
}
}
i += 1;
}
out
}
fn credentials(root: &Path) -> Result<(String, String)> {
let v: serde_json::Value = crate::fsx::read_json(&root.join("Settings/database.json"))?;
let good = |k: &str| {
v.get(k)
.and_then(|x| x.as_str())
.filter(|s| s.len() == 48 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
.map(str::to_string)
};
match (good("rootPassword"), good("appPassword")) {
(Some(r), Some(a)) => Ok((r, a)),
_ => Err(Error::Invalid("Invalid packaged database configuration.".into())),
}
}
/// Render every file the repack's services read. Refuses while a service runs and the folder or the ports
/// changed since the last render.
pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
let base = native_root(root)?;
let signature = serde_json::json!({
"root": root.to_string_lossy(),
"ports": serde_json::Value::Object(config.port_map()),
});
let previous = state::dir(root).join("configuration.json");
if previous.exists() {
let recorded: Option<serde_json::Value> = crate::fsx::read_json(&previous).ok();
if recorded.as_ref() != Some(&signature) && SERVICES.iter().any(|s| state::running(root, s).is_some()) {
return Err(Error::Invalid("Stop this repack before moving its folder or changing its ports.".into()));
}
}
let (root_password, app_password) = credentials(root)?;
for folder in ["Core/configs/modules", "Core/Logs", "BugReport/reports", "BugReport/Logs", "mysql/logs", ".state"] {
std::fs::create_dir_all(root.join(folder))?;
}
let mysql_port = config.mysql_port;
let mut values: Vec<(&str, String)> = vec![
("DATA", format!("{base}/Data")),
("LOGS", format!("{base}/Core/Logs")),
("ASCENSION_DBC", format!("{base}/Data/dbc/Ascension")),
("MYSQL_EXE", format!("{base}/mysql/bin/mysql.exe")),
("AUTH_PORT", config.auth_port.to_string()),
("WORLD_PORT", config.world_port.to_string()),
("RA_PORT", config.ra_port.to_string()),
];
for (key, db) in [
("LoginDatabaseInfo", "acore_auth"),
("WorldDatabaseInfo", config.realm.world_db),
("CharacterDatabaseInfo", config.realm.characters_db),
] {
values.push((key, format!("127.0.0.1;{mysql_port};acore;{app_password};{db}")));
}
let mut written = Vec::new();
for (name, target) in [
("authserver.conf", "Core/configs/authserver.conf"),
("worldserver.conf", "Core/configs/worldserver.conf"),
("mod_ascension_compat.conf", "Core/configs/modules/mod_ascension_compat.conf"),
] {
let mut text = read_text(&root.join("Settings").join(format!("{name}.template")))?;
for (key, value) in &values {
text = text.replace(&format!("@{key}@"), value);
}
let mut unresolved: Vec<String> = text
.split('\n')
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
.flat_map(placeholders)
.collect();
unresolved.sort();
unresolved.dedup();
if !unresolved.is_empty() {
return Err(Error::Service(
crate::error::ErrorCode::InvalidConfigValue,
format!("An unresolved placeholder remains in Settings/{name}.template: {}", unresolved.join(", ")),
));
}
// these three keep "\n" (Python wrote them with newline="\n")
std::fs::write(root.join(target), text.as_bytes())?;
written.push(root.join(target));
}
let custom = custom_mysql_options(root);
let files: [(&str, String); 3] = [
(
"Core/configs/modules/coa_bugreport.conf",
format!(
"# Managed by the repack launcher. Enabled whenever worldserver starts.\nCoABugReport.Enable = 1\nCoABugReport.SpoolDirectory = \"{base}/BugReport/reports\"\nCoABugReport.CooldownSeconds = 120\n"
),
),
(
"mysql/my.ini",
format!(
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n{custom}"
),
),
(
"mysql/admin-client.ini",
format!(
"[client]\nuser=root\npassword={root_password}\nhost=127.0.0.1\nport={mysql_port}\nprotocol=tcp\ndefault-character-set=utf8mb4\n"
),
),
];
for (rel, text) in files {
std::fs::write(root.join(rel), windows_text(&text))?;
written.push(root.join(rel));
}
state::write_json(&previous, &signature)?;
Ok(written)
}
/// The owner's file of extra MySQL options; the launcher rewrites `mysql/my.ini` at every start.
pub const CUSTOM_MYSQL: &str = "Settings/mysql-custom.ini";
/// The owner's MySQL options as written, and the lines a start will add to `[mysqld]`.
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomMysql {
pub text: String,
pub applied: String,
}
pub fn read_custom_mysql(root: &Path) -> CustomMysql {
let text = std::fs::read(root.join(CUSTOM_MYSQL))
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default();
CustomMysql { text, applied: custom_mysql_options(root) }
}
/// Save the owner's MySQL options; they apply at the next start of the database.
pub fn write_custom_mysql(root: &Path, text: &str) -> Result<CustomMysql> {
if text.len() > 16 * 1024 || text.contains(char::from(0)) {
return Err(Error::Invalid("The MySQL options must be plain text of at most 16 KB.".into()));
}
crate::fsx::atomic_write(&root.join(CUSTOM_MYSQL), text.replace("\r\n", "\n").as_bytes())?;
Ok(read_custom_mysql(root))
}
/// Options the server cannot run without, which only the launcher sets.
const MANAGED_MYSQL_OPTIONS: [&str; 10] = [
"basedir",
"datadir",
"port",
"bind-address",
"mysqlx",
"log-error",
"pid-file",
"socket",
"skip-networking",
"defaults-file",
];
/// `name = value` lines of the owner's file (outside any section or in `[mysqld]`), as lines for `[mysqld]`.
/// Comments, other sections, `!include` and the options the launcher manages are left out.
pub fn custom_mysql_options(root: &Path) -> String {
let Ok(bytes) = std::fs::read(root.join(CUSTOM_MYSQL)) else {
return String::new();
};
let text = String::from_utf8_lossy(&bytes);
let mut in_mysqld = true;
let mut out = String::new();
for line in text.trim_start_matches('\u{feff}').lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
if line.starts_with('[') {
in_mysqld = line.eq_ignore_ascii_case("[mysqld]");
continue;
}
if !in_mysqld || line.starts_with('!') {
continue;
}
let name = line
.split('=')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
.replace('_', "-");
let name = name.strip_prefix("loose-").unwrap_or(&name);
if name.is_empty() || MANAGED_MYSQL_OPTIONS.contains(&name) {
continue;
}
out.push_str(line);
out.push('\n');
}
out
}
#[cfg(windows)]
mod sys {
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
pub fn short_path(path: &Path) -> Option<String> {
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut buf = vec![0u16; 32768];
let n = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };
(n > 0 && (n as usize) < buf.len()).then(|| String::from_utf16_lossy(&buf[..n as usize]))
}
}
#[cfg(not(windows))]
mod sys {
pub fn short_path(_: &std::path::Path) -> Option<String> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
pub(crate) fn fixture(root: &Path) {
let w = |rel: &str, text: &[u8]| {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
};
w("Settings/repack.json", br#"{"authPort": 3724, "mysqlPort": 3307, "raPassword": "e0c39beaa5c14128", "raPort": 3443, "raUsername": "COAMANAGER", "worldPort": 8085}"#);
w("Settings/database.json", format!(r#"{{"rootPassword": "{}", "appPassword": "{}"}}"#, "a".repeat(48), "0123456789abcdef".repeat(3)).as_bytes());
w("Settings/authserver.conf.template", b"[authserver]\r\nLoginDatabaseInfo = \"@LoginDatabaseInfo@\"\r\nRealmServerPort = @AUTH_PORT@\r\nLogsDir = \"@LOGS@\"\r\n# @NOT_A_VALUE@ in a comment is fine\r\n");
w("Settings/worldserver.conf.template", "[worldserver]\nDataDir = \"@DATA@\"\nWorldServerPort = @WORLD_PORT@\nRa.Port = @RA_PORT@\nWorldDatabaseInfo = \"@WorldDatabaseInfo@\"\nCharacterDatabaseInfo = \"@CharacterDatabaseInfo@\"\nMySQLExecutable = \"@MYSQL_EXE@\"\nMotd = \"Ünïcode stays\"\n".as_bytes());
w("Settings/mod_ascension_compat.conf.template", b"Ascension.DbcDir = \"@ASCENSION_DBC@\"\rOld.Mac = 1\r");
}
#[test]
fn the_owners_mysql_options_are_kept_except_the_managed_ones() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
std::fs::write(
d.path().join(CUSTOM_MYSQL),
"\u{feff}# tuning\ninnodb_buffer_pool_size = 2G\nport=3999\nloose_bind_address=0.0.0.0\n!include C:/x.ini\n[client]\nuser=evil\n[mysqld]\nmax_connections=500\nDATADIR=D:/elsewhere\n",
)
.unwrap();
assert_eq!(
custom_mysql_options(d.path()),
"innodb_buffer_pool_size = 2G\nmax_connections=500\n"
);
assert_eq!(custom_mysql_options(&d.path().join("missing")), "");
}
#[test]
fn placeholders_left_outside_comments_are_refused() {
let d = tempfile::tempdir().unwrap();
fixture(d.path());
std::fs::write(d.path().join("Settings/worldserver.conf.template"), "A = @UNKNOWN@\n").unwrap();
let cfg = Settings::load(d.path(), 0).unwrap();
let err = prepare(d.path(), &cfg).unwrap_err().to_string();
assert!(err.contains("worldserver.conf.template: @UNKNOWN@"), "{err}");
}
#[test]
fn a_bad_password_file_is_refused() {
let d = tempfile::tempdir().unwrap();
fixture(d.path());
std::fs::write(d.path().join("Settings/database.json"), r#"{"rootPassword":"short","appPassword":"x"}"#).unwrap();
let cfg = Settings::load(d.path(), 0).unwrap();
assert!(prepare(d.path(), &cfg).unwrap_err().to_string().contains("Invalid packaged database configuration"));
}
/// Byte-for-byte the same files as the Python launcher. COA_MANAGE_PY = a manage.py to compare with (taken from
/// coa-server-build); skipped without it.
#[test]
fn renders_exactly_what_manage_py_renders() {
let Ok(manage) = std::env::var("COA_MANAGE_PY") else { return };
let python = std::env::var("COA_PYTHON").unwrap_or_else(|_| "python".into());
let rust = tempfile::tempdir().unwrap();
let py = tempfile::tempdir().unwrap();
for d in [rust.path(), py.path()] {
fixture(d);
}
std::fs::create_dir_all(py.path().join("Scripts")).unwrap();
std::fs::copy(&manage, py.path().join("Scripts/manage.py")).unwrap();
// manage.py imports squid_playerbots lazily; prepare does not need it.
let out = std::process::Command::new(&python)
.args(["-I", "-B"])
.arg(py.path().join("Scripts/manage.py"))
.arg("prepare")
.output()
.unwrap();
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
let cfg = Settings::load(rust.path(), 0).unwrap();
let written = prepare(rust.path(), &cfg).unwrap();
let root_text = |p: &Path, base: &Path| {
let n = native_root(base).unwrap();
String::from_utf8(std::fs::read(p).unwrap()).unwrap().replace(&n, "<ROOT>")
};
for file in &written {
let rel = file.strip_prefix(rust.path()).unwrap();
assert_eq!(
root_text(file, rust.path()),
root_text(&py.path().join(rel), py.path()),
"{} differs",
rel.display()
);
}
let sig = |base: &Path| -> serde_json::Value {
let mut v: serde_json::Value = crate::fsx::read_json(&base.join(".state/configuration.json")).unwrap();
v["root"] = serde_json::Value::Null;
v
};
assert_eq!(sig(rust.path()), sig(py.path()));
}
}
+310
View File
@@ -0,0 +1,310 @@
//! Restarts on a schedule (#202): once a day at the owner's local time, the world supervisor asks the world to
//! restart with an in-game countdown, waits for it to exit with AzerothCore's restart code and starts it again.
//! The database and the auth server keep running.
use std::path::{Path, PathBuf};
use std::time::Duration;
use chrono::{Datelike, Local, NaiveDateTime, NaiveTime, Timelike};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
const FILE: &str = "Settings/restart-schedule.json";
/// Present while a scheduled restart is under way, so a world that is briefly down is not taken for a crash.
const UNDER_WAY: &str = ".state/scheduled-restart";
/// The exit code of `server restart` (AzerothCore's `RESTART_EXIT_CODE`).
pub const RESTART_EXIT_CODE: i32 = 2;
/// A restart missed by more than this (the computer slept, the world started late) waits for the next day.
const LATE: Duration = Duration::from_secs(15 * 60);
/// A world that has not come back within this time no longer counts as restarting.
const UNDER_WAY_LIMIT: Duration = Duration::from_secs(45 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
#[default]
Sunday,
}
impl Weekday {
fn to_chrono(self) -> chrono::Weekday {
match self {
Self::Monday => chrono::Weekday::Mon,
Self::Tuesday => chrono::Weekday::Tue,
Self::Wednesday => chrono::Weekday::Wed,
Self::Thursday => chrono::Weekday::Thu,
Self::Friday => chrono::Weekday::Fri,
Self::Saturday => chrono::Weekday::Sat,
Self::Sunday => chrono::Weekday::Sun,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DueRestart {
pub moment: NaiveDateTime,
pub warning_minutes: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct RestartSchedule {
pub enabled: bool,
/// Local time, `HH:MM`.
pub time: String,
/// The in-game countdown before the restart, in minutes (1-60).
pub warning_minutes: u32,
pub weekly_enabled: bool,
pub weekly_day: Weekday,
/// Local time for weekly restart, `HH:MM`.
pub weekly_time: String,
/// The in-game countdown before the weekly restart, in minutes (1-60).
pub weekly_warning_minutes: u32,
}
impl Default for RestartSchedule {
fn default() -> Self {
Self {
enabled: false,
time: "05:00".into(),
warning_minutes: 5,
weekly_enabled: false,
weekly_day: Weekday::Sunday,
weekly_time: "05:00".into(),
weekly_warning_minutes: 5,
}
}
}
impl RestartSchedule {
fn parse_time(text: &str) -> Option<NaiveTime> {
NaiveTime::parse_from_str(text.trim(), "%H:%M").ok()
}
fn validate_entry(time: &str, warning_minutes: u32) -> Result<()> {
if Self::parse_time(time).is_none() {
return Err(Error::Invalid("The restart time must be HH:MM, for example 05:00.".into()));
}
if !(1..=60).contains(&warning_minutes) {
return Err(Error::Invalid("The restart warning must be 1 to 60 minutes.".into()));
}
Ok(())
}
fn validate(&self) -> Result<()> {
if self.enabled {
Self::validate_entry(&self.time, self.warning_minutes)?;
}
if self.weekly_enabled {
Self::validate_entry(&self.weekly_time, self.weekly_warning_minutes)?;
}
Ok(())
}
fn due_at(time_str: &str, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
let at = Self::parse_time(time_str)?;
let moment = now.date().and_time(at);
let late = now.signed_duration_since(moment).to_std().ok()?;
(late <= LATE && started < moment).then_some(moment)
}
/// The scheduled moment of `now`'s day, when a daily or weekly restart is due at `now` for a world started at `started`:
/// the moment has passed by less than [`LATE`] and the world was already running before it.
pub fn due_restart(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<DueRestart> {
if self.weekly_enabled && now.weekday() == self.weekly_day.to_chrono() {
if let Some(moment) = Self::due_at(&self.weekly_time, now, started) {
return Some(DueRestart {
moment,
warning_minutes: self.weekly_warning_minutes,
});
}
}
if self.enabled {
if let Some(moment) = Self::due_at(&self.time, now, started) {
return Some(DueRestart {
moment,
warning_minutes: self.warning_minutes,
});
}
}
None
}
/// The scheduled moment of `now`'s day, when a restart is due at `now` for a world started at `started`.
pub fn due(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option<NaiveDateTime> {
self.due_restart(now, started).map(|d| d.moment)
}
}
/// The folder whose schedule a world follows: an extra world (`<server>/.realms/<name>`) follows its server's.
fn owner(root: &Path) -> PathBuf {
if crate::launcher::settings::is_extra_world(root) {
if let Some(main) = root.parent().and_then(Path::parent) {
return main.to_path_buf();
}
}
root.to_path_buf()
}
pub fn load(root: &Path) -> RestartSchedule {
crate::fsx::read_json(&owner(root).join(FILE)).unwrap_or_default()
}
pub fn save(root: &Path, schedule: &RestartSchedule) -> Result<RestartSchedule> {
let mut schedule = schedule.clone();
schedule.time = schedule.time.trim().to_string();
schedule.weekly_time = schedule.weekly_time.trim().to_string();
schedule.validate()?;
if !schedule.enabled && RestartSchedule::parse_time(&schedule.time).is_none() {
schedule.time = RestartSchedule::default().time;
}
if !schedule.weekly_enabled && RestartSchedule::parse_time(&schedule.weekly_time).is_none() {
schedule.weekly_time = RestartSchedule::default().weekly_time;
}
crate::fsx::atomic_write_json(&owner(root).join(FILE), &schedule)?;
Ok(schedule)
}
pub fn now() -> NaiveDateTime {
Local::now().naive_local().with_nanosecond(0).unwrap_or_else(|| Local::now().naive_local())
}
pub fn mark_under_way(root: &Path) -> Result<()> {
let path = root.join(UNDER_WAY);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, b"")?;
Ok(())
}
pub fn clear_under_way(root: &Path) {
let _ = std::fs::remove_file(root.join(UNDER_WAY));
}
/// A scheduled restart of this world is under way (its world may be down for a few minutes).
pub fn under_way(root: &Path) -> bool {
std::fs::metadata(root.join(UNDER_WAY))
.and_then(|m| m.modified())
.is_ok_and(|t| t.elapsed().is_ok_and(|age| age < UNDER_WAY_LIMIT))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> NaiveDateTime {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
#[test]
fn a_restart_is_due_once_after_its_time_for_a_world_that_ran_before_it() {
let s = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5, ..RestartSchedule::default() };
let started = at("2026-11-14 20:00");
assert_eq!(s.due(at("2026-11-15 04:59"), started), None);
assert_eq!(s.due(at("2026-11-15 05:00"), started), Some(at("2026-11-15 05:00")));
assert_eq!(s.due(at("2026-11-15 05:14"), started), Some(at("2026-11-15 05:00")));
assert_eq!(s.due(at("2026-11-15 05:16"), started), None, "missed by too much");
// The world that came back at 05:06 is not restarted again that day.
assert_eq!(s.due(at("2026-11-15 05:10"), at("2026-11-15 05:06")), None);
assert_eq!(s.due(at("2026-11-16 05:01"), at("2026-11-15 05:06")), Some(at("2026-11-16 05:00")));
let off = RestartSchedule { enabled: false, ..s };
assert_eq!(off.due(at("2026-11-15 05:00"), started), None);
}
#[test]
fn weekly_restart_triggers_only_on_configured_weekday_and_independently_of_daily() {
// 2026-11-15 is Sunday; 2026-11-16 is Monday.
let s = RestartSchedule {
enabled: false,
weekly_enabled: true,
weekly_day: Weekday::Sunday,
weekly_time: "04:00".into(),
weekly_warning_minutes: 15,
..RestartSchedule::default()
};
let started = at("2026-11-14 20:00");
assert_eq!(s.due_restart(at("2026-11-15 03:59"), started), None);
assert_eq!(
s.due_restart(at("2026-11-15 04:05"), started),
Some(DueRestart { moment: at("2026-11-15 04:00"), warning_minutes: 15 })
);
// Monday does not trigger Sunday's weekly restart.
assert_eq!(s.due_restart(at("2026-11-16 04:05"), started), None);
// Both daily and weekly enabled: each triggers on its own schedule.
let both = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 5, ..s };
assert_eq!(
both.due_restart(at("2026-11-15 04:05"), started),
Some(DueRestart { moment: at("2026-11-15 04:00"), warning_minutes: 15 })
);
assert_eq!(
both.due_restart(at("2026-11-15 05:02"), at("2026-11-15 04:16")),
Some(DueRestart { moment: at("2026-11-15 05:00"), warning_minutes: 5 })
);
}
#[test]
fn schedules_are_validated_and_extra_worlds_follow_their_server() {
let d = tempfile::tempdir().unwrap();
assert_eq!(load(d.path()), RestartSchedule::default());
let bad = RestartSchedule { enabled: true, time: "25:00".into(), warning_minutes: 5, ..RestartSchedule::default() };
assert!(save(d.path(), &bad).is_err());
let quiet = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 0, ..RestartSchedule::default() };
assert!(save(d.path(), &quiet).is_err());
let bad_weekly = RestartSchedule {
weekly_enabled: true,
weekly_time: "99:00".into(),
..RestartSchedule::default()
};
assert!(save(d.path(), &bad_weekly).is_err());
let quiet_weekly = RestartSchedule {
weekly_enabled: true,
weekly_warning_minutes: 61,
..RestartSchedule::default()
};
assert!(save(d.path(), &quiet_weekly).is_err());
let good = RestartSchedule {
enabled: true,
time: " 04:30 ".into(),
warning_minutes: 10,
weekly_enabled: true,
weekly_day: Weekday::Wednesday,
weekly_time: " 03:15 ".into(),
weekly_warning_minutes: 20,
};
let saved = save(d.path(), &good).unwrap();
assert_eq!(saved.time, "04:30");
assert_eq!(saved.weekly_time, "03:15");
assert_eq!(saved.weekly_day, Weekday::Wednesday);
let extra = d.path().join(".realms/secondary");
std::fs::create_dir_all(&extra).unwrap();
assert!(load(&extra).enabled);
assert!(load(&extra).weekly_enabled);
// Legacy schedule JSON without weekly fields loads cleanly with defaults.
std::fs::write(
d.path().join(FILE),
r#"{"enabled":true,"time":"06:00","warningMinutes":10}"#,
)
.unwrap();
let legacy = load(d.path());
assert!(legacy.enabled);
assert_eq!(legacy.time, "06:00");
assert!(!legacy.weekly_enabled);
assert_eq!(legacy.weekly_day, Weekday::Sunday);
assert!(!under_way(d.path()));
mark_under_way(d.path()).unwrap();
assert!(under_way(d.path()));
clear_under_way(d.path());
assert!(!under_way(d.path()));
}
}
+768
View File
@@ -0,0 +1,768 @@
//! Starting, checking and stopping the services of one repack: MySQL, authserver, worldserver
//! (`manage.py start_mysql`, `start_auth`, `stop_all` and their helpers), with the same rules.
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use crate::error::{Error, ErrorCode, Result};
use crate::launcher::{settings::Settings, state};
use crate::process::ProcessIdentity;
pub type Progress<'a> = &'a dyn Fn(&str);
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
fn hidden(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
}
cmd
}
/// Start `exe` with its output appended to `log`, and record it as `name`. `env_remove` are variables of this
/// process the service must not see.
pub fn spawn(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path, env_remove: &[String]) -> Result<ProcessIdentity> {
let child = crate::launcher::spawn::start(exe, args, cwd, log, env_remove)?;
state::record(root, name, child.pid)
}
// ---------------------------------------------------------------------------------------------------------------
// Ports
// ---------------------------------------------------------------------------------------------------------------
/// What keeps a new server off a port.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PortBlock {
/// Processes listen on it.
Owned(Vec<u32>),
/// Windows keeps it in an excluded range (Hyper-V, WSL and Docker reserve such ranges); waiting never helps.
Reserved(u16, u16),
/// Windows still refuses it after the wait (a stopped process' socket, or an owner the table does not show).
Unavailable(i32),
}
/// Wait (up to `wait`) until `port` can be bound by a new server. A port with a listening owner or inside a
/// Windows excluded range is reported at once; a port Windows still holds for a stopped process (a PID-zero row)
/// is waited for. The test bind is exclusive (`SO_EXCLUSIVEADDRUSE`), never a shared one.
pub fn port_block(port: u16, wait: Duration, progress: Progress) -> std::result::Result<(), PortBlock> {
let deadline = Instant::now() + wait;
let mut announced = false;
let mut reserved: Option<Vec<(u16, u16)>> = None;
loop {
let mut owners: Vec<u32> = sys::tcp_rows_v4()
.into_iter()
.filter(|r| r.state == sys::LISTEN && r.local_port == port)
.map(|r| r.pid)
.collect();
owners.sort_unstable();
owners.dedup();
if owners.iter().any(|p| *p != 0) {
return Err(PortBlock::Owned(owners));
}
match sys::exclusive_bind(port) {
Ok(()) => return Ok(()),
Err(code) if code == 10013 || code == 10048 => {
let ranges = reserved.get_or_insert_with(sys::excluded_ranges);
if let Some((start, end)) = ranges.iter().copied().find(|(s, e)| (*s..=*e).contains(&port)) {
return Err(PortBlock::Reserved(start, end));
}
if Instant::now() >= deadline {
return Err(PortBlock::Unavailable(code));
}
if !announced {
progress(&format!("Waiting for Windows to release port {port}..."));
announced = true;
}
std::thread::sleep(Duration::from_millis(250));
}
Err(code) => return Err(PortBlock::Unavailable(code)),
}
}
}
fn port_error(port: u16, block: PortBlock) -> Error {
match block {
PortBlock::Owned(owners) => {
let list: Vec<String> = owners.iter().map(u32::to_string).collect();
Error::Service(
ErrorCode::PortInUse,
format!("Port {port} is already used (PID {}). Stop the other server or change Settings/repack.json.", list.join(", ")),
)
}
PortBlock::Reserved(start, end) => Error::Service(
ErrorCode::PortInUse,
format!(
"Port {port} is reserved by Windows (excluded range {start}-{end}; Hyper-V, WSL and Docker reserve such ranges). Choose another port in Settings/repack.json, or restart the Windows NAT service as administrator (net stop winnat, then net start winnat)."
),
),
PortBlock::Unavailable(code) if code == 10013 || code == 10048 => Error::Invalid(format!(
"Port {port} remains unavailable after 30 seconds (Windows bind error {code}). No process was stopped. Retry after the previous database shutdown has finished, or check the Windows port reservation."
)),
PortBlock::Unavailable(code) => Error::Invalid(format!("Port {port} cannot be checked (Windows error {code}).")),
}
}
/// [`port_block`] with up to 30 s of waiting, as an error a person can act on.
pub fn ensure_free(port: u16, progress: Progress) -> Result<()> {
port_block(port, Duration::from_secs(30), progress).map_err(|block| port_error(port, block))
}
/// The ports of this server's other services and extra worlds, which the database must not take.
fn ports_in_use_by_server(root: &Path, cfg: &Settings) -> Vec<u16> {
let mut ports = vec![cfg.auth_port, cfg.world_port, cfg.ra_port];
for tree in crate::multiworld::Tree::ALL {
let other = crate::multiworld::tree_root(root, tree);
if let Ok(other) = Settings::load(&other, 0) {
ports.extend([other.world_port, other.ra_port, other.auth_port]);
}
}
ports
}
/// Before the database starts: when its port is reserved by Windows or held by a program that is not this
/// server's MySQL, move the database to a free port and record it in `Settings/repack.json`. Only this server's
/// own services connect to MySQL (players never do), and every start renders their configs from that file, so
/// the move needs nothing else. Returns the new port, or `None` when the configured one is usable.
pub fn relocate_database_port(root: &Path, cfg: &Settings, offset: i32, progress: Progress) -> Result<Option<u16>> {
if cfg.shared_database || offset != 0 || state::running(root, "mysql").is_some() {
return Ok(None);
}
let block = match port_block(cfg.mysql_port, Duration::from_secs(30), progress) {
Ok(()) => return Ok(None),
Err(block) => block,
};
let ours = root.join("mysql/bin/mysqld.exe");
if let PortBlock::Owned(owners) = &block {
// This server's own database without a record: never start a second one on the same data.
let same = |pid: &u32| {
crate::process::identity(*pid).is_some_and(|p| same_file(Path::new(&p.exe), &ours))
};
if owners.iter().any(same) {
return Err(port_error(cfg.mysql_port, block));
}
}
let taken = ports_in_use_by_server(root, cfg);
let reserved = sys::excluded_ranges();
let candidate = (cfg.mysql_port.saturating_add(1)..=cfg.mysql_port.saturating_add(400))
.chain(33070..=33470)
.filter(|p| *p > 1024)
.find(|p| {
!taken.contains(p)
&& !reserved.iter().any(|(s, e)| (*s..=*e).contains(p))
&& port_block(*p, Duration::ZERO, &|_| {}).is_ok()
});
let Some(port) = candidate else {
return Err(port_error(cfg.mysql_port, block));
};
let reason = match &block {
PortBlock::Owned(_) => "used by another program",
PortBlock::Reserved(..) => "reserved by Windows",
PortBlock::Unavailable(_) => "unavailable",
};
let path = root.join("Settings/repack.json");
let mut raw = cfg.raw.clone();
raw.insert("mysqlPort".into(), port.into());
crate::fsx::atomic_write_json(&path, &serde_json::Value::Object(raw))?;
tracing::warn!(old = cfg.mysql_port, new = port, reason, "database moved to a free port");
progress(&format!("Port {} is {reason}; the database now uses port {port}.", cfg.mysql_port));
Ok(Some(port))
}
fn same_file(a: &Path, b: &Path) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a.to_string_lossy().eq_ignore_ascii_case(&b.to_string_lossy()),
_ => false,
}
}
/// The ranges of `netsh interface ipv4 show excludedportrange protocol=tcp`: every line that starts with two
/// port numbers (the headers are translated, the numbers are not).
pub(crate) fn parse_excluded_ranges(text: &str) -> Vec<(u16, u16)> {
text.lines()
.filter_map(|line| {
let mut parts = line.split_whitespace();
let start = parts.next()?.parse::<u16>().ok()?;
let end = parts.next()?.parse::<u16>().ok()?;
(start <= end).then_some((start, end))
})
.collect()
}
/// Is the recorded process of `name` serving `port`? Its listener row is the evidence; when a system does not
/// show the owner of a listener, the server side of a fresh loopback connection is (never for MySQL, whose
/// listener has always been visible and which should not get stray connections).
pub fn ready(root: &Path, name: &str, port: u16) -> bool {
let Some(record) = state::running(root, name) else { return false };
let listening = sys::tcp_rows_v4().iter().any(|r| r.state == sys::LISTEN && r.local_port == port && r.pid == record.pid);
if listening {
return crate::process::is_alive(&record);
}
if name == "mysql" {
return false;
}
accepted_by(port, record.pid) && crate::process::is_alive(&record)
}
/// Connect to 127.0.0.1:`port` and check that exactly one established server-side row, owned by `pid`, answers
/// that connection.
fn accepted_by(port: u16, pid: u32) -> bool {
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
let Ok(client) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else { return false };
let Ok(mine) = client.local_addr().map(|a| a.port()) else { return false };
let me = std::process::id();
let rows: Vec<sys::TcpRow> = sys::tcp_rows_v4()
.into_iter()
.chain(sys::tcp_rows_v6())
.filter(|r| r.remote_port == mine && r.remote_loopback && !(r.local_port == mine && r.pid == me))
.collect();
rows.len() == 1 && rows[0].state == sys::ESTABLISHED && rows[0].pid == pid
}
pub fn wait_ready(root: &Path, name: &str, port: u16, seconds: u64) -> Result<()> {
let until = Instant::now() + Duration::from_secs(seconds);
while Instant::now() < until {
if ready(root, name, port) {
return Ok(());
}
if state::running(root, name).is_none() {
return Err(Error::Service(ErrorCode::StartupFailed, format!("{name} stopped during startup. Check its log.")));
}
std::thread::sleep(Duration::from_millis(500));
}
Err(Error::Service(
ErrorCode::StartupFailed,
format!("{name} is still starting: its expected TCP listener on port {port} was not found; check its log."),
))
}
// ---------------------------------------------------------------------------------------------------------------
// MySQL client
// ---------------------------------------------------------------------------------------------------------------
/// Run SQL (or a `mysqladmin` command) with the repack's own client and administrator login.
pub fn mysql(root: &Path, sql: Option<&str>, admin: Option<&str>) -> Result<String> {
let exe = root.join(if admin.is_some() { "mysql/bin/mysqladmin.exe" } else { "mysql/bin/mysql.exe" });
let defaults = format!("--defaults-file={}", root.join("mysql/admin-client.ini").display());
let mut cmd = Command::new(exe);
hidden(&mut cmd).arg(defaults);
match admin {
Some(a) => cmd.arg(a),
None => cmd.args(["--batch", "--skip-column-names"]),
};
let payload = sql.map(|s| s.as_bytes().to_vec());
let timeout = if payload.as_ref().is_some_and(|p| p.len() > 1024 * 1024) { 900 } else { 90 };
cmd.stdin(if payload.is_some() { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn()?;
if let (Some(data), Some(mut stdin)) = (payload, child.stdin.take()) {
std::thread::spawn(move || {
use std::io::Write;
let _ = stdin.write_all(&data);
});
}
// Both outputs are read while the client runs: a full pipe would stop it (and look like a timeout).
let read = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut buf = Vec::new();
if let Some(mut p) = pipe {
let _ = p.read_to_end(&mut buf);
}
buf
})
};
let out_reader = read(child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
let err_reader = read(child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
let started = Instant::now();
let failed = |stderr: &[u8]| {
let text = String::from_utf8_lossy(stderr);
let detail = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().to_string();
let mut message = "The repack database command failed; check mysql/logs/mysql-error.log.".to_string();
if !detail.is_empty() {
message.push_str(&format!(" ({detail})"));
}
Error::Invalid(message)
};
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > Duration::from_secs(timeout) {
let _ = child.kill();
let _ = child.wait();
let _ = out_reader.join();
return Err(failed(b"timed out"));
}
std::thread::sleep(Duration::from_millis(50));
};
let stdout = out_reader.join().unwrap_or_default();
let stderr = err_reader.join().unwrap_or_default();
if !status.success() {
return Err(failed(&stderr));
}
Ok(String::from_utf8_lossy(&stdout).trim().to_string())
}
// ---------------------------------------------------------------------------------------------------------------
// Start and stop
// ---------------------------------------------------------------------------------------------------------------
pub fn start_mysql(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if cfg.shared_database {
// An extra world uses the main folder's database; it must already run.
return mysql(root, None, Some("ping")).map(|_| ()).map_err(|e| {
Error::Service(ErrorCode::DatabaseNotRunning, format!("The main server's database is not running. {e}"))
});
}
if state::running(root, "mysql").is_some() {
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
mysql(root, None, Some("ping"))?;
progress("MySQL is already running.");
return Ok(());
}
ensure_free(cfg.mysql_port, progress)?;
if !root.join("mysql/data/mysql").is_dir() {
return Err(Error::Service(ErrorCode::ServerFilesIncomplete, "The packaged database is missing. Extract the complete repack.".into()));
}
progress("Starting MySQL...");
let ini = format!("--defaults-file={}", root.join("mysql/my.ini").display());
spawn(root, "mysql", &root.join("mysql/bin/mysqld.exe"), &[&ini, "--no-monitor"], &root.join("mysql"), &root.join("mysql/logs/startup.log"), &cfg.env_remove)?;
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
mysql(root, None, Some("ping"))?;
mysql(
root,
Some(&format!(
"UPDATE acore_auth.realmlist SET name={},address='127.0.0.1',localAddress='127.0.0.1',port={} WHERE id={};",
crate::realm_names::sql_literal(&cfg.realm.name), cfg.world_port, cfg.realm.id
)),
None,
)?;
Ok(())
}
pub fn start_auth(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
start_mysql(root, cfg, progress)?;
if state::running(root, "auth").is_some() {
wait_ready(root, "auth", cfg.auth_port, 60)?;
progress("Authserver is already running.");
return Ok(());
}
ensure_free(cfg.auth_port, progress)?;
// An interrupted world startup can leave flag 3, which authserver excludes.
mysql(root, Some(&format!("UPDATE acore_auth.realmlist SET flag=0 WHERE id={};", cfg.realm.id)), None)?;
progress("Starting authserver...");
spawn(root, "auth", &root.join("Core/authserver.exe"), &["-c", "configs/authserver.conf"], &root.join("Core"), &root.join("Core/Logs/auth-console.log"), &cfg.env_remove)?;
wait_ready(root, "auth", cfg.auth_port, 60)
}
/// Stop the recorded process, only if it is still that process.
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
if !crate::process::is_alive(record) {
return Ok(());
}
sys::terminate(record)
}
pub fn wait_stopped(record: &ProcessIdentity, seconds: u64) -> bool {
let until = Instant::now() + Duration::from_secs(seconds);
while crate::process::is_alive(record) && Instant::now() < until {
std::thread::sleep(Duration::from_millis(250));
}
!crate::process::is_alive(record)
}
/// The recorded world, when it is this folder's own `Core/worldserver.exe` (never stop a process only because a
/// record names it).
fn owned_world(root: &Path) -> Result<Option<ProcessIdentity>> {
let Some(world) = state::running(root, "world") else { return Ok(None) };
let expected = root.join("Core/worldserver.exe");
let same = std::fs::canonicalize(&world.exe).ok().zip(std::fs::canonicalize(&expected).ok()).is_some_and(|(a, b)| a == b);
if !same {
return Err(Error::Invalid("World process ownership could not be verified; the database was left running.".into()));
}
Ok(Some(world))
}
/// Ask the world's console for a graceful shutdown. False when the console is not this world's or does not answer.
fn ask_shutdown(root: &Path, cfg: &Settings) -> bool {
ready(root, "world", cfg.ra_port)
&& crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
.and_then(|ra| ra.send_without_answer("server shutdown 1s 0"))
.is_ok()
}
/// Stop this folder's world without its console (unsaved progress since the last save is lost).
fn stop_world_process(world: &ProcessIdentity) -> Result<()> {
terminate(world).map_err(|_| Error::Invalid("Worldserver could not be stopped safely; its database was left running.".into()))?;
if !wait_stopped(world, 90) {
return Err(Error::Invalid("Worldserver is still stopping; its database was left running.".into()));
}
Ok(())
}
/// Stop the world at once, then everything else as [`stop_all`] does. Only when the user asked for it.
pub fn force_stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if let Some(world) = owned_world(root)? {
stop_world_process(&world)?;
progress("Force-stopped this server's verified world process; unsaved progress may be lost.");
}
stop_all(root, cfg, progress)
}
/// Stop everything of this repack, world first (gracefully through its console), its database last. An extra
/// world leaves the shared database alone.
pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
if let Some(world) = owned_world(root)? {
if ask_shutdown(root, cfg) {
progress("Graceful world shutdown requested.");
} else {
progress("World console unavailable; stopping this repack's recorded world process.");
stop_world_process(&world)?;
}
// A console request can be lost (seen when a client disconnected at once). While the world still runs
// and its console still answers, it has not begun to stop: ask again. Asking twice is harmless.
let mut stopped = wait_stopped(&world, 15);
for _ in 0..2 {
if stopped {
break;
}
if ask_shutdown(root, cfg) {
progress("The world has not begun to stop; shutdown requested again.");
}
stopped = wait_stopped(&world, 15);
}
if !stopped && !wait_stopped(&world, 45) {
return Err(Error::Invalid("Worldserver is still stopping; its database has been left running.".into()));
}
}
if let Some(supervisor) = state::running(root, "supervisor") {
if !wait_stopped(&supervisor, 45) {
return Err(Error::Invalid("The report relay is still finishing a request. Try Stop All again shortly.".into()));
}
}
if let Some(relay) = state::running(root, "relay") {
std::fs::write(state::dir(root).join("stop-relay"), b"")?;
if !wait_stopped(&relay, 40) {
return Err(Error::Invalid("The report relay did not finish; it was left running for recovery.".into()));
}
}
if let Some(auth) = state::running(root, "auth") {
terminate(&auth)?;
if !wait_stopped(&auth, 10) {
return Err(Error::Invalid("Authserver did not stop.".into()));
}
}
if let Some(database) = state::running(root, "mysql").filter(|_| !cfg.shared_database) {
let shutdown = mysql(root, None, Some("shutdown"));
if !wait_stopped(&database, 60) {
shutdown?;
return Err(Error::Invalid("MySQL is still stopping; wait before copying the repack.".into()));
}
}
progress("All services from this repack are stopped. It is safe to move or copy this folder.");
Ok(())
}
/// Which services run (`manage.py status-json`).
pub fn status(root: &Path) -> serde_json::Value {
let mut out = serde_json::Map::new();
for name in ["mysql", "auth", "world", "relay"] {
out.insert(name.into(), state::running(root, name).is_some().into());
}
let debug: bool = crate::fsx::read_json::<serde_json::Value>(&state::dir(root).join("debug-logs.json"))
.ok()
.and_then(|v| v.get("enabled").and_then(|e| e.as_bool()))
.unwrap_or(false);
out.insert("debugLogs".into(), debug.into());
serde_json::Value::Object(out)
}
pub fn log_path(root: &Path, name: &str) -> PathBuf {
match name {
"mysql" => root.join("mysql/logs/startup.log"),
"auth" => root.join("Core/Logs/auth-console.log"),
"world" => root.join("Core/Logs/world-console.log"),
"supervisor" => root.join("Core/Logs/supervisor.log"),
_ => root.join("BugReport/Logs/relay.log"),
}
}
// ---------------------------------------------------------------------------------------------------------------
// Windows
// ---------------------------------------------------------------------------------------------------------------
#[cfg(windows)]
mod sys {
use crate::error::{Error, Result};
use crate::process::ProcessIdentity;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::NetworkManagement::IpHelper::GetExtendedTcpTable;
use windows_sys::Win32::Networking::WinSock::{setsockopt, SOL_SOCKET, SO_EXCLUSIVEADDRUSE};
use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE};
pub const LISTEN: u32 = 2;
pub const ESTABLISHED: u32 = 5;
pub struct TcpRow {
pub state: u32,
pub local_port: u16,
pub remote_port: u16,
pub remote_loopback: bool,
pub pid: u32,
}
fn table(af: u32) -> Vec<u8> {
const TCP_TABLE_OWNER_PID_ALL: i32 = 5;
let mut size = 0u32;
let mut buf: Vec<u8> = Vec::new();
for _ in 0..4 {
let code = unsafe {
GetExtendedTcpTable(
if buf.is_empty() { std::ptr::null_mut() } else { buf.as_mut_ptr().cast() },
&mut size,
0,
af,
TCP_TABLE_OWNER_PID_ALL,
0,
)
};
match code {
0 if !buf.is_empty() => return buf,
0 | 122 => buf = vec![0u8; size as usize + 4096],
_ => return Vec::new(),
}
}
Vec::new()
}
fn u32_at(b: &[u8], o: usize) -> u32 {
u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
}
pub fn tcp_rows_v4() -> Vec<TcpRow> {
let b = table(2);
let mut out = Vec::new();
if b.len() < 4 {
return out;
}
for i in 0..u32_at(&b, 0) as usize {
let o = 4 + 24 * i;
if o + 24 > b.len() {
break;
}
let remote = u32_at(&b, o + 12).to_le_bytes();
out.push(TcpRow {
state: u32_at(&b, o),
local_port: u16::from_be((u32_at(&b, o + 8) & 0xFFFF) as u16),
remote_port: u16::from_be((u32_at(&b, o + 16) & 0xFFFF) as u16),
remote_loopback: remote == [127, 0, 0, 1],
pid: u32_at(&b, o + 20),
});
}
out
}
pub fn tcp_rows_v6() -> Vec<TcpRow> {
let b = table(23);
let mut out = Vec::new();
if b.len() < 4 {
return out;
}
// MIB_TCP6ROW_OWNER_PID: local addr 16, scope 4, local port 4, remote addr 16, scope 4, remote port 4, state 4, pid 4
for i in 0..u32_at(&b, 0) as usize {
let o = 4 + 56 * i;
if o + 56 > b.len() {
break;
}
let remote = &b[o + 24..o + 40];
let mapped_loopback = remote[..10].iter().all(|x| *x == 0) && remote[10] == 0xff && remote[11] == 0xff && remote[12..] == [127, 0, 0, 1];
out.push(TcpRow {
state: u32_at(&b, o + 48),
local_port: u16::from_be((u32_at(&b, o + 20) & 0xFFFF) as u16),
remote_port: u16::from_be((u32_at(&b, o + 44) & 0xFFFF) as u16),
remote_loopback: mapped_loopback,
pid: u32_at(&b, o + 52),
});
}
out
}
/// Bind 0.0.0.0:port exclusively and release it. Err carries the Windows socket error.
/// Windows' excluded TCP port ranges, read with the system's own netsh (never one from PATH or the server).
pub fn excluded_ranges() -> Vec<(u16, u16)> {
use std::os::windows::process::CommandExt;
let mut directory = vec![0u16; 32768];
let length = unsafe {
windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW(directory.as_mut_ptr(), directory.len() as u32)
} as usize;
if length == 0 || length >= directory.len() {
return Vec::new();
}
let netsh = std::path::PathBuf::from(String::from_utf16_lossy(&directory[..length])).join("netsh.exe");
let output = std::process::Command::new(netsh)
.args(["interface", "ipv4", "show", "excludedportrange", "protocol=tcp"])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.creation_flags(super::CREATE_NO_WINDOW)
.output();
match output {
Ok(out) if out.status.success() => super::parse_excluded_ranges(&String::from_utf8_lossy(&out.stdout)),
_ => Vec::new(),
}
}
pub fn exclusive_bind(port: u16) -> std::result::Result<(), i32> {
use socket2::{Domain, Socket, Type};
use std::os::windows::io::AsRawSocket;
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).map_err(|e| e.raw_os_error().unwrap_or(-1))?;
let one: i32 = 1;
let set = unsafe {
setsockopt(socket.as_raw_socket() as _, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (&one as *const i32).cast(), 4)
};
if set != 0 {
return Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(-1));
}
let addr: std::net::SocketAddr = ([0, 0, 0, 0], port).into();
socket.bind(&addr.into()).map_err(|e| e.raw_os_error().unwrap_or(-1))
}
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
unsafe {
let h = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, 0, record.pid);
if h.is_null() {
return Err(Error::Invalid("Unable to stop the repack process.".into()));
}
let same = crate::process::is_alive(record);
let ok = same && TerminateProcess(h, 0) != 0;
CloseHandle(h);
if !ok {
return Err(Error::Invalid("The process changed while stopping it.".into()));
}
}
Ok(())
}
}
#[cfg(not(windows))]
mod sys {
use crate::error::{Error, Result};
use crate::process::ProcessIdentity;
pub const LISTEN: u32 = 2;
pub const ESTABLISHED: u32 = 5;
pub struct TcpRow {
pub state: u32,
pub local_port: u16,
pub remote_port: u16,
pub remote_loopback: bool,
pub pid: u32,
}
pub fn tcp_rows_v4() -> Vec<TcpRow> {
Vec::new()
}
pub fn tcp_rows_v6() -> Vec<TcpRow> {
Vec::new()
}
pub fn exclusive_bind(_: u16) -> std::result::Result<(), i32> {
Ok(())
}
pub fn excluded_ranges() -> Vec<(u16, u16)> {
Vec::new()
}
pub fn terminate(_: &ProcessIdentity) -> Result<()> {
Err(Error::Invalid("not supported".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn excluded_ranges_are_read_from_translated_netsh_output() {
let english = "\r\nProtocol tcp Port Exclusion Ranges\r\n\r\nStart Port End Port\r\n---------- --------\r\n 3250 3349\r\n 50000 50059 *\r\n\r\n* - Administered port exclusions.\r\n";
assert_eq!(parse_excluded_ranges(english), vec![(3250, 3349), (50000, 50059)]);
let russian = "\r\nПротокол tcp Диапазоны исключения портов\r\n\r\nНачальный порт Конечный порт\r\n---------- --------\r\n 50000 50059 *\r\n\r\n* — управляемые исключения портов.\r\n";
assert_eq!(parse_excluded_ranges(russian), vec![(50000, 50059)]);
assert!(parse_excluded_ranges("").is_empty());
}
fn repack(dir: &Path, mysql: u16) {
std::fs::create_dir_all(dir.join("Settings")).unwrap();
std::fs::write(
dir.join("Settings/repack.json"),
format!(r#"{{"mysqlPort":{mysql},"authPort":3724,"worldPort":8085,"raPort":3443,"raUsername":"U","raPassword":"P"}}"#),
)
.unwrap();
}
#[test]
fn a_taken_database_port_moves_to_a_free_one_and_is_recorded() {
let d = tempfile::tempdir().unwrap();
let held = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
let port = held.local_addr().unwrap().port();
repack(d.path(), port);
let cfg = Settings::load(d.path(), 0).unwrap();
let said = std::cell::RefCell::new(Vec::new());
let moved = relocate_database_port(d.path(), &cfg, 0, &|line| said.borrow_mut().push(line.to_string()))
.unwrap()
.expect("moved");
assert_ne!(moved, port);
let again = Settings::load(d.path(), 0).unwrap();
assert_eq!(again.mysql_port, moved);
assert_eq!((again.auth_port, again.ra_username.as_str()), (3724, "U"), "other keys are kept");
assert!(said.borrow().iter().any(|l| l.contains("used by another program")), "{said:?}");
// The new port is usable: nothing moves on the next start.
assert_eq!(relocate_database_port(d.path(), &again, 0, &|_| {}).unwrap(), None);
}
#[test]
fn extra_worlds_and_shifted_test_ports_never_move_the_database() {
let d = tempfile::tempdir().unwrap();
let held = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
let port = held.local_addr().unwrap().port();
repack(d.path(), port);
let cfg = Settings::load(d.path(), 0).unwrap();
let shared = Settings { shared_database: true, ..cfg.clone() };
assert_eq!(relocate_database_port(d.path(), &shared, 0, &|_| {}).unwrap(), None);
assert_eq!(relocate_database_port(d.path(), &cfg, 5, &|_| {}).unwrap(), None);
assert_eq!(Settings::load(d.path(), 0).unwrap().mysql_port, port);
}
#[test]
fn a_port_with_a_listener_is_refused_and_a_free_one_passes() {
let held = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
let port = held.local_addr().unwrap().port();
let err = ensure_free(port, &|_| {}).unwrap_err().to_string();
assert!(err.contains(&format!("Port {port} is already used (PID {}", std::process::id())), "{err}");
drop(held);
ensure_free(port, &|_| {}).unwrap();
}
#[test]
fn a_service_is_ready_only_on_its_own_port() {
let d = tempfile::tempdir().unwrap();
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = held.local_addr().unwrap().port();
assert!(!ready(d.path(), "auth", port), "no record yet");
state::record(d.path(), "auth", std::process::id()).unwrap();
assert!(ready(d.path(), "auth", port));
// A port nobody listens on now (port + 1 may belong to a test running in parallel in this process).
let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let free = other.local_addr().unwrap().port();
drop(other);
assert!(!ready(d.path(), "auth", free));
}
#[test]
fn status_reads_the_records() {
let d = tempfile::tempdir().unwrap();
state::record(d.path(), "mysql", std::process::id()).unwrap();
let s = status(d.path());
assert_eq!(s["mysql"], true);
assert_eq!(s["world"], false);
assert_eq!(s["debugLogs"], false);
}
}
+172
View File
@@ -0,0 +1,172 @@
//! `Settings/repack.json`: ports and the console login of one repack (`manage.py settings()`).
use std::path::Path;
use crate::error::{Error, Result};
pub const PORT_KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
/// The realm a folder runs: its row in `acore_auth.realmlist` and its two game databases.
///
/// Without `Settings/realm-profile.json` this is what the repack launcher always did (realm 1 "AzerothCore" on
/// `acore_world`/`acore_characters`). With it, the active profile decides, as the Manager's realm patch of
/// `manage.py` did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Realm {
pub id: u32,
pub name: String,
pub world_db: &'static str,
pub characters_db: &'static str,
}
impl Realm {
pub fn load(root: &Path) -> Result<Realm> {
let path = root.join("Settings/realm-profile.json");
let (id, name, world_db, characters_db) = if !path.exists() {
(1, "AzerothCore", "acore_world", "acore_characters")
} else {
let v: serde_json::Value = crate::fsx::read_json(&path)?;
match v.get("active").and_then(|a| a.as_str()).unwrap_or("coa") {
"wildcard" => (2, "Wildcard", "acore_world_wildcard", "acore_characters_wildcard"),
"reborn" => (3, "Warcraft Reborn", "acore_world_reborn", "acore_characters_reborn"),
_ => (1, "Conquest of Azeroth", "acore_world", "acore_characters"),
}
};
// The owner's own name for this realm, when one was chosen in the Manager.
let name = crate::realm_names::name_or(root, id, name);
Ok(Realm { id, name, world_db, characters_db })
}
}
/// An extra world of a server (`<server>/.realms/<name>`): it shares the main folder's database and never
/// starts or stops it.
pub fn is_extra_world(root: &Path) -> bool {
root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Settings {
pub mysql_port: u16,
pub auth_port: u16,
pub world_port: u16,
pub ra_port: u16,
pub ra_username: String,
pub ra_password: String,
pub realm: Realm,
/// The database belongs to the main folder of this server (an extra world): it is only checked, never
/// started.
pub shared_database: bool,
/// Environment variables the started services must not see (for example a port override of the caller).
pub env_remove: Vec<String>,
/// The whole document, for keys this code does not know (kept when it is written back).
pub raw: serde_json::Map<String, serde_json::Value>,
}
impl Settings {
/// Read `Settings/repack.json`, with every port moved by `offset` (a second world of the same server runs on
/// shifted ports). The same checks as `manage.py`: integer ports in 1025..65535 after the offset, all
/// different.
pub fn load(root: &Path, offset: i32) -> Result<Settings> {
let bytes = std::fs::read(root.join("Settings/repack.json"))?;
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
let raw: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(text).map_err(|e| Error::Invalid(format!("Settings/repack.json: {e}")))?;
let mut ports = [0u16; 4];
for (i, key) in PORT_KEYS.iter().enumerate() {
// Python's `type(value) is not int` refuses booleans and floats alike.
let value = raw.get(*key).and_then(|v| v.as_i64()).filter(|_| raw[*key].is_i64() || raw[*key].is_u64());
let shifted = value.map(|v| v + i64::from(offset));
match shifted {
Some(p) if p > 1024 && p < 65536 => ports[i] = p as u16,
_ => return Err(Error::Service(crate::error::ErrorCode::InvalidConfigValue, "Invalid port in Settings/repack.json".into())),
}
}
let mut unique = ports.to_vec();
unique.sort_unstable();
unique.dedup();
if unique.len() != 4 {
return Err(Error::Invalid("Each service needs a different port.".into()));
}
let text_of = |k: &str| raw.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string();
Ok(Settings {
mysql_port: ports[0],
auth_port: ports[1],
world_port: ports[2],
ra_port: ports[3],
ra_username: text_of("raUsername"),
ra_password: text_of("raPassword"),
realm: Realm::load(root)?,
shared_database: is_extra_world(root),
env_remove: Vec::new(),
raw,
})
}
/// `{"mysqlPort": .., "authPort": .., "worldPort": .., "raPort": ..}` as `manage.py` records it in
/// `.state/configuration.json` (the keys of repack.json ending in "Port", in the file's order).
pub fn port_map(&self) -> serde_json::Map<String, serde_json::Value> {
let shifted = [self.mysql_port, self.auth_port, self.world_port, self.ra_port];
let mut out = serde_json::Map::new();
for key in self.raw.keys().filter(|k| k.ends_with("Port")) {
let value = PORT_KEYS
.iter()
.position(|p| p == key)
.map(|i| serde_json::Value::from(shifted[i]))
.unwrap_or_else(|| self.raw[key].clone());
out.insert(key.clone(), value);
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn write(dir: &Path, text: &str) {
std::fs::create_dir_all(dir.join("Settings")).unwrap();
std::fs::write(dir.join("Settings/repack.json"), text).unwrap();
}
#[test]
fn ports_are_checked_like_the_python_launcher() {
let d = tempfile::tempdir().unwrap();
write(d.path(), r#"{"mysqlPort":3307,"authPort":3724,"worldPort":8085,"raPort":3443,"raUsername":"U","raPassword":"P"}"#);
let s = Settings::load(d.path(), 0).unwrap();
assert_eq!((s.mysql_port, s.auth_port, s.world_port, s.ra_port), (3307, 3724, 8085, 3443));
assert_eq!(s.ra_username, "U");
let shifted = Settings::load(d.path(), 10).unwrap();
assert_eq!(shifted.world_port, 8095);
assert_eq!(shifted.port_map()["worldPort"], serde_json::json!(8095));
for bad in [
r#"{"mysqlPort":1024,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":"3307","authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":3307.0,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":true,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
r#"{"mysqlPort":3307,"authPort":3307,"worldPort":8085,"raPort":3443}"#,
r#"{"authPort":3724,"worldPort":8085,"raPort":3443}"#,
] {
write(d.path(), bad);
assert!(Settings::load(d.path(), 0).is_err(), "{bad}");
}
write(d.path(), "\u{feff}{\"mysqlPort\":3307,\"authPort\":3724,\"worldPort\":8085,\"raPort\":65535}");
assert!(Settings::load(d.path(), 1).is_err(), "65536 after the offset");
assert!(Settings::load(d.path(), 0).is_ok(), "a byte order mark is accepted");
}
#[test]
fn the_realm_follows_the_active_profile() {
let d = tempfile::tempdir().unwrap();
assert_eq!(Realm::load(d.path()).unwrap().name, "AzerothCore");
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
for (active, id, db) in [("coa", 1, "acore_world"), ("wildcard", 2, "acore_world_wildcard"), ("reborn", 3, "acore_world_reborn")] {
std::fs::write(d.path().join("Settings/realm-profile.json"), format!("{{\"active\":\"{active}\"}}")).unwrap();
let r = Realm::load(d.path()).unwrap();
assert_eq!((r.id, r.world_db), (id, db));
}
assert!(is_extra_world(&d.path().join(".realms/secondary")));
assert!(!is_extra_world(d.path()));
}
}
Binary file not shown.
+398
View File
@@ -0,0 +1,398 @@
//! SQUID Playerbots on a repack (`Scripts/squid_playerbots.py`): the bot modules must not both run, how long a
//! SQUID world may take to start, and its database, provisioned before the world starts.
//!
//! The SQL journals are the ones the Python script keeps, unchanged: `coa_squid_migrations(path, sha256)` and
//! `coa_squid_pending(path, sha256)` in every target schema, and the SQUID installer's `coa_bots_installed`.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use sha1::Digest as _;
use crate::error::{Error, Result};
/// `key = value` lines of a module config (comments and quotes dropped), as `options()` reads them.
pub fn options(path: &Path) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
let Ok(bytes) = std::fs::read(path) else { return out };
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
for line in text.lines() {
let line = line.trim_start();
let Some((key, rest)) = line.split_once('=') else { continue };
let key = key.trim_end();
if key.is_empty() || key.starts_with('#') || key.contains(char::is_whitespace) {
continue;
}
let value = rest.split('#').next().unwrap_or("").trim();
out.insert(key.to_string(), value.trim_matches('"').to_string());
}
out
}
/// A secondary world shares the primary's package files.
pub fn package_root(root: &Path) -> PathBuf {
let secondary = root.file_name().is_some_and(|n| n == "secondary")
&& root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms");
if secondary {
root.parent().and_then(Path::parent).map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf())
} else {
root.to_path_buf()
}
}
pub fn module_options(root: &Path, name: &str) -> (PathBuf, BTreeMap<String, String>) {
let folder = root.join("Core/configs/modules");
let active = folder.join(name);
let mut path = if active.exists() { active } else { folder.join(format!("{name}.dist")) };
if !path.exists() && name == "playerbots.conf" {
path = package_root(root).join("Core/configs/modules/playerbots.conf.dist");
}
let values = options(&path);
(path, values)
}
/// Invalid booleans count as the modules' compiled default: enabled.
pub fn enabled(values: &BTreeMap<String, String>, key: &str) -> bool {
!matches!(values.get(key).map(|v| v.to_ascii_lowercase()).as_deref(), Some("0" | "false" | "no" | "off"))
}
pub fn validate_bots(root: &Path) -> Result<()> {
let (a, av) = module_options(root, "mod_coa_playerbots.conf");
let (b, bv) = module_options(root, "playerbots.conf");
if a.exists() && b.exists() && enabled(&av, "CoaBots.Enable") && enabled(&bv, "AiPlayerbot.Enabled") {
return Err(Error::Invalid(
"CoA Companions and SQUID Playerbots cannot both be enabled. Disable one bot module in Modules or its config.".into(),
));
}
Ok(())
}
/// Seconds a world may take to open its port: SQUID loads its bots first.
pub fn startup_timeout(root: &Path) -> u64 {
let (path, values) = module_options(root, "playerbots.conf");
if path.exists() && enabled(&values, "AiPlayerbot.Enabled") {
1500
} else {
180
}
}
/// Replace (or append) `key = value` lines; the file is written with "\n" line ends.
pub fn set_options(path: &Path, values: &[(&str, String)]) -> Result<()> {
let bytes = std::fs::read(path)?;
let text = String::from_utf8_lossy(&bytes);
let mut text = text.strip_prefix('\u{feff}').unwrap_or(&text).replace("\r\n", "\n");
for (key, value) in values {
let line = format!("{key} = {value}");
let mut found = false;
let lines: Vec<String> = text
.split('\n')
.map(|l| {
let t = l.trim_start();
let matches = t.strip_prefix(key).is_some_and(|rest| rest.trim_start().starts_with('='));
if matches {
found = true;
line.clone()
} else {
l.to_string()
}
})
.collect();
text = lines.join("\n");
if !found {
text.push('\n');
text.push_str(&line);
text.push('\n');
}
}
crate::fsx::atomic_write(path, text.as_bytes())
}
fn valid_relative(rel: &str) -> bool {
!rel.is_empty() && rel.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-'))
}
/// Table names a base file creates (`CREATE TABLE [IF NOT EXISTS] name`).
fn created_tables(sql: &str) -> BTreeSet<String> {
let mut out = BTreeSet::new();
let upper = sql.to_ascii_uppercase();
let mut from = 0;
while let Some(i) = upper[from..].find("CREATE") {
let start = from + i + "CREATE".len();
from = start;
let rest = &sql[start..];
let mut words = rest.split_whitespace();
if !words.next().is_some_and(|w| w.eq_ignore_ascii_case("TABLE")) {
continue;
}
let mut name = words.next().unwrap_or("");
if name.eq_ignore_ascii_case("IF") {
let _ = words.next(); // NOT
let _ = words.next(); // EXISTS
name = words.next().unwrap_or("");
}
let name: String = name.trim_start_matches('`').chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
if !name.is_empty() {
out.insert(name);
}
}
out
}
fn sha256_hex(bytes: &[u8]) -> String {
crate::fsx::sha256_bytes(bytes)
}
fn sha1_hex(bytes: &[u8]) -> String {
let mut h = sha1::Sha1::new();
h.update(bytes);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
fn rows(text: &str) -> Vec<(String, String)> {
text.lines().filter_map(|r| r.split_once('\t')).map(|(a, b)| (a.to_string(), b.to_string())).collect()
}
/// Provision an enabled SQUID without replaying imported base tables (`prepare_playerbots`). `mysql(sql)` runs
/// SQL with the repack's administrator login and returns its output.
pub fn prepare_playerbots(root: &Path, mysql_port: u16, mysql: &dyn Fn(&str) -> Result<String>, progress: &dyn Fn(&str)) -> Result<()> {
let (mut path, values) = module_options(root, "playerbots.conf");
if !path.exists() || !enabled(&values, "AiPlayerbot.Enabled") {
return Ok(());
}
validate_bots(root)?;
let sql_root = package_root(root).join("Extras/SquidPlayerbots/sql");
if !sql_root.join("playerbots/base").is_dir() {
return Err(Error::Invalid("SQUID Playerbots database files are missing. Repair the server installation.".into()));
}
let world = options(&root.join("Core/configs/worldserver.conf"));
let mut schemas: Vec<(&str, String)> = Vec::new();
for (kind, key) in [("characters", "CharacterDatabaseInfo"), ("world", "WorldDatabaseInfo")] {
let schema = world.get(key).and_then(|v| v.rsplit(';').next()).unwrap_or("").to_string();
let ok = matches!(schema.as_str(), "acore_world" | "acore_characters" | "acore_world_wildcard" | "acore_characters_wildcard");
if !ok {
return Err(Error::Invalid("Unsupported world/characters database for SQUID Playerbots.".into()));
}
schemas.push((kind, schema));
}
schemas.push(("playerbots", "acore_playerbots".into()));
let list = |schema: &str| -> Result<BTreeSet<String>> {
Ok(mysql(&format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"))?
.lines()
.map(str::to_string)
.collect())
};
let existing_playerbots = list("acore_playerbots")?;
let bookkeeping = ["updates", "updates_include", "version_db_playerbots", "coa_squid_migrations", "coa_bots_installed", "coa_squid_pending"];
let data_tables: Vec<&String> = existing_playerbots.iter().filter(|t| !bookkeeping.contains(&t.as_str())).collect();
let mut installer_history = BTreeSet::new();
if existing_playerbots.contains("coa_bots_installed") {
for name in mysql("SELECT file FROM `acore_playerbots`.coa_bots_installed;")?.lines() {
let mut n = name.replace('\\', "/");
while n.contains("//") {
n = n.replace("//", "/");
}
let n = n.trim_matches('/').to_string();
if n.to_ascii_lowercase().ends_with(".sql") {
installer_history.insert(n);
}
}
}
let mut tables: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
let mut histories: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
let mut ledgers: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
for (kind, schema) in &schemas {
let t = if *kind == "playerbots" { existing_playerbots.clone() } else { list(schema)? };
if t.contains("coa_squid_pending") {
let pending = mysql(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?;
let pending = pending.trim();
if !pending.is_empty() {
return Err(Error::Invalid(format!(
"A SQUID base import was interrupted. Restore the database backup or repair the incomplete import before continuing; no SQL was applied: {pending}"
)));
}
}
let mut history = BTreeMap::new();
if t.contains("updates") {
for (name, digest) in rows(&mysql(&format!("SELECT name,hash FROM `{schema}`.updates;"))?) {
history.insert(name, digest.to_ascii_lowercase());
}
}
let mut ledger = BTreeMap::new();
if t.contains("coa_squid_migrations") {
for (name, digest) in rows(&mysql(&format!("SELECT path,sha256 FROM `{schema}`.coa_squid_migrations;"))?) {
ledger.insert(name, digest);
}
}
tables.insert(kind, t);
histories.insert(kind, history);
ledgers.insert(kind, ledger);
}
if !data_tables.is_empty() && installer_history.is_empty() && histories["playerbots"].is_empty() && ledgers["playerbots"].is_empty() {
for table in data_tables {
let quoted = table.replace('`', "``");
if mysql(&format!("SELECT EXISTS(SELECT 1 FROM `acore_playerbots`.`{quoted}` LIMIT 1);"))?.trim() == "1" {
return Err(Error::Invalid(
"Existing SQUID data has no recorded installation history. Repair the imported database history before continuing; no SQL was applied.".into(),
));
}
}
}
mysql("CREATE DATABASE IF NOT EXISTS acore_playerbots CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")?;
for host in ["localhost", "127.0.0.1"] {
mysql(&format!("GRANT ALL PRIVILEGES ON acore_playerbots.* TO 'acore'@'{host}';"))?;
}
let (_, password) = crate::db::credentials(root)?;
if password.len() != 48 || !password.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return Err(Error::Invalid("Invalid packaged database configuration.".into()));
}
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".dist")) {
let active = root.join("Core/configs/modules/playerbots.conf");
std::fs::create_dir_all(active.parent().unwrap())?;
std::fs::write(&active, std::fs::read(&path)?)?;
path = active;
}
set_options(
&path,
&[
("PlayerbotsDatabaseInfo", format!("\"127.0.0.1;{mysql_port};acore;{password};acore_playerbots\"")),
("Playerbots.Updates.EnableDatabases", "0".into()),
],
)?;
for (kind, schema) in &schemas {
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_migrations (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_pending (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
let history = &histories[kind];
let recorded = ledgers[kind].clone();
for stage in ["base", "updates", "custom"] {
let mut sources: Vec<PathBuf> = std::fs::read_dir(sql_root.join(kind).join(stage))
.map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "sql")).collect())
.unwrap_or_default();
sources.sort();
for source in sources {
let relative = source.strip_prefix(&sql_root).unwrap_or(&source).to_string_lossy().replace('\\', "/");
if !valid_relative(&relative) {
return Err(Error::Invalid("Invalid SQUID SQL filename.".into()));
}
let bytes = std::fs::read(&source)?;
let digest = sha256_hex(&bytes);
if let Some(previous) = recorded.get(&relative) {
if *previous != digest {
return Err(Error::Invalid(format!("A previously applied SQUID database migration changed: {relative}")));
}
if stage != "base" {
continue;
}
}
let ledger_sql = if recorded.contains_key(&relative) {
String::new()
} else {
format!("INSERT INTO `{schema}`.coa_squid_migrations VALUES ('{relative}','{digest}');")
};
let text = String::from_utf8_lossy(&bytes);
let text = text.strip_prefix('\u{feff}').unwrap_or(&text).to_string();
if stage == "base" {
let definitions = created_tables(&text);
let present: BTreeSet<String> = definitions.intersection(&tables[kind]).cloned().collect();
if !present.is_empty() && present != definitions {
return Err(Error::Invalid(format!("SQUID base file has only some of its tables. Repair the incomplete database before continuing: {relative}")));
}
if definitions.is_empty() {
return Err(Error::Invalid(format!("SQUID base file has no recognizable table definitions; repair is required: {relative}")));
}
if present == definitions {
if !ledger_sql.is_empty() {
mysql(&ledger_sql)?;
}
continue;
}
mysql(&format!("INSERT INTO `{schema}`.coa_squid_pending VALUES ('{relative}','{digest}'); COMMIT;"))?;
let complete = format!("DELETE FROM `{schema}`.coa_squid_pending WHERE path='{relative}' AND sha256='{digest}'; COMMIT;");
progress(&format!("Importing SQUID {relative} into {schema} ({} bytes); large imports may take several minutes...", bytes.len()));
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}\n{complete}")).map_err(|_| {
Error::Invalid(format!(
"SQUID import failed: {relative} in {schema}. The world server was not started. The incomplete import is recorded; restore a database backup or repair that import before retrying."
))
})?;
progress(&format!("Imported SQUID {relative}."));
if let Some(t) = tables.get_mut(kind) {
t.extend(definitions);
}
continue;
}
if installer_history.iter().any(|n| *n == relative || n.ends_with(&format!("/{relative}"))) {
mysql(&ledger_sql)?;
continue;
}
let file_name = source.file_name().unwrap_or_default().to_string_lossy().into_owned();
if let Some(upstream) = history.get(&file_name) {
let lf = String::from_utf8_lossy(&bytes).replace("\r\n", "\n");
let accepted = [sha1_hex(&bytes), sha1_hex(lf.as_bytes())];
if !upstream.is_empty() && !accepted.contains(upstream) {
return Err(Error::Invalid(format!("SQUID update history does not match the shipped SQL: {relative}")));
}
mysql(&ledger_sql)?;
continue;
}
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}"))?;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_lines_are_read_like_the_python_script() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("playerbots.conf");
std::fs::write(&p, "\u{feff}# comment = 1\nAiPlayerbot.Enabled = 0 # off\n Key.Two=\"quoted\"\nnot a line\nEmpty =\n").unwrap();
let o = options(&p);
assert_eq!(o.get("AiPlayerbot.Enabled").map(String::as_str), Some("0"));
assert_eq!(o.get("Key.Two").map(String::as_str), Some("quoted"));
assert_eq!(o.get("Empty").map(String::as_str), Some(""));
assert!(!o.contains_key("#"));
assert!(!enabled(&o, "AiPlayerbot.Enabled"));
assert!(enabled(&o, "Missing"));
}
#[test]
fn both_bot_modules_on_is_refused_and_squid_gets_a_long_startup() {
let d = tempfile::tempdir().unwrap();
let m = d.path().join("Core/configs/modules");
std::fs::create_dir_all(&m).unwrap();
std::fs::write(m.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap();
std::fs::write(m.join("playerbots.conf.dist"), "AiPlayerbot.Enabled = 1\n").unwrap();
assert!(validate_bots(d.path()).is_err());
assert_eq!(startup_timeout(d.path()), 1500);
std::fs::write(m.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
validate_bots(d.path()).unwrap();
assert_eq!(startup_timeout(d.path()), 180);
}
#[test]
fn options_are_replaced_or_appended() {
let d = tempfile::tempdir().unwrap();
let p = d.path().join("playerbots.conf");
std::fs::write(&p, "A = 1\r\n Playerbots.Updates.EnableDatabases = 1\r\n").unwrap();
set_options(&p, &[("Playerbots.Updates.EnableDatabases", "0".into()), ("PlayerbotsDatabaseInfo", "\"x\"".into())]).unwrap();
assert_eq!(std::fs::read_to_string(&p).unwrap(), "A = 1\nPlayerbots.Updates.EnableDatabases = 0\n\nPlayerbotsDatabaseInfo = \"x\"\n");
}
#[test]
fn base_tables_are_found() {
let t = created_tables("CREATE TABLE IF NOT EXISTS `ai_playerbot_names` (\n id int);\ncreate table playerbots_random_bots(x int);\n-- CREATE INDEX i ON t(x);");
assert_eq!(t, ["ai_playerbot_names".to_string(), "playerbots_random_bots".to_string()].into_iter().collect());
}
#[test]
fn a_secondary_world_uses_the_primary_package() {
assert_eq!(package_root(Path::new("C:/S/.realms/secondary")), Path::new("C:/S"));
assert_eq!(package_root(Path::new("C:/S")), Path::new("C:/S"));
}
}
+198
View File
@@ -0,0 +1,198 @@
//! `.state/`: which processes belong to this repack, and the one-action-at-a-time lock.
use std::fs::{File, OpenOptions};
use std::io::{Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use crate::error::{Error, Result};
use crate::fsx;
use crate::process::{self, ProcessIdentity};
pub fn dir(root: &Path) -> PathBuf {
root.join(".state")
}
/// Written like `manage.py atomic_json`: two-space JSON and a newline, now flushed to disk before it replaces
/// the old file.
pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
let mut text = serde_json::to_string_pretty(value)?;
text.push('\n');
fsx::atomic_write(path, text.as_bytes())
}
/// The recorded process of `name` when it is still that process (same executable and start time). A missing,
/// empty or damaged record is no process: `manage.py` failed on those, and every later start with it.
pub fn running(root: &Path, name: &str) -> Option<ProcessIdentity> {
let record = process::read_state_record(root, name)?;
process::is_alive(&record).then_some(record)
}
/// Record the process `pid` as `name`. Fails when it has already exited.
pub fn record(root: &Path, name: &str, pid: u32) -> Result<ProcessIdentity> {
let identity = process::identity(pid)
.ok_or_else(|| Error::Invalid(format!("{name} exited during startup; check its log.")))?;
write_json(&dir(root).join(format!("{name}.json")), &identity)?;
Ok(identity)
}
/// Held while one start/stop action runs. Byte 0 of `.state/control.lock` is locked, exactly the region
/// `msvcrt.locking(fd, LK_NBLCK, 1)` locks in `manage.py`, so a Python launcher and this one exclude each other.
pub struct ControlLock {
file: File,
owner: PathBuf,
}
impl ControlLock {
/// Wait up to `wait` for the lock. `action` is recorded for whoever waits next ("start-all", ...).
pub fn acquire(root: &Path, action: &str, wait: Duration, progress: &dyn Fn(&str)) -> Result<ControlLock> {
let state = dir(root);
std::fs::create_dir_all(&state)?;
let mut file = OpenOptions::new().read(true).append(true).create(true).open(state.join("control.lock"))?;
if file.seek(SeekFrom::End(0))? == 0 {
file.write_all(b"0")?;
file.flush()?;
}
let owner = state.join("control-owner.json");
let deadline = Instant::now() + wait;
let mut announced = false;
loop {
if sys::try_lock(&file)? {
break;
}
let detail = match fsx::read_json::<serde_json::Value>(&owner) {
Ok(v) if v.get("pid").is_some() && v.get("action").is_some() => {
format!(" PID {}, action {}.", v["pid"], v["action"].as_str().unwrap_or(""))
}
_ => " Owner information is unavailable.".into(),
};
if Instant::now() >= deadline {
return Err(Error::Service(crate::error::ErrorCode::OperationInProgress, format!("Another start/stop action is in progress.{detail}")));
}
if !announced {
progress(&format!("Waiting for the current server action.{detail}"));
announced = true;
}
std::thread::sleep(Duration::from_millis(250));
}
let started = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0);
let lock = ControlLock { file, owner };
write_json(
&lock.owner,
&serde_json::json!({ "pid": std::process::id(), "action": action, "started": started }),
)?;
Ok(lock)
}
}
/// Byte 0 of a file locked while held (`msvcrt.locking`), for example the bug-report relay's `relay.lock`.
pub struct FileLock {
file: File,
}
impl FileLock {
/// Take the lock, or `None` when another process (or handle) holds it.
pub fn try_acquire(path: &Path) -> Result<Option<FileLock>> {
let mut file = OpenOptions::new().read(true).append(true).create(true).open(path)?;
if file.seek(SeekFrom::End(0))? == 0 {
file.write_all(b"0")?;
file.flush()?;
}
Ok(sys::try_lock(&file)?.then_some(FileLock { file }))
}
}
impl Drop for FileLock {
fn drop(&mut self) {
sys::unlock(&self.file);
}
}
impl Drop for ControlLock {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.owner);
sys::unlock(&self.file);
}
}
#[cfg(windows)]
mod sys {
use std::fs::File;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{LockFile, UnlockFile};
/// `LockFile` on byte 0, length 1: the call `msvcrt.locking` makes. Non-blocking.
pub fn try_lock(file: &File) -> std::io::Result<bool> {
let ok = unsafe { LockFile(file.as_raw_handle() as _, 0, 0, 1, 0) };
if ok != 0 {
return Ok(true);
}
let err = std::io::Error::last_os_error();
// ERROR_LOCK_VIOLATION (33): someone else holds it.
if err.raw_os_error() == Some(33) {
Ok(false)
} else {
Err(err)
}
}
pub fn unlock(file: &File) {
unsafe {
UnlockFile(file.as_raw_handle() as _, 0, 0, 1, 0);
}
}
}
#[cfg(not(windows))]
mod sys {
use std::fs::File;
pub fn try_lock(_: &File) -> std::io::Result<bool> {
Ok(true)
}
pub fn unlock(_: &File) {}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_damaged_record_is_no_process() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir(d.path())).unwrap();
std::fs::write(dir(d.path()).join("mysql.json"), [0u8; 116]).unwrap();
assert!(running(d.path(), "mysql").is_none());
std::fs::write(dir(d.path()).join("auth.json"), b"").unwrap();
assert!(running(d.path(), "auth").is_none());
}
#[test]
fn this_process_is_recorded_and_found_running() {
let d = tempfile::tempdir().unwrap();
let me = record(d.path(), "probe", std::process::id()).unwrap();
assert_eq!(running(d.path(), "probe"), Some(me));
let text = std::fs::read_to_string(dir(d.path()).join("probe.json")).unwrap();
assert!(text.starts_with("{\n \"pid\": ") && text.ends_with("}\n"), "{text}");
}
#[test]
fn one_action_at_a_time() {
let d = tempfile::tempdir().unwrap();
let first = ControlLock::acquire(d.path(), "start-all", Duration::from_secs(1), &|_| {}).unwrap();
let owner: serde_json::Value = fsx::read_json(&dir(d.path()).join("control-owner.json")).unwrap();
assert_eq!(owner["action"], "start-all");
let said = std::sync::Mutex::new(Vec::new());
let second = ControlLock::acquire(d.path(), "stop-all", Duration::from_millis(600), &|m| said.lock().unwrap().push(m.to_string()));
if cfg!(windows) {
let err = second.err().expect("the second action waits and gives up").to_string();
assert!(err.contains("Another start/stop action is in progress") && err.contains("start-all"), "{err}");
assert_eq!(said.lock().unwrap().len(), 1);
}
drop(first);
assert!(!dir(d.path()).join("control-owner.json").exists());
ControlLock::acquire(d.path(), "stop-all", Duration::from_secs(1), &|_| {}).unwrap();
}
}
+360
View File
@@ -0,0 +1,360 @@
//! The world server and the bug-report relay beside it (`manage.py start_world`, `watch_world`, `wait_relay`),
//! and the detailed-logging switch (`debug_logs`).
//!
//! A world is started through a supervisor process that outlives the caller: it starts `worldserver.exe`, keeps
//! the relay running while the world runs, and stops the relay when the world ends. The supervisor is
//! `coa-launcher.exe watch-world`, or `manage.py watch-world` on a repack that does not ship it yet (both write
//! the same records). The relay itself is still the Python `BugReport/relay.py`, run through the repack's
//! Python, until it is ported too.
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use crate::error::{Error, ErrorCode, Result};
use crate::launcher::services::{self, ensure_free, mysql, spawn, start_mysql, wait_ready, Progress};
use crate::launcher::spawn::Proc;
use crate::launcher::{schedule, settings::Settings, squid, state};
fn stop_relay_flag(root: &Path) -> std::path::PathBuf {
state::dir(root).join("stop-relay")
}
/// The relay is up and has finished starting (it records itself as `relay-ready` once it serves).
pub fn wait_relay(root: &Path) -> Result<()> {
let until = Instant::now() + Duration::from_secs(20);
while Instant::now() < until {
if let (Some(relay), Some(ready)) = (state::running(root, "relay"), state::running(root, "relay-ready")) {
if relay == ready {
return Ok(());
}
}
std::thread::sleep(Duration::from_millis(250));
}
Err(Error::Invalid("Bug-report relay is not ready; check BugReport/Logs/relay.log.".into()))
}
/// The process that runs `watch-world` for a started world.
#[derive(Debug, Clone)]
pub enum Supervisor {
/// `coa-launcher.exe` (this crate's launcher).
Launcher(PathBuf),
/// The repack's Python with `Scripts/manage.py`.
Python { python: PathBuf, script: PathBuf },
}
impl Supervisor {
/// The supervisor a repack ships: `Scripts/coa-launcher.exe` when present, otherwise its Python launcher.
pub fn of(root: &Path) -> Result<Supervisor> {
let exe = root.join("Scripts/coa-launcher.exe");
if exe.is_file() {
return Ok(Supervisor::Launcher(exe));
}
let python = squid::package_root(root).join("Runtime/python/python.exe");
let script = root.join("Scripts/manage.py");
if python.is_file() && script.is_file() {
return Ok(Supervisor::Python { python, script });
}
Err(Error::Service(
ErrorCode::ServerFilesIncomplete,
"This server has no world supervisor (Scripts/coa-launcher.exe or Scripts/manage.py). Repair its program files.".into(),
))
}
}
/// How long a world may take to open both of its listeners, together: slow worlds (many bots, a cold disk) are
/// common, and the limit must not depend on the bot module.
const WORLD_STARTUP_SECONDS: u64 = 1500;
/// Wait until the world's console answers a command (it can listen before it accepts logins).
fn wait_console(root: &Path, cfg: &Settings, until: Instant) -> Result<()> {
let mut last = String::new();
while Instant::now() < until {
if state::running(root, "world").is_none() {
return Err(Error::Service(
ErrorCode::StartupFailed,
"World startup failed: worldserver stopped before its console accepted commands.".into(),
));
}
match crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).and_then(|mut ra| ra.run("server info")) {
Ok(_) => return Ok(()),
Err(e) => last = e.to_string(),
}
std::thread::sleep(Duration::from_millis(500));
}
Err(Error::Service(ErrorCode::StartupFailed, format!("World startup failed: its console is still starting. {last}")))
}
fn seconds_until(until: Instant) -> u64 {
until.saturating_duration_since(Instant::now()).as_secs()
}
/// Start the world (and its database, unless it is shared), and wait until its console accepts commands.
pub fn start_world(root: &Path, cfg: &Settings, offset: i32, supervisor: &Supervisor, progress: Progress) -> Result<()> {
start_mysql(root, cfg, progress)?;
squid::validate_bots(root)?;
let until = Instant::now() + Duration::from_secs(squid::startup_timeout(root).max(WORLD_STARTUP_SECONDS));
if state::running(root, "world").is_some() {
if state::running(root, "supervisor").is_none() {
return Err(Error::Service(
ErrorCode::WorldserverAlreadyRunning,
"Worldserver has no repack supervisor. Use Stop_All_Server.bat before restarting it.".into(),
));
}
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
wait_relay(root)?;
wait_console(root, cfg, until)?;
progress("Worldserver and bug-report relay are already running.");
return Ok(());
}
ensure_free(cfg.world_port, progress)?;
ensure_free(cfg.ra_port, progress)?;
if state::running(root, "supervisor").is_some() || state::running(root, "relay").is_some() {
return Err(Error::Service(
ErrorCode::OperationInProgress,
"The previous world/relay shutdown is still finishing. Try again shortly.".into(),
));
}
squid::prepare_playerbots(root, cfg.mysql_port, &|sql| mysql(root, Some(sql), None), progress)?;
progress("Starting worldserver and its bug-report relay...");
let _ = std::fs::remove_file(stop_relay_flag(root));
let offset_text = offset.to_string();
let root_text = root.to_string_lossy().into_owned();
let log = root.join("Core/Logs/supervisor.log");
match supervisor {
Supervisor::Launcher(exe) => {
spawn(root, "supervisor", exe, &["--root", &root_text, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
}
Supervisor::Python { python, script } => {
let script = script.to_string_lossy().into_owned();
spawn(root, "supervisor", python, &["-B", &script, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
}
};
let first = Instant::now() + Duration::from_secs(20);
while state::running(root, "world").is_none() && Instant::now() < first {
if state::running(root, "supervisor").is_none() {
return Err(Error::Service(ErrorCode::StartupFailed, "World startup failed; check Core/Logs/supervisor.log.".into()));
}
std::thread::sleep(Duration::from_millis(250));
}
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
wait_ready(root, "world", cfg.ra_port, seconds_until(until))?;
wait_relay(root)?;
wait_console(root, cfg, until)?;
progress("Worldserver and automatic bug reporting are ready.");
Ok(())
}
fn spawn_child(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path) -> Result<Proc> {
// The supervisor was started with the environment its services should have.
let child = crate::launcher::spawn::start(exe, args, cwd, log, &[])?;
state::record(root, name, child.pid)?;
Ok(child)
}
/// The relay worker: `coa-launcher relay-worker` when the supervisor is the launcher (`launcher`), otherwise the
/// repack's Python running `Scripts/manage.py relay-worker` (BugReport/relay.py).
fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result<Proc> {
let log = root.join("BugReport/Logs/relay.log");
if let Some(exe) = launcher {
let root_text = root.to_string_lossy().into_owned();
return spawn_child(root, "relay", exe, &["--root", &root_text, "relay-worker"], root, &log);
}
let python = squid::package_root(root).join("Runtime/python/python.exe");
let manage = root.join("Scripts/manage.py");
if !python.is_file() || !manage.is_file() {
return Err(Error::Invalid("The bug-report relay needs the repack's Python and Scripts/manage.py.".into()));
}
let manage = manage.to_string_lossy().into_owned();
spawn_child(root, "relay", &python, &["-B", &manage, "relay-worker"], root, &root.join("BugReport/Logs/relay.log"))
}
/// The supervisor (`watch-world`): run the world, keep the relay alive while it runs, stop the relay after it.
/// `launcher` is the launcher executable that runs the relay (`None`: the Python relay). At the owner's scheduled
/// time it asks the world to restart with an in-game countdown and starts it again when it exits for that.
pub fn watch_world(root: &Path, launcher: Option<&Path>, offset: i32, log: Progress) -> Result<()> {
squid::validate_bots(root)?;
let mut relay: Option<Proc> = None;
let mut last_log_clean = Instant::now();
loop {
if let Some(report) = crate::server_logging::auto_clean_if_needed(root) {
if report.freed_bytes > 0 {
log(&format!("Auto-cleaned server logs ({} MB freed).", report.freed_bytes / (1024 * 1024)));
}
}
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
let started = schedule::now();
let mut requested = false;
let mut last_check: Option<Instant> = None;
let code = loop {
if let Some(code) = world.try_wait() {
break code;
}
let dead = relay.as_ref().is_none_or(|r| r.try_wait().is_some());
if dead {
match spawn_relay(root, launcher) {
Ok(r) => relay = Some(r),
Err(e) => {
log(&format!("Report relay could not start ({e}); retrying."));
std::thread::sleep(Duration::from_secs(5));
continue;
}
}
}
if last_check.is_none_or(|t| t.elapsed() >= Duration::from_secs(30)) {
last_check = Some(Instant::now());
if schedule::under_way(root) && !requested {
// The world that a scheduled restart started again is back once it accepts connections.
if Settings::load(root, offset).is_ok_and(|cfg| services::ready(root, "world", cfg.world_port)) {
schedule::clear_under_way(root);
}
}
if !requested {
let plan = schedule::load(root);
if let Some(due) = plan.due_restart(schedule::now(), started) {
let seconds = due.warning_minutes * 60;
let asked = Settings::load(root, offset).and_then(|cfg| {
crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
.and_then(|mut ra| ra.run(&format!("server restart {seconds}")))
});
match asked {
Ok(_) => {
schedule::mark_under_way(root)?;
requested = true;
log(&format!("Scheduled restart: the world restarts in {} minutes.", due.warning_minutes));
}
Err(e) => log(&format!("Scheduled restart could not be requested ({e}); retrying.")),
}
}
}
if last_log_clean.elapsed() >= Duration::from_secs(300) {
last_log_clean = Instant::now();
if let Some(report) = crate::server_logging::auto_clean_if_needed(root) {
if report.freed_bytes > 0 {
log(&format!("Auto-cleaned server logs ({} MB freed).", report.freed_bytes / (1024 * 1024)));
}
}
}
}
std::thread::sleep(Duration::from_secs(2));
};
if requested && code == schedule::RESTART_EXIT_CODE as u32 {
log("Scheduled restart: starting the world again.");
if let Err(e) = squid::validate_bots(root) {
schedule::clear_under_way(root);
return Err(e);
}
continue;
}
schedule::clear_under_way(root);
break;
}
std::fs::write(stop_relay_flag(root), b"")?;
if let Some(r) = relay {
let until = Instant::now() + Duration::from_secs(40);
while r.try_wait().is_none() && Instant::now() < until {
std::thread::sleep(Duration::from_millis(250));
}
if r.try_wait().is_none() {
// An interrupted POST stays uncertain in the relay's journal; it is not resent.
if let Some(record) = state::running(root, "relay") {
services::terminate(&record)?;
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------------------------------------------
// Detailed logging (Debug_Logs_On.bat / Debug_Logs_Off.bat)
// ---------------------------------------------------------------------------------------------------------------
const DEBUG_TEMPLATES: [&str; 2] = ["worldserver.conf.template", "authserver.conf.template"];
/// One template line with every logger forced to Trace and the console/server appenders to the most detail.
fn debug_line(line: &str) -> String {
let body = line.strip_prefix('#').unwrap_or(line).trim_start();
for appender in ["Appender.Console", "Appender.Server"] {
if let Some(rest) = body.strip_prefix(appender).and_then(|r| r.strip_prefix('=')) {
let parts: Vec<&str> = rest.splitn(4, ',').collect();
if parts.len() == 4 && parts[..3].iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
return format!("{appender}={},6,7,{}", parts[0], parts[3]);
}
}
}
if let Some(rest) = body.strip_prefix("Logger.") {
if let Some((name, value)) = rest.split_once('=') {
if !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.') {
if let Some((level, tail)) = value.split_once(',') {
if !level.is_empty() && level.bytes().all(|b| b.is_ascii_digit()) {
return format!("Logger.{name}=6,{tail}");
}
}
}
}
}
let t = line.trim_end();
if let Some(v) = t.strip_prefix("Log.Async.Enable") {
let v = v.trim_start();
if let Some(n) = v.strip_prefix('=') {
let n = n.trim();
if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) {
return "Log.Async.Enable = 1".into();
}
}
}
line.to_string()
}
/// Turn detailed logging on or off (the templates; services apply it at their next start). Returns the changed
/// templates.
pub fn debug_logs(root: &Path, enable: bool) -> Result<Vec<String>> {
let mut changed = Vec::new();
for name in DEBUG_TEMPLATES {
let path = root.join("Settings").join(name);
let original = root.join("Settings").join(format!("{name}.original"));
if !original.exists() {
std::fs::write(&original, std::fs::read(&path)?)?;
}
let new_bytes = if enable {
let text = String::from_utf8(std::fs::read(&original)?).map_err(|_| Error::Invalid(format!("{name} is not UTF-8.")))?;
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
let mut out = text.lines().map(debug_line).collect::<Vec<_>>().join(newline);
if text.ends_with('\n') {
out.push_str(newline);
}
out.into_bytes()
} else {
std::fs::read(&original)?
};
if std::fs::read(&path)? != new_bytes {
std::fs::write(&path, &new_bytes)?;
changed.push(name.to_string());
}
}
state::write_json(&state::dir(root).join("debug-logs.json"), &serde_json::json!({ "enabled": enable }))?;
Ok(changed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detailed_logging_rewrites_loggers_and_restores_the_original() {
let d = tempfile::tempdir().unwrap();
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
let world = "Appender.Console=1,3,0\r\nAppender.Server=2,2,0,Server.log,w\r\n#Logger.module=4,Console Server\r\nLogger.root=5,Console Server\r\nLog.Async.Enable = 0\r\nOther = 1\r\n";
std::fs::write(d.path().join("Settings/worldserver.conf.template"), world).unwrap();
std::fs::write(d.path().join("Settings/authserver.conf.template"), "Logger.root=2,Console\n").unwrap();
let changed = debug_logs(d.path(), true).unwrap();
assert_eq!(changed.len(), 2);
assert_eq!(
std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(),
"Appender.Console=1,3,0\r\nAppender.Server=2,6,7,Server.log,w\r\nLogger.module=6,Console Server\r\nLogger.root=6,Console Server\r\nLog.Async.Enable = 1\r\nOther = 1\r\n"
);
assert_eq!(debug_logs(d.path(), true).unwrap().len(), 0, "already on");
debug_logs(d.path(), false).unwrap();
assert_eq!(std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(), world);
assert_eq!(services::status(d.path())["debugLogs"], false);
}
}
-85
View File
@@ -1,85 +0,0 @@
import runpy
import sys
import time
from pathlib import Path
script = sys.argv[1]
sys.path.insert(0, str(Path(script).resolve().parent))
sys.argv = sys.argv[1:]
launcher = runpy.run_path(script, run_name="coa_manager_launcher")
original_wait = launcher["wait_ready"]
world_deadline = None
def wait_ready(name, port, seconds=180):
global world_deadline
if name == "mysql":
seconds = max(seconds, 300)
elif name == "world":
# Both game and console listeners belong to one startup, including on old repacks.
# Ordinary CoA worlds can load slowly too; this must not depend on SQUID.
if world_deadline is None:
world_deadline = time.monotonic() + max(seconds, 1500)
seconds = max(0, world_deadline - time.monotonic())
return original_wait(name, port, seconds)
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
if sys.argv[1] in ("stop-all", "force-stop-all"):
shutdown = launcher["stop_all"].__globals__
class UnsafeShutdown(Exception):
pass
def stop_owned_world(world):
expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe"
if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world):
raise UnsafeShutdown("World process ownership could not be verified; the database was left running.")
try:
shutdown["terminate"](world)
except (OSError, RuntimeError) as error:
raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error
if not shutdown["wait_stopped"](world, 90):
raise UnsafeShutdown("Worldserver is still stopping; its database was left running.")
if "ra" in shutdown:
original_ra = shutdown["ra"]
def shutdown_command(command, config):
try:
return original_ra(command, config)
except (OSError, RuntimeError):
if not command.startswith("server shutdown "):
raise
world = shutdown["process"]("world")
if not world:
return "Worldserver has already stopped."
stop_owned_world(world)
return "Stopped this server's recorded world process without its unavailable console."
shutdown["ra"] = shutdown_command
config = launcher["settings"]()
with launcher["control_lock"]():
if sys.argv[1] == "force-stop-all":
world = shutdown["process"]("world")
if world:
stop_owned_world(world)
print("Force-stopped this server's verified world process; unsaved progress may be lost.", flush=True)
launcher["stop_all"](config)
else:
launcher["main"]()
if sys.argv[1] in ("start-all", "start-world"):
config = launcher["settings"]()
deadline = world_deadline if world_deadline is not None else time.monotonic() + 1500
last_error = None
while time.monotonic() < deadline:
if not launcher["process"]("world"):
raise RuntimeError("World startup failed: worldserver stopped before its console accepted commands.")
try:
launcher["ra"]("server info", config)
print("World console is accepting commands.", flush=True)
break
except (OSError, RuntimeError) as error:
last_error = error
time.sleep(0.5)
else:
raise RuntimeError(f"World startup failed: its console is still starting. {last_error}")
+222
View File
@@ -0,0 +1,222 @@
//! `Scripts/manage.py` as Managers up to 0.9.10 edited it.
//!
//! Those Managers ran the repack's Python launcher themselves and changed its text: an import fix for their bridge
//! and a realm-profile patch (database and realm row of the active realm). This Manager starts servers with
//! [`crate::launcher`] and never edits the file; it only has to recognise those edits, so that an update or a file
//! check treats a file one of them changed as unmodified. Nothing here writes a file.
use crate::error::{Error, Result};
const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
];
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
fn launcher_insert() -> String {
LAUNCHER_REALM_INSERT
.replace("profiles-v1", "profiles-v2")
.replace(
"return 2 if",
"return 3 if coa_realm() == 'reborn' else 2 if",
)
.replace(
"return 'Wildcard' if",
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
)
}
fn launcher_replacements() -> Vec<(&'static str, String)> {
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
}
/// The realm-profile patch older Managers wrote.
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
if source.contains("# coa-manager-realm-profiles-v2") {
return Ok(source.into());
}
if source.contains("# coa-manager-realm-profiles-v1") {
let original = unpatch_launcher(source)
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
return patch_launcher(&original);
}
let mut out = source.to_string();
for (from, to) in launcher_replacements() {
if !out.contains(from) {
return Err(Error::Invalid(
"This launcher does not support realm profiles. Update the server package first."
.into(),
));
}
out = out.replace(from, &to);
}
// Insert before the entry point so ROOT, json and functions are all defined when called.
let marker = "if __name__ == \"__main__\":";
if !out.contains(marker) {
return Err(Error::Invalid(
"Unrecognised server launcher entry point.".into(),
));
}
Ok(out.replace(marker, &format!("{}{marker}", launcher_insert())))
}
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
let (insert, replacements) = if source.contains(&launcher_insert()) {
(launcher_insert(), launcher_replacements())
} else if source.contains(LAUNCHER_REALM_INSERT) {
(
LAUNCHER_REALM_INSERT.into(),
LAUNCHER_REALM_REPLACEMENTS
.iter()
.map(|(a, b)| (*a, b.to_string()))
.collect(),
)
} else {
return None;
};
let mut original = source.replacen(&insert, "", 1);
for (from, to) in &replacements {
original = original.replace(to, from);
}
let mut check = original.clone();
for (from, to) in &replacements {
check = check.replace(from, to);
}
check = check.replace(
"if __name__ == \"__main__\":",
&format!("{insert}if __name__ == \"__main__\":"),
);
(check == source).then_some(original)
}
/// The import fix older Managers wrote (needed to run manage.py through their bridge).
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
if !text.contains("from squid_playerbots import") || text.contains(line) {
return Ok(text.into());
}
let root = "ROOT = Path(__file__).resolve().parents[1]";
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
return Err(Error::Invalid(
"The server launcher cannot load its integration scripts. Repair its program files."
.into(),
));
}
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
}
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
if signed.as_bytes() == actual {
return true;
}
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) {
return true;
}
patch_launcher(signed).is_ok_and(|s| {
s.as_bytes() == actual || patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual)
})
}
/// Recover legacy metadata only when undoing supported Manager edits reproduces the recorded hash.
pub(crate) fn launcher_matches_recorded(recorded: &str, actual: &[u8]) -> bool {
let Ok(text) = std::str::from_utf8(actual) else {
return false;
};
let without_import = text.replacen(
"ROOT = Path(__file__).resolve().parents[1]\nsys.path.insert(0, str(Path(__file__).resolve().parent))",
"ROOT = Path(__file__).resolve().parents[1]", 1,
);
for candidate in [
Some(without_import.clone()),
unpatch_launcher(&without_import),
]
.into_iter()
.flatten()
{
if crate::fsx::sha256_bytes(candidate.as_bytes()).eq_ignore_ascii_case(recorded)
&& launcher_matches(&candidate, actual)
{
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fsx;
use std::collections::BTreeMap;
use std::fs;
#[test]
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
let mut old = original.to_string();
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
old = old.replace(from, to);
}
old = old.replace(
"if __name__ == \"__main__\":",
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
);
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
let new = patch_launcher(&old).unwrap();
assert!(new.contains("acore_world_reborn"));
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
assert!(new.contains("return 'Warcraft Reborn' if"));
assert_eq!(patch_launcher(&new).unwrap(), new);
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
}
#[test]
fn unknown_launcher_is_refused_without_partial_patching() {
assert!(patch_launcher("print('custom launcher')").is_err());
}
#[test]
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
let fixed = patch_launcher_imports(text).unwrap();
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
assert!(fixed.ends_with("custom = 42\n"));
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
}
#[test]
fn a_launcher_patched_by_an_older_manager_stays_pristine_but_external_edits_conflict() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("server");
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
// What an older Manager left: the realm patch applied and its hash recorded as the pristine one.
let patched = patch_launcher(source).unwrap();
fsx::atomic_write(&root.join("Scripts/manage.py"), patched.as_bytes()).unwrap();
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
meta.original_hashes.insert("Scripts/manage.py".into(), fsx::sha256_bytes(patched.as_bytes()));
crate::registry::MetaDir::create(&root, &meta).unwrap();
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
})).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Replace
);
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
modified.extend_from_slice(b"# custom edit\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Conflict
);
}
}
+4 -1
View File
@@ -9,13 +9,13 @@
pub mod accounts; pub mod accounts;
pub mod allsettings; pub mod allsettings;
pub mod addons;
pub mod backup; pub mod backup;
pub mod channels; pub mod channels;
pub mod character_start_check; pub mod character_start_check;
pub mod cleanbase; pub mod cleanbase;
pub mod client; pub mod client;
pub mod client_graphics; pub mod client_graphics;
pub mod clientdl;
pub mod companions; pub mod companions;
pub mod config; pub mod config;
pub mod console; pub mod console;
@@ -28,6 +28,7 @@ pub mod diag;
pub mod docker; pub mod docker;
pub mod download; pub mod download;
pub mod driver; pub mod driver;
pub mod legacy_launcher;
pub mod error; pub mod error;
pub mod firewall; pub mod firewall;
pub mod friends; pub mod friends;
@@ -36,6 +37,7 @@ pub mod glue_config;
pub mod health; pub mod health;
pub mod install; pub mod install;
pub mod layout; pub mod layout;
pub mod launcher;
pub mod logging; pub mod logging;
pub mod server_logging; pub mod server_logging;
pub mod manifest; pub mod manifest;
@@ -54,6 +56,7 @@ pub mod ra;
pub mod race_availability; pub mod race_availability;
pub mod realm_registry; pub mod realm_registry;
pub mod realmlist; pub mod realmlist;
pub mod realm_names;
pub mod realms; pub mod realms;
pub mod registry; pub mod registry;
pub mod release; pub mod release;
+58 -1
View File
@@ -48,6 +48,10 @@ pub struct Entry {
/// Not shown on the Modules page; its settings are offered elsewhere (a server setting card). /// Not shown on the Modules page; its settings are offered elsewhere (a server setting card).
#[serde(default)] #[serde(default)]
pub hidden: bool, pub hidden: bool,
/// A part of another module, switched and set up inside that module's settings (Custom Races V2 brings
/// subclasses and the /dev menu).
#[serde(default)]
pub part_of: Option<String>,
} }
fn yes() -> bool { fn yes() -> bool {
@@ -111,6 +115,7 @@ pub struct ModuleView {
pub page: Option<String>, pub page: Option<String>,
pub hidden: bool, pub hidden: bool,
pub compatibility: String, pub compatibility: String,
pub part_of: Option<String>,
} }
pub fn list(root: &Path) -> Vec<ModuleView> { pub fn list(root: &Path) -> Vec<ModuleView> {
@@ -171,6 +176,32 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
Default::default() Default::default()
} }
/// The companion bots of this server build play Wildcard and Warcraft Reborn: their bot profiles for the standard
/// classes are in the world server or its bots plugin. Older builds only know Conquest of Azeroth characters.
pub fn companions_on_other_realms(root: &Path) -> bool {
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
static SEEN: OnceLock<Mutex<HashMap<(PathBuf, u64, Option<std::time::SystemTime>), bool>>> = OnceLock::new();
const MARKER: &[u8] = b"Druid_Guardian_Tank";
let mut files = vec![crate::layout::executables(root).0];
if let Ok(plugins) = fs::read_dir(root.join("Core/plugins")) {
files.extend(plugins.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("dll"))));
}
files.into_iter().any(|file| {
let Ok(meta) = fs::metadata(&file) else { return false };
let key = (file.clone(), meta.len(), meta.modified().ok());
let seen = SEEN.get_or_init(Mutex::default);
if let Some(found) = seen.lock().ok().and_then(|s| s.get(&key).copied()) {
return found;
}
let found = fs::read(&file).is_ok_and(|bytes| bytes.windows(MARKER.len()).any(|w| w == MARKER));
if let Ok(mut s) = seen.lock() {
s.insert(key, found);
}
found
})
}
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> { fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
let installed_commits = installed_module_commits(root); let installed_commits = installed_module_commits(root);
let wildcard = crate::realms::state(root) let wildcard = crate::realms::state(root)
@@ -203,7 +234,9 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
.map(|enabled| !enabled) .map(|enabled| !enabled)
.unwrap_or(true); .unwrap_or(true);
let blocked = dependency_missing let blocked = dependency_missing
|| (wildcard && matches!(e.id.as_str(), "companions" | "playerbots" | "dungeon-clear")); || (wildcard
&& (matches!(e.id.as_str(), "playerbots" | "dungeon-clear")
|| (e.id == "companions" && !companions_on_other_realms(root))));
let version = if e.id == "playerbots" { let version = if e.id == "playerbots" {
crate::squid::release(root).map(|release| { crate::squid::release(root).map(|release| {
[ [
@@ -256,6 +289,7 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
icon: e.icon, icon: e.icon,
page: e.page, page: e.page,
hidden: e.hidden, hidden: e.hidden,
part_of: e.part_of,
} }
}) })
.collect() .collect()
@@ -716,6 +750,27 @@ mod tests {
assert!(meta.join("backups").exists()); assert!(meta.join("backups").exists());
} }
#[test]
fn companions_open_on_other_realms_only_with_a_build_that_plays_them() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("server");
fs::create_dir_all(dir(&root)).unwrap();
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(root.join("Settings/realm-profile.json"), r#"{"active":"wildcard","wildcard_created":true}"#).unwrap();
for e in catalog().iter().filter(|e| matches!(e.id.as_str(), "companions" | "playerbots")) {
fs::write(dir(&root).join(format!("{}.dist", e.conf)), format!("{} = 0\n", e.enable_key)).unwrap();
}
let exe = crate::layout::executables(&root).0;
fs::write(&exe, b"an old world server").unwrap();
let view = |id: &str| list(&root).into_iter().find(|m| m.id == id).unwrap();
assert_eq!(view("companions").compatibility, "unsupported");
fs::write(&exe, b"profiles ... Druid_Guardian_Tank ... a new world server").unwrap();
assert!(companions_on_other_realms(&root));
assert_eq!(view("companions").compatibility, "experimental");
assert!(view("companions").switchable);
assert_eq!(view("playerbots").compatibility, "unsupported", "SQUID stays CoA-only");
}
fn test_catalog() -> Vec<Entry> { fn test_catalog() -> Vec<Entry> {
let one = |id: &str, name: &str, conf: &str, key: &str| Entry { let one = |id: &str, name: &str, conf: &str, key: &str| Entry {
id: id.into(), id: id.into(),
@@ -734,6 +789,7 @@ mod tests {
icon: String::new(), icon: String::new(),
page: None, page: None,
hidden: false, hidden: false,
part_of: None,
}; };
vec![ vec![
one( one(
@@ -1379,6 +1435,7 @@ mod tests {
icon: String::new(), icon: String::new(),
page: None, page: None,
hidden: false, hidden: false,
part_of: None,
}; };
let cat = vec![compat]; let cat = vec![compat];
let v = list_in(&cat, &root).remove(0); let v = list_in(&cat, &root).remove(0);
+70 -28
View File
@@ -97,6 +97,58 @@ pub fn world_root(main: &Path, mode: Mode) -> PathBuf {
.map_or_else(|| main.to_path_buf(), |t| tree_root(main, t)) .map_or_else(|| main.to_path_buf(), |t| tree_root(main, t))
} }
#[derive(Debug, Clone)]
pub struct BotOperationTarget {
pub world_root: PathBuf,
pub chars_db: &'static str,
pub ra_port: u16,
pub running: bool,
pub realm: Mode,
}
pub fn resolve_bot_operation_target(main: &Path, realm: Mode) -> Result<BotOperationTarget> {
let state = realms::state(main)?;
let chars_db = realm.schema("characters")?;
if realm == state.active {
let ports = crate::layout::read_ports(main);
let ra_port = ports.ra;
let status = process::observe(main, &ports);
let running = status.world.state != ServiceState::Stopped;
return Ok(BotOperationTarget {
world_root: main.to_path_buf(),
chars_db,
ra_port,
running,
realm,
});
}
let tree = Tree::ALL
.into_iter()
.find(|t| t.enabled(&state) && t.mode(state.active) == realm)
.ok_or_else(|| Error::Invalid(format!("Realm {} is not enabled in multiworld configuration.", realm.label())))?;
let root = tree_root(main, tree);
if !root.exists() {
return Err(Error::Invalid(format!("Multiworld directory for {} does not exist: {}", realm.label(), root.display())));
}
let ports = crate::layout::read_ports(&root);
let (_, default_ra) = tree.ports(&state);
let ra_port = if ports.ra != 0 { ports.ra } else { default_ra.unwrap_or(3444) };
let status = process::observe(&root, &ports);
let running = status.world.state != ServiceState::Stopped;
Ok(BotOperationTarget {
world_root: root,
chars_db,
ra_port,
running,
realm,
})
}
/// Any of the extra worlds is running or still stopping. /// Any of the extra worlds is running or still stopping.
pub fn is_running(main: &Path) -> bool { pub fn is_running(main: &Path) -> bool {
Tree::ALL.into_iter().any(|t| tree_running(main, t)) Tree::ALL.into_iter().any(|t| tree_running(main, t))
@@ -176,7 +228,6 @@ fn set_tree(main: &Path, tree: Tree, enabled: bool) -> Result<realms::View> {
} }
} }
} }
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
} }
let status = process::observe(main, &crate::layout::read_ports(main)); let status = process::observe(main, &crate::layout::read_ports(main));
if status.world.state != ServiceState::Stopped if status.world.state != ServiceState::Stopped
@@ -262,6 +313,12 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
&fsx::ensure_within(&second, &second.join("Core/reference"))?, &fsx::ensure_within(&second, &second.join("Core/reference"))?,
)?; )?;
} }
if main.join("Core/plugins").is_dir() {
copy_tree(
&main.join("Core/plugins"),
&fsx::ensure_within(&second, &second.join("Core/plugins"))?,
)?;
}
for entry in fs::read_dir(main.join("Core"))? { for entry in fs::read_dir(main.join("Core"))? {
let entry = entry?; let entry = entry?;
if entry.file_type()?.is_file() if entry.file_type()?.is_file()
@@ -349,25 +406,18 @@ fn prepare(main: &Path, tree: Tree) -> Result<PathBuf> {
..Default::default() ..Default::default()
}, },
)?; )?;
let source = fs::read_to_string(main.join("Scripts/manage.py"))?; // The world supervisor and the bug-report relay of the extra world (the launcher itself runs in the Manager
let source = secondary_launcher(&source)?; // and knows that this world shares the main database).
fsx::atomic_write(&second.join("Scripts/manage.py"), source.as_bytes())?; for script in ["Scripts/coa-launcher.exe", "Scripts/manage.py"] {
Ok(second) let target = second.join(script);
} if main.join(script).is_file() {
fs::create_dir_all(second.join("Scripts"))?;
fn secondary_launcher(source: &str) -> Result<String> { fsx::atomic_write(&target, &fs::read(main.join(script))?)?;
let marker = "def start_world(config, offset):\n start_mysql(config)"; } else if target.exists() {
let source = source.replace("\r\n", "\n"); fs::remove_file(&target)?;
if !source.contains(marker) {
return Err(Error::Invalid(
"The launcher does not support a shared database world. Update the server first."
.into(),
));
} }
Ok(source.replace( }
marker, Ok(second)
"def start_world(config, offset):\n mysql(admin=\"ping\")",
))
} }
fn start_tree(main: &Path, tree: Tree) -> Result<()> { fn start_tree(main: &Path, tree: Tree) -> Result<()> {
@@ -408,7 +458,7 @@ pub fn start(main: &Path) -> Result<()> {
fn stop_tree(main: &Path, tree: Tree) -> Result<()> { fn stop_tree(main: &Path, tree: Tree) -> Result<()> {
let second = tree_root(main, tree); let second = tree_root(main, tree);
if !second.join("Scripts/manage.py").exists() { if !second.join("Settings/repack.json").exists() {
if tree_running(main, tree) { if tree_running(main, tree) {
return Err(Error::Invalid(format!( return Err(Error::Invalid(format!(
"The running {}'s launcher is missing. The shared database was left running.", "The running {}'s launcher is missing. The shared database was left running.",
@@ -505,12 +555,4 @@ mod tests {
assert!(err.contains(expected), "{err}"); assert!(err.contains(expected), "{err}");
assert!(!realms::state(t.path()).unwrap().with_reborn); 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();
assert!(patched.contains("mysql(admin=\"ping\")"));
assert!(!patched.contains("start_mysql(config)"));
assert!(secondary_launcher("def start_world(): pass").is_err());
}
} }
+27 -10
View File
@@ -49,17 +49,19 @@ fn parse_counts(out: &str) -> Result<Population> {
}) })
} }
/// Read-only query with the game's own database account. Requires the database to be running. /// Read-only query with the game's own database account. Routes automatically to the active realm's characters database.
pub fn query(root: &Path) -> Result<Population> { pub fn query(root: &Path) -> Result<Population> {
let db = Db::from_repack(root, Account::App)?; let mode = crate::realms::state(root)
query_with( .map(|s| s.active)
&db, .unwrap_or(crate::realms::Mode::Coa);
&bot_account_prefix(root), query_for_realm(root, mode)
&crate::accounts::squid_bot_prefix(root),
)
} }
fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> { fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
counts_sql_for_db("acore_characters", prefix, squid_prefix)
}
pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<String> {
if [prefix, squid_prefix] if [prefix, squid_prefix]
.iter() .iter()
.any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric())) .any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()))
@@ -74,9 +76,9 @@ fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
let bots = let bots =
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')"); format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
Ok(format!( Ok(format!(
"SELECT (SELECT COUNT(*) FROM acore_characters.characters WHERE online=1), \ "SELECT (SELECT COUNT(*) FROM {chars_db}.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 {bots}), \ (SELECT COUNT(*) FROM {chars_db}.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});" (SELECT COUNT(*) FROM {chars_db}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});"
)) ))
} }
@@ -85,6 +87,21 @@ pub fn query_with(db: &Db, prefix: &str, squid_prefix: &str) -> Result<Populatio
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?) parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
} }
pub fn query_for_schema(db: &Db, chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<Population> {
parse_counts(&db.query(&counts_sql_for_db(chars_db, prefix, squid_prefix)?)?)
}
pub fn query_for_realm(root: &Path, mode: crate::realms::Mode) -> Result<Population> {
let db = Db::from_repack(root, Account::App)?;
let schema = mode.schema("characters")?;
query_for_schema(
&db,
schema,
&bot_account_prefix(root),
&crate::accounts::squid_bot_prefix(root),
)
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct Hardware { pub struct Hardware {
pub cores: u32, pub cores: u32,
+79 -1
View File
@@ -58,6 +58,23 @@ impl Ra {
Self::connect_to(read_ports(root).ra, &cfg.ra_username, &cfg.ra_password) Self::connect_to(read_ports(root).ra, &cfg.ra_username, &cfg.ra_password)
} }
/// Connect to the loopback RA port of the target realm world server.
pub fn connect_target(main: &Path, realm: Option<crate::realms::Mode>) -> Result<Ra> {
let mode = realm.unwrap_or_else(|| {
crate::realms::view(main).map(|v| v.active).unwrap_or_default()
});
let target = crate::multiworld::resolve_bot_operation_target(main, mode)?;
if !target.running {
return Err(Error::Invalid(format!(
"Realm {} worldserver is stopped; cannot execute online bot operation.",
target.realm.label()
)));
}
let cfg: RaSettings = fsx::read_json(&main.join("Settings/repack.json"))
.map_err(|_| Error::Invalid("The server console settings could not be read.".into()))?;
Self::connect_to(target.ra_port, &cfg.ra_username, &cfg.ra_password)
}
pub fn connect_to(port: u16, user: &str, password: &str) -> Result<Ra> { pub fn connect_to(port: u16, user: &str, password: &str) -> Result<Ra> {
let addr: SocketAddr = ([127, 0, 0, 1], port).into(); let addr: SocketAddr = ([127, 0, 0, 1], port).into();
let mut stream = let mut stream =
@@ -87,7 +104,28 @@ impl Ra {
let c = crate::console::check_command(cmd)?; let c = crate::console::check_command(cmd)?;
self.command(c) self.command(c)
} }
/// Send a command whose answer does not matter (`server shutdown`). The reply is still read (up to the next
/// prompt, the end of the connection, or a few seconds): closing a socket that holds unread data resets the
/// connection, and the server can then drop the command it has not processed yet.
pub fn send_without_answer(mut self, cmd: &str) -> Result<()> {
let c = crate::console::check_command(cmd)?;
self.stream.write_all(format!("{c}\r\n").as_bytes())?;
self.stream.flush()?;
self.stream.set_read_timeout(Some(Duration::from_secs(10)))?;
let mut seen = Vec::new();
let mut buf = [0u8; 4096];
while let Ok(n) = self.stream.read(&mut buf) {
if n == 0 {
break;
}
seen.extend_from_slice(&buf[..n]);
if seen.ends_with(b"AC>") || seen.len() > 1 << 20 {
break;
}
}
let _ = self.stream.shutdown(std::net::Shutdown::Both);
Ok(())
}
fn command(&mut self, cmd: &str) -> Result<String> { fn command(&mut self, cmd: &str) -> Result<String> {
debug_assert!(!cmd.contains(['\r', '\n'])); debug_assert!(!cmd.contains(['\r', '\n']));
self.stream.write_all(format!("{cmd}\r\n").as_bytes())?; self.stream.write_all(format!("{cmd}\r\n").as_bytes())?;
@@ -235,6 +273,11 @@ impl Ra {
Ok(out.lines().last().unwrap_or("").to_string()) Ok(out.lines().last().unwrap_or("").to_string())
} }
/// Delete the companion bots of custom races (RaceID above 11), every other bot stays. Returns how many.
pub fn purge_custom_race_bots(&mut self) -> Result<u32> {
Ok(first_number(&self.bot_command("botcmd purgecustomraces")?))
}
/// Ask the bot module to create `count` leveling bots (throttled by the module itself). Only a number is sent. /// Ask the bot module to create `count` leveling bots (throttled by the module itself). Only a number is sent.
pub fn spawn_bots(&mut self, count: u32) -> Result<String> { pub fn spawn_bots(&mut self, count: u32) -> Result<String> {
if !(1..=2000).contains(&count) { if !(1..=2000).contains(&count) {
@@ -249,6 +292,41 @@ impl Ra {
Ok(out.lines().last().unwrap_or("").to_string()) Ok(out.lines().last().unwrap_or("").to_string())
} }
/// Ask the bot module to spawn a fleet of bots of specific race and level (.botcmd spawnfleet <race> <level>).
pub fn spawn_fleet(&mut self, race: u8, level: u8) -> Result<String> {
let out = self.bot_command(&format!("botcmd spawnfleet {race} {level}"))?;
Ok(out.lines().last().unwrap_or("").to_string())
}
pub fn spawn_custom(
&mut self,
count: u32,
level: u8,
class_id: Option<u8>,
spec_id: Option<u32>,
archetype: Option<&str>,
) -> Result<String> {
let c = class_id.unwrap_or(0);
let s = spec_id.unwrap_or(0);
let a = archetype.unwrap_or("").trim();
let mut cmd = format!("botcmd spawncustom {count} {level}");
if !a.is_empty() {
cmd.push_str(&format!(" {c} {s} {a}"));
} else if s > 0 {
cmd.push_str(&format!(" {c} {s}"));
} else if c > 0 {
cmd.push_str(&format!(" {c}"));
}
let out = self.bot_command(&cmd)?;
Ok(out.lines().last().unwrap_or("").to_string())
}
/// Bring all offline bots online gradually (.botcmd loginall).
pub fn login_all(&mut self) -> Result<String> {
let out = self.bot_command("botcmd loginall")?;
Ok(out.lines().last().unwrap_or("").to_string())
}
/// Set a new password for an existing account. /// Set a new password for an existing account.
pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> { pub fn set_account_password(&mut self, name: &str, password: &str) -> Result<()> {
validate_account(name, password)?; validate_account(name, password)?;
+171
View File
@@ -269,9 +269,95 @@ pub fn save(
), ),
]), ]),
)?; )?;
write_snapshot(root, &current.catalog_sha256, &current.races)?;
status(root) status(root)
} }
/// Every race catalog (`ChrRaces.dbc` of the custom races overlay) a server build has shipped, by SHA-256:
/// RaceID -> name. Generated from the core repository's history of the overlay.
const SHIPPED_CATALOGS: &str = include_str!("race_catalogs.json");
/// The names of the catalog a restriction was saved against, written by every save.
const SNAPSHOT: &str = "Settings/race-catalog.json";
#[derive(serde::Deserialize, Serialize)]
struct Snapshot {
sha256: String,
races: BTreeMap<u32, String>,
}
/// RaceID -> name of the catalog with `hash`: this server's own snapshot, or a catalog a build shipped.
fn names_of(root: &Path, hash: &str) -> Option<BTreeMap<u32, String>> {
if let Ok(snapshot) = crate::fsx::read_json::<Snapshot>(&root.join(SNAPSHOT)) {
if snapshot.sha256.eq_ignore_ascii_case(hash) {
return Some(snapshot.races);
}
}
#[derive(serde::Deserialize)]
struct Shipped {
catalogs: BTreeMap<String, BTreeMap<u32, String>>,
}
let shipped: Shipped = serde_json::from_str(SHIPPED_CATALOGS).ok()?;
shipped.catalogs.get(&hash.to_ascii_lowercase()).cloned()
}
fn write_snapshot(root: &Path, hash: &str, races: &[Race]) -> Result<()> {
crate::fsx::atomic_write_json(
&root.join(SNAPSHOT),
&Snapshot {
sha256: hash.to_string(),
races: races.iter().map(|race| (race.id, race.name.clone())).collect(),
},
)
}
/// A server update that only adds races keeps the owner's restriction. The worldserver ignores a restriction
/// saved against another catalog (and with it the whole custom races switch), so before a start: when every
/// disabled race still has its RaceID and name in the new catalog, the restriction is bound to the new catalog.
/// Anything else (an unknown old catalog, a renamed or missing race) is left for the owner to review. Returns
/// whether the restriction was bound again.
pub fn rebind_unchanged(root: &Path) -> Result<bool> {
let conf_path = root.join(CONF);
let Ok(conf_bytes) = fs::read(&conf_path) else {
return Ok(false);
};
let mut conf = ConfFile::parse_bytes(&conf_bytes)?;
let configured = parse_ids(conf.get(KEY).unwrap_or(""))?;
let saved = conf
.get(CATALOG_KEY)
.unwrap_or("")
.trim()
.trim_matches('"')
.to_ascii_lowercase();
if configured.is_empty() || saved.is_empty() {
return Ok(false);
}
let Ok(bytes) = fs::read(dbc_path(root)?) else {
return Ok(false);
};
let current = hex::encode(Sha256::digest(&bytes));
if saved == current {
return Ok(false);
}
let races = catalog(&bytes)?;
let Some(before) = names_of(root, &saved) else {
tracing::warn!("race restriction saved against an unknown catalog; it needs the owner's review");
return Ok(false);
};
let now: BTreeMap<u32, &str> = races.iter().map(|race| (race.id, race.name.as_str())).collect();
let unchanged = configured
.iter()
.all(|id| before.get(id).is_some_and(|name| now.get(id) == Some(&name.as_str())));
if !unchanged {
tracing::warn!("a restricted race changed in the new catalog; the restriction needs the owner's review");
return Ok(false);
}
conf.set(CATALOG_KEY, &format!("\"{current}\""), &[]);
crate::fsx::atomic_write(&conf_path, conf.to_text().as_bytes())?;
write_snapshot(root, &current, &races)?;
tracing::info!(races = configured.len(), "race restriction kept for the updated race catalog");
Ok(true)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -292,6 +378,91 @@ mod tests {
bytes bytes
} }
fn catalog_of(rows: &[(u32, &str)]) -> Vec<u8> {
let mut strings = vec![0u8];
let mut offsets = Vec::new();
for (_, name) in rows {
offsets.push(strings.len() as u32);
strings.extend(name.as_bytes());
strings.push(0);
}
let mut bytes = b"WDBC".to_vec();
for value in [rows.len() as u32, 69, 276, strings.len() as u32] {
bytes.extend(value.to_le_bytes());
}
for ((id, _), offset) in rows.iter().zip(offsets) {
let mut row = vec![0; 276];
row[..4].copy_from_slice(&id.to_le_bytes());
row[56..60].copy_from_slice(&offset.to_le_bytes());
bytes.extend(row);
}
bytes.extend(strings);
bytes
}
fn restricted_server(catalog: &[u8], disabled: &str, saved_hash: &str) -> tempfile::TempDir {
let d = tempfile::tempdir().unwrap();
fs::create_dir_all(d.path().join("Data/dbc_races")).unwrap();
fs::create_dir_all(d.path().join("Core/configs/modules")).unwrap();
fs::write(d.path().join("Data/dbc_races/ChrRaces.dbc"), catalog).unwrap();
fs::write(
d.path().join(CONF),
format!("CoACustomRaces.Enable = 1\nCoACustomRaces.DisabledRaceIds = \"{disabled}\"\nCoACustomRaces.DisabledRaceCatalogSha256 = \"{saved_hash}\"\n"),
)
.unwrap();
d
}
fn sha(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
#[test]
fn a_catalog_that_only_adds_races_keeps_the_restriction() {
let old = catalog_of(&[(83, "Vulpera"), (97, "Gnoll")]);
let new = catalog_of(&[(83, "Vulpera"), (97, "Gnoll"), (120, "Nerubian")]);
let d = restricted_server(&new, "83", &sha(&old));
write_snapshot(d.path(), &sha(&old), &catalog(&old).unwrap()).unwrap();
assert!(rebind_unchanged(d.path()).unwrap());
let conf = ConfFile::parse_bytes(&fs::read(d.path().join(CONF)).unwrap()).unwrap();
assert_eq!(conf.get(KEY), Some("\"83\""));
assert_eq!(
conf.get(CATALOG_KEY).map(|h| h.trim_matches('"').to_string()),
Some(sha(&new))
);
assert_eq!(conf.get("CoACustomRaces.Enable"), Some("1"));
assert!(!rebind_unchanged(d.path()).unwrap(), "already bound");
}
#[test]
fn a_renamed_race_or_unknown_catalog_waits_for_review() {
let old = catalog_of(&[(83, "Thin Human"), (97, "Gnoll")]);
let renamed = catalog_of(&[(83, "Forgotten"), (97, "Gnoll")]);
let d = restricted_server(&renamed, "83", &sha(&old));
write_snapshot(d.path(), &sha(&old), &catalog(&old).unwrap()).unwrap();
assert!(!rebind_unchanged(d.path()).unwrap());
let unknown = restricted_server(&renamed, "97", &"ab".repeat(32));
assert!(!rebind_unchanged(unknown.path()).unwrap());
// Nothing is restricted: nothing to bind.
let empty = restricted_server(&renamed, "", &sha(&old));
assert!(!rebind_unchanged(empty.path()).unwrap());
}
#[test]
fn the_shipped_catalogs_include_1_9_2_and_v2_with_stable_ids() {
let shipped: serde_json::Value = serde_json::from_str(SHIPPED_CATALOGS).unwrap();
let catalogs = shipped["catalogs"].as_object().unwrap();
let size = |c: &serde_json::Value| c.as_object().unwrap().len();
assert!(catalogs.values().any(|c| size(c) == 95), "1.9.2 has 95 races");
let v2: Vec<_> = catalogs.values().filter(|c| size(c) == 112).collect();
assert_eq!(v2.len(), 1, "V2 has 112 races");
for old in catalogs.values().filter(|c| size(c) == 95) {
for (id, name) in old.as_object().unwrap() {
assert_eq!(&v2[0][id], name, "race {id}");
}
}
}
#[test] #[test]
fn catalog_preserves_ids_and_excludes_stock_and_nonplayable() { fn catalog_preserves_ids_and_excludes_stock_and_nonplayable() {
let mut bytes = dbc(); let mut bytes = dbc();
+639
View File
@@ -0,0 +1,639 @@
{
"catalogs": {
"0f9e05112d56609a87f0b1900be88f8130a8fcb24ee4acae585f1fd8d9144bf0": {
"1": "Human",
"10": "Blood Elf",
"100": "Drakonid",
"103": "Grummle",
"11": "Draenei",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Thin Human",
"33": "Thin Human",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"77": "High Order Skyborne",
"78": "Jinyu",
"79": "Arakkoa",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"9": "Goblin",
"97": "Saberon",
"98": "Drakonid",
"99": "Drakkin"
},
"358503359af5b05d16a76f61bab77b5c6221c792bcb0e11793eba8e279689ff7": {
"1": "Human",
"10": "Blood Elf",
"11": "Draenei",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Thin Human",
"33": "Thin Human",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"77": "High Order Skyborne",
"78": "Jinyu",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"9": "Goblin",
"97": "Saberon"
},
"6ad3ac1ad6ef7f32ed347e979cd1667bb5393d7a0967a859e5ba3cfa2a5d04c7": {
"1": "Human",
"10": "Blood Elf",
"100": "Drakonid",
"101": "Venthyr",
"102": "Centaur",
"103": "Grummle",
"104": "Slime Giant",
"106": "Mantid",
"107": "Kyrian",
"109": "Ethereal",
"11": "Draenei",
"110": "Sylvari",
"112": "Hozen",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Forgotten",
"33": "Forgotten",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"75": "Centaur",
"77": "High Order Skyborne",
"78": "Jinyu",
"79": "Arakkoa",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"87": "Faceless One",
"9": "Goblin",
"90": "Banshee",
"97": "Saberon",
"98": "Drakonid",
"99": "Drakkin"
},
"833e18c0f0550d400e78ee5db00bd65bf86d051861fe6b795c0539e3fd9f125d": {
"1": "Human",
"10": "Blood Elf",
"11": "Draenei",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Thin Human",
"33": "Thin Human",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"77": "High Order Skyborne",
"8": "Troll",
"9": "Goblin"
},
"9a49163b9a330d844f0add5a2023f538b828bd5c57d6ecbb3cd5b4196930c5da": {
"1": "Human",
"10": "Blood Elf",
"103": "Grummle",
"11": "Draenei",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Thin Human",
"33": "Thin Human",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"77": "High Order Skyborne",
"78": "Jinyu",
"79": "Arakkoa",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"9": "Goblin",
"97": "Saberon"
},
"b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f": {
"1": "Human",
"10": "Blood Elf",
"100": "Drakonid",
"101": "Venthyr",
"102": "Centaur",
"103": "Grummle",
"104": "Slime Giant",
"106": "Mantid",
"107": "Kyrian",
"109": "Ethereal",
"11": "Draenei",
"110": "Sylvari",
"112": "Hozen",
"12": "Zandalari Troll",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Forgotten",
"33": "Forgotten",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"75": "Centaur",
"77": "High Order Skyborne",
"78": "Jinyu",
"79": "Arakkoa",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"87": "Faceless One",
"9": "Goblin",
"90": "Banshee",
"97": "Saberon",
"98": "Drakonid",
"99": "Drakkin"
},
"bff09e612ba44567a5c7d928562d6261755504dc8948daa334e675bf49b54938": {
"1": "Human",
"10": "Blood Elf",
"100": "Drakonid",
"101": "Venthyr",
"102": "Centaur",
"103": "Grummle",
"104": "Slime Giant",
"105": "Gilgoblin",
"106": "Mantid",
"107": "Kyrian",
"109": "Ethereal",
"11": "Draenei",
"110": "Sylvari",
"111": "Sporeling",
"112": "Hozen",
"114": "Stormforged",
"118": "Elune's Chosen",
"119": "Mo'arg",
"12": "Zandalari Troll",
"120": "Nerubian",
"122": "Lich",
"123": "Mogu",
"125": "Lost One",
"13": "Worgen",
"14": "High Elf",
"15": "Tuskarr",
"16": "Kul Tiran",
"17": "Taunka",
"18": "Vrykul",
"19": "Vulpera",
"2": "Orc",
"20": "Pandaren",
"21": "Naga",
"22": "Broken",
"23": "Fel Orc",
"24": "Forest Troll",
"25": "Ice Troll",
"26": "Skeleton",
"27": "Earthen",
"28": "Drakkari Troll",
"29": "Pandaren",
"3": "Dwarf",
"30": "Murloc",
"31": "Murloc",
"32": "Forgotten",
"33": "Forgotten",
"34": "Fel Orc",
"35": "Naga",
"36": "Broken",
"37": "Skeleton",
"38": "Vrykul",
"39": "Tuskarr",
"4": "Night Elf",
"40": "Forest Troll",
"41": "Taunka",
"42": "Northrend Skeleton",
"43": "Ice Troll",
"44": "Drakkari Troll",
"45": "Leper Troll",
"46": "Troglodyte",
"47": "Alpha Worgen",
"48": "Dark Iron Dwarf",
"49": "Mag'har Orc",
"5": "Undead",
"50": "Furbolg",
"51": "Undead Gnome",
"52": "Orc",
"53": "Ogre",
"54": "Dracthyr",
"55": "Eredar",
"56": "Harpy",
"57": "Alpha Goblin",
"58": "Dracthyr",
"59": "Void Elf",
"6": "Tauren",
"60": "Illidari Blood Elf",
"61": "Illidari Night Elf",
"62": "Lightforged Draenei",
"63": "Nightborne",
"65": "Test Race",
"66": "Highmountain Tauren",
"67": "Mechagnome",
"68": "Earthen",
"69": "Earthen",
"7": "Gnome",
"70": "Haranir",
"71": "Haranir",
"72": "Windshaper Skyborne",
"74": "Vulpera",
"75": "Centaur",
"77": "High Order Skyborne",
"78": "Jinyu",
"79": "Arakkoa",
"8": "Troll",
"80": "Darkfallen",
"81": "Darkfallen",
"82": "Sethrak",
"83": "Gnoll",
"85": "Two-Headed Ogre",
"86": "Sureki",
"87": "Faceless One",
"88": "Qiraji",
"89": "Dreadlord",
"9": "Goblin",
"90": "Banshee",
"91": "Titan",
"92": "Wretched",
"93": "Fungarian",
"96": "Thin Human",
"97": "Saberon",
"98": "Drakonid",
"99": "Drakkin"
}
},
"schema": 1,
"source": "Corfirean/azerothcore-wotlk-coa modules/mod-coa-custom-races/data/dbc/ChrRaces.dbc"
}
+216
View File
@@ -0,0 +1,216 @@
//! The names players see in the realm list, chosen by the server owner.
//!
//! The launcher writes `acore_auth.realmlist.name` at every start, so a name typed into the database (or into
//! an old `manage.py`) did not last. The owner's choice lives in `Settings/realm-names.json` of the server's main
//! folder, keyed by realm id, and every start and every realm-list setup uses it; extra worlds read their main
//! folder's file.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use crate::error::{Error, Result};
use crate::fsx;
const FILE: &str = "Settings/realm-names.json";
/// `acore_auth.realmlist.name` is `varchar(32)`.
pub const MAX_CHARS: usize = 32;
#[derive(Debug, Default, Serialize, Deserialize)]
struct Names {
#[serde(default)]
names: BTreeMap<u32, String>,
}
/// The folder that owns the names: an extra world (`<server>/.realms/<name>`) belongs to `<server>`.
fn main_folder(root: &Path) -> PathBuf {
if crate::launcher::settings::is_extra_world(root) {
if let Some(main) = root.parent().and_then(Path::parent) {
return main.to_path_buf();
}
}
root.to_path_buf()
}
fn read(root: &Path) -> Names {
let path = main_folder(root).join(FILE);
if !path.is_file() {
return Names::default();
}
match fsx::read_json(&path) {
Ok(names) => names,
Err(error) => {
tracing::warn!(%error, "realm names could not be read; the default names are used");
Names::default()
}
}
}
/// A trimmed name the realm list can hold: 1 to 32 characters, no control characters.
pub fn validate(name: &str) -> Result<String> {
let name = name.trim();
if name.is_empty() {
return Err(Error::Invalid("The realm name cannot be empty.".into()));
}
if name.chars().count() > MAX_CHARS {
return Err(Error::Invalid(format!(
"The realm name can have at most {MAX_CHARS} characters."
)));
}
// The game client stores the realm as `SET realmName "<name>"` in Config.wtf.
if name.chars().any(|c| c.is_control() || c == '"') {
return Err(Error::Invalid(
"The realm name cannot contain quotation marks or control characters.".into(),
));
}
Ok(name.to_string())
}
/// The owner's name for realm `id`, if one was chosen.
pub fn custom(root: &Path, id: u32) -> Option<String> {
read(root)
.names
.remove(&id)
.and_then(|name| validate(&name).ok())
}
/// The name realm `id` shows: the owner's choice, or `default`.
pub fn name_or(root: &Path, id: u32, default: &str) -> String {
custom(root, id).unwrap_or_else(|| default.to_string())
}
/// The name the realm of `mode` shows.
pub fn for_mode(root: &Path, mode: crate::realms::Mode) -> String {
name_or(root, mode.realm_id(), mode.label())
}
/// Every chosen name.
pub fn all(root: &Path) -> BTreeMap<u32, String> {
read(root)
.names
.into_iter()
.filter_map(|(id, name)| validate(&name).ok().map(|name| (id, name)))
.collect()
}
/// Choose a name for realm `id`; `None` (or an empty name) returns it to its default.
pub fn set(root: &Path, id: u32, name: Option<&str>) -> Result<Option<String>> {
let mut names = read(root);
let chosen = match name.map(str::trim).filter(|n| !n.is_empty()) {
Some(name) => Some(validate(name)?),
None => None,
};
match &chosen {
Some(name) => names.names.insert(id, name.clone()),
None => names.names.remove(&id),
};
fsx::atomic_write_json(&main_folder(root).join(FILE), &names)?;
Ok(chosen)
}
/// A realm of this server and the name it shows.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct RealmName {
pub id: u32,
pub name: String,
pub default_name: String,
pub custom: bool,
}
/// The realms of a server with their names: Conquest of Azeroth (or the plain repack's "AzerothCore") and the
/// Wildcard and Warcraft Reborn realms that were created.
pub fn list(root: &Path) -> Result<Vec<RealmName>> {
let main = main_folder(root);
let mut realms: Vec<(u32, &'static str)> = Vec::new();
if main.join("Settings/realm-profile.json").exists() {
let state = crate::realms::state(&main)?;
realms.extend(state.modes().into_iter().map(|m| (m.realm_id(), m.label())));
} else {
realms.push((1, "AzerothCore"));
}
realms.sort_unstable();
realms.dedup();
Ok(realms
.into_iter()
.map(|(id, default)| {
let custom = custom(&main, id);
RealmName {
id,
name: custom.clone().unwrap_or_else(|| default.to_string()),
default_name: default.to_string(),
custom: custom.is_some(),
}
})
.collect())
}
/// Choose a name and, when the database runs, write it to the realm list at once (the auth server shows it
/// within its realm refresh interval). Returns the realms with their names.
pub fn rename(root: &Path, id: u32, name: Option<&str>) -> Result<Vec<RealmName>> {
let main = main_folder(root);
let known = list(&main)?;
let realm = known
.iter()
.find(|r| r.id == id)
.ok_or_else(|| Error::Invalid(format!("This server has no realm {id}.")))?;
let shown = set(&main, id, name)?.unwrap_or_else(|| realm.default_name.clone());
crate::backup::with_running_database(&main, |db| {
db.query(&format!(
"UPDATE acore_auth.realmlist SET name={} WHERE id={id};",
sql_literal(&shown)
))
.map(|_| ())
})?;
list(&main)
}
/// `text` as a MySQL string literal (quotes and backslashes escaped).
pub fn sql_literal(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('\'');
for c in text.chars() {
match c {
'\'' => out.push_str("''"),
'\\' => out.push_str("\\\\"),
c => out.push(c),
}
}
out.push('\'');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_are_validated_trimmed_and_reset() {
let d = tempfile::tempdir().unwrap();
assert_eq!(name_or(d.path(), 1, "Conquest of Azeroth"), "Conquest of Azeroth");
assert_eq!(set(d.path(), 1, Some(" Owner's Realm ")).unwrap().as_deref(), Some("Owner's Realm"));
assert_eq!(name_or(d.path(), 1, "x"), "Owner's Realm");
assert!(set(d.path(), 2, Some(&"a".repeat(33))).is_err());
assert!(set(d.path(), 2, Some("bad\nname")).is_err());
assert_eq!(set(d.path(), 2, Some("Царство")).unwrap().as_deref(), Some("Царство"));
assert_eq!(all(d.path()).len(), 2);
assert_eq!(set(d.path(), 1, Some(" ")).unwrap(), None);
assert_eq!(name_or(d.path(), 1, "Conquest of Azeroth"), "Conquest of Azeroth");
}
#[test]
fn an_extra_world_reads_its_main_folders_names() {
let d = tempfile::tempdir().unwrap();
set(d.path(), 2, Some("Wild Side")).unwrap();
let extra = d.path().join(".realms/secondary");
std::fs::create_dir_all(&extra).unwrap();
assert_eq!(custom(&extra, 2).as_deref(), Some("Wild Side"));
}
#[test]
fn names_are_safe_in_sql() {
assert_eq!(sql_literal(r"O'Neil \ realm"), r"'O''Neil \\ realm'");
}
}
+42 -251
View File
@@ -185,8 +185,20 @@ pub fn view(root: &Path) -> Result<View> {
} }
pub fn guard_module(root: &Path, id: &str) -> Result<()> { pub fn guard_module(root: &Path, id: &str) -> Result<()> {
if state(root)?.active != Mode::Coa && matches!(id, "companions" | "playerbots") { let s = state(root)?;
return Err(Error::Invalid("Bot class mechanics have not been validated for this realm. This module is unavailable on this realm.".into())); if matches!(id, "companions" | "playerbots") {
if let Ok(v) = view(root) {
if s.active == Mode::Wildcard && !v.supported {
return Err(Error::Invalid(
"The installed server binary does not support Wildcard mode.".into(),
));
}
if s.active == Mode::Reborn && !v.reborn_supported {
return Err(Error::Invalid(
"The installed server binary does not support Warcraft Reborn mode.".into(),
));
}
}
} }
Ok(()) Ok(())
} }
@@ -296,20 +308,14 @@ fn wildcard_configs(mut files: Files) -> Result<Files> {
} }
} }
} }
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] { // Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems
set( if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") {
&mut files, if let Ok(conf) = ConfFile::parse_bytes(bytes) {
"Core/configs/modules/mod_coa_playerbots.conf", if conf.get("CoaBots.Enable") == Some("1") {
key, set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?;
value, }
)?; }
} }
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files) Ok(files)
} }
@@ -337,20 +343,14 @@ fn reborn_configs(mut files: Files) -> Result<Files> {
set(&mut files, path, "RealmID", "3")?; set(&mut files, path, "RealmID", "3")?;
} }
} }
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] { // Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems
set( if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") {
&mut files, if let Ok(conf) = ConfFile::parse_bytes(bytes) {
"Core/configs/modules/mod_coa_playerbots.conf", if conf.get("CoaBots.Enable") == Some("1") {
key, set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?;
value, }
)?; }
} }
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files) Ok(files)
} }
@@ -534,8 +534,6 @@ pub fn ensure_created(root: &Path, mode: Mode) -> Result<()> {
"Update the server to a build with Warcraft Reborn support first.".into(), "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)?; let before = configs(root)?;
create_realm(root, &mut s, mode, &before) create_realm(root, &mut s, mode, &before)
} }
@@ -565,8 +563,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
"Disable the realms that start together 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)?; let before = configs(root)?;
fsx::atomic_write_json(&snapshot(root, s.active), &before)?; fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
create_realm(root, &mut s, mode, &before)?; create_realm(root, &mut s, mode, &before)?;
@@ -608,125 +604,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
view(root) view(root)
} }
/// Adapt the bundled launcher's canonical schema and realm choices without changing its supervision logic.
pub fn prepare_launcher(root: &Path) -> Result<()> {
// A Docker server has no launcher to adapt: the Docker backend reads the active realm itself.
if crate::docker::is_docker(root) {
return Ok(());
}
let path = root.join("Scripts/manage.py");
let source = fs::read_to_string(&path)?;
let patched = patch_launcher(&source)?;
if patched != source {
fsx::atomic_write(&path, patched.as_bytes())?;
// A Manager-owned transformation is still pristine for subsequent updates and file checks.
if let Ok(dir) = crate::registry::metadata_dir_for(root) {
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
if meta
.original_hashes
.get("Scripts/manage.py")
.is_some_and(|hash| hash == &fsx::sha256_bytes(source.as_bytes()))
{
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(patched.as_bytes()),
);
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
}
}
}
}
Ok(())
}
const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
];
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
fn launcher_insert() -> String {
LAUNCHER_REALM_INSERT
.replace("profiles-v1", "profiles-v2")
.replace(
"return 2 if",
"return 3 if coa_realm() == 'reborn' else 2 if",
)
.replace(
"return 'Wildcard' if",
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
)
}
fn launcher_replacements() -> Vec<(&'static str, String)> {
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
}
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
if source.contains("# coa-manager-realm-profiles-v2") {
return Ok(source.into());
}
if source.contains("# coa-manager-realm-profiles-v1") {
let original = unpatch_launcher(source)
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
return patch_launcher(&original);
}
let mut out = source.to_string();
for (from, to) in launcher_replacements() {
if !out.contains(from) {
return Err(Error::Invalid(
"This launcher does not support realm profiles. Update the server package first."
.into(),
));
}
out = out.replace(from, &to);
}
// Insert before the entry point so ROOT, json and functions are all defined when called.
let marker = "if __name__ == \"__main__\":";
if !out.contains(marker) {
return Err(Error::Invalid(
"Unrecognised server launcher entry point.".into(),
));
}
Ok(out.replace(marker, &format!("{}{marker}", launcher_insert())))
}
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
let (insert, replacements) = if source.contains(&launcher_insert()) {
(launcher_insert(), launcher_replacements())
} else if source.contains(LAUNCHER_REALM_INSERT) {
(
LAUNCHER_REALM_INSERT.into(),
LAUNCHER_REALM_REPLACEMENTS
.iter()
.map(|(a, b)| (*a, b.to_string()))
.collect(),
)
} else {
return None;
};
let mut original = source.replacen(&insert, "", 1);
for (from, to) in &replacements {
original = original.replace(to, from);
}
let mut check = original.clone();
for (from, to) in &replacements {
check = check.replace(from, to);
}
check = check.replace(
"if __name__ == \"__main__\":",
&format!("{insert}if __name__ == \"__main__\":"),
);
(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 /// 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 /// 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. /// Warcraft Reborn characters in the Conquest of Azeroth realm.
@@ -770,7 +647,6 @@ pub fn before_start(root: &Path) -> Result<()> {
if !root.join(STATE).exists() { if !root.join(STATE).exists() {
return Ok(()); return Ok(());
} }
prepare_launcher(root)?;
if s.simultaneous && !view(root)?.supported { if s.simultaneous && !view(root)?.supported {
return Err(Error::Invalid( return Err(Error::Invalid(
"The installed server build does not support simultaneous Wildcard startup.".into(), "The installed server build does not support simultaneous Wildcard startup.".into(),
@@ -805,19 +681,7 @@ pub fn before_start(root: &Path) -> Result<()> {
"The installed server build does not support Wildcard.".into(), "The installed server build does not support Wildcard.".into(),
)); ));
} }
let path = root.join("Core/configs/modules/mod_coa_playerbots.conf"); // Multi-realm Playerbots 1.0: bots are supported and enabled on all realms
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
conf.set("CoaBots.Enable", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
let path = root.join("Core/configs/modules/playerbots.conf");
let bytes = if path.exists() {
fs::read(&path)?
} else {
b"[worldserver]\n".to_vec()
};
let mut conf = ConfFile::parse_bytes(&bytes)?;
conf.set("AiPlayerbot.Enabled", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
} }
Ok(()) Ok(())
} }
@@ -831,8 +695,8 @@ pub fn setup_realmlist(root: &Path) -> Result<()> {
let port = layout::read_ports(root).world; let port = layout::read_ports(root).world;
for mode in s.modes().into_iter().filter(|m| *m != Mode::Coa) { for mode in s.modes().into_iter().filter(|m| *m != Mode::Coa) {
let id = mode.realm_id(); let id = mode.realm_id();
let name = mode.label(); let name = crate::realm_names::sql_literal(&crate::realm_names::name_or(root, id, mode.label()));
db.query(&format!("INSERT INTO acore_auth.realmlist (id,name,address,localAddress,localSubnetMask,port,icon,flag,timezone,gamebuild) SELECT {id},'{name}',address,localAddress,localSubnetMask,{port},icon,2,timezone,gamebuild FROM acore_auth.realmlist WHERE id=1 ON DUPLICATE KEY UPDATE port={port};"))?; db.query(&format!("INSERT INTO acore_auth.realmlist (id,name,address,localAddress,localSubnetMask,port,icon,flag,timezone,gamebuild) SELECT {id},{name},address,localAddress,localSubnetMask,{port},icon,2,timezone,gamebuild FROM acore_auth.realmlist WHERE id=1 ON DUPLICATE KEY UPDATE port={port},name={name};"))?;
} }
let ids = s let ids = s
.modes() .modes()
@@ -937,11 +801,12 @@ mod tests {
.get("RealmID"), .get("RealmID"),
Some("3") Some("3")
); );
// Requirement 6: Never alter alternative bot system settings (AiPlayerbot.Enabled) without explicit user choice
assert_eq!( assert_eq!(
ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"]) ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"])
.unwrap() .unwrap()
.get("AiPlayerbot.Enabled"), .get("AiPlayerbot.Enabled"),
Some("0") Some("1")
); );
write_configs(t.path(), &reborn).unwrap(); write_configs(t.path(), &reborn).unwrap();
write_configs(t.path(), &coa).unwrap(); write_configs(t.path(), &coa).unwrap();
@@ -955,8 +820,8 @@ mod tests {
}, },
) )
.unwrap(); .unwrap();
assert!(guard_module(t.path(), "companions").is_err()); assert!(guard_module(t.path(), "companions").is_ok());
assert!(guard_module(t.path(), "playerbots").is_err()); assert!(guard_module(t.path(), "playerbots").is_ok());
assert!(guard_module(t.path(), "content-scaling").is_ok()); assert!(guard_module(t.path(), "content-scaling").is_ok());
} }
@@ -1107,26 +972,6 @@ CoA.GameModeMask = 0
assert!(!v.supported); assert!(!v.supported);
} }
#[test]
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
let mut old = original.to_string();
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
old = old.replace(from, to);
}
old = old.replace(
"if __name__ == \"__main__\":",
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
);
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
let new = patch_launcher(&old).unwrap();
assert!(new.contains("acore_world_reborn"));
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
assert!(new.contains("return 'Warcraft Reborn' if"));
assert_eq!(patch_launcher(&new).unwrap(), new);
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
}
#[test] #[test]
fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() { fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
@@ -1157,20 +1002,6 @@ CoA.GameModeMask = 0
assert!(view(d.path()).unwrap().supported); assert!(view(d.path()).unwrap().supported);
} }
#[test]
fn a_docker_server_has_no_launcher_to_adapt() {
let d = tempfile::tempdir().unwrap();
fs::create_dir_all(d.path().join("Settings")).unwrap();
// No Scripts/manage.py anywhere: on a repack this fails, on a Docker server there is nothing to do.
assert!(prepare_launcher(d.path()).is_err());
fs::write(
d.path().join("Settings/docker.json"),
br#"{"project":"t1"}"#,
)
.unwrap();
prepare_launcher(d.path()).unwrap();
}
#[test] #[test]
fn fresh_wildcard_disables_bots_and_preserves_scaling() { fn fresh_wildcard_disables_bots_and_preserves_scaling() {
let mut f = Files::new(); let mut f = Files::new();
@@ -1178,6 +1009,10 @@ CoA.GameModeMask = 0
"Core/configs/modules/mod-coa-content-scaling.conf".into(), "Core/configs/modules/mod-coa-content-scaling.conf".into(),
b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(), b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(),
); );
f.insert(
"Core/configs/modules/mod_coa_playerbots.conf".into(),
b"[worldserver]\nCoaBots.Enable = 1\n".to_vec(),
);
f.insert( f.insert(
"Settings/worldserver.conf.template".into(), "Settings/worldserver.conf.template".into(),
b"[worldserver]\nRealmID = 1\n".to_vec(), b"[worldserver]\nRealmID = 1\n".to_vec(),
@@ -1188,7 +1023,7 @@ CoA.GameModeMask = 0
f["Core/configs/modules/mod-coa-content-scaling.conf"] f["Core/configs/modules/mod-coa-content-scaling.conf"]
); );
let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap(); let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap();
assert_eq!(c.get("CoaBots.Enable"), Some("0")); assert_eq!(c.get("CoaBots.Enable"), Some("1"));
assert_eq!( assert_eq!(
ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"]) ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"])
.unwrap() .unwrap()
@@ -1260,52 +1095,8 @@ CoA.GameModeMask = 0
}, },
) )
.unwrap(); .unwrap();
assert!(crate::modules::set_enabled(t.path(), t.path(), "companions", true).is_err()); assert!(guard_module(t.path(), "companions").is_ok());
assert!(crate::config::save( assert!(guard_module(t.path(), "playerbots").is_ok());
t.path(),
t.path(),
crate::config::Scope::Bots,
&BTreeMap::new()
)
.is_err());
assert!(guard_module(t.path(), "content-scaling").is_ok()); assert!(guard_module(t.path(), "content-scaling").is_ok());
} }
#[test]
fn unknown_launcher_is_refused_without_partial_patching() {
assert!(patch_launcher("print('custom launcher')").is_err());
}
#[test]
fn managed_launcher_patch_remains_pristine_but_external_edits_conflict() {
let d = tempfile::tempdir().unwrap();
let root = d.path().join("server");
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
meta.original_hashes.insert(
"Scripts/manage.py".into(),
fsx::sha256_bytes(source.as_bytes()),
);
let dir = crate::registry::MetaDir::create(&root, &meta).unwrap();
prepare_launcher(&root).unwrap();
let (_, meta) = crate::registry::MetaDir::open(&dir.root).unwrap();
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
})).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Replace
);
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
modified.extend_from_slice(b"# custom edit\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
prepare_launcher(&root).unwrap();
assert_eq!(
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
crate::update::Action::Conflict
);
}
} }
+14
View File
@@ -7,6 +7,10 @@ use std::path::{Path, PathBuf};
pub struct Profile { pub struct Profile {
pub host: String, pub host: String,
pub client_path: Option<String>, pub client_path: Option<String>,
/// The listed server `host` belongs to, when the player joined it through the server list: its account is
/// filled into the game's login box at every Play.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub realm: Option<String>,
} }
pub fn load(dir: &Path) -> Result<Profile> { pub fn load(dir: &Path) -> Result<Profile> {
@@ -43,12 +47,21 @@ pub fn save(dir: &Path, profile: &Profile) -> Result<()> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn a_profile_from_before_the_realm_field_still_loads() {
let d = tempfile::tempdir().unwrap();
std::fs::write(d.path().join("connection.json"), br#"{"host":"1.2.3.4","client_path":null}"#).unwrap();
let p = load(d.path()).unwrap();
assert_eq!((p.host.as_str(), p.realm), ("1.2.3.4", None));
}
#[test] #[test]
fn connection_needs_no_server_and_survives_restart() { fn connection_needs_no_server_and_survives_restart() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let profile = Profile { let profile = Profile {
host: "192.168.1.10".into(), host: "192.168.1.10".into(),
client_path: None, client_path: None,
realm: None,
}; };
save(dir.path(), &profile).unwrap(); save(dir.path(), &profile).unwrap();
assert_eq!(load(dir.path()).unwrap().host, profile.host); assert_eq!(load(dir.path()).unwrap().host, profile.host);
@@ -70,6 +83,7 @@ mod tests {
let profile = Profile { let profile = Profile {
host: "192.168.1.10".into(), host: "192.168.1.10".into(),
client_path: Some(game.to_string_lossy().into()), client_path: Some(game.to_string_lossy().into()),
realm: None,
}; };
save(dir.path(), &profile).unwrap(); save(dir.path(), &profile).unwrap();
assert!( assert!(
+265 -1
View File
@@ -1,4 +1,9 @@
use std::{fs, path::Path}; use std::{
fs,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use crate::{ use crate::{
config::{parser::ConfFile, Scope}, config::{parser::ConfFile, Scope},
@@ -6,6 +11,213 @@ use crate::{
fsx, fsx,
}; };
const SETTINGS_FILE: &str = "Settings/log-settings.json";
const DEFAULT_MAX_SIZE_MB: u64 = 500;
const MIN_MAX_SIZE_MB: u64 = 10;
const MAX_MAX_SIZE_MB: u64 = 100_000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct LogSettings {
pub auto_cleanup: bool,
pub max_size_mb: u64,
}
impl Default for LogSettings {
fn default() -> Self {
Self {
auto_cleanup: false,
max_size_mb: DEFAULT_MAX_SIZE_MB,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CleanLogsReport {
pub freed_bytes: u64,
pub remaining_bytes: u64,
pub deleted_files: u64,
pub skipped_files: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerLoggingView {
pub preset: Option<String>,
pub log_bytes: u64,
pub settings: LogSettings,
}
fn owner(root: &Path) -> PathBuf {
if crate::launcher::settings::is_extra_world(root) {
if let Some(main) = root.parent().and_then(Path::parent) {
return main.to_path_buf();
}
}
root.to_path_buf()
}
pub fn load_settings(root: &Path) -> LogSettings {
let mut settings: LogSettings =
fsx::read_json(&owner(root).join(SETTINGS_FILE)).unwrap_or_default();
if settings.max_size_mb < MIN_MAX_SIZE_MB || settings.max_size_mb > MAX_MAX_SIZE_MB {
settings.max_size_mb = DEFAULT_MAX_SIZE_MB;
}
settings
}
pub fn save_settings(root: &Path, settings: &LogSettings) -> Result<LogSettings> {
let mut settings = settings.clone();
if settings.auto_cleanup {
if !(MIN_MAX_SIZE_MB..=MAX_MAX_SIZE_MB).contains(&settings.max_size_mb) {
return Err(Error::Invalid(format!(
"Log auto-cleanup threshold must be between {MIN_MAX_SIZE_MB} and {MAX_MAX_SIZE_MB} MB."
)));
}
} else if !(MIN_MAX_SIZE_MB..=MAX_MAX_SIZE_MB).contains(&settings.max_size_mb) {
settings.max_size_mb = DEFAULT_MAX_SIZE_MB;
}
fsx::atomic_write_json(&owner(root).join(SETTINGS_FILE), &settings)?;
Ok(settings)
}
pub fn detect_preset(root: &Path) -> Option<String> {
let candidates = [
root.join("Core/configs/worldserver.conf"),
root.join("Settings/worldserver.conf.template"),
];
for path in candidates {
let Ok(bytes) = fs::read(&path) else {
continue;
};
let Ok(conf) = ConfFile::parse_bytes(&bytes) else {
continue;
};
let found = conf
.entries()
.find(|(k, _)| *k == "Logger.root")
.and_then(|(_, value)| {
value
.split(',')
.next()
.map(str::trim)
.and_then(|s| s.parse::<u32>().ok())
});
if let Some(level) = found {
return match level {
0 => Some("off".into()),
2 => Some("errors".into()),
4 => Some("normal".into()),
_ => None,
};
}
}
None
}
fn log_dirs(root: &Path) -> Vec<PathBuf> {
let base = owner(root);
let mut dirs = Vec::new();
for prefix in ["", ".realms/secondary/", ".realms/reborn/"] {
let candidate = base.join(format!("{prefix}Core/Logs"));
if let Ok(checked) = fsx::ensure_within(&base, &candidate) {
if checked.is_dir() {
dirs.push(checked);
}
}
}
dirs
}
fn measure_dir(dir: &Path) -> u64 {
let Ok(entries) = fs::read_dir(dir) else {
return 0;
};
let mut total = 0u64;
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
total = total.saturating_add(measure_dir(&path));
} else if meta.is_file() {
total = total.saturating_add(meta.len());
}
}
total
}
pub fn measure_logs(root: &Path) -> u64 {
log_dirs(root)
.into_iter()
.fold(0u64, |acc, dir| acc.saturating_add(measure_dir(&dir)))
}
fn clean_dir(dir: &Path, report: &mut CleanLogsReport, remove_empty_dir: bool) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
clean_dir(&path, report, true);
} else if meta.is_file() {
let size = meta.len();
match fs::remove_file(&path) {
Ok(()) => {
report.freed_bytes = report.freed_bytes.saturating_add(size);
report.deleted_files = report.deleted_files.saturating_add(1);
}
Err(_) => {
report.remaining_bytes = report.remaining_bytes.saturating_add(size);
report.skipped_files = report.skipped_files.saturating_add(1);
}
}
}
}
if remove_empty_dir {
let _ = fs::remove_dir(dir);
}
}
pub fn clean_logs(root: &Path) -> Result<CleanLogsReport> {
let mut report = CleanLogsReport {
freed_bytes: 0,
remaining_bytes: 0,
deleted_files: 0,
skipped_files: 0,
};
for dir in log_dirs(root) {
clean_dir(&dir, &mut report, false);
}
Ok(report)
}
pub fn auto_clean_if_needed(root: &Path) -> Option<CleanLogsReport> {
let settings = load_settings(root);
if !settings.auto_cleanup {
return None;
}
let limit = settings.max_size_mb.saturating_mul(1024 * 1024);
if measure_logs(root) <= limit {
return None;
}
clean_logs(root).ok()
}
pub fn state(root: &Path) -> ServerLoggingView {
ServerLoggingView {
preset: detect_preset(root),
log_bytes: measure_logs(root),
settings: load_settings(root),
}
}
fn transform(bytes: &[u8], preset: &str) -> Result<String> { fn transform(bytes: &[u8], preset: &str) -> Result<String> {
let level = match preset { let level = match preset {
"normal" => 4, "normal" => 4,
@@ -162,4 +374,56 @@ mod tests {
assert_eq!(transform(normal.as_bytes(), "normal").unwrap(), normal); assert_eq!(transform(normal.as_bytes(), "normal").unwrap(), normal);
assert!(transform(original, "unsupported").is_err()); assert!(transform(original, "unsupported").is_err());
} }
#[test]
fn detects_preset_measures_and_cleans_logs_across_realms() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("Core/configs")).unwrap();
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=4,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("normal"));
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=0,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("off"));
fs::write(root.join("Core/configs/worldserver.conf"), "Logger.root=2,Console Server\n").unwrap();
assert_eq!(detect_preset(root).as_deref(), Some("errors"));
fs::create_dir_all(root.join("Core/Logs/archive")).unwrap();
fs::create_dir_all(root.join(".realms/secondary/Core/Logs")).unwrap();
fs::write(root.join("Core/Logs/Server.log"), vec![b'a'; 1000]).unwrap();
fs::write(root.join("Core/Logs/archive/old.log"), vec![b'b'; 500]).unwrap();
fs::write(root.join(".realms/secondary/Core/Logs/Server.log"), vec![b'c'; 250]).unwrap();
assert_eq!(measure_logs(root), 1750);
let report = clean_logs(root).unwrap();
assert_eq!(report.freed_bytes, 1750);
assert_eq!(report.remaining_bytes, 0);
assert_eq!(report.deleted_files, 3);
assert_eq!(report.skipped_files, 0);
assert_eq!(measure_logs(root), 0);
assert!(!root.join("Core/Logs/archive").exists());
}
#[test]
fn log_settings_validate_and_auto_clean_only_above_threshold() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
assert_eq!(load_settings(root), LogSettings::default());
assert!(save_settings(root, &LogSettings { auto_cleanup: true, max_size_mb: 5 }).is_err());
let saved = save_settings(root, &LogSettings { auto_cleanup: true, max_size_mb: 10 }).unwrap();
assert!(saved.auto_cleanup);
assert_eq!(saved.max_size_mb, 10);
fs::create_dir_all(root.join("Core/Logs")).unwrap();
fs::write(root.join("Core/Logs/Server.log"), vec![b'x'; 1024]).unwrap();
// 1 KB < 10 MB: does not clean.
assert!(auto_clean_if_needed(root).is_none());
assert_eq!(measure_logs(root), 1024);
// Threshold check helper: writing > 10 MB triggers cleanup.
let over = vec![b'y'; 10 * 1024 * 1024 + 1];
fs::write(root.join("Core/Logs/Big.log"), over).unwrap();
let cleaned = auto_clean_if_needed(root).unwrap();
assert!(cleaned.freed_bytes > 10 * 1024 * 1024);
assert_eq!(measure_logs(root), 0);
}
} }
+8 -8
View File
@@ -403,7 +403,7 @@ pub fn plan(
match (fs::read_to_string(tree.join(&f.path)), fs::read(&target)) { match (fs::read_to_string(tree.join(&f.path)), fs::read(&target)) {
(Ok(signed), Ok(actual)) => { (Ok(signed), Ok(actual)) => {
fsx::sha256_bytes(signed.as_bytes()) == f.sha256 fsx::sha256_bytes(signed.as_bytes()) == f.sha256
&& crate::driver::launcher_matches(&signed, &actual) && crate::legacy_launcher::launcher_matches(&signed, &actual)
} }
_ => false, _ => false,
} }
@@ -418,7 +418,7 @@ pub fn plan(
let manager_launcher = f.path == "Scripts/manage.py" let manager_launcher = f.path == "Scripts/manage.py"
&& recorded.is_some_and(|hash| { && recorded.is_some_and(|hash| {
fs::read(&target).is_ok_and(|bytes| { fs::read(&target).is_ok_and(|bytes| {
crate::driver::launcher_matches_recorded(hash, &bytes) crate::legacy_launcher::launcher_matches_recorded(hash, &bytes)
}) })
}); });
if f.path == "Core/worldserver.exe" if f.path == "Core/worldserver.exe"
@@ -614,7 +614,7 @@ fn launcher_already_integrated(
if meta.original_hashes.get(&file.path) != Some(&fsx::sha256_bytes(&actual)) { if meta.original_hashes.get(&file.path) != Some(&fsx::sha256_bytes(&actual)) {
return Ok(false); return Ok(false);
} }
Ok(crate::driver::launcher_matches_recorded( Ok(crate::legacy_launcher::launcher_matches_recorded(
&file.sha256, &file.sha256,
&actual, &actual,
)) ))
@@ -968,7 +968,7 @@ fn finish(
fs::read_to_string(tree.join(&op.path)), fs::read_to_string(tree.join(&op.path)),
fs::read(root.join(&op.path)), fs::read(root.join(&op.path)),
) { ) {
(Ok(signed), Ok(actual)) if crate::driver::launcher_matches(&signed, &actual) => { (Ok(signed), Ok(actual)) if crate::legacy_launcher::launcher_matches(&signed, &actual) => {
fsx::sha256_bytes(&actual) fsx::sha256_bytes(&actual)
} }
_ => op.new_sha256.clone(), _ => op.new_sha256.clone(),
@@ -1060,7 +1060,7 @@ pub fn retry_validation(
&& fs::read_to_string(dir.join("tree").join(&op.path)) && fs::read_to_string(dir.join("tree").join(&op.path))
.ok() .ok()
.filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256) .filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256)
.is_some_and(|s| crate::driver::launcher_matches(&s, &bytes)); .is_some_and(|s| crate::legacy_launcher::launcher_matches(&s, &bytes));
if actual != file.sha256 && !launcher { if actual != file.sha256 && !launcher {
return Err(Error::Invalid(format!( return Err(Error::Invalid(format!(
"{} changed since the update was applied; use repair or rollback.", "{} changed since the update was applied; use repair or rollback.",
@@ -2347,9 +2347,9 @@ mod tests {
fn legacy_launcher_world(import_patch: bool) -> World { fn legacy_launcher_world(import_patch: bool) -> World {
let w = world(&[("Scripts/manage.py", b"new release launcher")], false); let w = world(&[("Scripts/manage.py", b"new release launcher")], false);
let mut source = crate::realms::patch_launcher(LEGACY_LAUNCHER).unwrap(); let mut source = crate::legacy_launcher::patch_launcher(LEGACY_LAUNCHER).unwrap();
if import_patch { if import_patch {
source = crate::driver::patch_launcher_imports(&source).unwrap(); source = crate::legacy_launcher::patch_launcher_imports(&source).unwrap();
} }
write(&w.root, "Scripts/manage.py", source.as_bytes()); write(&w.root, "Scripts/manage.py", source.as_bytes());
let (_, mut meta) = MetaDir::open(&w.meta).unwrap(); let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
@@ -2576,7 +2576,7 @@ mod tests {
let w = world(&[("Scripts/manage.py", source)], false); let w = world(&[("Scripts/manage.py", source)], false);
run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap(); run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap();
let integrated = let integrated =
crate::driver::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap(); crate::legacy_launcher::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap();
write(&w.root, "Scripts/manage.py", integrated.as_bytes()); write(&w.root, "Scripts/manage.py", integrated.as_bytes());
let (_, mut meta) = MetaDir::open(&w.meta).unwrap(); let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
meta.original_hashes.insert( meta.original_hashes.insert(
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "coa-launcher"
description = "The CoA repack launcher (Start_All_Server.bat and friends) without Python"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "coa-launcher"
path = "src/main.rs"
[dependencies]
coa-core = { path = "../coa-core" }
serde_json = "1"
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_System_Console"] }
+222
View File
@@ -0,0 +1,222 @@
//! `coa-launcher.exe`: the repack launcher, the same commands as `Scripts/manage.py`.
//!
//! It lives in `<server>/Scripts/` next to manage.py (the server folder is its parent), or takes `--root <folder>`.
//! Errors are printed as `ERROR: <message>` on stderr with exit code 1, exactly like manage.py, because the
//! Manager reads them.
use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use coa_core::launcher::ops::{self, Action};
use coa_core::launcher::{services, settings::Settings, state, world};
const ACTIONS: [&str; 18] = [
"start-all", "start-mysql", "start-auth", "start-world", "stop-all", "force-stop-all", "status", "status-json", "create-account",
"create-account-once", "console", "ra-once", "prepare", "watch-world", "relay-worker", "debug-logs-on",
"debug-logs-off", "debug-logs-status",
];
fn say(text: &str) {
println!("{text}");
let _ = std::io::stdout().flush();
}
fn usage() -> String {
format!("usage: coa-launcher [--root <server>] [--port-offset N] {{{}}}", ACTIONS.join(","))
}
struct Args {
root: PathBuf,
offset: i32,
action: String,
}
fn parse() -> Result<Args, String> {
let mut root: Option<PathBuf> = None;
let mut offset = 0;
let mut action = None;
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
"--root" => root = Some(PathBuf::from(it.next().ok_or_else(usage)?)),
"--port-offset" => offset = it.next().and_then(|v| v.parse().ok()).ok_or_else(usage)?,
_ if ACTIONS.contains(&a.as_str()) && action.is_none() => action = Some(a),
_ => return Err(usage()),
}
}
let root = match root {
Some(r) => r,
None => {
// <server>/Scripts/coa-launcher.exe -> <server>
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
exe.parent().and_then(Path::parent).map(Path::to_path_buf).ok_or("cannot find the server folder")?
}
};
Ok(Args { root, offset, action: action.ok_or_else(usage)? })
}
fn read_line(prompt: &str) -> std::io::Result<String> {
print!("{prompt}");
std::io::stdout().flush()?;
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
Ok(line.trim_end_matches(['\r', '\n']).to_string())
}
/// Read a line without showing it (passwords).
fn read_secret(prompt: &str) -> std::io::Result<String> {
#[cfg(windows)]
unsafe {
use windows_sys::Win32::System::Console::{GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_ECHO_INPUT, STD_INPUT_HANDLE};
let h = GetStdHandle(STD_INPUT_HANDLE);
let mut mode = 0;
if GetConsoleMode(h, &mut mode) != 0 {
SetConsoleMode(h, mode & !ENABLE_ECHO_INPUT);
let line = read_line(prompt);
SetConsoleMode(h, mode);
println!();
return line;
}
}
read_line(prompt)
}
fn valid_login(text: &str) -> bool {
(1..=16).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_alphanumeric())
}
fn ra(cfg: &Settings, root: &Path, command: &str) -> Result<String, String> {
if !services::ready(root, "world", cfg.ra_port) {
return Err("Start this repack's worldserver first.".into());
}
let mut console = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).map_err(|e| e.to_string())?;
console.run(command).map_err(|e| e.to_string())
}
fn run(args: Args) -> Result<(), String> {
let root = args.root.as_path();
let e = |x: coa_core::Error| x.to_string();
match args.action.as_str() {
"watch-world" => {
let me = std::env::current_exe().map_err(|x| x.to_string())?;
return world::watch_world(root, Some(&me), args.offset, &|m| say(m)).map_err(e);
}
"relay-worker" => return coa_core::launcher::relay::worker(root).map_err(e),
"debug-logs-status" => {
let on = services::status(root)["debugLogs"].as_bool().unwrap_or(false);
say(&format!("Detailed server logging is {}.", if on { "ON" } else { "off" }));
if on {
say("Every AzerothCore logger is forced to Trace level in Core/Logs (Server.log, Auth.log, world-console.log, auth-console.log). Expect much larger, faster-growing log files.");
}
say("Run Debug_Logs_On.bat / Debug_Logs_Off.bat, then restart the affected service(s) to apply.");
return Ok(());
}
"debug-logs-on" | "debug-logs-off" => {
let on = args.action == "debug-logs-on";
let changed = {
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
world::debug_logs(root, on).map_err(e)?
};
if changed.is_empty() {
say(&format!("Detailed logging was already {}.", if on { "on" } else { "off" }));
} else {
say(&format!("{} detailed logging in: {}", if on { "Enabled" } else { "Restored" }, changed.join(", ")));
}
say("Restart the affected service(s) (Stop_All_Server.bat then Start_All_Server.bat) to apply this.");
return Ok(());
}
_ => {}
}
let cfg = Settings::load(root, args.offset).map_err(e)?;
match args.action.as_str() {
"console" => {
say("World console. Enter a server command, or exit to close this window.");
loop {
let command = read_line("AC> ").map_err(|x| x.to_string())?;
let command = command.trim();
if command.eq_ignore_ascii_case("exit") || command.eq_ignore_ascii_case("quit") {
return Ok(());
}
if !command.is_empty() {
say(&ra(&cfg, root, command)?);
}
}
}
"create-account" => {
let name = read_line("New account name (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
let name = name.trim();
let password = read_secret("New account password (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
let again = read_secret("Repeat password: ").map_err(|x| x.to_string())?;
if !valid_login(name) || !valid_login(&password) {
return Err("Use 1-16 letters or digits for the account name and password.".into());
}
if password != again {
return Err("Passwords do not match.".into());
}
say(&ra(&cfg, root, &format!("account create {name} {password}"))?);
if read_line("Give this account GM permissions? [y/N]: ").map_err(|x| x.to_string())?.trim().eq_ignore_ascii_case("y") {
say(&ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
}
return Ok(());
}
"ra-once" => {
let command = read_line("").map_err(|x| x.to_string())?;
let command = command.trim();
if command.is_empty() {
return Err("No command given.".into());
}
say(&ra(&cfg, root, command)?);
return Ok(());
}
"create-account-once" => {
let line = read_line("").map_err(|x| x.to_string())?;
let request: serde_json::Value = serde_json::from_str(&line).map_err(|x| x.to_string())?;
let name = request.get("username").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
let password = request.get("password").and_then(|v| v.as_str()).unwrap_or("").to_string();
if !valid_login(&name) || !valid_login(&password) {
return Err("Use 1-16 letters or digits for the account name and password.".into());
}
let mut messages = vec![ra(&cfg, root, &format!("account create {name} {password}"))?];
if request.get("gm").and_then(|v| v.as_bool()).unwrap_or(false) {
messages.push(ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
}
say(&serde_json::json!({ "messages": messages }).to_string());
return Ok(());
}
_ => {}
}
match args.action.as_str() {
"status" | "status-json" => {
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
if args.action == "status-json" {
say(&services::status(root).to_string());
} else {
for name in ["mysql", "auth", "world", "relay"] {
let line = match state::running(root, name) {
Some(r) => format!("{name:12} running (PID {})", r.pid),
None => format!("{name:12} stopped"),
};
say(&line);
}
}
return Ok(());
}
_ => {}
}
let action = Action::parse(&args.action).ok_or_else(usage)?;
let me = world::Supervisor::Launcher(std::env::current_exe().map_err(|x| x.to_string())?);
ops::run(root, &cfg, args.offset, action, Some(&me), &|m| say(m)).map_err(e)?;
if args.action.starts_with("start-") {
say("Use Stop_All_Server.bat to shut down this repack safely.");
}
Ok(())
}
fn main() {
let result = parse().and_then(run);
if let Err(message) = result {
eprintln!("ERROR: {message}");
std::process::exit(1);
}
}
+42
View File
@@ -165,6 +165,48 @@
"enable_key": "CoACustomRaces.Enable", "enable_key": "CoACustomRaces.Enable",
"default_on": false "default_on": false
}, },
{
"id": "subclass",
"name": "Subclasses and Hero Races",
"description": {
"en": "Part of Custom Races V2: a second class for the Thin Twins and the Two-Headed Ogre, and two players sharing one character.",
"ru": "Часть Custom Races V2: второй класс для Хрупких близнецов и Двуглавого огра и один персонаж на двух игроков.",
"de": "Teil von Custom Races V2: eine zweite Klasse für die Dünnen Zwillinge und die Zweiköpfige Ogerin sowie zwei Spieler an einer Figur.",
"fr": "Partie de Custom Races V2 : une seconde classe pour les Jumeaux maigres et l'Ogre à deux têtes, et deux joueurs pour un personnage.",
"es": "Parte de Custom Races V2: una segunda clase para los Gemelos delgados y el Ogro de dos cabezas, y dos jugadores en un personaje.",
"zh": "Custom Races V2 的一部分:为瘦弱双子和双头食人魔提供第二职业,并允许两名玩家共用一个角色。"
},
"repo": "https://github.com/Corfirean/azerothcore-wotlk-coa",
"conf": "mod_subclass.conf",
"switchable": true,
"status": "early",
"icon": "races",
"enable_key": "Subclass.Enable",
"default_on": true,
"part_of": "custom-races",
"hidden": true
},
{
"id": "dev-menu",
"name": "Dev Menu",
"description": {
"en": "Part of Custom Races V2: the in-game /dev editor for game masters (NPCs, items).",
"ru": "Часть Custom Races V2: внутриигровой редактор /dev для гейм-мастеров (НПС, предметы).",
"de": "Teil von Custom Races V2: der /dev-Editor im Spiel für Spielleiter (NPCs, Gegenstände).",
"fr": "Partie de Custom Races V2 : l'éditeur /dev en jeu pour les maîtres du jeu (PNJ, objets).",
"es": "Parte de Custom Races V2: el editor /dev del juego para los máster (PNJ, objetos).",
"zh": "Custom Races V2 的一部分:供游戏管理员使用的游戏内 /dev 编辑器(NPC、物品)。"
},
"repo": "https://github.com/Corfirean/azerothcore-wotlk-coa",
"conf": "mod_ilusixn_devmenu.conf",
"switchable": true,
"status": "early",
"icon": "sparkles",
"enable_key": "DevMenu.Enable",
"default_on": true,
"part_of": "custom-races",
"hidden": true
},
{ {
"id": "time-is-time", "id": "time-is-time",
"name": "TimeIsTime", "name": "TimeIsTime",
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "coa-server-manager", "name": "coa-server-manager",
"version": "0.9.9", "version": "0.9.16",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "coa-server-manager", "name": "coa-server-manager",
"version": "0.9.9", "version": "0.9.16",
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2.12.0", "@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0", "@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "coa-server-manager", "name": "coa-server-manager",
"private": true, "private": true,
"version": "0.9.9", "version": "0.9.16",
"license": "AGPL-3.0-only", "license": "AGPL-3.0-only",
"type": "module", "type": "module",
"scripts": { "scripts": {
+122
View File
@@ -422,6 +422,128 @@
"max": 40, "max": 40,
"unit": "yards" "unit": "yards"
}, },
{
"key": "CoaBots.Scaling.Enable",
"type": "bool",
"category": "combat",
"title": "Bot strength help in dungeons and raids",
"description": "Master switch for the multipliers below. They are all 1 (no change) until you raise them.",
"default": true,
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CoaBots.Scaling.Dungeons",
"type": "bool",
"category": "combat",
"title": "Help in 5-player dungeons",
"description": "Apply the multipliers while a bot is in a 5-player dungeon.",
"default": true,
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CoaBots.Scaling.Raids",
"type": "bool",
"category": "combat",
"title": "Help in raids",
"description": "Apply the multipliers while a bot is in a raid.",
"default": true,
"advanced": false,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CoaBots.Scaling.Battlegrounds",
"type": "bool",
"category": "combat",
"title": "Help in battlegrounds and arenas",
"description": "Apply the multipliers in battlegrounds and arenas.",
"default": false,
"advanced": true,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CoaBots.Scaling.World",
"type": "bool",
"category": "combat",
"title": "Help in the open world",
"description": "Apply the multipliers outside dungeons and raids. Usually not wanted.",
"default": false,
"advanced": true,
"restartRequired": "world",
"dangerous": false
},
{
"key": "CoaBots.Scaling.DamageDone",
"type": "float",
"category": "combat",
"title": "Bot damage",
"description": "Multiplies the damage bots and their pets deal to creatures. 1 is no change; higher makes content easier.",
"default": 1.0,
"advanced": false,
"restartRequired": "world",
"dangerous": false,
"min": 0.1,
"max": 10,
"unit": "x"
},
{
"key": "CoaBots.Scaling.HealingDone",
"type": "float",
"category": "combat",
"title": "Bot healing",
"description": "Multiplies the healing bots cast. 1 is no change.",
"default": 1.0,
"advanced": false,
"restartRequired": "world",
"dangerous": false,
"min": 0.1,
"max": 10,
"unit": "x"
},
{
"key": "CoaBots.Scaling.DamageTaken",
"type": "float",
"category": "combat",
"title": "Damage taken by bots",
"description": "Multiplies the damage creatures deal to bots. Below 1 bots take less; 1 is no change.",
"default": 1.0,
"advanced": false,
"restartRequired": "world",
"dangerous": false,
"min": 0.1,
"max": 10,
"unit": "x"
},
{
"key": "CoaBots.Scaling.TankThreat",
"type": "float",
"category": "combat",
"title": "Tank threat",
"description": "Extra threat generated by bot tanks so they hold the enemy's attention. 1 is no change.",
"default": 1.0,
"advanced": false,
"restartRequired": "world",
"dangerous": false,
"min": 1,
"max": 10,
"unit": "x"
},
{
"key": "CoaBots.Scaling.BossTuning",
"type": "bool",
"category": "combat",
"title": "Extra help against four bosses",
"description": "Adds stronger multipliers for Loken, the Drakkari Elemental, the Drakkari Colossus and Gal'darah, whom level 60 bots could not beat otherwise. For testing; off by default.",
"default": false,
"advanced": true,
"restartRequired": "world",
"dangerous": false
},
{ {
"key": "CoaBots.WorldBrain.MountDistanceMin", "key": "CoaBots.WorldBrain.MountDistanceMin",
"type": "int", "type": "int",
+1
View File
@@ -24,3 +24,4 @@ coa-core = { path = "../crates/coa-core" }
coa-registry-proto = { path = "../crates/coa-registry-proto" } coa-registry-proto = { path = "../crates/coa-registry-proto" }
coa-control-proto = { path = "../crates/coa-control-proto" } coa-control-proto = { path = "../crates/coa-control-proto" }
tracing = "0.1" tracing = "0.1"
uuid = { version = "1", features = ["v4"] }
+1
View File
@@ -439,6 +439,7 @@ pub(crate) async fn join_realm(
let mut profile = coa_core::remote_client::load(&dir) let mut profile = coa_core::remote_client::load(&dir)
.map_err(|e| fail("other", e.to_string()))?; .map_err(|e| fail("other", e.to_string()))?;
profile.host = host; profile.host = host;
profile.realm = Some(realm.clone());
coa_core::remote_client::save(&dir, &profile) coa_core::remote_client::save(&dir, &profile)
.map_err(|e| fail("launch", e.to_string()))?; .map_err(|e| fail("launch", e.to_string()))?;
super::play(state, REMOTE_CLIENT_ID.to_string()) super::play(state, REMOTE_CLIENT_ID.to_string())
+514 -283
View File
File diff suppressed because it is too large. Load diff
+12
View File
@@ -11,3 +11,15 @@ pub fn close_to_tray(dir: &Path) -> coa_core::Result<bool> {
pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> { pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled) coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled)
} }
/// Clear the game's cache of server data before every Play (on unless the player turned it off).
pub fn clear_cache_on_play(dir: &Path) -> bool {
std::fs::read(dir.join("clear-game-cache.json"))
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or(true)
}
pub fn save_clear_cache_on_play(dir: &Path, enabled: bool) -> coa_core::Result<()> {
coa_core::fsx::atomic_write_json(&dir.join("clear-game-cache.json"), &enabled)
}
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager", "productName": "CoA Server Manager",
"version": "0.9.9", "version": "0.9.16",
"identifier": "com.coa.servermanager", "identifier": "com.coa.servermanager",
"build": { "build": {
"beforeDevCommand": "npm run dev", "beforeDevCommand": "npm run dev",
+18
View File
@@ -36,3 +36,21 @@ Manager 0.9.8 preparation refreshes the bundled server history through 0.261030.
The two reviewed upcoming records are in `tools/reviewed-manager-notes.json` and The two reviewed upcoming records are in `tools/reviewed-manager-notes.json` and
`tools/reviewed-server-notes.json`; every new note has all five translations. `tools/reviewed-server-notes.json`; every new note has all five translations.
These files describe preparation and do not add unpublished releases to canonical history. These files describe preparation and do not add unpublished releases to canonical history.
Manager 0.9.10 refreshes the bundled server history through 0.261104.94 from
canonical build commit `a9c6b17c8c1a295680fda4ad4bcdde266357264d` on 2026-11-08.
The reviewed upcoming Manager and server records carry translations in all five languages.
Manager 0.9.12 refreshes the bundled server history through 0.261108.95 from
canonical build commit `ca04f96f600481446f97ac611c7f914d786af00b` on 2026-11-14.
The reviewed upcoming Manager and server records carry translations in all five languages.
Manager 0.9.13 refreshes the bundled server history through 0.261114.106 from
canonical build commit `3308e3a957cd9fd1a2cd145a7f023f2cf521c54c` on 2026-11-15.
The reviewed upcoming Manager and server records (Custom Races V2, 213 server notes)
carry translations in all five languages.
Manager 0.9.14 refreshes the bundled server history through 0.261115.110 from
canonical build commit `45c013be9ade3001581e5201cacda6cd6bb6b01c` on 2026-11-16.
The reviewed upcoming Manager (12 notes) and server (6 notes) records
carry translations in all five languages.
File diff suppressed because it is too large. Load diff
+848
View File
@@ -1571,6 +1571,854 @@
}, },
"experimentalFeatures": [], "experimentalFeatures": [],
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261030.90...server-0.261101.92" "compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261030.90...server-0.261101.92"
},
{
"tag": "server-0.261104.94",
"version": "0.261104.94",
"date": "2026-11-04",
"url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261104.94",
"notes": [
"Companions avoid repeating unreachable routes in the open world",
"Server startup waits for ports that Windows is still releasing",
"Updated the reviewed CoA upstream snapshot"
],
"snapshot": "f67a6d8545e4c6ece2f819f9dd2642fe5a81a69c959946a1031859c19b5c4d74",
"components": {
"upstream": {
"repository": "jealous-sound/azerothcore-wotlk-coa",
"ref": "a34c5ad7167b6b2087a678cb4344c6cbe6abb823",
"sha": "a34c5ad7167b6b2087a678cb4344c6cbe6abb823"
},
"core": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "14cf375f1e006770b330d3fb89201ace54bfca24",
"sha": "14cf375f1e006770b330d3fb89201ace54bfca24"
},
"bots": {
"repository": "Corfirean/mod-coa-playerbots",
"ref": "447558bc27d6bb447aaf10eefcb2e85ac2b15c32",
"sha": "447558bc27d6bb447aaf10eefcb2e85ac2b15c32"
},
"scaling": {
"repository": "Corfirean/mod-coa-content-scaling",
"ref": "3c2febf636bd09087bb278e381b975271a70fdf6",
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
},
"manager": {
"repository": "Corfirean/coa-server-manager",
"ref": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
"sha": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7"
},
"races": {
"repository": "ilusixn/azerothcore-wotlk-coa",
"ref": "coa-custom-1.9.2",
"sha": "31bd63d309b8b0fb4f1a4d9b793a343b8ac36f1e",
"assets": [
{
"name": "CoA-Custom-1.9.2-Client-1.zip",
"size": 1513021586,
"digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-2.zip",
"size": 1198283005,
"digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-3.zip",
"size": 1678829573,
"digest": "sha256:907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-4.zip",
"size": 502385128,
"digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-5.zip",
"size": 168079711,
"digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip"
},
{
"name": "CoA-Custom-1.9.2-Server.zip",
"size": 53004560,
"digest": "sha256:b893813573a4d3f6a0003c1f174582d3def997f37b402cbca44d53055d2fc1d2",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Server.zip"
},
{
"name": "INSTALL-GUIDE.txt",
"size": 3006,
"digest": "sha256:f17e97fafa3225901d1caf8c3b8141293f98fbfb8c9243c0c4717278c60146aa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/INSTALL-GUIDE.txt"
},
{
"name": "PATCH-NOTES-1.9.2.txt",
"size": 2822,
"digest": "sha256:f2fd4693ba181959a572d3fb10a0050e9ff6c4f735b3ab0019c7d16712db28cb",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/PATCH-NOTES-1.9.2.txt"
}
]
},
"squid": {
"repository": "Zyth45/mod-playerbots",
"ref": "v2.8.2",
"sha": "fa4cfd31997367b3e574a2b89b858c4669ff53fb",
"patch": "patches/squid-coa-validation.patch",
"patchSha256": "9b101db17369fb5a6af3f7e99323f7770eb8650ba3b5e9b3970bf09a0ef5d32f"
},
"build": {
"repository": "Corfirean/coa-server-build",
"ref": "d9aaa5263154473b2fe1623172492f88e6e03d73",
"sha": "d9aaa5263154473b2fe1623172492f88e6e03d73"
},
"dungeon-clear": {
"repository": "Zyth45/mod-dungeon-clear",
"sha": "9a9d09cf512e0a883af9cda6973445b81c123b13",
"patch": "patches/dungeon-clear-coa-validation.patch",
"patchSha256": "956f278865e22ee75c984ca22ff8238150b5886c9934ddfe64dd9c832c912dcc",
"ref": "9a9d09cf512e0a883af9cda6973445b81c123b13"
},
"navigation": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sourceRelease": "navigation-20261012",
"manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683",
"archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60",
"assets": [
{
"name": "navigation.zip.001",
"size": 1500000000,
"sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001"
},
{
"name": "navigation.zip.002",
"size": 1377006470,
"sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002"
}
]
}
},
"experimentalFeatures": [],
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261101.92...server-0.261104.94"
},
{
"tag": "server-0.261108.95",
"version": "0.261108.95",
"date": "2026-11-08",
"url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261108.95",
"notes": [
"Login server startup works when Windows does not list its listening port",
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear",
"Updated SQUID Playerbots to 2.9.4",
"Updated the reviewed CoA upstream snapshot"
],
"snapshot": "0f331e3289864531d19b2eb185080c18ddd9eaa7be9befa28d6f4b50b5dc2a3f",
"components": {
"upstream": {
"repository": "jealous-sound/azerothcore-wotlk-coa",
"ref": "f8955cb9b29042c359a938ff732e4b608dd62ea5",
"sha": "f8955cb9b29042c359a938ff732e4b608dd62ea5"
},
"core": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "85ecc2122efd4bc168e750ab35c3e3e8d9c49735",
"sha": "85ecc2122efd4bc168e750ab35c3e3e8d9c49735"
},
"bots": {
"repository": "Corfirean/mod-coa-playerbots",
"ref": "0588a8e5cdfe54f81fe47bbb40fc9f75d29662e3",
"sha": "0588a8e5cdfe54f81fe47bbb40fc9f75d29662e3"
},
"scaling": {
"repository": "Corfirean/mod-coa-content-scaling",
"ref": "3c2febf636bd09087bb278e381b975271a70fdf6",
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
},
"manager": {
"repository": "Corfirean/coa-server-manager",
"ref": "711f378ae82f75d3fc64368c042889c773315c54",
"sha": "711f378ae82f75d3fc64368c042889c773315c54"
},
"races": {
"repository": "ilusixn/azerothcore-wotlk-coa",
"ref": "coa-custom-1.9.2",
"sha": "31bd63d309b8b0fb4f1a4d9b793a343b8ac36f1e",
"assets": [
{
"name": "CoA-Custom-1.9.2-Client-1.zip",
"size": 1513021586,
"digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-2.zip",
"size": 1198283005,
"digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-3.zip",
"size": 1678829573,
"digest": "sha256:907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-4.zip",
"size": 502385128,
"digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-5.zip",
"size": 168079711,
"digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip"
},
{
"name": "CoA-Custom-1.9.2-Server.zip",
"size": 53004560,
"digest": "sha256:b893813573a4d3f6a0003c1f174582d3def997f37b402cbca44d53055d2fc1d2",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Server.zip"
},
{
"name": "INSTALL-GUIDE.txt",
"size": 3006,
"digest": "sha256:f17e97fafa3225901d1caf8c3b8141293f98fbfb8c9243c0c4717278c60146aa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/INSTALL-GUIDE.txt"
},
{
"name": "PATCH-NOTES-1.9.2.txt",
"size": 2822,
"digest": "sha256:f2fd4693ba181959a572d3fb10a0050e9ff6c4f735b3ab0019c7d16712db28cb",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/PATCH-NOTES-1.9.2.txt"
}
]
},
"squid": {
"repository": "Zyth45/mod-playerbots",
"ref": "v2.9.4",
"sha": "75d1784f66f3c731340a96f72bfbd301974b6ab4",
"patch": "patches/squid-coa-validation.patch",
"patchSha256": "244cd2d8b04b3158665e44f40ebb6d4088a867a052ff5c3a9553d604652fe2d1"
},
"build": {
"repository": "Corfirean/coa-server-build",
"ref": "2e9fee5b953455e39d8acb70cf9bb32ee09e9288",
"sha": "2e9fee5b953455e39d8acb70cf9bb32ee09e9288"
},
"dungeon-clear": {
"repository": "Zyth45/mod-dungeon-clear",
"sha": "081a04f4208056dbb90717a5d10fe1e593943d5b",
"patch": "patches/dungeon-clear-coa-validation.patch",
"patchSha256": "4078f8284ef011142c970cb8e812055e370ba858502de82f86a831d16fe1ec66",
"ref": "081a04f4208056dbb90717a5d10fe1e593943d5b"
},
"navigation": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sourceRelease": "navigation-20261012",
"manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683",
"archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60",
"assets": [
{
"name": "navigation.zip.001",
"size": 1500000000,
"sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001"
},
{
"name": "navigation.zip.002",
"size": 1377006470,
"sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002"
}
]
}
},
"experimentalFeatures": [],
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261104.94...server-0.261108.95"
},
{
"tag": "server-0.261114.106",
"version": "0.261114.106",
"date": "2026-11-14",
"url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261114.106",
"notes": [
"Optional extra strength for bots in dungeons and raids",
"Bot performance metrics and optional scheduling controls are available for testing",
"Database startup can recover when Windows omits its listening port",
"Updated Dungeon Clear to 3.0.0 to match SQUID Playerbots 3.0",
"Automatic world restarts wait for the previous supervisor to finish",
"The server's own Auction House Bot stays in charge when SQUID Playerbots 3.0 is installed",
"Updated SQUID Playerbots to 3.0",
"Updated the reviewed CoA upstream snapshot"
],
"snapshot": "5ecaa04281576af58df11d5d39151cbebb4f2dfb10fffb84098d2809709cb68f",
"components": {
"upstream": {
"repository": "jealous-sound/azerothcore-wotlk-coa",
"ref": "96afaf0f51cc4b37f1eba282bffb1c5aab353de6",
"sha": "96afaf0f51cc4b37f1eba282bffb1c5aab353de6"
},
"core": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "8850b229fe2653a954a2e753c5a9b293bf4e500b",
"sha": "8850b229fe2653a954a2e753c5a9b293bf4e500b"
},
"bots": {
"repository": "Corfirean/mod-coa-playerbots",
"ref": "30a5a555f56fda8f4ccad14be8438bd0532d85b9",
"sha": "30a5a555f56fda8f4ccad14be8438bd0532d85b9"
},
"scaling": {
"repository": "Corfirean/mod-coa-content-scaling",
"ref": "3c2febf636bd09087bb278e381b975271a70fdf6",
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
},
"manager": {
"repository": "Corfirean/coa-server-manager",
"ref": "d71c5635e3262a775b400a1c90ac81d7bddcbeaf",
"sha": "d71c5635e3262a775b400a1c90ac81d7bddcbeaf"
},
"races": {
"repository": "ilusixn/azerothcore-wotlk-coa",
"ref": "coa-custom-1.9.2",
"sha": "31bd63d309b8b0fb4f1a4d9b793a343b8ac36f1e",
"assets": [
{
"name": "CoA-Custom-1.9.2-Client-1.zip",
"size": 1513021586,
"digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-2.zip",
"size": 1198283005,
"digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-3.zip",
"size": 1678829573,
"digest": "sha256:907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-4.zip",
"size": 502385128,
"digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip"
},
{
"name": "CoA-Custom-1.9.2-Client-5.zip",
"size": 168079711,
"digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip"
},
{
"name": "CoA-Custom-1.9.2-Server.zip",
"size": 53004560,
"digest": "sha256:b893813573a4d3f6a0003c1f174582d3def997f37b402cbca44d53055d2fc1d2",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Server.zip"
},
{
"name": "INSTALL-GUIDE.txt",
"size": 3006,
"digest": "sha256:f17e97fafa3225901d1caf8c3b8141293f98fbfb8c9243c0c4717278c60146aa",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/INSTALL-GUIDE.txt"
},
{
"name": "PATCH-NOTES-1.9.2.txt",
"size": 2822,
"digest": "sha256:f2fd4693ba181959a572d3fb10a0050e9ff6c4f735b3ab0019c7d16712db28cb",
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/PATCH-NOTES-1.9.2.txt"
}
]
},
"squid": {
"repository": "Zyth45/mod-playerbots",
"ref": "v3.0",
"sha": "4ef5ed9ebe75a330de7df19639a042391e037e15",
"patch": "patches/squid-coa-validation.patch",
"patchSha256": "2cc45bc6555d5bb3e91728840f9de6e73c002c73b270a37732a1499956241c5f"
},
"build": {
"repository": "Corfirean/coa-server-build",
"ref": "be0c1eef3aa4b20c4203dbf54ac66b63d4e6df05",
"sha": "be0c1eef3aa4b20c4203dbf54ac66b63d4e6df05"
},
"dungeon-clear": {
"repository": "Zyth45/mod-dungeon-clear",
"sha": "6efb59eae96bcc0730fc083314dd28d55970bbf4",
"patch": "patches/dungeon-clear-coa-validation.patch",
"patchSha256": "2845d389422e3a59e5c186ecf54b03f64f1dcc22cdef15729b60c354ae72cd6f",
"ref": "6efb59eae96bcc0730fc083314dd28d55970bbf4"
},
"navigation": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sourceRelease": "navigation-20261012",
"manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683",
"archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60",
"assets": [
{
"name": "navigation.zip.001",
"size": 1500000000,
"sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001"
},
{
"name": "navigation.zip.002",
"size": 1377006470,
"sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002"
}
]
}
},
"experimentalFeatures": [],
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261108.95...server-0.261114.106"
},
{
"tag": "server-0.261115.110",
"version": "0.261115.110",
"date": "2026-11-15",
"url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261115.110",
"notes": [
"Test build of the subclass module for two-headed Ogres",
"Thin Twins can earn a subclass through their own quest, the Bravery Badge",
"A two-headed Ogre's ranged subclass can shoot at point-blank range",
"Ogres have a new racial, Tolerance",
"Standard-class Ogres and Thin Humans start with only their own class kit",
"Helmets sit on the Thin Human's head instead of his chest",
"LiveMon shows live damage, healing, crowd control and subclass combo statistics",
"Standard-class Ogres and Thin Twins can take a CoA class as their subclass",
"Thin Human and Two-Headed Ogre are now their own playable races",
"Subclassed relic users can hold a relic beside a ranged weapon",
"Server options to limit subclassing or turn the two subclass races off",
"A standard subclass brings its whole basic kit, skills and weapons",
"Two-Headed Ogres and Thin Humans with a standard class can now pick a subclass",
"Thin Humans find more gold with the Hand-Me-Downs racial",
"Two-Headed Ogres wear helmets on both heads",
"Flying mounts no longer fly in Kalimdor and the Eastern Kingdoms",
"LiveMon's character tab can be closed and goes away for deleted characters",
"Classic classes can be limited to their Wrath of the Lich King abilities",
"Dual Wield shows once in the spellbook",
"Two-Headed Ogres get Subclass Bar 1 for the other head's spells",
"Subclass forms leave Two-Headed Ogres in their own body and turn the twin brother instead",
"CoA subclass trees show their specialization painting in the subclass tab",
"Characters with a subclass no longer get Dual Specialization",
"You can hold only one subclass book and one insight at a time",
"Thin Humans and Two-Headed Ogres get the quests of their starting zone",
"The Bravery Badge and the Book of Origins look and read like a badge and a book",
"Ghost Wolf and Travel Form turn the whole ogre, and the twin brother rides the beast",
"Standard-class mains can spend points in their subclass trees and reset main talents",
"Your subclass's trainer can reset only your subclass talents",
"The Thin Human's cape lies along his back instead of sticking out like a board",
"The twin brother finishes pointing before hopping off and readies his weapon with you",
"The twin brother fights with his melee weapon up close and sits close behind you on mounts",
"The twin brother copies your pose on hover discs, carpets and other unusual mounts",
"Two-Headed Ogres sit in cars and keep their mace drawn after a shot",
"Two-Headed Ogres fight with a weapon in one hand and a gun in the other",
"The Ogre's Agree or Disagree racial now shows what it will do next",
"The Thin Twins' brother turns into a worgen in every subclass Cursed Form",
"Leaps and charges ordered for the Thin Twins' brother move him instead of you",
"CoA classes taken as a subclass get their class mechanics",
"Thin Twins and Two-Headed Ogres keep their weapons in a subclass Cursed Form",
"Hovering a Guardian standard no longer causes a Lua error",
"LiveMon shows specialization names instead of their signature spells",
"Ogre eyes are picked by colour, with a Blind checkbox for each eye",
"Two-headed ogres no longer keep casting after a subclass spell with a cast time",
"Two-headed ogres cast every subclass spell with the left arm",
"The other half only shoots when you attack a target out of melee reach",
"The other head raises her hand while casting and your presses come first",
"Saving talent changes no longer fails for characters with a subclass",
"The second-way quest no longer pops up at level 20",
"Every race can create the standard classes the creation screen offers again",
"Subclass Bar 1 shows cooldowns, charges and casts like a normal action bar",
"Subclass Bar 1 refills itself when you change subclass",
"Subclass Bar 1 appears as soon as you choose a subclass",
"Subclass Bar 1 works like an action bar and can live in Bartender4",
"A subclass can never be the character's own class",
"New characters no longer inherit the subclass of a deleted character",
"Sun Cleric, Barbarian, Bloodmage and Cultist subclass resources use the game's own orbs",
"Shapeshifting no longer takes away the twin brother or the subclass",
"A subclass specialization now teaches the ability its passive promises",
"Subclass stances and forms appear only on the subclass stance bar",
"Subclass vows, auras and formations move to the subclass stance bar",
"The Thin Human's cape rests on his shoulders and moves with them",
"The twin brother gets a real spot in cars and rides along in passenger seats",
"The twin brother puts his weapons away while he wears a subclass shape",
"The Thin Twins' brother now shows the flash and glow of subclass forms",
"The twin brother sneaks along in stealth instead of staying behind",
"The stance button takes a Thin Twin out of a form his brother wears again",
"The Two-Head and Two-Thins tabs show one wide background and the right class icon",
"The Two-Head and Two-Thins trees use the game's own talent nodes",
"Agree or Disagree takes one spellbook slot that changes name and icon",
"Subclass talent trees no longer let you spend more points than you have",
"Your brother stays at your side when you melee with a bow equipped",
"A melee brother stays on your target and keeps fighting",
"The Two-Headed Ogre twists her body less while her other head casts",
"Thin Twins and Two-Headed Ogres are Hero Races that need a level 60 character",
"The Two-Headed Ogre's portrait shows both heads instead of her body",
"Your other half's spells break your stealth, and Running Wild ends when you stealth",
"Spells your other half casts now trigger the class's talents and resources",
"Your other half takes the subclass's Cat, Bear and stance forms on their own",
"Your other head or brother can no longer finish a cast while you run",
"The other head's hand glows while she casts",
"With Play Easy on, your other half uses abilities that cost health",
"New racial passives explain the shared and split resource pools",
"The dressing room works for races without their own background, no extra addon needed",
"Your brother climbs onto your Travel Form or wolf even after a fight",
"When your brother uses Running Wild, you ride on his back",
"In Running Wild you ride on your brother's shoulders",
"Your weapons no longer go missing after a Running Wild ride",
"When both halves use the same resource, their pool is twice as big",
"The subclass window shows every CoA class's own background at full strength",
"You can rearrange Subclass Bar 1 during combat without an error",
"Your other head or brother has a cast bar of their own",
"Choice talents in the subclass window show as one node with two options",
"SpellActivationOverlay can light up Subclass Bar 1",
"Your subclass's resource now shows as an extra bar under your portrait",
"Your other half's resource bar keeps its value when you log out and back in",
"Rage, energy and runic power subclasses now get and use their resource",
"Subclass resource orbs only appear when your subclass specialization can fill them",
"Your subclass specialization comes with its first class talent learned",
"Your main class's key stat now also powers your subclass",
"Subclass talents follow the paths and point requirements of their tree",
"Your summons follow your brother while he walks beside you",
"Your brother rides on the back of your Travel Form cat and moves with it",
"Dressing your twin in the wardrobe no longer causes an addon error",
"Your brother rides on your back in Wargstride",
"A Bloodmage subclass's Cursed Form no longer replaces your own action bar",
"Pressing an active subclass stance or form again turns it off",
"Character select shows your subclass under your class",
"The Two-Headed Ogre's second head no longer pokes through hats",
"Two-Headed Ogres keep aiming between shots instead of idling",
"Two-Headed Ogres who shoot rest their gun on the shoulder when not firing",
"Two-Headed Ogres who shoot themselves aim and fire their gun with the right hand",
"Two-Headed Ogres who shoot fire their bullets from the gun hand",
"The wardrobe shows a Two-Headed Ogre's applied look and her saved outfits apply again",
"The second head's quest mark floats over her head in cities and inns",
"Subclass Bar 1 no longer fills up with Throw, Shoot, Wand and Auto Attack",
"Abilities you learn from your subclass no longer land on your own action bars",
"A caster Two-Headed Ogre keeps her staff in hand while her second head shoots",
"A Two-Headed Ogre's staff keeps its size when she puts it on her back",
"A shooting subclass starts Auto Shot on right-click without logging out first",
"A Hunter subclass keeps Auto Shot going while the main head casts or moves",
"Weapons and armor from a subclass stay usable after logging in again",
"Two-Headed Ogres are Horde again and Thin Twins share Forgotten race rules",
"Thin Humans and Two-Headed Ogres can no longer be created as Hero",
"The Two-Headed Ogre stays in her combat stance between attacks",
"The second-head tab only shows for Two-Headed Ogres and Thin Twins",
"Thin Twins capes no longer show their inside at the shoulders",
"Thin Twins keep short hair under hats",
"Thin Twins keep their face, cape and hat fit with CoA Custom 1.9.2",
"Thin Twins show their class gear in character creation",
"Two-Headed Ogre capes drape over her back",
"CoA Custom 1.9.5 races work on the subclass server",
"With Play easy, cowboy the brother leaves a spent timed form",
"The Two-Headed Ogre casts with a raised fist before her face",
"The second-head client patch is now patch-ZZZZT.MPQ",
"Dual Wield shows once in the spellbook, whichever class teaches it",
"The subclass addon keeps working when the Twins or Ogre are renamed",
"The subclass name shows only on the character tab",
"The Thin Twins' Accursed brother keeps his distance until he takes his cursed form",
"The Thin Twins' brother follows a form's cost, cooldown and duration",
"The Thin Twins' own mana bar no longer flickers",
"Witch Hunter Vault now springs over in a handspring instead of a jump",
"The Twins brother keeps his timed form and no longer takes forms a spell forbids",
"The Twins brother faces his target, leaps in and leaves a form to heal you",
"With Play easy, cowboy, the brother uses his timed forms in a fight",
"Original races no longer look broken in the 64-bit client's character creation",
"Subclasses get their specialization's free passives, like the Pyromancer's draconic form",
"The subclass cast bar no longer gets stuck and can always be Alt-dragged",
"Pick-one talents in the subclass window no longer overlap their neighbours",
"Subclass spells get their rank upgrades, resources and class mechanics",
"Subclass talents that replace a spell now replace it for the subclass too",
"The Thin Twins keep their own hairstyle under hats",
"The Twins brother takes the look of the cursed form he actually uses",
"The Twins brother stands beside you at character select in his own clothes",
"The Twins brother climbs down from your back before taking a form",
"Spells the Twins brother casts no longer play a cast animation on you",
"The Thin Twins brother is now your mirror image",
"The Thin Twins brother can have his own face, hair style and beard",
"A script builds the original races' Vault patches from your own client files",
"The subclass client patch is now built after the release's own patches",
"The mirrored Thin Twins brother is built from the current Thin Twins model",
"Pressing your subclass mount again dismounts you",
"Removing a subclass dismisses the pet it let you summon",
"Removing a Warlock or Paladin subclass no longer unlearns your mounts",
"Removing a subclass no longer leaves its spells in your spellbook",
"A Starcaller subclass shows Lunar Phase as CoA's moon",
"Your twin's or other head's pet gets its own movable pet bar",
"A Ranged Head stands still while the Melee Head is offline",
"A bot plays the missing head of a Two-Players ogre",
"A Ranged Head keeps an echo of its deleted Melee Head's gear",
"Two-Players ogres hold books, pouches and orbs forward in the off hand",
"Two-Players ogres can pair up as Melee Head and Ranged Head",
"Paired Two-Players heads share one body",
"SquidBots Lite no longer prints \"Command 'dc status' does not exist\" at login",
"The subclass action bar no longer causes a blocked-action error in combat",
"Two-Players heads split their abilities into melee for the body and ranged for the rider",
"Two-Players heads gain Agree or Disagree stacks when they fight together",
"Two-Players heads can only be CoA classes",
"The Ranged Head's gear slots are frozen in ice and can no longer be dragged",
"Two-Players heads find the abilities they borrow on their own bar",
"Two-Players ogres can Bonk Heads! together once the heads have agreed long enough",
"Abilities lent between Two-Players heads follow each head's respecs and new spells",
"Two-Players ogres can use Mutate Me! to take the eyes-everywhere look and back",
"A Two-Players ogre fills one party spot and enters dungeons as one player",
"A Two-Players ogre joins a party only when there is room for both heads",
"A Ranged Head's own frame now stands for the shared Two-Players body",
"The Two-Players Ranged Head shares the body's health and both heads get full kill XP",
"The Two-Players Ranged Head shares the body's gear",
"Two-Players heads split quest gold, share one resource pool and keep their head's specs",
"Mobs attacked by the Two-Players Ranged Head now fight the body",
"Two-Players Twins: the second brother rides piggyback on the first, visible as himself",
"Bot plans panel shows what your group's bots are doing and lets you pick their next quest",
"Questing bots do all their quests in one area before moving on",
"The Twins' second brother keeps and wears his own gear on his brother's back",
"A Two-Players twin can call his brother to his side until another player joins him",
"Agree now raises spell and ranged hit too, not only melee hit",
"Two-Players ogres drop their mount when either head attacks",
"The other head's abilities now go on your own action bars",
"A bot body keeps questing, looting and resting after a fight instead of standing still",
"A bot body's SquidBots menu now opens from a button on your own player frame",
"Character select shows a Two-Players head's joined name and its partner's class",
"The Ranged Head now goes into and out of Dungeon Finder dungeons with the body",
"Two-Players can be switched off with Subclass.TwoPlayers.Enable",
"The other head's abilities only cost you resources when they actually go off",
"Character select shows a Two-Players ogre in his Mutate Me look",
"The Ranged Head gets the enchant, gem and suffix stats of the shared gear",
"The Ranged Head of a Two-Headed Ogre no longer pops out of the body at logout",
"A Ranged Head and its bot body are in one party again, so party chat and bot orders work",
"A bot riding as the Ranged Head no longer rests, roams or makes the body sit down",
"The character sheet of a Two-Players head shows the other head's class",
"Two-Players Ogres can fit a carried mount in a window and share the fit",
"Custom Races V2 with 17 new races, subclasses and the Fading Island",
"Updated Custom Races to 2.0"
],
"snapshot": "d3d10476d144d2a701a5a122f1f249ff8219f7a6324e007cb3e153d4628973f7",
"components": {
"upstream": {
"repository": "jealous-sound/azerothcore-wotlk-coa",
"ref": "96afaf0f51cc4b37f1eba282bffb1c5aab353de6",
"sha": "96afaf0f51cc4b37f1eba282bffb1c5aab353de6"
},
"core": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "9740ced5c41806115d851ab37ab34f28e1e8b712",
"sha": "9740ced5c41806115d851ab37ab34f28e1e8b712"
},
"bots": {
"repository": "Corfirean/mod-coa-playerbots",
"ref": "30a5a555f56fda8f4ccad14be8438bd0532d85b9",
"sha": "30a5a555f56fda8f4ccad14be8438bd0532d85b9"
},
"scaling": {
"repository": "Corfirean/mod-coa-content-scaling",
"ref": "3c2febf636bd09087bb278e381b975271a70fdf6",
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
},
"manager": {
"repository": "Corfirean/coa-server-manager",
"ref": "d3527312803fb5a3e1cd48e01496645a8bbc9dcf",
"sha": "d3527312803fb5a3e1cd48e01496645a8bbc9dcf"
},
"races": {
"repository": "ilusixn/CustomRacesCoa",
"ref": "coa-custom-2.0",
"sha": "dae0c661f7197bafd0a42d80866fa8709b3792c9",
"assets": [
{
"name": "CoA-Custom-Races-V2-Credits.csv",
"size": 5487,
"digest": "sha256:9afb0b777498d14601476bed7ce82a449ce2b80af5dae107f7309081c1936882",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-Races-V2-Credits.csv"
},
{
"name": "CoA-Custom-Races-V2-Credits.xlsx",
"size": 10129,
"digest": "sha256:d24b51f42870e9ab370279e37ea1cd894b7a208cb8960548c0f465222d50c850",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-Races-V2-Credits.xlsx"
},
{
"name": "CoA-Custom-V2-Client-1.zip",
"size": 1513021586,
"digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-1.zip"
},
{
"name": "CoA-Custom-V2-Client-2.zip",
"size": 1198283005,
"digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-2.zip"
},
{
"name": "CoA-Custom-V2-Client-3.zip",
"size": 1671130705,
"digest": "sha256:0af34199f0739ce086adb0371d3de7c1a0f5ca9c62ecde6b0efe9286e33874a8",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-3.zip"
},
{
"name": "CoA-Custom-V2-Client-4.zip",
"size": 502385128,
"digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-4.zip"
},
{
"name": "CoA-Custom-V2-Client-5.zip",
"size": 168079711,
"digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-5.zip"
},
{
"name": "CoA-Custom-V2-Client-6.zip",
"size": 1881526537,
"digest": "sha256:91db79b7b451856fa9e45daea52e0fe1c04676653dd8a88e6627f04ee7b47759",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-6.zip"
},
{
"name": "CoA-Custom-V2-Client-7.zip",
"size": 734725114,
"digest": "sha256:4c5532d775d206a3b913a6111040bb96b95c683b74c08a6131ed9f38db8e2b39",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-7.zip"
},
{
"name": "CoA-Custom-V2-Client-8.zip",
"size": 734216670,
"digest": "sha256:bdaa1d047e8767bd5715f1e8465d116220597d9c135a43e2dda02e12ce2e5526",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-8.zip"
},
{
"name": "CoA-Custom-V2-Client-9.zip",
"size": 195235400,
"digest": "sha256:0764893543084a12d15578fe734f66ba4519740794a6b3b3a38a08594c38c640",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Client-9.zip"
},
{
"name": "CoA-Custom-V2-Server.zip",
"size": 63983587,
"digest": "sha256:8970d61eea40f53cea4c27481edd85d2b2647cd32eb88932e0077da3b4a77d23",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/CoA-Custom-V2-Server.zip"
},
{
"name": "creation-screen.png",
"size": 2139517,
"digest": "sha256:84c3144f34ef8015e8612e412da03383241124d58e36c703eeb2a525096a5795",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/creation-screen.png"
},
{
"name": "INSTALL-GUIDE.txt",
"size": 2504,
"digest": "sha256:da402117a90a60a029fdce9a94125ddd28b386a73f37c180992befca57e9f13a",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/INSTALL-GUIDE.txt"
},
{
"name": "PATCH-NOTES-V2.txt",
"size": 4388,
"digest": "sha256:82901d54b1f13cd8b2e7a73a7c2fdc3e237f8090c332729bc553818834fe27d0",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/PATCH-NOTES-V2.txt"
},
{
"name": "RACES.md",
"size": 8629,
"digest": "sha256:1e7a9aaee354b07924a8cdda5e4dbffe4cad88f215d68efb74d8d0832403422d",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/RACES.md"
},
{
"name": "SHA256SUMS.txt",
"size": 938,
"digest": "sha256:a68591f04d661b558523133f99411fd4a7e32f1b45f79f977bb0989246f11179",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/SHA256SUMS.txt"
},
{
"name": "showcase.mp4",
"size": 81658913,
"digest": "sha256:a3d4b4f561bb12dcc91da562c5ee79157143f4b67997479edb2152b27b925a2a",
"url": "https://github.com/ilusixn/CustomRacesCoa/releases/download/coa-custom-2.0/showcase.mp4"
}
],
"server": [
{
"repository": "stefanw1337/azerothcore-wotlk-coa",
"branch": "stefanw1337-subclassing-test",
"sha": "ccea52d17a27482784e705e9cc913b68dedd9f85"
}
],
"provenance": [
{
"repository": "ilusixn/Fading-Islands-Restore",
"sha": "e150de1cb496314af752e98021e57ca93d5d799d",
"used": "server/core-patches"
},
{
"repository": "ilusixn/Custom-Race-3.3.5a",
"sha": "ac907655bd43dec2eff1b4ff509f7fb574325c58",
"used": "server/core racials"
},
{
"repository": "ilusixn/ilusixn-dev-menu",
"sha": "ea50a8533a3402c69c8773677db1027ec1180d2c",
"used": "modules/mod-ilusixn-devmenu"
}
]
},
"squid": {
"repository": "Zyth45/mod-playerbots",
"ref": "v3.0",
"sha": "4ef5ed9ebe75a330de7df19639a042391e037e15",
"patch": "patches/squid-coa-validation.patch",
"patchSha256": "2cc45bc6555d5bb3e91728840f9de6e73c002c73b270a37732a1499956241c5f"
},
"build": {
"repository": "Corfirean/coa-server-build",
"ref": "9a122d049e8be457444389e9756936bcdb4e7ef5",
"sha": "9a122d049e8be457444389e9756936bcdb4e7ef5"
},
"dungeon-clear": {
"repository": "Zyth45/mod-dungeon-clear",
"sha": "6efb59eae96bcc0730fc083314dd28d55970bbf4",
"patch": "patches/dungeon-clear-coa-validation.patch",
"patchSha256": "2845d389422e3a59e5c186ecf54b03f64f1dcc22cdef15729b60c354ae72cd6f",
"ref": "6efb59eae96bcc0730fc083314dd28d55970bbf4"
},
"navigation": {
"repository": "Corfirean/azerothcore-wotlk-coa",
"ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
"sourceRelease": "navigation-20261012",
"manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683",
"archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60",
"assets": [
{
"name": "navigation.zip.001",
"size": 1500000000,
"sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001"
},
{
"name": "navigation.zip.002",
"size": 1377006470,
"sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471",
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002"
}
]
}
},
"experimentalFeatures": [],
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261114.106...server-0.261115.110"
} }
] ]
} }
+15 -14
View File
@@ -1,6 +1,7 @@
// Dev-only: lets the UI run in a plain browser for visual review. Never bundled in production builds. // Dev-only: lets the UI run in a plain browser for visual review. Never bundled in production builds.
import { auctionCategories, auctionQualities } from "../lib/moduleSettings"; import { auctionCategories, auctionQualities } from "../lib/moduleSettings";
import moduleCatalog from "../../modules/catalog.json"; import moduleCatalog from "../../modules/catalog.json";
import addonCatalog from "../../addons/catalog.json";
import botsSchema from "../../schemas/bots.json"; import botsSchema from "../../schemas/bots.json";
import serverSchema from "../../schemas/server.json"; import serverSchema from "../../schemas/server.json";
import botsPresets from "../../schemas/presets/bots.json"; import botsPresets from "../../schemas/presets/bots.json";
@@ -29,6 +30,8 @@ export {};
(window as any).__TAURI_INTERNALS__ = { (window as any).__TAURI_INTERNALS__ = {
transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x, transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x,
invoke: async (cmd: string, args?: any)=>{ invoke: async (cmd: string, args?: any)=>{
if(cmd==="clear_game_cache_on_play") return localStorage.getItem("demo-clear-cache")!=="0";
if(cmd==="set_clear_game_cache_on_play"){localStorage.setItem("demo-clear-cache",args.enabled?"1":"0");return;}
if(cmd==="close_to_tray") return localStorage.getItem("demo-close-tray")==="1"; if(cmd==="close_to_tray") return localStorage.getItem("demo-close-tray")==="1";
if(cmd==="set_close_to_tray"){localStorage.setItem("demo-close-tray",args.enabled?"1":"0");return;} if(cmd==="set_close_to_tray"){localStorage.setItem("demo-close-tray",args.enabled?"1":"0");return;}
if(cmd==="client_graphics") return JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}'); if(cmd==="client_graphics") return JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}');
@@ -39,6 +42,13 @@ export {};
if(cmd==="pending_update") return null; if(cmd==="pending_update") return null;
if(cmd==="plugin:app|version") return "0.8.2"; if(cmd==="plugin:app|version") return "0.8.2";
if(cmd==="release_history") throw new Error("Offline demo: using bundled notes"); if(cmd==="release_history") throw new Error("Offline demo: using bundled notes");
if(cmd==="addons_list"||cmd==="addons_install"||cmd==="addons_remove"){const w=window as any;w.__addons=w.__addons??{dragonui:"old"};if(cmd==="addons_install"){await new Promise(r=>setTimeout(r,700));w.__addons[args.addon]="new";}if(cmd==="addons_remove")delete w.__addons[args.addon];return addonCatalog.addons.map((a:any)=>({id:a.id,name:a.name,description:a.description,author:a.author,license:a.license,needs:a.needs??null,repo:a.repo,size:a.files.reduce((s:number,f:any)=>s+f.size,0),installed:a.id in w.__addons,updateAvailable:w.__addons[a.id]==="old",foreignFolders:a.id==="coacombat"&&!(a.id in w.__addons)?["CoACombat"]:[],bundled:null as string|null})).concat([{id:"coa-dev-menu",name:"CoA Dev Menu",description:{en:"The in-game /dev editor for game masters.",ru:"Внутриигровой редактор /dev для гейм-мастеров. Ставится вместе с клиентским патчем Custom Races V2 и включается вместе с ним."},author:"ilusixn",license:"see repository",needs:null,repo:"https://github.com/ilusixn/ilusixn-dev-menu",size:0,installed:true,updateAvailable:false,foreignFolders:[],bundled:"custom-races"}]);}
if(cmd==="custom_race_characters") return {players:2,companionBots:14,squidBots:0};
if(cmd==="purge_custom_race_bots"){await new Promise(r=>setTimeout(r,500));return 14;}
if(cmd==="restart_schedule"||cmd==="restart_schedule_save"){const w=window as any;w.__sched=w.__sched??{enabled:false,time:"05:00",warningMinutes:5,weeklyEnabled:false,weeklyDay:"sunday",weeklyTime:"05:00",weeklyWarningMinutes:5};if(cmd==="restart_schedule_save"){const s=args.schedule;if(s.enabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.time))throw new Error("The restart time must be HH:MM, for example 05:00.");if(s.weeklyEnabled&&!/^([01]\d|2[0-3]):[0-5]\d$/.test(s.weeklyTime))throw new Error("The restart time must be HH:MM, for example 05:00.");w.__sched={...s};}return {schedule:w.__sched,supported:true};}
if(cmd==="server_logging_state"||cmd==="server_logging_preset"||cmd==="server_logging_settings_save"||cmd==="server_logs_clean"){const w=window as any;w.__logs=w.__logs??{preset:"normal",logBytes:148*1024*1024,settings:{autoCleanup:false,maxSizeMb:500}};if(cmd==="server_logging_preset"){w.__logs.preset=args.preset;return;}if(cmd==="server_logging_settings_save"){w.__logs.settings={...args.settings};}if(cmd==="server_logs_clean"){const freed=w.__logs.logBytes;w.__logs.logBytes=0;return {freedBytes:freed,remainingBytes:0,deletedFiles:freed>0?3:0,skippedFiles:0};}return w.__logs;}
if(cmd==="mysql_custom"||cmd==="mysql_custom_save"){const w=window as any;if(cmd==="mysql_custom_save")w.__my=args.text;const text:string=w.__my??"";const applied=text.split("\n").map((l:string)=>l.trim()).filter((l:string)=>l&&!l.startsWith("#")&&!/^(port|datadir|basedir|bind[-_]address)\b/i.test(l)).map((l:string)=>l+"\n").join("");return {text,applied};}
if(cmd==="realm_names"||cmd==="realm_rename"){const w=window as any;w.__rn=w.__rn??{};const defs:[number,string][]=[[1,"Conquest of Azeroth"],[2,"Wildcard"]];if(cmd==="realm_rename"){await new Promise(r=>setTimeout(r,300));const n=(args.name??"").trim();if(n.length>32||n.includes('"'))throw new Error("The realm name can have at most 32 characters.");if(n)w.__rn[args.realmId]=n;else delete w.__rn[args.realmId];}return defs.map(([id,d])=>({id,name:w.__rn[id]??d,defaultName:d,custom:id in w.__rn}));}
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_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_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==="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}; }
@@ -60,37 +70,28 @@ export {};
if(cmd==="list_presets"){const pr=args?.scope==="server"?serverPresets:botsPresets;return (pr.presets as any[]).map(p=>({id:p.id,title:p.title,description:p.description}));} if(cmd==="list_presets"){const pr=args?.scope==="server"?serverPresets:botsPresets;return (pr.presets as any[]).map(p=>({id:p.id,title:p.title,description:p.description}));}
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};} if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]}; if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
if(cmd==="top_up_startup_fleet") return 0;
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};} if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261028.83":"0.261026.81",to_version:"0.261028.83",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000}; if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261028.83":"0.261026.81",to_version:"0.261028.83",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261028.83"},migrations:null};} if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261028.83"},migrations:null};}
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_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==="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==="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_")){ if(cmd==="client_status") return {linked:((window as any).__client??"none")!=="none"};
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==="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_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_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;} 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;}
if(cmd==="realmlist_delete"){const rl=(window as any).__rl;rl.profiles=rl.profiles.filter((x: any)=>x.id!==args.profileId);return null;} if(cmd==="realmlist_delete"){const rl=(window as any).__rl;rl.profiles=rl.profiles.filter((x: any)=>x.id!==args.profileId);return null;}
if(cmd==="account_delete") return null; if(cmd==="account_delete") return null;
if(cmd==="modules_list") return [{id:"companions",name:"CoA Companions",description:{en:"Companion bots for groups, dungeons and your guild.",ru:"Боты-компаньоны для групп, подземелий и гильдии."},repo:"https://github.com/Corfirean/mod-coa-playerbots",installed:true,enabled:modState["companions"],switchable:true,status:"beta",icon:"bot",page:"bots"},{id:"content-scaling",name:"Content Scaling",description:{en:"Scales dungeons and raids to your group, with solo modes.",ru:"Подстраивает подземелья и рейды под вашу группу, есть соло-режимы."},repo:"https://github.com/Corfirean/mod-coa-content-scaling",installed:true,enabled:modState["content-scaling"],switchable:true,status:"early",icon:"scaling",page:null},{id:"tbc-content",name:"TBC Content",description:{en:"Outland dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Запределья, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content",installed:true,enabled:modState["tbc-content"],switchable:true,status:"early",icon:"tbc",page:null},{id:"wotlk-content",name:"WotLK Content",description:{en:"Northrend dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Нордскола, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content",installed:true,enabled:modState["wotlk-content"],switchable:true,status:"early",icon:"wotlk",page:null},{id:"ah-bot",name:"Auction House Bot",description:{en:"Fills the auction house with realistic, adjustable listings.",ru:"Наполняет аукцион реалистичными настраиваемыми лотами."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["ah-bot"] ?? false,switchable:true,status:"early",icon:"gavel",page:null,hidden:false},{id:"npc-enchanter",name:"NPC Enchanter",description:{en:"An NPC that enchants your gear for you.",ru:"НПС, который зачаровывает ваше снаряжение."},repo:"https://github.com/azerothcore/mod-npc-enchanter",installed:true,enabled:modState["npc-enchanter"],switchable:true,status:"early",icon:"sparkles",page:null,hidden:false},{id:"playerbots",name:"SQUID's Playerbots",description:{en:"An alternative bot system with random bots and full AI.",ru:"Альтернативная система ботов со случайными ботами и полным ИИ."},repo:"https://github.com/Zyth45/mod-playerbots",installed:true,enabled:modState["playerbots"] ?? false,switchable:true,status:"early",icon:"swords",page:"bots",hidden:false},{id:"client-compat",name:"Client compatibility",description:{en:"Client-server link and appearance unlocks.",ru:"Связь клиента с сервером и разблокировка внешних видов."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["client-compat"],switchable:false,status:"release",icon:"plug",page:null,hidden:true}, ...moduleCatalog.modules.filter(m => m.id === "time-is-time").map(m => ({...m, installed:true, enabled:modState[m.id] ?? true, switchable:true, page:null, hidden:false}))].map(m => ({...m, has_settings: !["tbc-content", "wotlk-content"].includes(m.id), compatibility: realm !== "coa" ? (["companions", "playerbots"].includes(m.id) ? "unsupported" : m.id === "client-compat" ? "compatible" : "experimental") : "compatible", switchable: realm !== "coa" && ["companions", "playerbots"].includes(m.id) ? false : m.switchable})); if(cmd==="modules_list") return [{id:"companions",name:"CoA Companions",description:{en:"Companion bots for groups, dungeons and your guild.",ru:"Боты-компаньоны для групп, подземелий и гильдии."},repo:"https://github.com/Corfirean/mod-coa-playerbots",installed:true,enabled:modState["companions"],switchable:true,status:"beta",icon:"bot",page:"bots"},{id:"content-scaling",name:"Content Scaling",description:{en:"Scales dungeons and raids to your group, with solo modes.",ru:"Подстраивает подземелья и рейды под вашу группу, есть соло-режимы."},repo:"https://github.com/Corfirean/mod-coa-content-scaling",installed:true,enabled:modState["content-scaling"],switchable:true,status:"early",icon:"scaling",page:null},{id:"tbc-content",name:"TBC Content",description:{en:"Outland dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Запределья, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-tbc-content",installed:true,enabled:modState["tbc-content"],switchable:true,status:"early",icon:"tbc",page:null},{id:"wotlk-content",name:"WotLK Content",description:{en:"Northrend dungeons and raids, scaled to your level range.",ru:"Подземелья и рейды Нордскола, подогнанные под ваши уровни."},repo:"https://github.com/Corfirean/mod-coa-content-scaling/tree/main/content-packs/mod-coa-wotlk-content",installed:true,enabled:modState["wotlk-content"],switchable:true,status:"early",icon:"wotlk",page:null},{id:"ah-bot",name:"Auction House Bot",description:{en:"Fills the auction house with realistic, adjustable listings.",ru:"Наполняет аукцион реалистичными настраиваемыми лотами."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["ah-bot"] ?? false,switchable:true,status:"early",icon:"gavel",page:null,hidden:false},{id:"npc-enchanter",name:"NPC Enchanter",description:{en:"An NPC that enchants your gear for you.",ru:"НПС, который зачаровывает ваше снаряжение."},repo:"https://github.com/azerothcore/mod-npc-enchanter",installed:true,enabled:modState["npc-enchanter"],switchable:true,status:"early",icon:"sparkles",page:null,hidden:false},{id:"playerbots",name:"SQUID's Playerbots",description:{en:"An alternative bot system with random bots and full AI.",ru:"Альтернативная система ботов со случайными ботами и полным ИИ."},repo:"https://github.com/Zyth45/mod-playerbots",installed:true,enabled:modState["playerbots"] ?? false,switchable:true,status:"early",icon:"swords",page:"bots",hidden:false},{id:"client-compat",name:"Client compatibility",description:{en:"Client-server link and appearance unlocks.",ru:"Связь клиента с сервером и разблокировка внешних видов."},repo:"https://github.com/Corfirean/azerothcore-wotlk-coa",installed:true,enabled:modState["client-compat"],switchable:false,status:"release",icon:"plug",page:null,hidden:true}, ...moduleCatalog.modules.filter(m => ["time-is-time", "custom-races", "subclass", "dev-menu"].includes(m.id)).map(m => ({...m, installed:true, enabled:modState[m.id] ?? true, switchable:true, page:null, hidden:(m as any).hidden ?? false}))].map(m => ({...m, has_settings: !["tbc-content", "wotlk-content"].includes(m.id), compatibility: realm !== "coa" ? (["companions", "playerbots"].includes(m.id) ? "unsupported" : m.id === "client-compat" ? "compatible" : "experimental") : "compatible", switchable: realm !== "coa" && ["companions", "playerbots"].includes(m.id) ? false : m.switchable}));
if(cmd==="module_set_enabled"){ if(args.enabled && ["companions","playerbots"].includes(args.module) && modState[args.module === "companions" ? "playerbots" : "companions"]) throw {human:{code:"bot_modules_conflict",title:"",message:"",actions:[]},technical:"Only one bot system may be enabled."}; modState[args.module]=args.enabled; return null; } if(cmd==="module_set_enabled"){ if(args.enabled && ["companions","playerbots"].includes(args.module) && modState[args.module === "companions" ? "playerbots" : "companions"]) throw {human:{code:"bot_modules_conflict",title:"",message:"",actions:[]},technical:"Only one bot system may be enabled."}; modState[args.module]=args.enabled; return null; }
if(cmd==="all_settings") return [{key:"Visibility.Distance.Continents",value:"100",default:"90",doc:"Description: Visibility distance on continents. Range: 45-250 Default: 90",changed:true},{key:"Death.SicknessLevel",value:"11",default:"11",doc:"Description: Character level up to which characters get resurrection sickness. Default: 11",changed:false},{key:"Rate.Drop.Item.Epic",value:"3",default:"1",doc:"Description: Drop rates for money and items based on quality. Default: 1",changed:true},{key:"Instance.ResetTimeHour",value:"4",default:"4",doc:"Description: Hour of the day when the global instance reset occurs. Range: 0-23 Default: 4 - (04:00 AM)",changed:false},{key:"PlayerLimit",value:"1000",default:"1000",doc:"Description: Maximum number of players in the world.",changed:false}]; if(cmd==="all_settings") return [{key:"Visibility.Distance.Continents",value:"100",default:"90",doc:"Description: Visibility distance on continents. Range: 45-250 Default: 90",changed:true},{key:"Death.SicknessLevel",value:"11",default:"11",doc:"Description: Character level up to which characters get resurrection sickness. Default: 11",changed:false},{key:"Rate.Drop.Item.Epic",value:"3",default:"1",doc:"Description: Drop rates for money and items based on quality. Default: 1",changed:true},{key:"Instance.ResetTimeHour",value:"4",default:"4",doc:"Description: Hour of the day when the global instance reset occurs. Range: 0-23 Default: 4 - (04:00 AM)",changed:false},{key:"PlayerLimit",value:"1000",default:"1000",doc:"Description: Maximum number of players in the world.",changed:false}];
if(cmd==="all_settings_save") return Object.keys(args&&args.changes||{}); if(cmd==="all_settings_save") return Object.keys(args&&args.changes||{});
if(cmd==="module_settings" && args.module==="client-compat") return [{key:"CoA.UnlockLocalAppearanceCatalog",value:"1",default:"1",doc:""},{key:"CoA.UnlockAllVanity",value:"1",default:"1",doc:""},{key:"CoA.AutoCollectAppearances",value:"0",default:"1",doc:""},{key:"CoA.LearnOwnedCompanions",value:"1",default:"1",doc:""},{key:"CoA.MaxRidingFromStart",value:"1",default:"1",doc:""}]; if(cmd==="module_settings" && args.module==="client-compat") return [{key:"CoA.UnlockLocalAppearanceCatalog",value:"1",default:"1",doc:""},{key:"CoA.UnlockAllVanity",value:"1",default:"1",doc:""},{key:"CoA.AutoCollectAppearances",value:"0",default:"1",doc:""},{key:"CoA.LearnOwnedCompanions",value:"1",default:"1",doc:""},{key:"CoA.MaxRidingFromStart",value:"1",default:"1",doc:""}];
if(cmd==="module_settings"){ if(cmd==="module_settings"){
const S:Record<string,{key:string;value:string;default:string;doc:string}[]>={ const S:Record<string,{key:string;value:string;default:string;doc:string}[]>={
"subclass": [["Subclass.Enable","1"],["Subclass.MinLevel","20"],["Subclass.ThinHuman.Enable","1"],["Subclass.TwoHeadedOgre.Enable","1"],["Subclass.TwoPlayers.Enable","1"],["Subclass.StandardClasses","0"],["Subclass.StandardMains","0"],["Subclass.HeroRaces.RequiredLevel","60"],["Subclass.BookDropChance","5"]].map(([key,value])=>({key,value,default:value,doc:"Option of mod-subclass."})),
"dev-menu": [{key:"DevMenu.Enable",value:"1",default:"1",doc:"Answer the addon's requests."},{key:"DevMenu.MinSecurity",value:"2",default:"2",doc:"Lowest account security level allowed to use the menu."},{key:"DevMenu.Items.FirstId",value:"0",default:"0",doc:"First id of the item ids the Create an item tab uses."}],
"time-is-time": [{key:"TimeIsTime.Enable",value:"1",default:"1",doc:""},{key:"TimeIsTime.Announce",value:"1",default:"1",doc:""},{key:"TimeIsTime.SpeedRate",value:"1.0",default:"1.0",doc:""},{key:"TimeIsTime.TimeStart",value:"0",default:"0",doc:""},{key:"TimeIsTime.HourOffset",value:"0.0",default:"0.0",doc:""}], "time-is-time": [{key:"TimeIsTime.Enable",value:"1",default:"1",doc:""},{key:"TimeIsTime.Announce",value:"1",default:"1",doc:""},{key:"TimeIsTime.SpeedRate",value:"1.0",default:"1.0",doc:""},{key:"TimeIsTime.TimeStart",value:"0",default:"0",doc:""},{key:"TimeIsTime.HourOffset",value:"0.0",default:"0.0",doc:""}],
"npc-enchanter":[{key:"Enchanter.Enable",value:"1",default:"1",doc:"Enable the module."},{key:"Enchanter.Announce",value:"0",default:"0",doc:"Announce the module when the player logs in."},{key:"Enchanter.CostCopper",value:"0",default:"0",doc:"What one enchantment costs, in copper (10000 = 1 gold). 0 = free."},{key:"Enchanter.MessageTimer",value:"60000",default:"60000",doc:"How often the NPC emotes, in milliseconds."}], "npc-enchanter":[{key:"Enchanter.Enable",value:"1",default:"1",doc:"Enable the module."},{key:"Enchanter.Announce",value:"0",default:"0",doc:"Announce the module when the player logs in."},{key:"Enchanter.CostCopper",value:"0",default:"0",doc:"What one enchantment costs, in copper (10000 = 1 gold). 0 = free."},{key:"Enchanter.MessageTimer",value:"60000",default:"60000",doc:"How often the NPC emotes, in milliseconds."}],
"playerbots":[{"key": "AiPlayerbot.RandomBotAutologin", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.MinRandomBots", "value": "500", "default": "500", "doc": ""}, {"key": "AiPlayerbot.MaxRandomBots", "value": "500", "default": "500", "doc": ""}, {"key": "AiPlayerbot.RandomBotAccountCount", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotMinLevel", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotMaxLevel", "value": "60", "default": "60", "doc": ""}, {"key": "AiPlayerbot.SyncLevelWithPlayers", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotInvitePlayer", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotJoinLfg", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotJoinBG", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotAutoJoinBG", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotTalk", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotEmote", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotSuggestDungeons", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaClassesOnly", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSmartHeal", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSmartTank", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSpecRotations", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaInterruptCoordination", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.MaxAddedBots", "value": "40", "default": "40", "doc": ""}, {"key": "AiPlayerbot.BotAutologin", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.DisabledWithoutRealPlayer", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.AddClassCommand", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.KeepAltsInGroup", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.CoaRecruitSameFaction", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaLfgBots", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotXPRate", "value": "1.0", "default": "1.0", "doc": ""}, {"key": "AiPlayerbot.FollowDistance", "value": "1.5", "default": "1.5", "doc": ""}, {"key": "AiPlayerbot.Enabled", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotAccountPrefix", "value": "\"rndbot\"", "default": "\"rndbot\"", "doc": ""}, {"key": "AiPlayerbot.RandomBotUpdateInterval", "value": "20", "default": "20", "doc": ""}], "playerbots":[{"key": "AiPlayerbot.RandomBotAutologin", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.MinRandomBots", "value": "500", "default": "500", "doc": ""}, {"key": "AiPlayerbot.MaxRandomBots", "value": "500", "default": "500", "doc": ""}, {"key": "AiPlayerbot.RandomBotAccountCount", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotMinLevel", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotMaxLevel", "value": "60", "default": "60", "doc": ""}, {"key": "AiPlayerbot.SyncLevelWithPlayers", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotInvitePlayer", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotJoinLfg", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotJoinBG", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotAutoJoinBG", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotTalk", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotEmote", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotSuggestDungeons", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaClassesOnly", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSmartHeal", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSmartTank", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaSpecRotations", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaInterruptCoordination", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.MaxAddedBots", "value": "40", "default": "40", "doc": ""}, {"key": "AiPlayerbot.BotAutologin", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.DisabledWithoutRealPlayer", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.AddClassCommand", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.KeepAltsInGroup", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.CoaRecruitSameFaction", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.CoaLfgBots", "value": "1", "default": "1", "doc": ""}, {"key": "AiPlayerbot.RandomBotXPRate", "value": "1.0", "default": "1.0", "doc": ""}, {"key": "AiPlayerbot.FollowDistance", "value": "1.5", "default": "1.5", "doc": ""}, {"key": "AiPlayerbot.Enabled", "value": "0", "default": "0", "doc": ""}, {"key": "AiPlayerbot.RandomBotAccountPrefix", "value": "\"rndbot\"", "default": "\"rndbot\"", "doc": ""}, {"key": "AiPlayerbot.RandomBotUpdateInterval", "value": "20", "default": "20", "doc": ""}],
+73 -45
View File
@@ -46,7 +46,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
"mod.switching": "Änderungen werden angewendet… Bitte warten.", "mod.switching": "Änderungen werden angewendet… Bitte warten.",
"portable.experimental": "Experimentelle Funktion: Portable Charaktere befinden sich noch in aktiver Entwicklung. Fehler können auftreten.", "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.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.title": "Einen Server hosten",
"welcome.host.text": "Einen neuen Server installieren oder einen vorhandenen verwalten.", "welcome.host.text": "Einen neuen Server installieren oder einen vorhandenen verwalten.",
"welcome.connect.title": "Mit anderem Server verbinden", "welcome.connect.title": "Mit anderem Server verbinden",
@@ -117,7 +117,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
"btn.stopSmall": "Stoppen", "btn.stopSmall": "Stoppen",
"btn.restart": "Neustart", "btn.restart": "Neustart",
"btn.startWithoutUpdate": "Ohne Update starten", "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.", "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.play": "SPIELEN",
"btn.startPlay": "STARTEN & SPIELEN", "btn.startPlay": "STARTEN & SPIELEN",
@@ -260,6 +259,7 @@ const de: Partial<Record<keyof typeof en, string>> = {
"client.updateAddon": "Begleiter-Addon aktualisieren", "client.updateAddon": "Begleiter-Addon aktualisieren",
"client.addonNote": "Begleiter-Addon installiert. Andere Addons wurden nicht angetastet.", "client.addonNote": "Begleiter-Addon installiert. Andere Addons wurden nicht angetastet.",
"client.changeFolder": "Ordner ändern …", "client.changeFolder": "Ordner ändern …",
"client.getFromSite": "Launcher holen…",
// Diagnostics // Diagnostics
"diag.title": "Diagnose", "diag.title": "Diagnose",
@@ -597,6 +597,8 @@ const de: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Wie viele sich anmelden", "comp.startCount": "Wie viele sich anmelden",
"comp.startSave": "Speichern", "comp.startSave": "Speichern",
"comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.", "comp.startSaved": "Gespeichert. Gilt ab dem nächsten Serverstart.",
"comp.startTopUp": "Gespeichert. {n} weitere Begleiter werden erstellt, damit {max} existieren; die übrigen gibt es schon.",
"comp.startTopUpConfirm": "{n} weitere Begleiter erstellen, damit {max} existieren? Vorhandene werden nicht erneut erstellt.",
"comp.startHint": "Bots, die sich nicht anmelden, bleiben gespeichert und können später online gebracht werden.", "comp.startHint": "Bots, die sich nicht anmelden, bleiben gespeichert und können später online gebracht werden.",
"comp.startInvalid": "Gib eine ganze Zahl von 0 bis 5000 ein.", "comp.startInvalid": "Gib eine ganze Zahl von 0 bis 5000 ein.",
@@ -645,51 +647,26 @@ const de: Partial<Record<keyof typeof en, string>> = {
// Game client download and update // Game client download and update
"btn.close": "Schließen", "btn.close": "Schließen",
"btn.setupClient": "Spielclient einrichten", "btn.setupClient": "Spielclient einrichten",
"btn.updateClient": "CLIENT AKTUALISIEREN",
"client.setup.title": "Spielclient einrichten", "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.have": "Ich habe bereits einen Client",
"client.setup.download": "Client herunterladen", "client.setup.getLauncher": "Launcher holen (coa-development.org)",
"client.setup.downloadHint": "Etwa 43 GB", "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.dl.pickParent": "Wähle, wohin der Spielclient soll", "client.setup.haveHint": "Wähle den Ordner, in den der Launcher das Spiel installiert hat, oder eine andere Kopie des Clients.",
"client.dl.confirmText": "Version {v}, {size}. Er wird in diesem Ordner gespeichert:", "client.setup.hdHint": "Standard- oder HD-Grafik wählst du im Launcher: Öffne dort die Einstellungen und schalte „HD graphics“ um. Der Manager kann das nicht ändern.",
"client.dl.free": "Freier Platz auf diesem Laufwerk: {free}.", "races.patch.active": "Client-Patch: Aktiv",
"client.dl.notEnough": "Nicht genug freier Platz: {need} nötig, {free} verfügbar. Wähle ein anderes Laufwerk.", "races.patch.disabled": "Client-Patch: Deaktiviert (.disabled)",
"client.dl.otherFolder": "Anderer Ordner …", "races.patch.notInstalled": "Client-Patch: Nicht installiert",
"client.dl.start": "Herunterladen", "races.patch.partial": "Client-Patch: {a}/{b} MPQ",
"races.patch.partialHint": "Dateien fehlen oder wurden geändert. Repariere den Client-Patch.",
"races.patch.install": "Client-Patch installieren",
"races.patch.repair": "Client-Patch reparieren",
"races.patch.uninstall": "Client-Patch entfernen",
"races.patch.willEnable": "Der Patch ist nach der Installation aktiv.",
"races.patch.willStayOff": "Der Patch bleibt nach der Installation deaktiviert: Das Servermodul ist aus oder fehlt.",
"client.dl.back": "Zurück", "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.done": "Der Spielclient ist bereit",
"client.dl.doneText": "Er ist mit diesem Server verknüpft. Du kannst auf PLAY drücken.", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "Passwort anzeigen", "pw.show": "Passwort anzeigen",
@@ -773,6 +750,53 @@ const de: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Diagnose sammeln und melden", "overview.reportBtn": "Diagnose sammeln und melden",
// Realmlist switcher and modules page // Realmlist switcher and modules page
"mysql.title": "MySQL-Einstellungen",
"mysql.hint": "Eigene MySQL-Optionen, eine Zeile name = wert. Sie werden bei jedem Start der Datenbank zu my.ini hinzugefügt und bleiben nach Updates erhalten. Port, Adressen und Datenpfade verwaltet der Manager; hier werden sie ignoriert.",
"mysql.save": "Speichern",
"mysql.saved": "Gespeichert; Server neu starten, um sie anzuwenden.",
"mysql.applied": "Angewandte Optionen: {count}",
"sched.title": "Geplanter Neustart",
"sched.enable": "Die Welt jeden Tag neu starten",
"sched.weeklyEnable": "Die Welt jede Woche neu starten",
"sched.day": "Tag",
"sched.days.monday": "Montag",
"sched.days.tuesday": "Dienstag",
"sched.days.wednesday": "Mittwoch",
"sched.days.thursday": "Donnerstag",
"sched.days.friday": "Freitag",
"sched.days.saturday": "Samstag",
"sched.days.sunday": "Sonntag",
"sched.time": "Uhrzeit",
"sched.warning": "Vorwarnung (Minuten)",
"sched.hint": "Die Welt startet zu dieser Uhrzeit dieses Computers neu, mit einem Countdown im Spielchat; die Datenbank läuft weiter, Spieler melden sich danach wieder an. Ein laufender Server übernimmt die neue Zeit innerhalb einer Minute.",
"sched.save": "Speichern",
"sched.saved": "Gespeichert.",
"sched.unsupported": "Dieser Server kann das noch nicht: Aktualisiere ihn auf einen Build mit dem neuen Launcher.",
"client.clearCache": "Spiel-Cache vor jedem Start leeren",
"client.clearCacheHint": "Das Spiel merkt sich Kreaturen, Gegenstände und Quests vom Server (Cache/WDB). Nach einem Server-Update zeigen sie sonst alte Namen und Werte; der Cache füllt sich in Sekunden wieder.",
"addons.withServer": "Kommt mit dem Server und wird mit ihm aktualisiert.",
"addons.withRaces": "Mit dem Client-Patch Custom Races V2 installiert und mit ihm geschaltet; der Manager installiert ihn nicht separat.",
"addons.withRacesMissing": "Kommt mit dem Client-Patch Custom Races V2 (Module, Custom Races); installiere den Patch, um ihn zu bekommen.",
"addons.title": "Addons",
"addons.hint": "Community-Addons für Conquest of Azeroth. Jedes kommt in einer geprüften Version vom GitHub seines Autors; jede Datei wird vor der Installation in Interface/AddOns geprüft. Schließe zuerst das Spiel.",
"addons.by": "von {author}",
"addons.installed": "Installiert",
"addons.update": "Update verfügbar",
"addons.needsSquid": "Für SQUID's Playerbots.",
"addons.foreign": "Ein Ordner {folders} ist schon da; er wird nach AddOns/.coa-addons-backup verschoben.",
"addons.doInstall": "Installieren",
"addons.doUpdate": "Aktualisieren",
"addons.doRemove": "Entfernen",
"races.offCharacters": "Eigene Völker sind aus: {players} Spielerfigur(en) und {bots} Bot(s) eigener Völker bleiben der Welt fern, bis sie wieder an sind (ein Client ohne Patch würde bei ihnen abstürzen).",
"races.purgeBots": "{n} Begleiter-Bot(s) eigener Völker löschen",
"races.purged": "{n} Bot(s) eigener Völker gelöscht.",
"realm.namesTitle": "Realmnamen",
"realm.namesHint": "So heißt der Realm in der Realmliste der Spieler. Ein laufender Server zeigt den Namen sofort, und er bleibt nach Updates erhalten.",
"realm.nameSave": "Speichern",
"realm.nameReset": "Standardname",
"realm.nameDefault": "Standard: {name}",
"realm.nameSaved": "Gespeichert.",
"realm.nameQuotes": "Anführungszeichen sind nicht erlaubt: Der Spielclient speichert den Namen in Anführungszeichen.",
"realm.profileLabel": "Realm", "realm.profileLabel": "Realm",
"realm.switching": "Realm wird gewechselt…", "realm.switching": "Realm wird gewechselt…",
"realm.rebornCreate": "Warcraft-Reborn-Realm erstellen", "realm.rebornCreate": "Warcraft-Reborn-Realm erstellen",
@@ -893,7 +917,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
"dash.openBrowser": "Im Browser öffnen", "dash.openBrowser": "Im Browser öffnen",
"dash.update": "Dashboard aktualisieren", "dash.update": "Dashboard aktualisieren",
"upd.startAfter": "Server nach dem Update starten (sonst bleibt ein angehaltener Server angehalten)", "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.folder": "Sicherungsordner",
"bk.folderDefault": "Standard", "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.", "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.",
@@ -906,8 +929,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
"remove.stopFirst": "Halte zuerst den Server an.", "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.", "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}", "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.address": "Netzwerkadresse",
"fr.lan.automatic": "Automatisch", "fr.lan.automatic": "Automatisch",
"fr.lan.default": "Standard", "fr.lan.default": "Standard",
@@ -1089,6 +1110,13 @@ const de: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Nur Fehler", "serverLogs.errors": "Nur Fehler",
"serverLogs.off": "Aus", "serverLogs.off": "Aus",
"serverLogs.saved": "Gespeichert. Zum Anwenden den Server neu starten.", "serverLogs.saved": "Gespeichert. Zum Anwenden den Server neu starten.",
"serverLogs.autoClean": "Serverlogs nach Größe automatisch bereinigen",
"serverLogs.maxSize": "Max. Größe",
"serverLogs.autoCleanHint": "Löscht alte Logdateien, wenn Core/Logs diese Größe überschreitet (geprüft beim Start der Welt und regelmäßig während des Betriebs).",
"serverLogs.currentSize": "Aktuelle Loggröße: {size}",
"serverLogs.cleanNow": "Logs bereinigen ({size})",
"serverLogs.cleaned": "{freed} an Logs bereinigt.",
"serverLogs.skippedInUse": "{remaining} werden vom laufenden Server verwendet und konnten nicht entfernt werden.",
"mod.requiresSquid": "Aktivieren Sie SQUID-Bots, um Dungeon Clear zu verwenden.", "mod.requiresSquid": "Aktivieren Sie SQUID-Bots, um Dungeon Clear zu verwenden.",
}; };
+74 -46
View File
@@ -43,7 +43,7 @@ const en = {
"races.existing": "Existing characters keep their race and data.", "races.existing": "Existing characters keep their race and data.",
"mod.switching": "Applying changes… Please wait.", "mod.switching": "Applying changes… Please wait.",
"remote.clientReady": "Your client is ready. Save the host’s address, then press Play.", "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.title": "Host a server",
"welcome.host.text": "Install a new server or manage one you already have.", "welcome.host.text": "Install a new server or manage one you already have.",
"welcome.connect.title": "Connect to another server", "welcome.connect.title": "Connect to another server",
@@ -57,6 +57,53 @@ const en = {
"remote.hostInstead": "Host my own server", "remote.hostInstead": "Host my own server",
"welcome.roleSubtitle": "How would you like to play?", "welcome.roleSubtitle": "How would you like to play?",
"mysql.title": "MySQL settings",
"mysql.hint": "Your own MySQL options, one name = value per line. They are added to my.ini at every start of the database and stay after updates. The port, addresses and data paths are managed by the Manager and ignored here.",
"mysql.save": "Save",
"mysql.saved": "Saved; restart the server to apply.",
"mysql.applied": "Options applied: {count}",
"sched.title": "Scheduled restart",
"sched.enable": "Restart the world every day",
"sched.weeklyEnable": "Restart the world every week",
"sched.day": "Day",
"sched.days.monday": "Monday",
"sched.days.tuesday": "Tuesday",
"sched.days.wednesday": "Wednesday",
"sched.days.thursday": "Thursday",
"sched.days.friday": "Friday",
"sched.days.saturday": "Saturday",
"sched.days.sunday": "Sunday",
"sched.time": "Time",
"sched.warning": "Warning (minutes)",
"sched.hint": "The world restarts at this time of this computer with a countdown in the game chat; the database keeps running and players log in again after it. A minute after saving, the running server follows the new time.",
"sched.save": "Save",
"sched.saved": "Saved.",
"sched.unsupported": "This server cannot do it yet: update the server to a build with the new launcher.",
"client.clearCache": "Clear the game cache before every Play",
"client.clearCacheHint": "The game remembers creatures, items and quests it got from a server (Cache/WDB). After a server update they can show old names and stats; the cache fills again within seconds.",
"addons.withServer": "Comes with the server and is updated with it.",
"addons.withRaces": "Installed with the Custom Races V2 client patch and switched with it; the Manager does not install it separately.",
"addons.withRacesMissing": "Comes with the Custom Races V2 client patch (Modules, Custom Races); install the patch to get it.",
"addons.title": "Addons",
"addons.hint": "Community addons for Conquest of Azeroth. Each comes from its author's GitHub at a checked version; every file is verified before it is installed into Interface/AddOns. Close the game first.",
"addons.by": "by {author}",
"addons.installed": "Installed",
"addons.update": "Update available",
"addons.needsSquid": "For SQUID's Playerbots.",
"addons.foreign": "A folder named {folders} is already there; it will be moved to AddOns/.coa-addons-backup.",
"addons.doInstall": "Install",
"addons.doUpdate": "Update",
"addons.doRemove": "Remove",
"races.offCharacters": "Custom races are off: {players} player character(s) and {bots} bot(s) of custom races stay out of the world until they are on again (a game client without the patch would crash on them).",
"races.purgeBots": "Delete the {n} companion bot(s) of custom races",
"races.purged": "Deleted {n} bot(s) of custom races.",
"realm.namesTitle": "Realm names",
"realm.namesHint": "The name players see in the realm list. A running server shows it at once, and it stays after updates.",
"realm.nameSave": "Save",
"realm.nameReset": "Default name",
"realm.nameDefault": "Default: {name}",
"realm.nameSaved": "Saved.",
"realm.nameQuotes": "Quotation marks are not allowed: the game client stores the name in quotes.",
"realm.profileLabel": "Realm", "realm.profileLabel": "Realm",
"realm.startupTitle": "Realm startup", "realm.startupTitle": "Realm startup",
"realm.secondWorld": "Second world", "realm.secondWorld": "Second world",
@@ -160,7 +207,6 @@ const en = {
"btn.stopSmall": "Stop", "btn.stopSmall": "Stop",
"btn.restart": "Restart", "btn.restart": "Restart",
"btn.startWithoutUpdate": "Start without updating", "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.", "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.play": "PLAY",
"btn.startPlay": "START & PLAY", "btn.startPlay": "START & PLAY",
@@ -320,6 +366,7 @@ const en = {
"client.updateAddon": "Update companion addon", "client.updateAddon": "Update companion addon",
"client.addonNote": "Companion addon installed. Other addons were not touched.", "client.addonNote": "Companion addon installed. Other addons were not touched.",
"client.changeFolder": "Change folder…", "client.changeFolder": "Change folder…",
"client.getFromSite": "Get the launcher…",
// Diagnostics // Diagnostics
"diag.title": "Diagnostics", "diag.title": "Diagnostics",
@@ -658,6 +705,8 @@ const en = {
"comp.startCount": "How many log in", "comp.startCount": "How many log in",
"comp.startSave": "Save", "comp.startSave": "Save",
"comp.startSaved": "Saved. It applies the next time the server starts.", "comp.startSaved": "Saved. It applies the next time the server starts.",
"comp.startTopUp": "Saved. Creating {n} more companions so that {max} exist; the others already exist.",
"comp.startTopUpConfirm": "Create {n} more companions so that {max} exist? Companions that already exist are not created again.",
"comp.startHint": "Bots that do not log in stay saved and can be brought online later.", "comp.startHint": "Bots that do not log in stay saved and can be brought online later.",
"comp.startInvalid": "Enter a whole number from 0 to 5000.", "comp.startInvalid": "Enter a whole number from 0 to 5000.",
@@ -703,54 +752,29 @@ const en = {
"overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.", "overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.",
"nav.updateDot": "Update available", "nav.updateDot": "Update available",
// Game client download and update // Game client: link a folder or get the community launcher
"btn.close": "Close", "btn.close": "Close",
"btn.setupClient": "Set up game client", "btn.setupClient": "Set up game client",
"btn.updateClient": "UPDATE CLIENT",
"client.setup.title": "Set up the game 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.have": "I already have a client",
"client.setup.download": "Download the client", "client.setup.getLauncher": "Get the launcher (coa-development.org)",
"client.setup.downloadHint": "About 43 GB", "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.dl.pickParent": "Choose where to put the game client", "client.setup.haveHint": "Pick the folder the launcher installed the game to, or any other copy of the client.",
"client.dl.confirmText": "Version {v}, {size}. It will be saved in this folder:", "client.setup.hdHint": "Standard or HD graphics is chosen in the launcher: open its Settings and switch \"HD graphics\". The Manager cannot change it.",
"client.dl.free": "Free space on that drive: {free}.", "races.patch.active": "Client Patch: Active",
"client.dl.notEnough": "Not enough free space: {need} needed, {free} available. Choose another drive.", "races.patch.disabled": "Client Patch: Disabled (.disabled)",
"client.dl.otherFolder": "Other folder…", "races.patch.notInstalled": "Client Patch: Not Installed",
"client.dl.start": "Download", "races.patch.partial": "Client Patch: {a}/{b} MPQ",
"races.patch.partialHint": "Files are missing or changed. Repair the client patch.",
"races.patch.install": "Install Client Patch",
"races.patch.repair": "Repair Client Patch",
"races.patch.uninstall": "Uninstall Client Patch",
"races.patch.willEnable": "The patch will be enabled after installation.",
"races.patch.willStayOff": "The patch will stay disabled after installation: the server module is off or missing.",
"client.dl.back": "Back", "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.done": "The game client is ready",
"client.dl.doneText": "It is linked to this server. You can press PLAY.", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "Show password", "pw.show": "Show password",
@@ -939,7 +963,6 @@ const en = {
"dash.openBrowser": "Open in the browser", "dash.openBrowser": "Open in the browser",
"dash.update": "Update the dashboard", "dash.update": "Update the dashboard",
"upd.startAfter": "Start the server after updating it (otherwise a stopped server stays stopped)", "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.folder": "Backup folder",
"bk.folderDefault": "default", "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.", "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.",
@@ -952,8 +975,6 @@ const en = {
"remove.stopFirst": "Stop the server first.", "remove.stopFirst": "Stop the server first.",
"remove.confirm": "Remove this server from the Manager?\n\n{path}\n\nNo files are deleted.", "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}", "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", "nav.characters": "Characters",
"q.characters": "Which of my characters can play where?", "q.characters": "Which of my characters can play where?",
"portable.experimental": "Experimental feature: portable characters are still in active development. Bugs may occur.", "portable.experimental": "Experimental feature: portable characters are still in active development. Bugs may occur.",
@@ -1299,6 +1320,13 @@ const en = {
"serverLogs.errors": "Errors only", "serverLogs.errors": "Errors only",
"serverLogs.off": "Off", "serverLogs.off": "Off",
"serverLogs.saved": "Saved. Restart the server to apply.", "serverLogs.saved": "Saved. Restart the server to apply.",
"serverLogs.autoClean": "Auto-clean server logs by size",
"serverLogs.maxSize": "Max size",
"serverLogs.autoCleanHint": "Clears old log files when Core/Logs exceeds this size (checked on world start and periodically while running).",
"serverLogs.currentSize": "Current log size: {size}",
"serverLogs.cleanNow": "Clean logs ({size})",
"serverLogs.cleaned": "Cleaned {freed} of logs.",
"serverLogs.skippedInUse": "{remaining} in use by the running server could not be removed.",
"mod.requiresSquid": "Enable SQUID bots to use Dungeon Clear.", "mod.requiresSquid": "Enable SQUID bots to use Dungeon Clear.",
} as const; } as const;
+73 -45
View File
@@ -46,7 +46,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
"mod.switching": "Aplicando cambios… Espera un momento.", "mod.switching": "Aplicando cambios… Espera un momento.",
"portable.experimental": "Función experimental: los personajes portátiles siguen en desarrollo activo. Pueden producirse errores.", "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.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.title": "Alojar un servidor",
"welcome.host.text": "Instalar un servidor nuevo o gestionar uno existente.", "welcome.host.text": "Instalar un servidor nuevo o gestionar uno existente.",
"welcome.connect.title": "Conectarse a otro servidor", "welcome.connect.title": "Conectarse a otro servidor",
@@ -117,7 +117,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
"btn.stopSmall": "Detener", "btn.stopSmall": "Detener",
"btn.restart": "Reiniciar", "btn.restart": "Reiniciar",
"btn.startWithoutUpdate": "Iniciar sin actualizar", "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.", "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.play": "JUGAR",
"btn.startPlay": "INICIAR Y JUGAR", "btn.startPlay": "INICIAR Y JUGAR",
@@ -260,6 +259,7 @@ const es: Partial<Record<keyof typeof en, string>> = {
"client.updateAddon": "Actualizar addon de compañeros", "client.updateAddon": "Actualizar addon de compañeros",
"client.addonNote": "Addon de compañeros instalado. Los demás addons no se tocaron.", "client.addonNote": "Addon de compañeros instalado. Los demás addons no se tocaron.",
"client.changeFolder": "Cambiar carpeta…", "client.changeFolder": "Cambiar carpeta…",
"client.getFromSite": "Obtener el launcher…",
// Diagnostics // Diagnostics
"diag.title": "Diagnóstico", "diag.title": "Diagnóstico",
@@ -597,6 +597,8 @@ const es: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Cuántos inician sesión", "comp.startCount": "Cuántos inician sesión",
"comp.startSave": "Guardar", "comp.startSave": "Guardar",
"comp.startSaved": "Guardado. Se aplica la próxima vez que se inicie el servidor.", "comp.startSaved": "Guardado. Se aplica la próxima vez que se inicie el servidor.",
"comp.startTopUp": "Guardado. Se crean {n} compañeros más para que existan {max}; los demás ya existen.",
"comp.startTopUpConfirm": "¿Crear {n} compañeros más para que existan {max}? Los que ya existen no se crean de nuevo.",
"comp.startHint": "Los bots que no inician sesión quedan guardados y se pueden conectar más tarde.", "comp.startHint": "Los bots que no inician sesión quedan guardados y se pueden conectar más tarde.",
"comp.startInvalid": "Introduce un número entero de 0 a 5000.", "comp.startInvalid": "Introduce un número entero de 0 a 5000.",
@@ -645,51 +647,26 @@ const es: Partial<Record<keyof typeof en, string>> = {
// Game client download and update // Game client download and update
"btn.close": "Cerrar", "btn.close": "Cerrar",
"btn.setupClient": "Configurar el cliente del juego", "btn.setupClient": "Configurar el cliente del juego",
"btn.updateClient": "ACTUALIZAR CLIENTE",
"client.setup.title": "Configurar el cliente del juego", "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.have": "Ya tengo un cliente",
"client.setup.download": "Descargar el cliente", "client.setup.getLauncher": "Obtener el launcher (coa-development.org)",
"client.setup.downloadHint": "Unos 43 GB", "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.dl.pickParent": "Elige dónde guardar el cliente del juego", "client.setup.haveHint": "Elige la carpeta donde el launcher instaló el juego, o cualquier otra copia del cliente.",
"client.dl.confirmText": "Versión {v}, {size}. Se guardará en esta carpeta:", "client.setup.hdHint": "Los gráficos estándar o HD se eligen en el launcher: abre sus Ajustes y cambia «HD graphics». El Manager no puede cambiarlo.",
"client.dl.free": "Espacio libre en esa unidad: {free}.", "races.patch.active": "Parche del cliente: Activo",
"client.dl.notEnough": "No hay espacio suficiente: se necesitan {need} y hay {free}. Elige otra unidad.", "races.patch.disabled": "Parche del cliente: Desactivado (.disabled)",
"client.dl.otherFolder": "Otra carpeta…", "races.patch.notInstalled": "Parche del cliente: No instalado",
"client.dl.start": "Descargar", "races.patch.partial": "Parche del cliente: {a}/{b} MPQ",
"races.patch.partialHint": "Faltan archivos o han cambiado. Repara el parche del cliente.",
"races.patch.install": "Instalar parche del cliente",
"races.patch.repair": "Reparar parche del cliente",
"races.patch.uninstall": "Desinstalar parche del cliente",
"races.patch.willEnable": "El parche estará activo después de la instalación.",
"races.patch.willStayOff": "El parche seguirá desactivado después de la instalación: el módulo del servidor está apagado o falta.",
"client.dl.back": "Atrás", "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.done": "El cliente del juego está listo",
"client.dl.doneText": "Está vinculado a este servidor. Puedes pulsar PLAY.", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "Mostrar contraseña", "pw.show": "Mostrar contraseña",
@@ -773,6 +750,53 @@ const es: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Reunir el diagnóstico y avisar", "overview.reportBtn": "Reunir el diagnóstico y avisar",
// Realmlist switcher and modules page // Realmlist switcher and modules page
"mysql.title": "Ajustes de MySQL",
"mysql.hint": "Tus propias opciones de MySQL, una línea nombre = valor. Se añaden a my.ini en cada inicio de la base de datos y se mantienen tras las actualizaciones. El puerto, las direcciones y las rutas de datos los gestiona el Manager y aquí se ignoran.",
"mysql.save": "Guardar",
"mysql.saved": "Guardado; reinicia el servidor para aplicarlo.",
"mysql.applied": "Opciones aplicadas: {count}",
"sched.title": "Reinicio programado",
"sched.enable": "Reiniciar el mundo cada día",
"sched.weeklyEnable": "Reiniciar el mundo cada semana",
"sched.day": "Día",
"sched.days.monday": "Lunes",
"sched.days.tuesday": "Martes",
"sched.days.wednesday": "Miércoles",
"sched.days.thursday": "Jueves",
"sched.days.friday": "Viernes",
"sched.days.saturday": "Sábado",
"sched.days.sunday": "Domingo",
"sched.time": "Hora",
"sched.warning": "Aviso (minutos)",
"sched.hint": "El mundo se reinicia a esta hora de este ordenador con una cuenta atrás en el chat del juego; la base de datos sigue en marcha y los jugadores vuelven a entrar después. Un servidor en marcha sigue la nueva hora en menos de un minuto.",
"sched.save": "Guardar",
"sched.saved": "Guardado.",
"sched.unsupported": "Este servidor aún no puede hacerlo: actualízalo a una versión con el nuevo lanzador.",
"client.clearCache": "Vaciar la caché del juego antes de cada inicio",
"client.clearCacheHint": "El juego recuerda criaturas, objetos y misiones recibidos del servidor (Cache/WDB). Tras actualizar el servidor pueden mostrar nombres y estadísticas antiguos; la caché se llena de nuevo en segundos.",
"addons.withServer": "Viene con el servidor y se actualiza con él.",
"addons.withRaces": "Instalado con el parche de cliente Custom Races V2 y activado con él; el Manager no lo instala por separado.",
"addons.withRacesMissing": "Viene con el parche de cliente Custom Races V2 (Módulos, Custom Races); instala el parche para tenerlo.",
"addons.title": "Addons",
"addons.hint": "Addons de la comunidad para Conquest of Azeroth. Cada uno viene del GitHub de su autor en una versión comprobada; cada archivo se verifica antes de instalarlo en Interface/AddOns. Cierra antes el juego.",
"addons.by": "de {author}",
"addons.installed": "Instalado",
"addons.update": "Actualización disponible",
"addons.needsSquid": "Para SQUID's Playerbots.",
"addons.foreign": "Ya hay una carpeta {folders}; se moverá a AddOns/.coa-addons-backup.",
"addons.doInstall": "Instalar",
"addons.doUpdate": "Actualizar",
"addons.doRemove": "Quitar",
"races.offCharacters": "Las razas personalizadas están desactivadas: {players} personaje(s) de jugadores y {bots} bot(s) de esas razas quedan fuera del mundo hasta reactivarlas (un cliente sin el parche se cerraría al verlos).",
"races.purgeBots": "Borrar los {n} bot(s) acompañantes de razas personalizadas",
"races.purged": "Borrados {n} bot(s) de razas personalizadas.",
"realm.namesTitle": "Nombres de los reinos",
"realm.namesHint": "El nombre que ven los jugadores en la lista de reinos. Un servidor en marcha lo muestra al instante y se mantiene tras las actualizaciones.",
"realm.nameSave": "Guardar",
"realm.nameReset": "Nombre predeterminado",
"realm.nameDefault": "Predeterminado: {name}",
"realm.nameSaved": "Guardado.",
"realm.nameQuotes": "No se permiten comillas: el cliente del juego guarda el nombre entre comillas.",
"realm.profileLabel": "Reino", "realm.profileLabel": "Reino",
"realm.switching": "Cambiando de reino…", "realm.switching": "Cambiando de reino…",
"realm.rebornCreate": "Crear reino Warcraft Reborn", "realm.rebornCreate": "Crear reino Warcraft Reborn",
@@ -893,7 +917,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
"dash.openBrowser": "Abrir en el navegador", "dash.openBrowser": "Abrir en el navegador",
"dash.update": "Actualizar el panel", "dash.update": "Actualizar el panel",
"upd.startAfter": "Iniciar el servidor tras actualizarlo (si no, un servidor detenido sigue detenido)", "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.folder": "Carpeta de copias de seguridad",
"bk.folderDefault": "predeterminada", "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.", "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.",
@@ -906,8 +929,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
"remove.stopFirst": "Detén primero el servidor.", "remove.stopFirst": "Detén primero el servidor.",
"remove.confirm": "¿Quitar este servidor del Manager?\n\n{path}\n\nNo se borra ningún archivo.", "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}", "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.address": "Dirección de red",
"fr.lan.automatic": "Automática", "fr.lan.automatic": "Automática",
"fr.lan.default": "Predeterminada", "fr.lan.default": "Predeterminada",
@@ -1089,6 +1110,13 @@ const es: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Solo errores", "serverLogs.errors": "Solo errores",
"serverLogs.off": "Desactivados", "serverLogs.off": "Desactivados",
"serverLogs.saved": "Guardado. Reinicia el servidor para aplicar los cambios.", "serverLogs.saved": "Guardado. Reinicia el servidor para aplicar los cambios.",
"serverLogs.autoClean": "Limpiar automáticamente los registros del servidor por tamaño",
"serverLogs.maxSize": "Tamaño máx.",
"serverLogs.autoCleanHint": "Borra los archivos de registro antiguos cuando Core/Logs supera este tamaño (se comprueba al iniciar el mundo y periódicamente mientras funciona).",
"serverLogs.currentSize": "Tamaño actual de los registros: {size}",
"serverLogs.cleanNow": "Limpiar registros ({size})",
"serverLogs.cleaned": "Se limpiaron {freed} de registros.",
"serverLogs.skippedInUse": "{remaining} están en uso por el servidor en marcha y no se pudieron eliminar.",
"mod.requiresSquid": "Activa los bots SQUID para usar Dungeon Clear.", "mod.requiresSquid": "Activa los bots SQUID para usar Dungeon Clear.",
}; };
+73 -45
View File
@@ -46,7 +46,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"mod.switching": "Application des modifications… Veuillez patienter.", "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.", "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.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.title": "Héberger un serveur",
"welcome.host.text": "Installer un serveur ou gérer un serveur existant.", "welcome.host.text": "Installer un serveur ou gérer un serveur existant.",
"welcome.connect.title": "Rejoindre un autre serveur", "welcome.connect.title": "Rejoindre un autre serveur",
@@ -117,7 +117,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"btn.stopSmall": "Arrêter", "btn.stopSmall": "Arrêter",
"btn.restart": "Redémarrer", "btn.restart": "Redémarrer",
"btn.startWithoutUpdate": "Démarrer sans mise à jour", "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.", "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.play": "JOUER",
"btn.startPlay": "DÉMARRER ET JOUER", "btn.startPlay": "DÉMARRER ET JOUER",
@@ -260,6 +259,7 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"client.updateAddon": "Mettre à jour l’addon des compagnons", "client.updateAddon": "Mettre à jour l’addon des compagnons",
"client.addonNote": "Addon des compagnons installé. Les autres addons n’ont pas été touchés.", "client.addonNote": "Addon des compagnons installé. Les autres addons n’ont pas été touchés.",
"client.changeFolder": "Changer de dossier…", "client.changeFolder": "Changer de dossier…",
"client.getFromSite": "Obtenir le lanceur…",
// Diagnostics // Diagnostics
"diag.title": "Diagnostic", "diag.title": "Diagnostic",
@@ -597,6 +597,8 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Combien se connectent", "comp.startCount": "Combien se connectent",
"comp.startSave": "Enregistrer", "comp.startSave": "Enregistrer",
"comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.", "comp.startSaved": "Enregistré. S’applique au prochain démarrage du serveur.",
"comp.startTopUp": "Enregistré. {n} compagnons de plus sont créés pour qu’il y en ait {max} ; les autres existent déjà.",
"comp.startTopUpConfirm": "Créer {n} compagnons de plus pour qu’il y en ait {max} ? Ceux qui existent déjà ne sont pas recréés.",
"comp.startHint": "Les bots qui ne se connectent pas restent enregistrés et peuvent être mis en ligne plus tard.", "comp.startHint": "Les bots qui ne se connectent pas restent enregistrés et peuvent être mis en ligne plus tard.",
"comp.startInvalid": "Saisissez un nombre entier de 0 à 5000.", "comp.startInvalid": "Saisissez un nombre entier de 0 à 5000.",
@@ -645,51 +647,26 @@ const fr: Partial<Record<keyof typeof en, string>> = {
// Game client download and update // Game client download and update
"btn.close": "Fermer", "btn.close": "Fermer",
"btn.setupClient": "Configurer le client du jeu", "btn.setupClient": "Configurer le client du jeu",
"btn.updateClient": "METTRE À JOUR LE CLIENT",
"client.setup.title": "Configurer le client du jeu", "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.have": "J’ai déjà un client",
"client.setup.download": "Télécharger le client", "client.setup.getLauncher": "Obtenir le lanceur (coa-development.org)",
"client.setup.downloadHint": "Environ 43 Go", "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.dl.pickParent": "Choisissez où placer le client du jeu", "client.setup.haveHint": "Choisissez le dossier où le lanceur a installé le jeu, ou toute autre copie du client.",
"client.dl.confirmText": "Version {v}, {size}. Il sera enregistré dans ce dossier :", "client.setup.hdHint": "Les graphismes standard ou HD se choisissent dans le lanceur : ouvrez ses Paramètres et basculez « HD graphics ». Le Manager ne peut pas le modifier.",
"client.dl.free": "Espace libre sur ce disque : {free}.", "races.patch.active": "Patch client : actif",
"client.dl.notEnough": "Espace libre insuffisant : {need} nécessaires, {free} disponibles. Choisissez un autre disque.", "races.patch.disabled": "Patch client : désactivé (.disabled)",
"client.dl.otherFolder": "Autre dossier…", "races.patch.notInstalled": "Patch client : non installé",
"client.dl.start": "Télécharger", "races.patch.partial": "Patch client : {a}/{b} MPQ",
"races.patch.partialHint": "Des fichiers manquent ou ont changé. Réparez le patch client.",
"races.patch.install": "Installer le patch client",
"races.patch.repair": "Réparer le patch client",
"races.patch.uninstall": "Désinstaller le patch client",
"races.patch.willEnable": "Le patch sera activé après l'installation.",
"races.patch.willStayOff": "Le patch restera désactivé après l'installation : le module du serveur est désactivé ou absent.",
"client.dl.back": "Retour", "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.done": "Le client du jeu est prêt",
"client.dl.doneText": "Il est lié à ce serveur. Vous pouvez appuyer sur PLAY.", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "Afficher le mot de passe", "pw.show": "Afficher le mot de passe",
@@ -773,6 +750,53 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"overview.reportBtn": "Rassembler le diagnostic et signaler", "overview.reportBtn": "Rassembler le diagnostic et signaler",
// Realmlist switcher and modules page // Realmlist switcher and modules page
"mysql.title": "Paramètres MySQL",
"mysql.hint": "Vos propres options MySQL, une ligne nom = valeur. Elles sont ajoutées à my.ini à chaque démarrage de la base et restent après les mises à jour. Le port, les adresses et les chemins de données sont gérés par le Manager et ignorés ici.",
"mysql.save": "Enregistrer",
"mysql.saved": "Enregistré ; redémarrez le serveur pour appliquer.",
"mysql.applied": "Options appliquées : {count}",
"sched.title": "Redémarrage planifié",
"sched.enable": "Redémarrer le monde chaque jour",
"sched.weeklyEnable": "Redémarrer le monde chaque semaine",
"sched.day": "Jour",
"sched.days.monday": "Lundi",
"sched.days.tuesday": "Mardi",
"sched.days.wednesday": "Mercredi",
"sched.days.thursday": "Jeudi",
"sched.days.friday": "Vendredi",
"sched.days.saturday": "Samedi",
"sched.days.sunday": "Dimanche",
"sched.time": "Heure",
"sched.warning": "Avertissement (minutes)",
"sched.hint": "Le monde redémarre à cette heure de cet ordinateur avec un compte à rebours dans le chat du jeu ; la base de données continue de tourner et les joueurs se reconnectent ensuite. Un serveur en marche suit la nouvelle heure en moins d'une minute.",
"sched.save": "Enregistrer",
"sched.saved": "Enregistré.",
"sched.unsupported": "Ce serveur ne le permet pas encore : mettez-le à jour vers une version avec le nouveau lanceur.",
"client.clearCache": "Vider le cache du jeu avant chaque lancement",
"client.clearCacheHint": "Le jeu garde les créatures, objets et quêtes reçus du serveur (Cache/WDB). Après une mise à jour du serveur, ils peuvent montrer d'anciens noms et statistiques ; le cache se remplit en quelques secondes.",
"addons.withServer": "Fourni avec le serveur et mis à jour avec lui.",
"addons.withRaces": "Installé avec le patch client Custom Races V2 et activé avec lui ; le Manager ne l'installe pas séparément.",
"addons.withRacesMissing": "Fourni avec le patch client Custom Races V2 (Modules, Custom Races) ; installez le patch pour l'obtenir.",
"addons.title": "Addons",
"addons.hint": "Addons de la communauté pour Conquest of Azeroth. Chacun vient du GitHub de son auteur dans une version vérifiée ; chaque fichier est contrôlé avant l'installation dans Interface/AddOns. Fermez d'abord le jeu.",
"addons.by": "par {author}",
"addons.installed": "Installé",
"addons.update": "Mise à jour disponible",
"addons.needsSquid": "Pour SQUID's Playerbots.",
"addons.foreign": "Un dossier {folders} existe déjà ; il sera déplacé vers AddOns/.coa-addons-backup.",
"addons.doInstall": "Installer",
"addons.doUpdate": "Mettre à jour",
"addons.doRemove": "Supprimer",
"races.offCharacters": "Les races personnalisées sont désactivées : {players} personnage(s) de joueurs et {bots} bot(s) de ces races restent hors du monde jusqu'à leur réactivation (un client sans le patch planterait en les voyant).",
"races.purgeBots": "Supprimer les {n} bot(s) compagnons de races personnalisées",
"races.purged": "{n} bot(s) de races personnalisées supprimé(s).",
"realm.namesTitle": "Noms des royaumes",
"realm.namesHint": "Le nom que les joueurs voient dans la liste des royaumes. Un serveur en marche l'affiche aussitôt, et il reste après les mises à jour.",
"realm.nameSave": "Enregistrer",
"realm.nameReset": "Nom par défaut",
"realm.nameDefault": "Par défaut : {name}",
"realm.nameSaved": "Enregistré.",
"realm.nameQuotes": "Les guillemets ne sont pas autorisés : le client du jeu enregistre le nom entre guillemets.",
"realm.profileLabel": "Royaume", "realm.profileLabel": "Royaume",
"realm.switching": "Changement de royaume…", "realm.switching": "Changement de royaume…",
"realm.rebornCreate": "Créer le royaume Warcraft Reborn", "realm.rebornCreate": "Créer le royaume Warcraft Reborn",
@@ -893,7 +917,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"dash.openBrowser": "Ouvrir dans le navigateur", "dash.openBrowser": "Ouvrir dans le navigateur",
"dash.update": "Mettre à jour le tableau de bord", "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é)", "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.folder": "Dossier des sauvegardes",
"bk.folderDefault": "par défaut", "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.", "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.",
@@ -906,8 +929,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"remove.stopFirst": "Arrêtez d’abord le serveur.", "remove.stopFirst": "Arrêtez d’abord le serveur.",
"remove.confirm": "Retirer ce serveur du Manager ?\n\n{path}\n\nAucun fichier n’est supprimé.", "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}", "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.address": "Adresse réseau",
"fr.lan.automatic": "Automatique", "fr.lan.automatic": "Automatique",
"fr.lan.default": "Par défaut", "fr.lan.default": "Par défaut",
@@ -1089,6 +1110,13 @@ const fr: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Erreurs uniquement", "serverLogs.errors": "Erreurs uniquement",
"serverLogs.off": "Désactivés", "serverLogs.off": "Désactivés",
"serverLogs.saved": "Enregistré. Redémarrez le serveur pour appliquer.", "serverLogs.saved": "Enregistré. Redémarrez le serveur pour appliquer.",
"serverLogs.autoClean": "Nettoyer automatiquement les journaux du serveur selon leur taille",
"serverLogs.maxSize": "Taille max.",
"serverLogs.autoCleanHint": "Supprime les anciens fichiers journaux quand Core/Logs dépasse cette taille (vérifié au démarrage du monde et périodiquement pendant son fonctionnement).",
"serverLogs.currentSize": "Taille actuelle des journaux : {size}",
"serverLogs.cleanNow": "Nettoyer les journaux ({size})",
"serverLogs.cleaned": "{freed} de journaux nettoyés.",
"serverLogs.skippedInUse": "{remaining} sont utilisés par le serveur en cours et n’ont pas pu être supprimés.",
"mod.requiresSquid": "Activez les bots SQUID pour utiliser Dungeon Clear.", "mod.requiresSquid": "Activez les bots SQUID pour utiliser Dungeon Clear.",
}; };
+73 -45
View File
@@ -46,7 +46,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"mod.switching": "Применяем изменения… Подождите.", "mod.switching": "Применяем изменения… Подождите.",
"portable.experimental": "Экспериментальная функция: портативные персонажи ещё в активной разработке. Возможны ошибки.", "portable.experimental": "Экспериментальная функция: портативные персонажи ещё в активной разработке. Возможны ошибки.",
"remote.clientReady": "Клиент готов. Сохраните адрес хоста и нажмите «Играть».", "remote.clientReady": "Клиент готов. Сохраните адрес хоста и нажмите «Играть».",
"remote.clientIntro": "Выберите существующий клиент игры или скачайте его здесь. Локальный сервер не требуется.", "remote.clientIntro": "Выберите готовый клиент игры или получите его через лаунчер сообщества. Локальный сервер не нужен.",
"welcome.host.title": "Хочу быть хостом", "welcome.host.title": "Хочу быть хостом",
"welcome.host.text": "Установить новый сервер или управлять существующим.", "welcome.host.text": "Установить новый сервер или управлять существующим.",
"welcome.connect.title": "Подключиться к другому серверу", "welcome.connect.title": "Подключиться к другому серверу",
@@ -60,6 +60,53 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"remote.hostInstead": "Создать свой сервер", "remote.hostInstead": "Создать свой сервер",
"welcome.roleSubtitle": "Как вы хотите играть?", "welcome.roleSubtitle": "Как вы хотите играть?",
"mysql.title": "Настройки MySQL",
"mysql.hint": "Свои параметры MySQL, по одному «имя = значение» в строке. Они добавляются в my.ini при каждом запуске базы и сохраняются после обновлений. Порт, адреса и пути к данным задаёт Manager, здесь они игнорируются.",
"mysql.save": "Сохранить",
"mysql.saved": "Сохранено; перезапустите сервер, чтобы применить.",
"mysql.applied": "Применяется параметров: {count}",
"sched.title": "Перезапуск по расписанию",
"sched.enable": "Перезапускать мир каждый день",
"sched.weeklyEnable": "Перезапускать мир каждую неделю",
"sched.day": "День",
"sched.days.monday": "Понедельник",
"sched.days.tuesday": "Вторник",
"sched.days.wednesday": "Среда",
"sched.days.thursday": "Четверг",
"sched.days.friday": "Пятница",
"sched.days.saturday": "Суббота",
"sched.days.sunday": "Воскресенье",
"sched.time": "Время",
"sched.warning": "Предупреждение (минуты)",
"sched.hint": "Мир перезапускается в это время этого компьютера, с обратным отсчётом в игровом чате; база данных продолжает работать, игроки заходят снова после перезапуска. Работающий сервер подхватывает новое время в течение минуты.",
"sched.save": "Сохранить",
"sched.saved": "Сохранено.",
"sched.unsupported": "Этот сервер пока так не умеет: обновите его до сборки с новым лаунчером.",
"client.clearCache": "Очищать кэш игры перед каждым запуском",
"client.clearCacheHint": "Игра запоминает существ, предметы и задания, полученные от сервера (Cache/WDB). После обновления сервера там остаются старые названия и характеристики; кэш снова заполняется за секунды.",
"addons.withServer": "Поставляется вместе с сервером и обновляется вместе с ним.",
"addons.withRaces": "Установлен вместе с клиентским патчем Custom Races V2 и включается вместе с ним; отдельно Manager его не ставит.",
"addons.withRacesMissing": "Поставляется с клиентским патчем Custom Races V2 (Модули → Custom Races); установите патч, чтобы он появился.",
"addons.title": "Аддоны",
"addons.hint": "Аддоны сообщества для Conquest of Azeroth. Каждый берётся с GitHub автора в проверенной версии; перед установкой в Interface/AddOns проверяется каждый файл. Сначала закройте игру.",
"addons.by": "автор: {author}",
"addons.installed": "Установлен",
"addons.update": "Есть обновление",
"addons.needsSquid": "Для SQUID's Playerbots.",
"addons.foreign": "Папка {folders} уже есть; она будет перенесена в AddOns/.coa-addons-backup.",
"addons.doInstall": "Установить",
"addons.doUpdate": "Обновить",
"addons.doRemove": "Удалить",
"races.offCharacters": "Кастомные расы выключены: {players} персонаж(ей) игроков и {bots} бот(ов) кастомных рас не входят в мир, пока расы снова не включены (клиент без патча падал бы при виде их).",
"races.purgeBots": "Удалить ботов-компаньонов кастомных рас: {n}",
"races.purged": "Удалено ботов кастомных рас: {n}.",
"realm.namesTitle": "Названия реалмов",
"realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.",
"realm.nameSave": "Сохранить",
"realm.nameReset": "Стандартное название",
"realm.nameDefault": "По умолчанию: {name}",
"realm.nameSaved": "Сохранено.",
"realm.nameQuotes": "Кавычки нельзя: клиент игры хранит название в кавычках.",
"realm.profileLabel": "Реалм", "realm.profileLabel": "Реалм",
"realm.startupTitle": "Запуск реалмов", "realm.startupTitle": "Запуск реалмов",
"realm.secondWorld": "Второй мир", "realm.secondWorld": "Второй мир",
@@ -160,7 +207,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"btn.stopSmall": "Остановить", "btn.stopSmall": "Остановить",
"btn.restart": "Перезапустить", "btn.restart": "Перезапустить",
"btn.startWithoutUpdate": "Запустить без обновления", "btn.startWithoutUpdate": "Запустить без обновления",
"btn.playWithoutUpdate": "Играть без обновления",
"import.squidRepackWarning": "Этот репак SquidBots проверяет хеш worldserver. Замена файла может нарушить работу Start_All_Bots и coa_update. Перед заменой менеджер запросит ваше решение.", "import.squidRepackWarning": "Этот репак SquidBots проверяет хеш worldserver. Замена файла может нарушить работу Start_All_Bots и coa_update. Перед заменой менеджер запросит ваше решение.",
"btn.play": "ИГРАТЬ", "btn.play": "ИГРАТЬ",
"btn.startPlay": "ЗАПУСТИТЬ И ИГРАТЬ", "btn.startPlay": "ЗАПУСТИТЬ И ИГРАТЬ",
@@ -303,6 +349,7 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"client.updateAddon": "Обновить аддон компаньонов", "client.updateAddon": "Обновить аддон компаньонов",
"client.addonNote": "Аддон компаньонов установлен. Другие аддоны не затронуты.", "client.addonNote": "Аддон компаньонов установлен. Другие аддоны не затронуты.",
"client.changeFolder": "Сменить папку…", "client.changeFolder": "Сменить папку…",
"client.getFromSite": "Скачать лаунчер…",
// Diagnostics // Diagnostics
"diag.title": "Диагностика", "diag.title": "Диагностика",
@@ -641,6 +688,8 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"comp.startCount": "Сколько входит", "comp.startCount": "Сколько входит",
"comp.startSave": "Сохранить", "comp.startSave": "Сохранить",
"comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.", "comp.startSaved": "Сохранено. Вступит в силу при следующем запуске сервера.",
"comp.startTopUp": "Сохранено. Создаётся ещё {n} компаньонов, чтобы их стало {max}; остальные уже есть.",
"comp.startTopUpConfirm": "Создать ещё {n} компаньонов, чтобы их стало {max}? Уже существующие заново не создаются.",
"comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.", "comp.startHint": "Боты, которые не входят, остаются сохранёнными, их можно вывести в сеть позже.",
"comp.startInvalid": "Введите целое число от 0 до 5000.", "comp.startInvalid": "Введите целое число от 0 до 5000.",
@@ -689,51 +738,26 @@ const ru: Partial<Record<keyof typeof en, string>> = {
// Game client download and update // Game client download and update
"btn.close": "Закрыть", "btn.close": "Закрыть",
"btn.setupClient": "Настроить клиент игры", "btn.setupClient": "Настроить клиент игры",
"btn.updateClient": "ОБНОВИТЬ КЛИЕНТ",
"client.setup.title": "Настройка клиента игры", "client.setup.title": "Настройка клиента игры",
"client.setup.intro": "Чтобы играть, нужен клиент игры. Выберите уже имеющийся или позвольте менеджеру скачать его.", "client.setup.intro": "Чтобы играть, нужен клиент игры. Сообщество выдаёт его через свой официальный лаунчер.",
"client.setup.have": "У меня уже есть клиент", "client.setup.have": "У меня уже есть клиент",
"client.setup.download": "Скачать клиент", "client.setup.getLauncher": "Скачать лаунчер (coa-development.org)",
"client.setup.downloadHint": "Примерно 43 ГБ", "client.setup.getLauncherHint": "Откроет сайт сообщества в браузере. Скачайте и установите лаунчер, войдите в свой аккаунт и дайте ему скачать игру (около 43 ГБ).",
"client.dl.pickParent": "Выберите, куда поместить клиент игры", "client.setup.haveHint": "Укажите папку, куда лаунчер установил игру, или любую другую копию клиента.",
"client.dl.confirmText": "Версия {v}, {size}. Клиент будет сохранён в эту папку:", "client.setup.hdHint": "Стандартная или HD-графика выбирается в лаунчере: откройте его «Настройки» и переключите «HD graphics». Менеджер этого изменить не может.",
"client.dl.free": "Свободно на этом диске: {free}.", "races.patch.active": "Патч клиента: Включен",
"client.dl.notEnough": "Недостаточно места: нужно {need}, доступно {free}. Выберите другой диск.", "races.patch.disabled": "Патч клиента: Отключен (.disabled)",
"client.dl.otherFolder": "Другая папка…", "races.patch.notInstalled": "Патч клиента: Не установлен",
"client.dl.start": "Скачать", "races.patch.partial": "Патч клиента: {a}/{b} MPQ",
"races.patch.partialHint": "Файлы отсутствуют или изменены. Восстановите патч клиента.",
"races.patch.install": "Установить патч клиента",
"races.patch.repair": "Восстановить патч клиента",
"races.patch.uninstall": "Удалить патч клиента",
"races.patch.willEnable": "После установки патч будет включён.",
"races.patch.willStayOff": "После установки патч останется отключённым: модуль сервера выключен или отсутствует.",
"client.dl.back": "Назад", "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.done": "Клиент игры готов",
"client.dl.doneText": "Он привязан к этому серверу. Можно нажимать PLAY.", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "Показать пароль", "pw.show": "Показать пароль",
@@ -922,7 +946,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"dash.openBrowser": "Открыть в браузере", "dash.openBrowser": "Открыть в браузере",
"dash.update": "Обновить панель", "dash.update": "Обновить панель",
"upd.startAfter": "Запускать сервер после обновления (иначе выключенный сервер останется выключенным)", "upd.startAfter": "Запускать сервер после обновления (иначе выключенный сервер останется выключенным)",
"client.startAfter": "Запускать игру после обновления клиента",
"bk.folder": "Папка резервных копий", "bk.folder": "Папка резервных копий",
"bk.folderDefault": "по умолчанию", "bk.folderDefault": "по умолчанию",
"bk.folderNote": "Новые копии сохраняются сюда, например на другой диск. Прежние копии остаются на месте и по-прежнему в списке. Папка должна быть вне папки сервера.", "bk.folderNote": "Новые копии сохраняются сюда, например на другой диск. Прежние копии остаются на месте и по-прежнему в списке. Папка должна быть вне папки сервера.",
@@ -935,8 +958,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"remove.stopFirst": "Сначала остановите сервер.", "remove.stopFirst": "Сначала остановите сервер.",
"remove.confirm": "Убрать этот сервер из Manager?\n\n{path}\n\nФайлы не удаляются.", "remove.confirm": "Убрать этот сервер из Manager?\n\n{path}\n\nФайлы не удаляются.",
"upd.dbUnchecked": "Не удалось проверить базу данных, поэтому неизвестно, нужны ли ей изменения: {why}", "upd.dbUnchecked": "Не удалось проверить базу данных, поэтому неизвестно, нужны ли ей изменения: {why}",
"client.job.checking": "Проверка клиента…",
"client.job.updating": "Обновление клиента",
"nav.characters": "Персонажи", "nav.characters": "Персонажи",
"q.characters": "Какие мои персонажи где могут играть?", "q.characters": "Какие мои персонажи где могут играть?",
"portable.title": "Персонажи", "portable.title": "Персонажи",
@@ -1282,6 +1303,13 @@ const ru: Partial<Record<keyof typeof en, string>> = {
"serverLogs.errors": "Только ошибки", "serverLogs.errors": "Только ошибки",
"serverLogs.off": "Выключены", "serverLogs.off": "Выключены",
"serverLogs.saved": "Сохранено. Перезапустите сервер для применения.", "serverLogs.saved": "Сохранено. Перезапустите сервер для применения.",
"serverLogs.autoClean": "Автоочистка логов сервера по размеру",
"serverLogs.maxSize": "Макс. размер",
"serverLogs.autoCleanHint": "Очищает старые файлы логов при превышении порога в Core/Logs (проверяется при запуске мира и периодически во время работы).",
"serverLogs.currentSize": "Текущий размер логов: {size}",
"serverLogs.cleanNow": "Очистить логи ({size})",
"serverLogs.cleaned": "Очищено логов: {freed}.",
"serverLogs.skippedInUse": "{remaining} заняты работающим сервером и не были удалены.",
"mod.requiresSquid": "Для Dungeon Clear сначала включите SQUID bots.", "mod.requiresSquid": "Для Dungeon Clear сначала включите SQUID bots.",
}; };
+73 -45
View File
@@ -44,7 +44,7 @@ const zh = {
"mod.switching": "正在应用更改…请稍候。", "mod.switching": "正在应用更改…请稍候。",
"portable.experimental": "实验性功能:便携角色仍在积极开发中,可能存在错误。", "portable.experimental": "实验性功能:便携角色仍在积极开发中,可能存在错误。",
"remote.clientReady": "客户端已就绪。保存服主地址,然后点击开始游戏。", "remote.clientReady": "客户端已就绪。保存服主地址,然后点击开始游戏。",
"remote.clientIntro": "选择已有游戏客户端,或在此下载。无需安装本地服务器。", "remote.clientIntro": "选择已有的游戏客户端,或通过社区的启动器获取。无需本地服务器。",
"welcome.host.title": "我要搭建服务器", "welcome.host.title": "我要搭建服务器",
"welcome.host.text": "安装新服务器或管理已有服务器。", "welcome.host.text": "安装新服务器或管理已有服务器。",
"welcome.connect.title": "连接其他服务器", "welcome.connect.title": "连接其他服务器",
@@ -58,6 +58,53 @@ const zh = {
"remote.hostInstead": "搭建自己的服务器", "remote.hostInstead": "搭建自己的服务器",
"welcome.roleSubtitle": "你想如何游玩?", "welcome.roleSubtitle": "你想如何游玩?",
"mysql.title": "MySQL 设置",
"mysql.hint": "自定义 MySQL 选项,每行一个“名称 = 值”。每次数据库启动时都会加入 my.ini,更新后也会保留。端口、地址和数据路径由 Manager 管理,此处会被忽略。",
"mysql.save": "保存",
"mysql.saved": "已保存;重启服务器后生效。",
"mysql.applied": "生效的选项:{count}",
"sched.title": "定时重启",
"sched.enable": "每天重启世界",
"sched.weeklyEnable": "每周重启世界",
"sched.day": "星期",
"sched.days.monday": "星期一",
"sched.days.tuesday": "星期二",
"sched.days.wednesday": "星期三",
"sched.days.thursday": "星期四",
"sched.days.friday": "星期五",
"sched.days.saturday": "星期六",
"sched.days.sunday": "星期日",
"sched.time": "时间",
"sched.warning": "提前警告(分钟)",
"sched.hint": "世界会在本机的这个时间重启,并在游戏聊天中倒计时;数据库保持运行,玩家在重启后重新登录。正在运行的服务器会在一分钟内采用新时间。",
"sched.save": "保存",
"sched.saved": "已保存。",
"sched.unsupported": "此服务器暂不支持:请将服务器更新到带有新启动器的版本。",
"client.clearCache": "每次启动前清空游戏缓存",
"client.clearCacheHint": "游戏会保存从服务器获得的生物、物品和任务(Cache/WDB)。服务器更新后,这些缓存可能显示旧的名称和属性;缓存会在几秒内重新生成。",
"addons.withServer": "随服务器提供,并随服务器一起更新。",
"addons.withRaces": "随 Custom Races V2 客户端补丁安装并一起开关;Manager 不会单独安装它。",
"addons.withRacesMissing": "随 Custom Races V2 客户端补丁提供(模块 → Custom Races);安装补丁后即可获得。",
"addons.title": "插件",
"addons.hint": "Conquest of Azeroth 的社区插件。每个插件都来自作者的 GitHub 的已核验版本;安装到 Interface/AddOns 前会逐个校验文件。请先关闭游戏。",
"addons.by": "作者:{author}",
"addons.installed": "已安装",
"addons.update": "有可用更新",
"addons.needsSquid": "用于 SQUID's Playerbots。",
"addons.foreign": "已存在名为 {folders} 的文件夹;它会被移到 AddOns/.coa-addons-backup。",
"addons.doInstall": "安装",
"addons.doUpdate": "更新",
"addons.doRemove": "移除",
"races.offCharacters": "自定义种族已关闭:{players} 个玩家角色和 {bots} 个自定义种族机器人在重新开启前不会进入世界(没有补丁的游戏客户端看到它们会崩溃)。",
"races.purgeBots": "删除 {n} 个自定义种族的伙伴机器人",
"races.purged": "已删除 {n} 个自定义种族机器人。",
"realm.namesTitle": "服务器名称",
"realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。",
"realm.nameSave": "保存",
"realm.nameReset": "默认名称",
"realm.nameDefault": "默认:{name}",
"realm.nameSaved": "已保存。",
"realm.nameQuotes": "不能使用引号:游戏客户端用引号保存名称。",
"realm.profileLabel": "服务器", "realm.profileLabel": "服务器",
"realm.switching": "正在切换服务器…", "realm.switching": "正在切换服务器…",
"realm.rebornCreate": "创建 Warcraft Reborn 服务器", "realm.rebornCreate": "创建 Warcraft Reborn 服务器",
@@ -132,7 +179,6 @@ const zh = {
"btn.stopSmall": "停止", "btn.stopSmall": "停止",
"btn.restart": "重启", "btn.restart": "重启",
"btn.startWithoutUpdate": "不更新启动服务器", "btn.startWithoutUpdate": "不更新启动服务器",
"btn.playWithoutUpdate": "不更新开始游戏",
"import.squidRepackWarning": "此 SquidBots 整合包会检查 worldserver 哈希。替换程序可能导致 Start_All_Bots 和 coa_update 无法运行。更新前会要求您选择。", "import.squidRepackWarning": "此 SquidBots 整合包会检查 worldserver 哈希。替换程序可能导致 Start_All_Bots 和 coa_update 无法运行。更新前会要求您选择。",
"btn.play": "开始游戏", "btn.play": "开始游戏",
"btn.startPlay": "启动并开始游戏", "btn.startPlay": "启动并开始游戏",
@@ -275,6 +321,7 @@ const zh = {
"client.updateAddon": "更新随从插件", "client.updateAddon": "更新随从插件",
"client.addonNote": "随从插件已安装。其他插件未受任何影响。", "client.addonNote": "随从插件已安装。其他插件未受任何影响。",
"client.changeFolder": "更换文件夹…", "client.changeFolder": "更换文件夹…",
"client.getFromSite": "获取启动器…",
// Diagnostics // Diagnostics
"diag.title": "诊断", "diag.title": "诊断",
@@ -612,6 +659,8 @@ const zh = {
"comp.startCount": "自动登录随从数量", "comp.startCount": "自动登录随从数量",
"comp.startSave": "保存", "comp.startSave": "保存",
"comp.startSaved": "已保存。将在下次服务器启动时生效。", "comp.startSaved": "已保存。将在下次服务器启动时生效。",
"comp.startTopUp": "已保存。正在再创建 {n} 个同伴,使总数达到 {max};其余已存在。",
"comp.startTopUpConfirm": "再创建 {n} 个同伴,使总数达到 {max}?已存在的不会重复创建。",
"comp.startHint": "未登录的随从仍保留在数据库中,随时可在需要时手动调出上线。", "comp.startHint": "未登录的随从仍保留在数据库中,随时可在需要时手动调出上线。",
"comp.startInvalid": "请输入 0 到 5000 之间的整数。", "comp.startInvalid": "请输入 0 到 5000 之间的整数。",
@@ -660,51 +709,26 @@ const zh = {
// Game client download and update // Game client download and update
"btn.close": "关闭", "btn.close": "关闭",
"btn.setupClient": "配置游戏客户端", "btn.setupClient": "配置游戏客户端",
"btn.updateClient": "更新客户端",
"client.setup.title": "配置游戏客户端", "client.setup.title": "配置游戏客户端",
"client.setup.intro": "进行游戏需要安装匹配的客户端。你可以关联已有的游戏客户端,也可以让管理器为你自动下载。", "client.setup.intro": "进行游戏需要安装客户端。社区通过其官方启动器提供客户端。",
"client.setup.have": "已有游戏客户端", "client.setup.have": "已有游戏客户端",
"client.setup.download": "下载全新客户端", "client.setup.getLauncher": "获取启动器(coa-development.org)",
"client.setup.downloadHint": "约 43 GB", "client.setup.getLauncherHint": "在浏览器中打开社区网站。在那里下载并安装启动器,用你的账号登录,让它下载游戏(约 43 GB)。",
"client.dl.pickParent": "选择游戏客户端存放位置", "client.setup.haveHint": "选择启动器安装游戏的文件夹,或任何其他客户端副本。",
"client.dl.confirmText": "版本 {v},体积 {size}。将被保存在以下文件夹中:", "client.setup.hdHint": "标准或高清画质在启动器中选择:打开启动器的“设置”,切换“HD graphics”。Manager 无法更改。",
"client.dl.free": "该驱动器剩余空间:{free}。", "races.patch.active": "客户端补丁:已启用",
"client.dl.notEnough": "磁盘剩余空间不足:需要 {need},可用 {free}。请选择其他驱动器。", "races.patch.disabled": "客户端补丁:已停用 (.disabled)",
"client.dl.otherFolder": "选择其他文件夹…", "races.patch.notInstalled": "客户端补丁:未安装",
"client.dl.start": "开始下载", "races.patch.partial": "客户端补丁:{a}/{b} MPQ",
"races.patch.partialHint": "文件缺失或已被修改。请修复客户端补丁。",
"races.patch.install": "安装客户端补丁",
"races.patch.repair": "修复客户端补丁",
"races.patch.uninstall": "卸载客户端补丁",
"races.patch.willEnable": "安装后补丁将被启用。",
"races.patch.willStayOff": "安装后补丁仍将保持停用:服务器模块已关闭或不存在。",
"client.dl.back": "返回", "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.done": "游戏客户端已就绪",
"client.dl.doneText": "已成功关联至此服务器。你可以点击“开始游戏”了。", "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 // Accounts panel, password toggle, install size, addon explanation
"pw.show": "显示密码", "pw.show": "显示密码",
@@ -893,7 +917,6 @@ const zh = {
"dash.openBrowser": "在浏览器中打开", "dash.openBrowser": "在浏览器中打开",
"dash.update": "更新仪表盘", "dash.update": "更新仪表盘",
"upd.startAfter": "更新后启动服务器(否则已停止的服务器保持停止)", "upd.startAfter": "更新后启动服务器(否则已停止的服务器保持停止)",
"client.startAfter": "更新客户端后启动游戏",
"bk.folder": "备份文件夹", "bk.folder": "备份文件夹",
"bk.folderDefault": "默认", "bk.folderDefault": "默认",
"bk.folderNote": "新备份将保存在这里,例如另一个驱动器上。之前的备份保留在原处,仍会列出。该文件夹必须位于服务器文件夹之外。", "bk.folderNote": "新备份将保存在这里,例如另一个驱动器上。之前的备份保留在原处,仍会列出。该文件夹必须位于服务器文件夹之外。",
@@ -906,8 +929,6 @@ const zh = {
"remove.stopFirst": "请先停止服务器。", "remove.stopFirst": "请先停止服务器。",
"remove.confirm": "要从 Manager 中移除此服务器吗?\n\n{path}\n\n不会删除任何文件。", "remove.confirm": "要从 Manager 中移除此服务器吗?\n\n{path}\n\n不会删除任何文件。",
"upd.dbUnchecked": "无法检查数据库,因此不清楚是否有待应用的数据库更改:{why}", "upd.dbUnchecked": "无法检查数据库,因此不清楚是否有待应用的数据库更改:{why}",
"client.job.checking": "正在检查游戏客户端…",
"client.job.updating": "正在更新游戏客户端",
"err.docker_unavailable.title": "Docker 不可用", "err.docker_unavailable.title": "Docker 不可用",
"err.docker_unavailable.message": "此服务器通过 Docker 运行。请安装并启动 Docker,确保当前用户有权使用它,然后重试。", "err.docker_unavailable.message": "此服务器通过 Docker 运行。请安装并启动 Docker,确保当前用户有权使用它,然后重试。",
"fr.lan.address": "网络地址", "fr.lan.address": "网络地址",
@@ -1091,6 +1112,13 @@ const zh = {
"serverLogs.errors": "仅错误", "serverLogs.errors": "仅错误",
"serverLogs.off": "关闭", "serverLogs.off": "关闭",
"serverLogs.saved": "已保存。重启服务器后生效。", "serverLogs.saved": "已保存。重启服务器后生效。",
"serverLogs.autoClean": "按大小自动清理服务器日志",
"serverLogs.maxSize": "最大大小",
"serverLogs.autoCleanHint": "当 Core/Logs 超过此大小时清理旧日志文件(在世界启动时和运行期间定期检查)。",
"serverLogs.currentSize": "当前日志大小:{size}",
"serverLogs.cleanNow": "清理日志({size})",
"serverLogs.cleaned": "已清理 {freed} 日志。",
"serverLogs.skippedInUse": "{remaining} 正被运行中的服务器占用,无法删除。",
"mod.requiresSquid": "请先启用 SQUID 机器人,再使用 Dungeon Clear。", "mod.requiresSquid": "请先启用 SQUID 机器人,再使用 Dungeon Clear。",
} as const; } as const;
+10
View File
@@ -148,6 +148,16 @@
"t": "Suchradius für Ziele", "t": "Suchradius für Ziele",
"d": "Wie weit ein Bot innerhalb eines Zielgebiets nach Questzielen sucht." "d": "Wie weit ein Bot innerhalb eines Zielgebiets nach Questzielen sucht."
}, },
"CoaBots.Scaling.Enable": {"t": "Stärkehilfe für Bots in Dungeons und Schlachtzügen", "d": "Hauptschalter für die Multiplikatoren unten. Bis du sie erhöhst, sind alle 1 (keine Änderung)."},
"CoaBots.Scaling.Dungeons": {"t": "Hilfe in 5-Spieler-Dungeons", "d": "Multiplikatoren anwenden, solange ein Bot in einem 5-Spieler-Dungeon ist."},
"CoaBots.Scaling.Raids": {"t": "Hilfe in Schlachtzügen", "d": "Multiplikatoren anwenden, solange ein Bot in einem Schlachtzug ist."},
"CoaBots.Scaling.Battlegrounds": {"t": "Hilfe in Schlachtfeldern und Arenen", "d": "Multiplikatoren in Schlachtfeldern und Arenen anwenden."},
"CoaBots.Scaling.World": {"t": "Hilfe in der offenen Welt", "d": "Multiplikatoren außerhalb von Dungeons und Schlachtzügen anwenden. Meist nicht gewünscht."},
"CoaBots.Scaling.DamageDone": {"t": "Schaden der Bots", "d": "Multipliziert den Schaden, den Bots und ihre Begleiter Kreaturen zufügen. 1 heißt keine Änderung; höher macht Inhalte leichter."},
"CoaBots.Scaling.HealingDone": {"t": "Heilung der Bots", "d": "Multipliziert die Heilung, die Bots wirken. 1 heißt keine Änderung."},
"CoaBots.Scaling.DamageTaken": {"t": "Schaden an Bots", "d": "Multipliziert den Schaden, den Kreaturen Bots zufügen. Unter 1 erleiden Bots weniger; 1 heißt keine Änderung."},
"CoaBots.Scaling.TankThreat": {"t": "Bedrohung der Tanks", "d": "Zusätzliche Bedrohung durch Bot-Tanks, damit sie die Aufmerksamkeit der Gegner halten. 1 heißt keine Änderung."},
"CoaBots.Scaling.BossTuning": {"t": "Zusatzhilfe gegen vier Bosse", "d": "Fügt stärkere Multiplikatoren für Loken, den Drakkari-Elementar, den Drakkari-Koloss und Gal'darah hinzu, die Bots der Stufe 60 sonst nicht besiegten. Zum Testen; standardmäßig aus."},
"CoaBots.WorldBrain.EngageRange": { "CoaBots.WorldBrain.EngageRange": {
"t": "Angriffsentfernung", "t": "Angriffsentfernung",
"d": "Entfernung, ab der ein Bot einen Quest-Gegner bekämpft." "d": "Entfernung, ab der ein Bot einen Quest-Gegner bekämpft."
+10
View File
@@ -148,6 +148,16 @@
"t": "Radio de búsqueda de objetivos", "t": "Radio de búsqueda de objetivos",
"d": "Hasta dónde examina un bot en busca de objetivos de misión dentro de una zona de objetivo." "d": "Hasta dónde examina un bot en busca de objetivos de misión dentro de una zona de objetivo."
}, },
"CoaBots.Scaling.Enable": {"t": "Ayuda de fuerza para bots en mazmorras y bandas", "d": "Interruptor general de los multiplicadores de abajo. Hasta que los subas, todos valen 1 (sin cambios)."},
"CoaBots.Scaling.Dungeons": {"t": "Ayuda en mazmorras de 5 jugadores", "d": "Aplica los multiplicadores mientras un bot está en una mazmorra de 5 jugadores."},
"CoaBots.Scaling.Raids": {"t": "Ayuda en bandas", "d": "Aplica los multiplicadores mientras un bot está en una banda."},
"CoaBots.Scaling.Battlegrounds": {"t": "Ayuda en campos de batalla y arenas", "d": "Aplica los multiplicadores en campos de batalla y arenas."},
"CoaBots.Scaling.World": {"t": "Ayuda en el mundo abierto", "d": "Aplica los multiplicadores fuera de mazmorras y bandas. Normalmente no se desea."},
"CoaBots.Scaling.DamageDone": {"t": "Daño de los bots", "d": "Multiplica el daño que los bots y sus mascotas infligen a las criaturas. 1 no cambia nada; más alto facilita el contenido."},
"CoaBots.Scaling.HealingDone": {"t": "Curación de los bots", "d": "Multiplica la curación que lanzan los bots. 1 no cambia nada."},
"CoaBots.Scaling.DamageTaken": {"t": "Daño recibido por los bots", "d": "Multiplica el daño que las criaturas infligen a los bots. Por debajo de 1 los bots reciben menos; 1 no cambia nada."},
"CoaBots.Scaling.TankThreat": {"t": "Amenaza de los tanques", "d": "Amenaza extra que generan los tanques bot para mantener la atención de los enemigos. 1 no cambia nada."},
"CoaBots.Scaling.BossTuning": {"t": "Ayuda extra contra cuatro jefes", "d": "Añade multiplicadores más fuertes para Loken, el elemental drakkari, el coloso drakkari y Gal'darah, a quienes los bots de nivel 60 no vencían de otro modo. Para pruebas; desactivado por defecto."},
"CoaBots.WorldBrain.EngageRange": { "CoaBots.WorldBrain.EngageRange": {
"t": "Distancia de enfrentamiento", "t": "Distancia de enfrentamiento",
"d": "Distancia a la que un bot empieza a combatir a un monstruo de misión." "d": "Distancia a la que un bot empieza a combatir a un monstruo de misión."
+10
View File
@@ -148,6 +148,16 @@
"t": "Rayon de recherche des cibles", "t": "Rayon de recherche des cibles",
"d": "Jusqu’où un bot cherche des cibles de quête dans une zone d’objectif." "d": "Jusqu’où un bot cherche des cibles de quête dans une zone d’objectif."
}, },
"CoaBots.Scaling.Enable": {"t": "Aide de puissance pour les bots en donjon et en raid", "d": "Interrupteur général des multiplicateurs ci-dessous. Tant que vous ne les augmentez pas, ils valent tous 1 (aucun changement)."},
"CoaBots.Scaling.Dungeons": {"t": "Aide en donjon à 5 joueurs", "d": "Applique les multiplicateurs tant qu'un bot est dans un donjon à 5 joueurs."},
"CoaBots.Scaling.Raids": {"t": "Aide en raid", "d": "Applique les multiplicateurs tant qu'un bot est dans un raid."},
"CoaBots.Scaling.Battlegrounds": {"t": "Aide en champ de bataille et en arène", "d": "Applique les multiplicateurs en champ de bataille et en arène."},
"CoaBots.Scaling.World": {"t": "Aide en monde ouvert", "d": "Applique les multiplicateurs hors des donjons et des raids. Rarement souhaité."},
"CoaBots.Scaling.DamageDone": {"t": "Dégâts des bots", "d": "Multiplie les dégâts que les bots et leurs familiers infligent aux créatures. 1 : aucun changement ; plus élevé = contenu plus facile."},
"CoaBots.Scaling.HealingDone": {"t": "Soins des bots", "d": "Multiplie les soins lancés par les bots. 1 : aucun changement."},
"CoaBots.Scaling.DamageTaken": {"t": "Dégâts subis par les bots", "d": "Multiplie les dégâts que les créatures infligent aux bots. Sous 1, les bots en subissent moins ; 1 : aucun changement."},
"CoaBots.Scaling.TankThreat": {"t": "Menace des tanks", "d": "Menace supplémentaire générée par les tanks bots, pour qu'ils gardent l'attention des ennemis. 1 : aucun changement."},
"CoaBots.Scaling.BossTuning": {"t": "Aide supplémentaire contre quatre boss", "d": "Ajoute des multiplicateurs plus forts pour Loken, l'élémentaire drakkari, le colosse drakkari et Gal'darah, que les bots de niveau 60 ne battaient pas autrement. Pour les tests ; désactivé par défaut."},
"CoaBots.WorldBrain.EngageRange": { "CoaBots.WorldBrain.EngageRange": {
"t": "Distance d’engagement", "t": "Distance d’engagement",
"d": "Distance à laquelle un bot commence à combattre un monstre de quête." "d": "Distance à laquelle un bot commence à combattre un monstre de quête."
+10
View File
@@ -148,6 +148,16 @@
"t": "Радиус поиска целей", "t": "Радиус поиска целей",
"d": "Как далеко бот высматривает цели заданий внутри области задачи." "d": "Как далеко бот высматривает цели заданий внутри области задачи."
}, },
"CoaBots.Scaling.Enable": {"t": "Помощь ботам в подземельях и рейдах", "d": "Главный выключатель множителей ниже. Пока вы их не повысите, все равны 1 (без изменений)."},
"CoaBots.Scaling.Dungeons": {"t": "Помощь в подземельях на 5 человек", "d": "Применять множители, пока бот находится в подземелье на 5 человек."},
"CoaBots.Scaling.Raids": {"t": "Помощь в рейдах", "d": "Применять множители, пока бот находится в рейде."},
"CoaBots.Scaling.Battlegrounds": {"t": "Помощь на полях боя и аренах", "d": "Применять множители на полях боя и аренах."},
"CoaBots.Scaling.World": {"t": "Помощь в открытом мире", "d": "Применять множители вне подземелий и рейдов. Обычно не нужно."},
"CoaBots.Scaling.DamageDone": {"t": "Урон ботов", "d": "Умножает урон, который наносят существам боты и их питомцы. 1 — без изменений, больше — проще."},
"CoaBots.Scaling.HealingDone": {"t": "Лечение ботов", "d": "Умножает лечение, которое накладывают боты. 1 — без изменений."},
"CoaBots.Scaling.DamageTaken": {"t": "Урон по ботам", "d": "Умножает урон, который существа наносят ботам. Меньше 1 — боты получают меньше урона, 1 — без изменений."},
"CoaBots.Scaling.TankThreat": {"t": "Угроза танков", "d": "Дополнительная угроза от ботов-танков, чтобы они удерживали внимание врагов. 1 — без изменений."},
"CoaBots.Scaling.BossTuning": {"t": "Дополнительная помощь против четырёх боссов", "d": "Добавляет усиленные множители для Локена, элементаля Драккари, колосса Драккари и Гал'дараха, которых боты 60 уровня иначе не побеждали. Для тестов; по умолчанию выключено."},
"CoaBots.WorldBrain.EngageRange": { "CoaBots.WorldBrain.EngageRange": {
"t": "Дистанция начала боя", "t": "Дистанция начала боя",
"d": "Расстояние, на котором бот начинает бой с монстром из задания." "d": "Расстояние, на котором бот начинает бой с монстром из задания."
+10
View File
@@ -168,6 +168,16 @@
"t": "任务目标搜索半径", "t": "任务目标搜索半径",
"d": "机器人在目标区域内寻找任务怪或任务道具的扫描范围。" "d": "机器人在目标区域内寻找任务怪或任务道具的扫描范围。"
}, },
"CoaBots.Scaling.Enable": {"t": "机器人在地下城和团队副本中的强度辅助", "d": "下方倍率的总开关。在你调高之前,所有倍率均为1(无变化)。"},
"CoaBots.Scaling.Dungeons": {"t": "5人地下城辅助", "d": "机器人处于5人地下城时应用倍率。"},
"CoaBots.Scaling.Raids": {"t": "团队副本辅助", "d": "机器人处于团队副本时应用倍率。"},
"CoaBots.Scaling.Battlegrounds": {"t": "战场与竞技场辅助", "d": "在战场和竞技场中应用倍率。"},
"CoaBots.Scaling.World": {"t": "野外辅助", "d": "在地下城和团队副本之外应用倍率。通常不需要。"},
"CoaBots.Scaling.DamageDone": {"t": "机器人伤害", "d": "倍乘机器人及其宠物对生物造成的伤害。1表示无变化;越高内容越容易。"},
"CoaBots.Scaling.HealingDone": {"t": "机器人治疗", "d": "倍乘机器人施放的治疗量。1表示无变化。"},
"CoaBots.Scaling.DamageTaken": {"t": "机器人受到的伤害", "d": "倍乘生物对机器人造成的伤害。低于1时机器人受到的伤害更少;1表示无变化。"},
"CoaBots.Scaling.TankThreat": {"t": "坦克仇恨", "d": "机器人坦克额外产生的仇恨,使其更容易吸引敌人注意。1表示无变化。"},
"CoaBots.Scaling.BossTuning": {"t": "针对四个首领的额外辅助", "d": "为洛肯、达卡莱元素、达卡莱巨像和加尔达拉添加更强的倍率,60级机器人否则无法击败他们。用于测试;默认关闭。"},
"CoaBots.WorldBrain.EngageRange": { "CoaBots.WorldBrain.EngageRange": {
"t": "开战交战距离", "t": "开战交战距离",
"d": "机器人发现任务目标怪并开始主动进入战斗的距离。" "d": "机器人发现任务目标怪并开始主动进入战斗的距离。"
+75 -40
View File
@@ -54,9 +54,28 @@ export interface StatusView {
observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null }; observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null };
busy: boolean; busy: boolean;
path_exists: boolean; path_exists: boolean;
scheduled_restart?: boolean;
} }
export type RealmMode = "coa" | "wildcard" | "reborn"; export type RealmMode = "coa" | "wildcard" | "reborn";
export interface CustomRaceCharacters { players: number; companionBots: number; squidBots: number }
export interface AddonView { id: string; name: string; description: Record<string, string>; author: string; license: string; needs: string | null; repo: string; size: number; installed: boolean; updateAvailable: boolean; foreignFolders: string[]; bundled?: string | null }
export type Weekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
export interface RestartSchedule {
enabled: boolean;
time: string;
warningMinutes: number;
weeklyEnabled: boolean;
weeklyDay: Weekday;
weeklyTime: string;
weeklyWarningMinutes: number;
}
export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean }
export interface LogSettings { autoCleanup: boolean; maxSizeMb: number }
export interface CleanLogsReport { freedBytes: number; remainingBytes: number; deletedFiles: number; skippedFiles: number }
export interface ServerLoggingView { preset: "normal" | "errors" | "off" | null; logBytes: number; settings: LogSettings }
export interface CustomMysql { text: string; applied: string }
export interface RealmName { id: number; name: string; defaultName: string; custom: 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 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 { export interface DatabaseCheck {
realm: RealmMode; realm: RealmMode;
@@ -230,6 +249,7 @@ export interface ModuleView {
/** not shown on the Modules page */ /** not shown on the Modules page */
hidden: boolean; hidden: boolean;
compatibility?: "compatible" | "experimental" | "unsupported" | "requires-squid"; compatibility?: "compatible" | "experimental" | "unsupported" | "requires-squid";
part_of?: string | null;
} }
export interface ModuleSetting { export interface ModuleSetting {
@@ -353,6 +373,16 @@ export interface CompanionSizes {
sizes: { id: string; title: string; bots: number; warning: string | null }[]; sizes: { id: string; title: string; bots: number; warning: string | null }[];
} }
export interface WildcardArchetypeDto {
id: string;
name: string;
roles: number;
primary_stat: number;
author: string;
difficulty: number;
category: number;
}
export interface ClientInfo { export interface ClientInfo {
path: string; path: string;
executable: string; executable: string;
@@ -362,36 +392,8 @@ export interface ClientInfo {
} }
export interface ClientStatus { export interface ClientStatus {
/** A usable client folder is linked. */
linked: boolean; 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"; export type ClientPatchState = "not-installed" | "enabled" | "disabled" | "partially-installed";
@@ -486,6 +488,19 @@ export const api = {
realmProfiles: (id: string) => invoke<RealmProfiles>("realm_profiles", { id }), realmProfiles: (id: string) => invoke<RealmProfiles>("realm_profiles", { id }),
realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke<RealmProfiles>("realm_select", { id, mode, restart }), 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 }), realmSimultaneous: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_simultaneous", { id, enabled }),
customRaceCharacters: (id: string) => invoke<CustomRaceCharacters | null>("custom_race_characters", { id }),
purgeCustomRaceBots: (id: string) => invoke<number>("purge_custom_race_bots", { id }),
addonsList: (id: string) => invoke<AddonView[]>("addons_list", { id }),
addonsInstall: (id: string, addon: string) => invoke<AddonView[]>("addons_install", { id, addon }),
addonsRemove: (id: string, addon: string) => invoke<AddonView[]>("addons_remove", { id, addon }),
clearGameCacheOnPlay: () => invoke<boolean>("clear_game_cache_on_play"),
setClearGameCacheOnPlay: (enabled: boolean) => invoke<void>("set_clear_game_cache_on_play", { enabled }),
restartSchedule: (id: string) => invoke<RestartScheduleView>("restart_schedule", { id }),
restartScheduleSave: (id: string, schedule: RestartSchedule) => invoke<RestartScheduleView>("restart_schedule_save", { id, schedule }),
mysqlCustom: (id: string) => invoke<CustomMysql>("mysql_custom", { id }),
mysqlCustomSave: (id: string, text: string) => invoke<CustomMysql>("mysql_custom_save", { id, text }),
realmNames: (id: string) => invoke<RealmName[]>("realm_names", { id }),
realmRename: (id: string, realmId: number, name: string | null) => invoke<RealmName[]>("realm_rename", { id, realmId, name }),
realmWithReborn: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_with_reborn", { id, enabled }), realmWithReborn: (id: string, enabled: boolean) => invoke<RealmProfiles>("realm_with_reborn", { id, enabled }),
checkDatabase: (id: string) => invoke<DatabaseCheck[]>("check_database", { id }), checkDatabase: (id: string) => invoke<DatabaseCheck[]>("check_database", { id }),
repairServer: (id: string) => invoke<RepairReport>("repair_server", { id }), repairServer: (id: string) => invoke<RepairReport>("repair_server", { id }),
@@ -499,7 +514,10 @@ export const api = {
forceStop: (id: string) => invoke<DriverOutcome>("force_stop_server", { id }), forceStop: (id: string) => invoke<DriverOutcome>("force_stop_server", { id }),
stop: (id: string) => invoke<DriverOutcome>("stop_server", { id }), stop: (id: string) => invoke<DriverOutcome>("stop_server", { id }),
settings: (id: string, scope: Scope) => invoke<SettingsView>("get_settings", { id, scope }), settings: (id: string, scope: Scope) => invoke<SettingsView>("get_settings", { id, scope }),
serverLoggingState: (id: string) => invoke<ServerLoggingView>("server_logging_state", { id }),
serverLoggingPreset: (id: string, preset: "normal" | "errors" | "off") => invoke<void>("server_logging_preset", { id, preset }), serverLoggingPreset: (id: string, preset: "normal" | "errors" | "off") => invoke<void>("server_logging_preset", { id, preset }),
serverLoggingSettingsSave: (id: string, settings: LogSettings) => invoke<ServerLoggingView>("server_logging_settings_save", { id, settings }),
serverLogsClean: (id: string) => invoke<CleanLogsReport>("server_logs_clean", { id }),
save: (id: string, scope: Scope, changes: Record<string, JsonValue>) => invoke<SaveReport>("save_settings", { id, scope, changes }), save: (id: string, scope: Scope, changes: Record<string, JsonValue>) => invoke<SaveReport>("save_settings", { id, scope, changes }),
presets: (scope: Scope) => invoke<PresetInfo[]>("list_presets", { scope }), presets: (scope: Scope) => invoke<PresetInfo[]>("list_presets", { scope }),
backups: (id: string) => invoke<RecoveryPoint[]>("list_backups", { id }), backups: (id: string) => invoke<RecoveryPoint[]>("list_backups", { id }),
@@ -553,15 +571,37 @@ export const api = {
invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }), invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }),
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }), rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }), retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
population: (id: string) => invoke<Population | null>("get_population", { id }), /** Creates the companions the startup fleet is missing (the limit is a fleet size). Returns how many were queued. */
stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }), topUpStartupFleet: (id: string, realm?: RealmMode) => invoke<number>("top_up_startup_fleet", { id, realm: realm ?? null }),
takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }), population: (id: string, realm?: RealmMode) => invoke<Population | null>("get_population", { id, realm: realm ?? null }),
despawnSome: (id: string, count: number) => invoke<{ count: number }>("companions_despawn_some", { id, count }), stopSpawning: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_stop_spawning", { id, realm: realm ?? null }),
deleteAllCompanions: (id: string) => invoke<{ count: number }>("companions_delete_all", { id }), takeOffline: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_take_offline", { id, realm: realm ?? null }),
despawnSome: (id: string, count: number, realm?: RealmMode) => invoke<{ count: number }>("companions_despawn_some", { id, count, realm: realm ?? null }),
deleteAllCompanions: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_delete_all", { id, realm: realm ?? null }),
loginAllCompanions: (id: string, realm?: RealmMode) => invoke<string>("companions_login_all", { id, realm: realm ?? null }),
spawnBotFleet: (id: string, race: number, level: number, realm?: RealmMode) => invoke<string>("companions_spawn_fleet", { id, race, level, realm: realm ?? null }),
openLink: (url: string) => invoke<void>("open_link", { url }), openLink: (url: string) => invoke<void>("open_link", { url }),
performance: (id: string) => invoke<Performance | null>("get_performance", { id }), performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
companionSizes: () => invoke<CompanionSizes>("companion_sizes"), companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }), addCompanions: (
id: string,
count: number,
realm?: RealmMode,
level?: number,
classId?: number,
specId?: number,
archetype?: string
) =>
invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", {
id,
count,
realm: realm ?? null,
level: level ?? null,
class_id: classId ?? null,
spec_id: specId ?? null,
archetype: archetype ?? null,
}),
getWildcardArchetypes: (id: string) => invoke<WildcardArchetypeDto[]>("get_wildcard_archetypes", { id }),
clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }),
clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }),
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }), clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
@@ -569,11 +609,6 @@ export const api = {
setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }), setRealmlist: (id: string, host: string) => invoke<string[]>("client_realmlist", { id, host }),
installAddon: (id: string) => invoke<void>("client_install_addon", { id }), installAddon: (id: string) => invoke<void>("client_install_addon", { id }),
clientStatus: (id: string) => invoke<ClientStatus>("client_status", { 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 }), customRacesStatus: (id: string) => invoke<CustomRacesClientStatus | null>("custom_races_status", { id }),
raceAvailability: (id: string) => invoke<RaceAvailability>("race_availability", { id }), raceAvailability: (id: string) => invoke<RaceAvailability>("race_availability", { id }),
raceAvailabilitySave: (id: string, catalogSha256: string, realm: RealmMode, disabledRaceIds: number[]) => raceAvailabilitySave: (id: string, catalogSha256: string, realm: RealmMode, disabledRaceIds: number[]) =>
-116
View File
@@ -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
View File
@@ -2,8 +2,8 @@ import { useSyncExternalStore } from "react";
import { api, type ClientStatus } from "@/lib/api"; 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 game client is linked, for the main screen. The Manager does not download or update the client (the
* whether a newer one has been published. Checked at start and every five minutes (one small request; no game file is read). * community's official launcher does), so this is a local check only.
*/ */
interface State { interface State {
status: ClientStatus | null; status: ClientStatus | null;
@@ -13,7 +13,6 @@ interface State {
const EMPTY: State = { status: null, checking: false }; const EMPTY: State = { status: null, checking: false };
const states = new Map<string, State>(); const states = new Map<string, State>();
const listeners = new Set<() => void>(); const listeners = new Set<() => void>();
const CHECK_EVERY_MS = 5 * 60 * 1000;
const get = (id: string) => states.get(id) ?? EMPTY; const get = (id: string) => states.get(id) ?? EMPTY;
function set(id: string, next: Partial<State>) { function set(id: string, next: Partial<State>) {
@@ -27,19 +26,12 @@ export async function checkClient(id: string): Promise<void> {
try { try {
set(id, { status: await api.clientStatus(id) }); set(id, { status: await api.clientStatus(id) });
} catch { } catch {
// offline: keep what we knew // keep what we knew
} finally { } finally {
set(id, { checking: false }); 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 { export function useClientStatus(id: string): State {
return useSyncExternalStore( return useSyncExternalStore(
(l) => { (l) => {
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more