diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2068d18..89e69b8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -517,3 +517,14 @@ The reference install classifies as **Healthy (customised)**: repack shape, bina hour, world thread stalled); (2) no active `coa.conf` (`CoA.Enable = 1`) because packages contain only `*.conf.dist`. Fixed: `clean-base` restores quiet templates, `assemble-tree` ships `coa.conf.dist`, and the Manager creates missing module `.conf` files from their `.dist` on install and before each start of a Manager-installed server. + +* **Game client download through the Manager** (idea 2026-10-01, researched, not built). The community PTR launcher + ("Conquest of AzerothCore" Electron app from `ConquestOfAzerothSetup-0.6.9.exe`) reads its client from + `https://launcher-api.coa-development.org/downloads/client/latest.json` (`{schema, version, publishedAt, files:[{path,size,sha256}]}`; + 200 files, 43.2 GiB: `Ascension.exe`, DLLs and ~40 big `Data/*.MPQ`) and fetches each file as the content-addressed object + `.../downloads/client/objects/` (Cloudflare, `Accept-Ranges`, immutable cache), 3 attempts, 30 s stall timeout, `.part` + files, sha256 check, resume via `Range`. The Manager already has everything needed (resumable verified downloads, free-space + check): a "Download game client" card with folder choice, overall progress, update check against `latest.json`, and the + existing safety rule (the Manager only ever writes its own client folder, never an existing one without asking). Open points: + ask the launcher/community maintainers before putting load on their API; DBCs live inside the MPQ patch archives (extracting + them would need an MPQ reader), so the server's `Data\dbc` still comes from our `base` package for now. diff --git a/src/dev/mock.ts b/src/dev/mock.ts index 80d310c..1700f49 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -31,6 +31,8 @@ export {}; 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==="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.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,download_bytes:6000000}; + if(cmd==="apply_update"){await new Promise((r: any)=>setTimeout(r,1500));(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},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_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."}]}; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 5a3cdc6..928a3b5 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -568,6 +568,16 @@ const de: Partial> = { "comp.despawnCount": "Wie viele abmelden", "comp.despawnHint": "Entlastet sofort: Jeder Bot online kostet Serverzeit. Sie bleiben gespeichert und kommen beim nächsten Start zurück, wenn die automatische Anmeldung an ist.", "comp.despawnSomeDone": "{n} Begleiter abgemeldet. Sie bleiben gespeichert.", + + // Server update button + "btn.update": "AKTUALISIEREN", + "btn.updating": "WIRD AKTUALISIERT …", + "btn.updateTo": "Auf {v} aktualisieren", + "overview.updateAvail": "Ein Server-Update ist verfügbar: {to} (du hast {from}).", + "overview.updateConflicts": "Einige Dateien wurden von dir geändert. Entscheide in den Einstellungen, was damit geschehen soll.", + "overview.openUpdates": "Updates öffnen", + "overview.updatingNote": "Update läuft: Der Server wird gestoppt, gesichert, aktualisiert und zur Prüfung erneut gestartet.", + "nav.updateDot": "Update verfügbar", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 1619c83..e8d687c 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -568,6 +568,16 @@ const en = { "comp.despawnCount": "How many to log out", "comp.despawnHint": "Eases the load right away: every online bot costs server time. They stay saved and return at the next start if automatic login is on.", "comp.despawnSomeDone": "{n} companions logged out. They stay saved.", + + // Server update button + "btn.update": "UPDATE", + "btn.updating": "UPDATING…", + "btn.updateTo": "Update to {v}", + "overview.updateAvail": "A server update is available: {to} (you have {from}).", + "overview.updateConflicts": "Some files were changed by you. Choose what to do with them in Settings.", + "overview.openUpdates": "Open updates", + "overview.updatingNote": "Updating: the server is stopped, backed up, updated and started again to check that it works.", + "nav.updateDot": "Update available", } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index e9fb022..1463619 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -568,6 +568,16 @@ const es: Partial> = { "comp.despawnCount": "Cuántos desconectar", "comp.despawnHint": "Alivia la carga al instante: cada bot conectado cuesta tiempo de servidor. Quedan guardados y vuelven en el próximo inicio si el inicio de sesión automático está activado.", "comp.despawnSomeDone": "{n} compañeros desconectados. Quedan guardados.", + + // Server update button + "btn.update": "ACTUALIZAR", + "btn.updating": "ACTUALIZANDO…", + "btn.updateTo": "Actualizar a {v}", + "overview.updateAvail": "Hay una actualización del servidor: {to} (tienes {from}).", + "overview.updateConflicts": "Algunos archivos los cambiaste tú. Decide en Ajustes qué hacer con ellos.", + "overview.openUpdates": "Abrir actualizaciones", + "overview.updatingNote": "Actualizando: el servidor se detiene, se respalda, se actualiza y se inicia de nuevo para comprobar que funciona.", + "nav.updateDot": "Actualización disponible", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index aafd1eb..1aacfa5 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -568,6 +568,16 @@ const fr: Partial> = { "comp.despawnCount": "Combien déconnecter", "comp.despawnHint": "Allège aussitôt la charge : chaque bot en ligne coûte du temps serveur. Ils restent enregistrés et reviennent au prochain démarrage si la connexion automatique est activée.", "comp.despawnSomeDone": "{n} compagnons déconnectés. Ils restent enregistrés.", + + // Server update button + "btn.update": "METTRE À JOUR", + "btn.updating": "MISE À JOUR…", + "btn.updateTo": "Mettre à jour vers {v}", + "overview.updateAvail": "Une mise à jour du serveur est disponible : {to} (vous avez {from}).", + "overview.updateConflicts": "Certains fichiers ont été modifiés par vous. Choisissez dans les Paramètres ce qu’il faut en faire.", + "overview.openUpdates": "Ouvrir les mises à jour", + "overview.updatingNote": "Mise à jour : le serveur est arrêté, sauvegardé, mis à jour puis relancé pour vérifier qu’il fonctionne.", + "nav.updateDot": "Mise à jour disponible", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 9335063..38f186e 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -568,6 +568,16 @@ const ru: Partial> = { "comp.despawnCount": "Сколько убрать", "comp.despawnHint": "Сразу снижает нагрузку: каждый бот в сети отнимает время сервера. Они остаются сохранёнными и вернутся при следующем запуске, если включён автоматический вход.", "comp.despawnSomeDone": "Убрано из игры компаньонов: {n}. Они остаются сохранёнными.", + + // Server update button + "btn.update": "ОБНОВИТЬ", + "btn.updating": "ОБНОВЛЯЮ…", + "btn.updateTo": "Обновить до {v}", + "overview.updateAvail": "Доступно обновление сервера: {to} (сейчас {from}).", + "overview.updateConflicts": "Часть файлов изменена вами. Решите, что с ними делать, в Настройках.", + "overview.openUpdates": "Открыть обновления", + "overview.updatingNote": "Идёт обновление: сервер останавливается, сохраняется резервная копия, затем он обновляется и запускается снова для проверки.", + "nav.updateDot": "Есть обновление", }; export default ru; diff --git a/src/lib/serverUpdate.ts b/src/lib/serverUpdate.ts new file mode 100644 index 0000000..7def550 --- /dev/null +++ b/src/lib/serverUpdate.ts @@ -0,0 +1,84 @@ +import { useSyncExternalStore } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { api, asUiError, type UpdatePreview } from "@/lib/api"; + +/** + * Server update status for the main screen and the navigation: checked when the app starts and every five minutes, + * and applied from the main button when nothing needs a decision (files the owner changed are decided in Settings). + */ +export interface ServerUpdateState { + preview: UpdatePreview | null; + available: boolean; + checking: boolean; + applying: boolean; + step: string | null; + percent: number; + error: string | null; +} + +const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null }; +const states = new Map(); +const listeners = new Set<() => void>(); +export const CHECK_EVERY_MS = 5 * 60 * 1000; + +const get = (id: string) => states.get(id) ?? EMPTY; +function set(id: string, next: Partial) { + states.set(id, { ...get(id), ...next }); + listeners.forEach((l) => l()); +} + +export async function checkServerUpdate(id: string): Promise { + const cur = get(id); + if (cur.applying || cur.checking) return; + set(id, { checking: true }); + try { + const p = await api.checkUpdate(id); + set(id, { preview: p, available: p.to_version !== (p.from_version ?? ""), error: null }); + } catch (e) { + // offline or no package published: keep what we knew and stay quiet + set(id, { error: asUiError(e).human.code }); + } finally { + set(id, { checking: false }); + } +} + +/** Check now and then every five minutes. Returns the function that stops it. */ +export function startServerUpdatePolling(id: string): () => void { + void checkServerUpdate(id); + const t = setInterval(() => void checkServerUpdate(id), CHECK_EVERY_MS); + return () => clearInterval(t); +} + +/** Apply the pending update when no file needs a decision. Resolves true on success. */ +export async function applyServerUpdate(id: string): Promise { + const p = get(id).preview; + if (!p || p.conflicts.length > 0 || get(id).applying) return false; + set(id, { applying: true, step: null, percent: 0, error: null }); + let un: (() => void) | undefined; + try { + un = await listen<{ step: string; percent: number }>("update-progress", (e) => set(id, { step: e.payload.step, percent: e.payload.percent })); + } catch { + /* progress is optional */ + } + try { + await api.applyUpdate(id, {}); + return true; + } catch (e) { + set(id, { error: asUiError(e).human.code }); + return false; + } finally { + un?.(); + set(id, { applying: false }); + void checkServerUpdate(id); + } +} + +export function useServerUpdate(id: string): ServerUpdateState { + return useSyncExternalStore( + (l) => { + listeners.add(l); + return () => listeners.delete(l); + }, + () => get(id), + ); +} diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index a84962b..73a393f 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -3,6 +3,7 @@ import { Loader2 } from "lucide-react"; import { api, asUiError, type ClientInfo, type Human, type Performance, type Population, type ServerSummary, type ServiceStatus, type StatusView } from "@/lib/api"; import { cn, formatUptime } from "@/lib/utils"; import { useHuman, useT } from "@/i18n"; +import { applyServerUpdate, useServerUpdate } from "@/lib/serverUpdate"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -58,7 +59,7 @@ function Row({ label, s }: { label: string; s: ServiceStatus }) { ); } -export function Overview({ server, onForget }: { server: ServerSummary; onForget: () => Promise }) { +export function Overview({ server, onForget, onOpenUpdates }: { server: ServerSummary; onForget: () => Promise; onOpenUpdates: () => void }) { const t = useT(); const human = useHuman(); const [status, setStatus] = useState(null); @@ -69,6 +70,8 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget const [client, setClient] = useState(null); const [playing, setPlaying] = useState(false); const [perf, setPerf] = useState(null); + const upd = useServerUpdate(server.id); + const needsDecision = (upd.preview?.conflicts.length ?? 0) > 0; const [startBots, setStartBots] = useState(undefined); useEffect(() => { @@ -236,6 +239,17 @@ export function Overview({ server, onForget }: { server: ServerSummary; onForget {transitioning && } {t("btn.stop")} + ) : upd.available ? ( + ) : ( )} {running && ( - )} + {running && upd.available && ( + + )} {anyUp && !running && ( ))} @@ -87,7 +95,7 @@ export function Shell(props: {
{page === "overview" ? ( - props.onForget(server.id)} /> + props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} /> ) : page === "bots" || page === "server" ? ( ) : page === "console" ? (