diff --git a/changelog.d/20261115-scheduled-restart.md b/changelog.d/20261115-scheduled-restart.md new file mode 100644 index 0000000..eca0af3 --- /dev/null +++ b/changelog.d/20261115-scheduled-restart.md @@ -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. diff --git a/crates/coa-core/src/launcher/mod.rs b/crates/coa-core/src/launcher/mod.rs index 786583c..a400f22 100644 --- a/crates/coa-core/src/launcher/mod.rs +++ b/crates/coa-core/src/launcher/mod.rs @@ -14,6 +14,7 @@ pub mod ops; pub mod relay; pub mod render; +pub mod schedule; pub mod services; pub mod settings; pub mod spawn; diff --git a/crates/coa-core/src/launcher/schedule.rs b/crates/coa-core/src/launcher/schedule.rs new file mode 100644 index 0000000..97eb9d6 --- /dev/null +++ b/crates/coa-core/src/launcher/schedule.rs @@ -0,0 +1,162 @@ +//! 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::{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, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +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, +} + +impl Default for RestartSchedule { + fn default() -> Self { + Self { + enabled: false, + time: "05:00".into(), + warning_minutes: 5, + } + } +} + +impl RestartSchedule { + fn at(&self) -> Option { + NaiveTime::parse_from_str(self.time.trim(), "%H:%M").ok() + } + + fn validate(&self) -> Result<()> { + if self.at().is_none() { + return Err(Error::Invalid("The restart time must be HH:MM, for example 05:00.".into())); + } + if !(1..=60).contains(&self.warning_minutes) { + return Err(Error::Invalid("The restart warning must be 1 to 60 minutes.".into())); + } + Ok(()) + } + + /// The scheduled moment of `now`'s day, when a 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(&self, now: NaiveDateTime, started: NaiveDateTime) -> Option { + if !self.enabled { + return None; + } + let moment = now.date().and_time(self.at()?); + let late = now.signed_duration_since(moment).to_std().ok()?; + (late <= LATE && started < moment).then_some(moment) + } +} + +/// The folder whose schedule a world follows: an extra world (`/.realms/`) 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 { + let mut schedule = schedule.clone(); + schedule.time = schedule.time.trim().to_string(); + if schedule.enabled { + schedule.validate()?; + } else if schedule.at().is_none() { + schedule.time = RestartSchedule::default().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 }; + 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 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 }; + assert!(save(d.path(), &bad).is_err()); + let quiet = RestartSchedule { enabled: true, time: "05:00".into(), warning_minutes: 0 }; + assert!(save(d.path(), &quiet).is_err()); + let good = RestartSchedule { enabled: true, time: " 04:30 ".into(), warning_minutes: 10 }; + assert_eq!(save(d.path(), &good).unwrap().time, "04:30"); + let extra = d.path().join(".realms/secondary"); + std::fs::create_dir_all(&extra).unwrap(); + assert!(load(&extra).enabled); + 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())); + } +} diff --git a/crates/coa-core/src/launcher/world.rs b/crates/coa-core/src/launcher/world.rs index 5d495aa..12206d5 100644 --- a/crates/coa-core/src/launcher/world.rs +++ b/crates/coa-core/src/launcher/world.rs @@ -13,7 +13,7 @@ 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::{settings::Settings, squid, state}; +use crate::launcher::{schedule, settings::Settings, squid, state}; fn stop_relay_flag(root: &Path) -> std::path::PathBuf { state::dir(root).join("stop-relay") @@ -169,24 +169,70 @@ fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result { } /// 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). -pub fn watch_world(root: &Path, launcher: Option<&Path>, log: Progress) -> Result<()> { +/// `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 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 mut relay: Option = None; - while world.try_wait().is_none() { - 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; + loop { + 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 = 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 plan.due(schedule::now(), started).is_some() { + let seconds = plan.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.", plan.warning_minutes)); + } + Err(e) => log(&format!("Scheduled restart could not be requested ({e}); retrying.")), + } + } + } + } + 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; } - std::thread::sleep(Duration::from_secs(2)); + schedule::clear_under_way(root); + break; } std::fs::write(stop_relay_flag(root), b"")?; if let Some(r) = relay { diff --git a/crates/coa-launcher/src/main.rs b/crates/coa-launcher/src/main.rs index 4c606cd..031ea0e 100644 --- a/crates/coa-launcher/src/main.rs +++ b/crates/coa-launcher/src/main.rs @@ -100,7 +100,7 @@ fn run(args: Args) -> Result<(), 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), &|m| say(m)).map_err(e); + 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" => { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 39a1b1d..c84c637 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -350,6 +350,8 @@ struct StatusView { observed: Observed, busy: bool, path_exists: bool, + /// A scheduled restart is under way: a world that is down for a few minutes did not crash. + scheduled_restart: bool, } /// Where the Manager keeps its own state (server list, logs). `%LOCALAPPDATA%` on Windows, the XDG data folder elsewhere. @@ -548,9 +550,12 @@ async fn server_status( let root = path_of(&state, &id)?; let busy = state.busy.lock().map(|b| b.contains(&id)).unwrap_or(false); let path_exists = root.is_dir(); - let observed = tauri::async_runtime::spawn_blocking(move || { + let (observed, scheduled_restart) = tauri::async_runtime::spawn_blocking(move || { let ports = layout::read_ports(&root); - process::observe(&root, &ports) + ( + process::observe(&root, &ports), + coa_core::launcher::schedule::under_way(&root), + ) }) .await .map_err(|e| Error::Invalid(e.to_string()))?; @@ -558,6 +563,7 @@ async fn server_status( observed, busy, path_exists, + scheduled_restart, }) } @@ -1238,6 +1244,46 @@ async fn realm_select( result } +#[derive(serde::Serialize)] +struct RestartScheduleView { + schedule: coa_core::launcher::schedule::RestartSchedule, + /// The server ships the Rust world supervisor that carries out the schedule. + supported: bool, +} + +#[tauri::command] +async fn restart_schedule( + state: State<'_, AppState>, + id: String, +) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + Ok(RestartScheduleView { + schedule: coa_core::launcher::schedule::load(&root), + supported: root.join("Scripts/coa-launcher.exe").is_file(), + }) + }) + .await +} + +/// Restart the world every day at the owner's local time; the running supervisor reads it within a minute. +#[tauri::command] +async fn restart_schedule_save( + state: State<'_, AppState>, + id: String, + schedule: coa_core::launcher::schedule::RestartSchedule, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + Ok(RestartScheduleView { + schedule: coa_core::launcher::schedule::save(&root, &schedule)?, + supported: root.join("Scripts/coa-launcher.exe").is_file(), + }) + }) + .await +} + #[tauri::command] async fn mysql_custom( state: State<'_, AppState>, @@ -3034,6 +3080,8 @@ pub fn run() { realm_rename, mysql_custom, mysql_custom_save, + restart_schedule, + restart_schedule_save, check_database, repair_server, module_set_enabled, diff --git a/src/dev/mock.ts b/src/dev/mock.ts index a6719ec..01e0057 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -39,6 +39,7 @@ export {}; if(cmd==="pending_update") return null; if(cmd==="plugin:app|version") return "0.8.2"; if(cmd==="release_history") throw new Error("Offline demo: using bundled notes"); + 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}));} 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}; diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 80d0b47..45480ff 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -778,6 +778,14 @@ const de: Partial> = { "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.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.", "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 3eb093e..0a0e49e 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -62,6 +62,14 @@ const en = { "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.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.", "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 affdc3c..8277914 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -778,6 +778,14 @@ const es: Partial> = { "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.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.", "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 a9765e4..83af20b 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -778,6 +778,14 @@ const fr: Partial> = { "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.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.", "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 e6a9d75..d89b6cd 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -65,6 +65,14 @@ const ru: Partial> = { "mysql.save": "Сохранить", "mysql.saved": "Сохранено; перезапустите сервер, чтобы применить.", "mysql.applied": "Применяется параметров: {count}", + "sched.title": "Перезапуск по расписанию", + "sched.enable": "Перезапускать мир каждый день", + "sched.time": "Время", + "sched.warning": "Предупреждение (минуты)", + "sched.hint": "Мир перезапускается в это время этого компьютера, с обратным отсчётом в игровом чате; база данных продолжает работать, игроки заходят снова после перезапуска. Работающий сервер подхватывает новое время в течение минуты.", + "sched.save": "Сохранить", + "sched.saved": "Сохранено.", + "sched.unsupported": "Этот сервер пока так не умеет: обновите его до сборки с новым лаунчером.", "realm.namesTitle": "Названия реалмов", "realm.namesHint": "Так реалм называется в списке реалмов у игроков. Работающий сервер показывает новое название сразу, и оно сохраняется после обновлений.", "realm.nameSave": "Сохранить", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 354948c..be8c31a 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -63,6 +63,14 @@ const zh = { "mysql.save": "保存", "mysql.saved": "已保存;重启服务器后生效。", "mysql.applied": "生效的选项:{count}", + "sched.title": "定时重启", + "sched.enable": "每天重启世界", + "sched.time": "时间", + "sched.warning": "提前警告(分钟)", + "sched.hint": "世界会在本机的这个时间重启,并在游戏聊天中倒计时;数据库保持运行,玩家在重启后重新登录。正在运行的服务器会在一分钟内采用新时间。", + "sched.save": "保存", + "sched.saved": "已保存。", + "sched.unsupported": "此服务器暂不支持:请将服务器更新到带有新启动器的版本。", "realm.namesTitle": "服务器名称", "realm.namesHint": "玩家在服务器列表中看到的名称。运行中的服务器会立即显示新名称,更新后也会保留。", "realm.nameSave": "保存", diff --git a/src/lib/api.ts b/src/lib/api.ts index b7a366f..aa84fd7 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -54,9 +54,12 @@ export interface StatusView { observed: { mysql: ServiceStatus; auth: ServiceStatus; world: ServiceStatus; secondary_world?: ServiceStatus | null; reborn_world?: ServiceStatus | null }; busy: boolean; path_exists: boolean; + scheduled_restart?: boolean; } export type RealmMode = "coa" | "wildcard" | "reborn"; +export interface RestartSchedule { enabled: boolean; time: string; warningMinutes: number } +export interface RestartScheduleView { schedule: RestartSchedule; supported: boolean } 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 } @@ -488,6 +491,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 }), + restartSchedule: (id: string) => invoke("restart_schedule", { id }), + restartScheduleSave: (id: string, schedule: RestartSchedule) => invoke("restart_schedule_save", { id, schedule }), mysqlCustom: (id: string) => invoke("mysql_custom", { id }), mysqlCustomSave: (id: string, text: string) => invoke("mysql_custom_save", { id, text }), realmNames: (id: string) => invoke("realm_names", { id }), diff --git a/src/screens/Overview.tsx b/src/screens/Overview.tsx index 9252e89..edb4127 100644 --- a/src/screens/Overview.tsx +++ b/src/screens/Overview.tsx @@ -228,7 +228,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o } else { if (alive.current) setPop(null); if ( - lifecycle.observe(false, actionRef.current !== null, serverUpdateBlocksRestart(server.id)) + lifecycle.observe(false, actionRef.current !== null || s.scheduled_restart === true, serverUpdateBlocksRestart(server.id)) ) { setHasCrashHistory(true); const now = Date.now(); diff --git a/src/screens/RestartScheduleSettings.tsx b/src/screens/RestartScheduleSettings.tsx new file mode 100644 index 0000000..0734ffe --- /dev/null +++ b/src/screens/RestartScheduleSettings.tsx @@ -0,0 +1,57 @@ +import { useEffect, useState } from "react"; +import { api, asUiError, type RestartSchedule } from "@/lib/api"; +import { Card } from "@/components/ui/card"; +import { Button } from "@/components/ui/button"; +import { useT } from "@/i18n"; + +/** A daily world restart at a chosen local time, with an in-game countdown (#202). */ +export function RestartScheduleSettings({ serverId }: { serverId: string }) { + const t = useT(); + const [saved, setSaved] = useState(null); + const [draft, setDraft] = useState({ enabled: false, time: "05:00", warningMinutes: 5 }); + const [supported, setSupported] = useState(true); + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + let alive = true; + void api.restartSchedule(serverId).then(v => { if (alive) { setSaved(v.schedule); setDraft(v.schedule); setSupported(v.supported); } }).catch(e => { if (alive) setError(asUiError(e).technical); }); + return () => { alive = false; }; + }, [serverId]); + + async function save() { + setBusy(true); setError(null); setDone(false); + try { const v = await api.restartScheduleSave(serverId, draft); setSaved(v.schedule); setDraft(v.schedule); setSupported(v.supported); setDone(true); } + catch (e) { setError(asUiError(e).technical); } + finally { setBusy(false); } + } + + const changed = !!saved && JSON.stringify(saved) !== JSON.stringify(draft); + const minutesOk = Number.isInteger(draft.warningMinutes) && draft.warningMinutes >= 1 && draft.warningMinutes <= 60; + const input = "rounded border border-line bg-bg px-2 py-1 text-sm text-ink outline-none focus:border-gold"; + return +

{t("sched.title")}

+ +
+ + +
+

{t("sched.hint")}

+ {!supported &&

{t("sched.unsupported")}

} +
+ + {done && {t("sched.saved")}} +
+ {error &&

{error}

} +
; +} diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx index dda693e..bbe3875 100644 --- a/src/screens/SettingsHome.tsx +++ b/src/screens/SettingsHome.tsx @@ -14,6 +14,7 @@ import { GameDataCard } from "./GameDataCard"; import { RealmStartupSettings } from "./RealmStartupSettings"; import { RealmNameSettings } from "./RealmNameSettings"; import { MySqlSettings } from "./MySqlSettings"; +import { RestartScheduleSettings } from "./RestartScheduleSettings"; import { AutoRestartSettings } from "./AutoRestartSettings"; import { DiagnosticsCard } from "./DiagnosticsCard"; import { RepairCard } from "./RepairCard"; @@ -52,7 +53,7 @@ export function SettingsHome({ serverId, path, onForget }: { serverId: string; s - +