diff --git a/changelog.d/20261116-custom-race-characters-off.md b/changelog.d/20261116-custom-race-characters-off.md new file mode 100644 index 0000000..c25e14b --- /dev/null +++ b/changelog.d/20261116-custom-race-characters-off.md @@ -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. diff --git a/crates/coa-core/src/custom_races.rs b/crates/coa-core/src/custom_races.rs index 8a26506..1f355ec 100644 --- a/crates/coa-core/src/custom_races.rs +++ b/crates/coa-core/src/custom_races.rs @@ -515,6 +515,46 @@ fn is_switched(client: &Path, file: &PatchFile) -> bool { entry_point || suffix(&client.join(&file.path), "original").is_file() } +/// Characters of custom races (RaceID above 11) on the active realm: a game client without the client patch +/// crashes when one of them comes into view, so the server keeps them out of the world while custom races are +/// off. `None` when the database is not running. +#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CustomRaceCharacters { + pub players: u32, + pub companion_bots: u32, + pub squid_bots: u32, +} + +pub fn custom_race_characters(root: &Path) -> Result> { + let squid = crate::accounts::squid_bot_prefix(root); + let characters = crate::realms::state(root) + .map(|s| s.active) + .unwrap_or_default() + .schema("characters")?; + crate::backup::with_running_database(root, |db| { + let out = db.query(&format!( + "SELECT \ + IFNULL(SUM(a.username NOT LIKE 'COABOTHOST%' AND a.username NOT LIKE '{squid}%'), 0), \ + IFNULL(SUM(a.username LIKE 'COABOTHOST%'), 0), \ + IFNULL(SUM(a.username LIKE '{squid}%'), 0) \ + FROM {characters}.characters c JOIN acore_auth.account a ON a.id = c.account WHERE c.race > 11;" + ))?; + let numbers: Vec = out + .lines() + .last() + .unwrap_or("") + .split('\t') + .map(|n| n.trim().parse().unwrap_or(0)) + .collect(); + Ok(CustomRaceCharacters { + players: numbers.first().copied().unwrap_or(0), + companion_bots: numbers.get(1).copied().unwrap_or(0), + squid_bots: numbers.get(2).copied().unwrap_or(0), + }) + }) +} + /// Only complete, verified payloads are reported as enabled or disabled. pub fn client_patch_status(client_path: &Path) -> ClientPatchStatus { let data = client_path.join("Data"); diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index cad0bcd..09580e0 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -258,6 +258,11 @@ impl Ra { 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 { + 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. pub fn spawn_bots(&mut self, count: u32) -> Result { if !(1..=2000).contains(&count) { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8552c36..29ae5ec 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1479,6 +1479,33 @@ async fn custom_races_install( result } +#[tauri::command] +async fn custom_race_characters( + state: State<'_, AppState>, + id: String, +) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || coa_core::custom_races::custom_race_characters(&root)).await +} + +/// Delete the companion bots of custom races through the running world's console. Returns how many. +#[tauri::command] +async fn purge_custom_race_bots( + state: State<'_, AppState>, + id: String, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let o = coa_core::process::observe(&root, &layout::read_ports(&root)); + if o.world.state != coa_core::process::ServiceState::Running { + return Err(Error::Invalid("Start the server to delete bots.".into())); + } + Ra::connect(&root)?.purge_custom_race_bots() + }) + .await +} + #[tauri::command] async fn addons_list( state: State<'_, AppState>, @@ -3152,6 +3179,8 @@ pub fn run() { restart_schedule_save, clear_game_cache_on_play, set_clear_game_cache_on_play, + custom_race_characters, + purge_custom_race_bots, addons_list, addons_install, addons_remove, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 522d171..b628d38 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -43,6 +43,8 @@ export {}; if(cmd==="plugin:app|version") return "0.8.2"; 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};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.");w.__sched={...s};}return {schedule:w.__sched,supported:true};} 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}));} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 5ef7bf5..835d7db 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -801,6 +801,9 @@ const de: Partial> = { "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", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 59371c1..574aec9 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -85,6 +85,9 @@ const en = { "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", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index c8127c9..6152227 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -801,6 +801,9 @@ const es: Partial> = { "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", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index e8384bd..72eae25 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -801,6 +801,9 @@ const fr: Partial> = { "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", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index a4958ff..ac93859 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -88,6 +88,9 @@ const ru: Partial> = { "addons.doInstall": "Установить", "addons.doUpdate": "Обновить", "addons.doRemove": "Удалить", + "races.offCharacters": "Кастомные расы выключены: {players} персонаж(ей) игроков и {bots} бот(ов) кастомных рас не входят в мир, пока расы снова не включены (клиент без патча падал бы при виде их).", + "races.purgeBots": "Удалить ботов-компаньонов кастомных рас: {n}", + "races.purged": "Удалено ботов кастомных рас: {n}.", "realm.namesTitle": "Названия реалмов", "realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.", "realm.nameSave": "Сохранить", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 332fce4..693a463 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -86,6 +86,9 @@ const zh = { "addons.doInstall": "安装", "addons.doUpdate": "更新", "addons.doRemove": "移除", + "races.offCharacters": "自定义种族已关闭:{players} 个玩家角色和 {bots} 个自定义种族机器人在重新开启前不会进入世界(没有补丁的游戏客户端看到它们会崩溃)。", + "races.purgeBots": "删除 {n} 个自定义种族的伙伴机器人", + "races.purged": "已删除 {n} 个自定义种族机器人。", "realm.namesTitle": "服务器名称", "realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。", "realm.nameSave": "保存", diff --git a/src/lib/api.ts b/src/lib/api.ts index 29d87f5..c52de5a 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -58,6 +58,7 @@ export interface StatusView { } export type RealmMode = "coa" | "wildcard" | "reborn"; +export interface CustomRaceCharacters { players: number; companionBots: number; squidBots: number } export interface AddonView { id: string; name: string; description: Record; author: string; license: string; needs: string | null; repo: string; size: number; installed: boolean; updateAvailable: boolean; foreignFolders: string[]; bundled?: string | null } export interface RestartSchedule { enabled: boolean; time: string; warningMinutes: number } export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean } @@ -493,6 +494,8 @@ export const api = { realmProfiles: (id: string) => invoke("realm_profiles", { id }), realmSelect: (id: string, mode: RealmMode, restart: boolean) => invoke("realm_select", { id, mode, restart }), realmSimultaneous: (id: string, enabled: boolean) => invoke("realm_simultaneous", { id, enabled }), + customRaceCharacters: (id: string) => invoke("custom_race_characters", { id }), + purgeCustomRaceBots: (id: string) => invoke("purge_custom_race_bots", { id }), addonsList: (id: string) => invoke("addons_list", { id }), addonsInstall: (id: string, addon: string) => invoke("addons_install", { id, addon }), addonsRemove: (id: string, addon: string) => invoke("addons_remove", { id, addon }), diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index 710d797..9aa63ae 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -1,7 +1,7 @@ import { Fragment, useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from "react"; import { listen } from "@tauri-apps/api/event"; import { Bot, Clock, Flame, Gavel, Loader2, Plug, Puzzle, Scaling, Settings2, Snowflake, Sparkles, Swords, Users, type LucideProps } from "lucide-react"; -import { api, asUiError, type CustomRacesClientStatus, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; +import { api, asUiError, type CustomRacesClientStatus, CustomRaceCharacters, type CustomRacesProgress, type ModuleSetting, type ModuleView, type UiError } from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -94,6 +94,9 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId const [toggling, setToggling] = useState(null); const [changed, setChanged] = useState(false); const [racesPatchStatus, setRacesPatchStatus] = useState(null); + const [raceChars, setRaceChars] = useState(null); + const [purging, setPurging] = useState(false); + const [purged, setPurged] = useState(null); const [racesInstalling, setRacesInstalling] = useState(false); const [racesProgress, setRacesProgress] = useState(null); @@ -104,6 +107,7 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId } catch { // ignore } + setRaceChars(await api.customRaceCharacters(serverId).catch(() => null)); }, [serverId]); const [guard, setGuard] = useState(null); const [racesGuard, setRacesGuard] = useState(null); @@ -241,6 +245,18 @@ export function ModulesPage({ serverId, onChanged, onRegisterGuard }: { serverId {m.id === "custom-races" && (
+ {!m.enabled && raceChars && raceChars.players + raceChars.companionBots + raceChars.squidBots > 0 && ( +
+

{t("races.offCharacters", { players: raceChars.players, bots: raceChars.companionBots + raceChars.squidBots })}

+ {raceChars.companionBots > 0 && } +
+ )} + {purged !== null &&

{t("races.purged", { n: purged })}

}

{locale === "ru" ? "Установленная версия патча клиента: " : "Installed client patch version: "}{racesPatchStatus?.version ?? (locale === "ru" ? "не записана" : "not recorded")}

{racesInstalling && racesProgress ? (