diff --git a/crates/coa-core/src/backup.rs b/crates/coa-core/src/backup.rs index c3094ea..41be4b6 100644 --- a/crates/coa-core/src/backup.rs +++ b/crates/coa-core/src/backup.rs @@ -177,6 +177,14 @@ pub fn with_database(root: &Path, f: impl FnOnce(&Db) -> Result) -> Result result } +/// Run `f` only if the database is already up; `None` (and nothing started) otherwise. +pub fn with_running_database(root: &Path, f: impl FnOnce(&Db) -> Result) -> Result> { + let db = Db::from_repack(root, Account::Admin)?; + let observed = process::observe(root, &read_ports(root)); + if observed.mysql.state != ServiceState::Running || !db.ping() { return Ok(None); } + f(&db).map(Some) +} + fn wanted_databases(kind: Kind) -> &'static [&'static str] { match kind { Kind::Quick | Kind::Database => &["characters", "auth"], diff --git a/crates/coa-core/src/install.rs b/crates/coa-core/src/install.rs index 2e88aa4..2d88ee2 100644 --- a/crates/coa-core/src/install.rs +++ b/crates/coa-core/src/install.rs @@ -183,7 +183,7 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> { let started = driver::run(root, Verb::StartMysql)?; if !started.ok { - return Err(Error::Invalid(started.human.map(|h| h.message.to_string()).unwrap_or_else(|| "The database could not be started.".into()))); + return Err(Error::Invalid(format!("The database could not be started. {}", driver::startup_failure(root, &started)))); } let result = (|| -> Result<()> { let db = Db::from_repack(root, Account::Admin)?; @@ -210,8 +210,14 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> { } Ok(()) })(); - let _ = driver::run(root, Verb::StopAll); + let stopped = driver::run(root, Verb::StopAll); result?; + // A database that keeps running locks its files, and the folder could not be moved into place afterwards. + match stopped { + Ok(out) if out.ok => {} + Ok(out) => return Err(Error::Invalid(format!("The database could not be stopped after preparing it. {}", driver::startup_failure(root, &out)))), + Err(e) => return Err(e), + } fs::remove_file(&boot)?; Ok(()) } @@ -250,7 +256,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result { if staging_root.join(MARKER).is_file() { fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created } else { - return Err(Error::Invalid(format!("{} already exists and was not created by the Manager.", staging_root.display()))); + return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display()))); } } fs::create_dir_all(&staging_root)?; @@ -268,9 +274,8 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result { } Ok(()) })?; - fs::remove_file(staging_root.join(MARKER))?; - - // 4. Commit: the only moment the destination changes. + // 4. Commit: the only moment the destination changes. The marker stays until everything is done, so an + // unfinished install can always be recognised as ours (and cleaned up), wherever it stopped. say("Finishing", 95, None); if dest.exists() { fs::remove_dir(&dest)?; // only succeeds for an empty folder (preflight verified) @@ -288,15 +293,24 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result { } let md = MetaDir::create(&dest, &meta)?; fsx::atomic_write(&md.root.join("manifests").join("base.json"), &manifest_bytes)?; + // Complete from here on: the marker goes just before the server is listed. + fs::remove_file(dest.join(MARKER))?; p.registry.register(&meta.id, &dest)?; say("Ready", 100, None); Ok(Installed { id: meta.id, path: dest.to_string_lossy().into_owned(), version: m.version.clone() }) })(); - if result.is_err() && staging_root.join(MARKER).exists() { - // Unfinished work of ours; the destination was never touched. - let _ = driver::run(&staging_root, Verb::StopAll); - let _ = fs::remove_dir_all(&staging_root); + if result.is_err() { + if staging_root.join(MARKER).exists() { + // Unfinished work of ours; the destination was never touched. + let _ = driver::run(&staging_root, Verb::StopAll); + let _ = fs::remove_dir_all(&staging_root); + } else if dest.join(MARKER).is_file() { + // Failed after the folder was moved into place. The destination was empty or absent before (preflight), + // so what carries our marker is only our unfinished install. + let _ = driver::run(&dest, Verb::StopAll); + let _ = fs::remove_dir_all(&dest); + } } result } diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index 7ff06ea..26a9986 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -259,14 +259,29 @@ pub struct Preview { pub migrations: usize, pub pending_migrations: usize, pub download_bytes: u64, + /// False when the pending SQL was not counted (database stopped during a background check, or an error). + pub database_checked: bool, /// Why the database could not be inspected. The check still answers about the files; applying the update starts /// the database itself and reports its own failure. #[serde(skip_serializing_if = "Option::is_none")] pub database_check_error: Option, } +/// Whether looking for an update may start the database to count pending SQL. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DatabaseAccess { + /// An explicit check: start the database if it is stopped (and stop it again afterwards). + Start, + /// The background check that repeats every few minutes must not start and stop MySQL on a stopped server. + OnlyIfRunning, +} + /// Describe the update; a managed launcher may need a one-time authenticated payload check. pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &str, resolutions: &BTreeMap) -> Result { + preview_with(root, meta, source, trusted_key, resolutions, DatabaseAccess::Start) +} + +pub fn preview_with(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &str, resolutions: &BTreeMap, access: DatabaseAccess) -> Result { let meta_dir = crate::registry::metadata_dir_for(root)?; let _lock = operation_lock(&meta_dir)?; ensure_recovered(&meta_dir)?; @@ -283,11 +298,12 @@ pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &s } // Counting pending SQL needs the database. If it cannot be started the files can still be compared, so report // that instead of failing the whole check. - let (pending_migrations, database_check_error) = match (RepackEnv { root, meta_dir: &meta_dir }).pending_migrations(&m) { - Ok(count) => (count, None), + let (pending_migrations, database_checked, database_check_error) = match (RepackEnv { root, meta_dir: &meta_dir }).pending_migrations_with(&m, access) { + Ok(Some(count)) => (count, true, None), + Ok(None) => (m.migrations.len(), false, None), Err(error) => { tracing::warn!(%error, "update check: the database could not be inspected"); - (m.migrations.len(), Some(error.to_string())) + (m.migrations.len(), false, Some(error.to_string())) } }; Ok(Preview { @@ -298,6 +314,7 @@ pub fn preview(root: &Path, meta: &InstallMeta, source: &Source, trusted_key: &s migrations: m.migrations.len(), pending_migrations, download_bytes: m.archive.as_ref().map(|a| a.parts.iter().map(|p| p.size).sum()).unwrap_or(0), + database_checked, database_check_error, }) } @@ -748,8 +765,13 @@ pub struct RepackEnv<'a> { impl RepackEnv<'_> { pub fn pending_migrations(&self, manifest: &Manifest) -> Result { - if manifest.migrations.is_empty() { return Ok(0); } - crate::backup::with_database(self.root, |db| { + Ok(self.pending_migrations_with(manifest, DatabaseAccess::Start)?.unwrap_or(0)) + } + + /// `None` when the database is not running and `access` forbids starting it. + pub fn pending_migrations_with(&self, manifest: &Manifest, access: DatabaseAccess) -> Result> { + if manifest.migrations.is_empty() { return Ok(Some(0)); } + let count = |db: &crate::db::Db| -> Result { let realms = crate::realms::state(self.root)?; let mut modes = vec![realms.active]; if realms.wildcard_created { modes.push(if realms.active == crate::realms::Mode::Coa { crate::realms::Mode::Wildcard } else { crate::realms::Mode::Coa }); } @@ -759,7 +781,11 @@ impl RepackEnv<'_> { count += crate::migrations::pending_count(&db.clone().for_realm(mode), &list)?; } Ok(count) - }) + }; + match access { + DatabaseAccess::Start => crate::backup::with_database(self.root, count).map(Some), + DatabaseAccess::OnlyIfRunning => crate::backup::with_running_database(self.root, count), + } } pub(crate) fn verify_recovery_point(&self, point: &crate::backup::RecoveryPoint) -> Result<()> { if point.kind != crate::backup::Kind::Full || !["characters", "auth", "world", "configs"].iter().all(|name| point.components.iter().any(|c| c.name == *name)) { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3592012..08c3133 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -684,12 +684,14 @@ fn install_meta(root: &std::path::Path) -> Result<(PathBuf, InstallMeta)> { } #[tauri::command] -async fn check_update(state: State<'_, AppState>, id: String, source: Option) -> std::result::Result { +async fn check_update(state: State<'_, AppState>, id: String, source: Option, background: Option) -> std::result::Result { let root = path_of(&state, &id)?; let src = update_source(source); + // The check that repeats every few minutes must not start and stop the database of a stopped server. + let access = if background.unwrap_or(false) { update::DatabaseAccess::OnlyIfRunning } else { update::DatabaseAccess::Start }; blocking(move || { let (_, meta) = install_meta(&root)?; - update::preview(&root, &meta, &src, coa_core::signing::EMBEDDED_PUBLIC_KEY, &Default::default()) + update::preview_with(&root, &meta, &src, coa_core::signing::EMBEDDED_PUBLIC_KEY, &Default::default(), access) }) .await } diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 7fc74bd..fc9f56b 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -20,7 +20,7 @@ const de: Partial> = { "nav.overview": "Übersicht", "nav.bots": "Bots", "nav.server": "Server", - "nav.players": "Spieler", + "nav.players": "Konten", "nav.friends": "Mit Freunden spielen", "nav.backups": "Sicherungen", "nav.console": "Konsole", @@ -32,7 +32,7 @@ const de: Partial> = { "q.overview": "Läuft mein Server?", "q.bots": "Wie sind meine Bots eingestellt?", "q.server": "Wie verhält sich mein Server?", - "q.players": "Wer spielt gerade?", + "q.players": "Wer kann sich im Spiel anmelden?", "q.friends": "Wie kann mein Freund beitreten?", "q.backups": "Sind meine Daten sicher?", "q.console": "Was macht der Server gerade?", @@ -167,7 +167,7 @@ const de: Partial> = { "install.open": "MEINEN SERVER ÖFFNEN", // Players - "players.title": "Spieler", + "players.title": "Konten", "players.createTitle": "Erstelle dein Konto", "players.createText": "Das sind der Name und das Passwort, mit denen du dich im Spiel anmeldest.", "players.startFirst": "Starte zuerst den Server – Konten werden erstellt, solange er läuft.", @@ -827,6 +827,11 @@ const de: Partial> = { "set.searchAll": "Alle Einstellungen nach Name oder Beschreibung durchsuchen…", "set.search": "Einstellungen durchsuchen…", "upd.current": "Du bist auf dem neuesten Stand (Version {v}).", + "remove.title": "Diesen Server aus dem Manager entfernen", + "remove.text": "Der Manager zeigt diesen Server nicht mehr an. Es werden keine Dateien, Datenbanken oder Sicherungen gelöscht; den Ordner kannst du später über „Weiteren Server verwalten“ wieder hinzufügen.", + "remove.button": "Aus dem Manager entfernen", + "remove.stopFirst": "Halte zuerst den Server an.", + "remove.confirm": "Diesen Server aus dem Manager entfernen?\n\n{path}\n\nEs werden keine Dateien gelöscht.", "upd.dbUnchecked": "Die Datenbank konnte nicht geprüft werden, daher sind offene Datenbankänderungen unbekannt: {why}", "client.job.checking": "Client wird geprüft…", "client.job.updating": "Client wird aktualisiert", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index af81ef5..c293a94 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -51,7 +51,7 @@ const en = { "nav.overview": "Overview", "nav.bots": "Bots", "nav.server": "Server", - "nav.players": "Players", + "nav.players": "Accounts", "nav.friends": "Play with Friends", "nav.backups": "Backups", "nav.console": "Console", @@ -63,7 +63,7 @@ const en = { "q.overview": "Is my server running?", "q.bots": "How are my bots configured?", "q.server": "How does my server behave?", - "q.players": "Who is playing right now?", + "q.players": "Who can log in to the game?", "q.friends": "How can my friend join?", "q.backups": "Is my data safe?", "q.console": "What is the server doing?", @@ -200,7 +200,7 @@ const en = { "install.open": "OPEN MY SERVER", // Players - "players.title": "Players", + "players.title": "Accounts", "players.createTitle": "Create your account", "players.createText": "This is the name and password you use to log in to the game.", "players.startFirst": "Start the server first — accounts are created while it is running.", @@ -848,6 +848,11 @@ const en = { "set.searchAll": "Search all settings by name or description…", "set.search": "Search settings…", "upd.current": "You are up to date (version {v}).", + "remove.title": "Remove this server from the Manager", + "remove.text": "The Manager stops listing this server. No files, databases or backups are deleted, and you can add the folder again later with “Manage another server”.", + "remove.button": "Remove from Manager", + "remove.stopFirst": "Stop the server first.", + "remove.confirm": "Remove this server from the Manager?\n\n{path}\n\nNo files are deleted.", "upd.dbUnchecked": "The database could not be checked, so pending database changes are unknown: {why}", "client.job.checking": "Checking the client…", "client.job.updating": "Updating the client", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 4336f40..d6432ba 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -20,7 +20,7 @@ const es: Partial> = { "nav.overview": "Resumen", "nav.bots": "Bots", "nav.server": "Servidor", - "nav.players": "Jugadores", + "nav.players": "Cuentas", "nav.friends": "Jugar con amigos", "nav.backups": "Copias de seguridad", "nav.console": "Consola", @@ -32,7 +32,7 @@ const es: Partial> = { "q.overview": "¿Está funcionando mi servidor?", "q.bots": "¿Cómo están configurados mis bots?", "q.server": "¿Cómo se comporta mi servidor?", - "q.players": "¿Quién está jugando ahora?", + "q.players": "¿Quién puede entrar al juego?", "q.friends": "¿Cómo puede unirse mi amigo?", "q.backups": "¿Están seguros mis datos?", "q.console": "¿Qué está haciendo el servidor?", @@ -167,7 +167,7 @@ const es: Partial> = { "install.open": "ABRIR MI SERVIDOR", // Players - "players.title": "Jugadores", + "players.title": "Cuentas", "players.createTitle": "Crea tu cuenta", "players.createText": "Este es el nombre y la contraseña con los que inicias sesión en el juego.", "players.startFirst": "Inicia primero el servidor: las cuentas se crean mientras está en marcha.", @@ -827,6 +827,11 @@ const es: Partial> = { "set.searchAll": "Buscar en todos los ajustes por nombre o descripción…", "set.search": "Buscar ajustes…", "upd.current": "Estás al día (versión {v}).", + "remove.title": "Quitar este servidor del Manager", + "remove.text": "El Manager deja de mostrar este servidor. No se borran archivos, bases de datos ni copias de seguridad, y puedes volver a añadir la carpeta con «Gestionar otro servidor».", + "remove.button": "Quitar del Manager", + "remove.stopFirst": "Detén primero el servidor.", + "remove.confirm": "¿Quitar este servidor del Manager?\n\n{path}\n\nNo se borra ningún archivo.", "upd.dbUnchecked": "No se pudo comprobar la base de datos, así que se desconocen los cambios pendientes: {why}", "client.job.checking": "Comprobando el cliente…", "client.job.updating": "Actualizando el cliente", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 83b52a2..0aa1d4e 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -20,7 +20,7 @@ const fr: Partial> = { "nav.overview": "Vue d’ensemble", "nav.bots": "Bots", "nav.server": "Serveur", - "nav.players": "Joueurs", + "nav.players": "Comptes", "nav.friends": "Jouer avec des amis", "nav.backups": "Sauvegardes", "nav.console": "Console", @@ -32,7 +32,7 @@ const fr: Partial> = { "q.overview": "Mon serveur fonctionne-t-il ?", "q.bots": "Comment mes bots sont-ils configurés ?", "q.server": "Comment se comporte mon serveur ?", - "q.players": "Qui joue en ce moment ?", + "q.players": "Qui peut se connecter au jeu ?", "q.friends": "Comment mon ami peut-il se connecter ?", "q.backups": "Mes données sont-elles en sécurité ?", "q.console": "Que fait le serveur ?", @@ -167,7 +167,7 @@ const fr: Partial> = { "install.open": "OUVRIR MON SERVEUR", // Players - "players.title": "Joueurs", + "players.title": "Comptes", "players.createTitle": "Créez votre compte", "players.createText": "C’est le nom et le mot de passe que vous utilisez pour vous connecter au jeu.", "players.startFirst": "Démarrez d’abord le serveur : les comptes sont créés pendant qu’il fonctionne.", @@ -827,6 +827,11 @@ const fr: Partial> = { "set.searchAll": "Rechercher dans tous les réglages par nom ou description…", "set.search": "Rechercher un réglage…", "upd.current": "Vous êtes à jour (version {v}).", + "remove.title": "Retirer ce serveur du Manager", + "remove.text": "Le Manager n’affiche plus ce serveur. Aucun fichier, base de données ni sauvegarde n’est supprimé, et vous pourrez rajouter le dossier plus tard avec « Gérer un autre serveur ».", + "remove.button": "Retirer du Manager", + "remove.stopFirst": "Arrêtez d’abord le serveur.", + "remove.confirm": "Retirer ce serveur du Manager ?\n\n{path}\n\nAucun fichier n’est supprimé.", "upd.dbUnchecked": "La base de données n'a pas pu être vérifiée ; les modifications en attente sont donc inconnues : {why}", "client.job.checking": "Vérification du client…", "client.job.updating": "Mise à jour du client", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index a6ae392..8a23d89 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -51,7 +51,7 @@ const ru: Partial> = { "nav.overview": "Обзор", "nav.bots": "Боты", "nav.server": "Сервер", - "nav.players": "Игроки", + "nav.players": "Аккаунты", "nav.friends": "Игра с друзьями", "nav.backups": "Резервные копии", "nav.console": "Консоль", @@ -63,7 +63,7 @@ const ru: Partial> = { "q.overview": "Мой сервер работает?", "q.bots": "Как настроены мои боты?", "q.server": "Как ведёт себя мой сервер?", - "q.players": "Кто сейчас играет?", + "q.players": "Кто может войти в игру?", "q.friends": "Как подключиться другу?", "q.backups": "Мои данные в безопасности?", "q.console": "Что делает сервер?", @@ -198,7 +198,7 @@ const ru: Partial> = { "install.open": "ОТКРЫТЬ МОЙ СЕРВЕР", // Players - "players.title": "Игроки", + "players.title": "Аккаунты", "players.createTitle": "Создайте свою учётную запись", "players.createText": "Это имя и пароль, с которыми вы входите в игру.", "players.startFirst": "Сначала запустите сервер — учётные записи создаются, пока он работает.", @@ -846,6 +846,11 @@ const ru: Partial> = { "set.searchAll": "Поиск по всем настройкам: название или описание…", "set.search": "Поиск по настройкам…", "upd.current": "У вас последняя версия ({v}).", + "remove.title": "Убрать сервер из Manager", + "remove.text": "Manager перестанет показывать этот сервер. Файлы, базы данных и резервные копии не удаляются, папку можно добавить снова через «Управлять другим сервером».", + "remove.button": "Убрать из Manager", + "remove.stopFirst": "Сначала остановите сервер.", + "remove.confirm": "Убрать этот сервер из Manager?\n\n{path}\n\nФайлы не удаляются.", "upd.dbUnchecked": "Не удалось проверить базу данных, поэтому неизвестно, нужны ли ей изменения: {why}", "client.job.checking": "Проверка клиента…", "client.job.updating": "Обновление клиента", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 9b21111..5386709 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -32,7 +32,7 @@ const zh = { "nav.overview": "概览", "nav.bots": "机器人", "nav.server": "服务器", - "nav.players": "玩家", + "nav.players": "账号", "nav.friends": "好友联机", "nav.backups": "备份", "nav.console": "控制台", @@ -44,7 +44,7 @@ const zh = { "q.overview": "服务器当前是否正在运行?", "q.bots": "机器人目前是如何配置的?", "q.server": "服务器机制与规则是如何运行的?", - "q.players": "当前有哪些玩家在线?", + "q.players": "谁可以登录游戏?", "q.friends": "好友如何加入我的服务器?", "q.backups": "我的数据是否安全?", "q.console": "服务器正在输出什么日志?", @@ -179,7 +179,7 @@ const zh = { "install.open": "打开我的服务器", // Players - "players.title": "玩家", + "players.title": "账号", "players.createTitle": "创建游戏账号", "players.createText": "用于登录游戏的账号名称和密码。", "players.startFirst": "请先启动服务器 —— 账号需要在服务器运行时创建。", @@ -827,6 +827,11 @@ const zh = { "set.searchAll": "按名称或描述搜索全部设置…", "set.search": "搜索设置…", "upd.current": "当前已是最新版本 ({v})。", + "remove.title": "从 Manager 中移除此服务器", + "remove.text": "Manager 将不再列出此服务器。不会删除任何文件、数据库或备份,之后可通过“管理其他服务器”重新添加该文件夹。", + "remove.button": "从 Manager 中移除", + "remove.stopFirst": "请先停止服务器。", + "remove.confirm": "要从 Manager 中移除此服务器吗?\n\n{path}\n\n不会删除任何文件。", "upd.dbUnchecked": "无法检查数据库,因此不清楚是否有待应用的数据库更改:{why}", "client.job.checking": "正在检查游戏客户端…", "client.job.updating": "正在更新游戏客户端", diff --git a/src/lib/api.ts b/src/lib/api.ts index 5d2ddb4..0713057 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -285,6 +285,8 @@ export interface UpdatePreview { migrations: number; pending_migrations?: number; download_bytes: number; + /** False when pending database changes were not counted (stopped server during a background check, or an error). */ + database_checked?: boolean; /** Set when the database could not be inspected; the file comparison is still valid. */ database_check_error?: string; } @@ -451,7 +453,8 @@ export const api = { cancelInstall: () => invoke("cancel_install"), createAccount: (id: string, username: string, password: string, administrator: boolean) => invoke("create_account", { id, username, password, administrator }), - checkUpdate: (id: string, source?: string) => invoke("check_update", { id, source: source ?? null }), + /** `background`: the repeating check, which must not start the database of a stopped server. */ + checkUpdate: (id: string, source?: string, background?: boolean) => invoke("check_update", { id, source: source ?? null, background: background ?? false }), pendingUpdate: (id: string) => invoke("pending_update", { id }), applyUpdate: (id: string, resolutions: Record, source?: string) => invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }), diff --git a/src/lib/serverUpdate.ts b/src/lib/serverUpdate.ts index cc74040..eeab33e 100644 --- a/src/lib/serverUpdate.ts +++ b/src/lib/serverUpdate.ts @@ -34,12 +34,12 @@ function set(id: string, next: Partial) { listeners.forEach((l) => l()); } -export async function checkServerUpdate(id: string): Promise { +export async function checkServerUpdate(id: string, background = false): Promise { const cur = get(id); if (cur.applying || cur.checking) return; set(id, { checking: true }); try { - const p = await api.checkUpdate(id); + const p = await api.checkUpdate(id, undefined, background); set(id, { preview: p, available: !isUpdateCurrent(p), error: null }); } catch (e) { // A cached offer is no longer safe after an update or failed recheck. @@ -51,8 +51,8 @@ export async function checkServerUpdate(id: string): Promise { /** 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); + void checkServerUpdate(id, true); + const t = setInterval(() => void checkServerUpdate(id, true), CHECK_EVERY_MS); return () => clearInterval(t); } diff --git a/src/lib/serverUpdateStatus.ts b/src/lib/serverUpdateStatus.ts index dd5a76d..f32b52c 100644 --- a/src/lib/serverUpdateStatus.ts +++ b/src/lib/serverUpdateStatus.ts @@ -3,5 +3,5 @@ import type { UpdatePreview } from "./api"; export function isUpdateCurrent(preview: UpdatePreview): boolean { return preview.from_version === preview.to_version && preview.items.every((item) => item.action === "skip") - && (preview.database_check_error !== undefined || (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0); + && (preview.database_check_error !== undefined || preview.database_checked === false || (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0); } diff --git a/src/screens/InstallServer.tsx b/src/screens/InstallServer.tsx index 32a9c42..c9f92f8 100644 --- a/src/screens/InstallServer.tsx +++ b/src/screens/InstallServer.tsx @@ -158,9 +158,14 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;

{error.human.code === "unknown" ? t("install.failedTitle") : human(error.human).title}

{error.human.code === "unknown" ? error.technical : human(error.human).message}

{t("install.nothingInstalled")}

- +
+ + +
{showDetails &&
{error.technical}
} )} diff --git a/src/screens/RemoveServerCard.tsx b/src/screens/RemoveServerCard.tsx new file mode 100644 index 0000000..f8edfcc --- /dev/null +++ b/src/screens/RemoveServerCard.tsx @@ -0,0 +1,39 @@ +import { useEffect, useState } from "react"; +import { api, asUiError } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { useT } from "@/i18n"; + +/** Takes a server out of the Manager's list. Nothing on disk is deleted, so the folder can be added again later. */ +export function RemoveServerCard({ serverId, path, onForget }: { serverId: string; path: string; onForget: () => Promise }) { + const t = useT(); + const [running, setRunning] = useState(false); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let active = true; + void api.status(serverId).then((s) => { + if (!active) return; + const all = [s.observed.mysql, s.observed.auth, s.observed.world, ...(s.observed.secondary_world ? [s.observed.secondary_world] : [])]; + setRunning(all.some((x) => x.state === "running" || x.state === "starting" || x.state === "stopping")); + }).catch(() => { /* an unreadable status must not hide the button */ }); + return () => { active = false; }; + }, [serverId]); + + async function remove() { + if (!window.confirm(t("remove.confirm", { path }))) return; + setBusy(true); setError(null); + try { await onForget(); } + catch (e) { setError(asUiError(e).technical); setBusy(false); } + } + + return +

{t("remove.title")}

+

{t("remove.text")}

+

{path}

+ + {running &&

{t("remove.stopFirst")}

} + {error &&

{error}

} +
; +} diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx index 60ab99a..f613a13 100644 --- a/src/screens/SettingsHome.tsx +++ b/src/screens/SettingsHome.tsx @@ -9,6 +9,7 @@ import { Card } from "@/components/ui/card"; import { ClientCard } from "@/screens/ClientCard"; import { DiagnosticsCard } from "@/screens/DiagnosticsCard"; import { AboutCard } from "@/screens/AboutCard"; +import { RemoveServerCard } from "@/screens/RemoveServerCard"; import { hasKey, useHuman, useI18n, type Key } from "@/i18n"; import { LanguagePicker } from "@/components/LanguagePicker"; import { RealmStartupSettings } from "@/screens/RealmStartupSettings"; @@ -18,7 +19,7 @@ function mb(bytes: number) { return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`; } -export function SettingsHome({ serverId }: { serverId: string }) { +export function SettingsHome({ serverId, path, onForget }: { serverId: string; path: string; onForget: () => Promise }) { const { t } = useI18n(); const upd = useServerUpdate(serverId); const human = useHuman(); @@ -197,9 +198,14 @@ export function SettingsHome({ serverId }: { serverId: string }) { {done && pendingChecked && !pendingStateError &&

{done}

} {error && ( -

- {error.human.code === "unknown" ? error.technical : human(error.human).message} -

+
+

+ {error.human.code === "unknown" ? error.technical : human(error.human).message} +

+ +
)} {preview?.database_check_error && ( @@ -264,6 +270,8 @@ export function SettingsHome({ serverId }: { serverId: string }) { )} + + ); } diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index aa4a804..4a6b134 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -139,7 +139,7 @@ export function Shell(props: { ) : page === "friends" ? ( ) : page === "settings" ? ( - + props.onForget(server.id)} /> ) : page === "players" ? ( ) : page === "backups" ? (