diff --git a/README.md b/README.md index 7aba7d0..2a2d12e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LokiASAM -**Loki Ark Survival Ascended Server Manager** — a desktop app for managing dedicated ASA servers on Linux and Windows. +**Loki ARK Survival Ascended Server Manager** — a desktop app for managing dedicated ASA servers on Linux and Windows. Built with Tauri v2, Next.js, and Rust. No web browser required, no monthly subscription, no cloud dependency. @@ -12,15 +12,18 @@ Built with Tauri v2, Next.js, and Rust. No web browser required, no monthly subs - **SteamCMD integration** — automated install, update, and validation with a shared cache to speed up multi-server setups - **Server configuration** — edit `GameUserSettings.ini` and `Game.ini` with a structured section editor or raw textarea - **RCON console** — live terminal with command history, presets, and broadcast support -- **Live log viewer** — tail server logs in real time with filtering and auto-scroll +- **Live log viewer** — tail server logs in real time with filtering and auto-scroll; archives and crash logs accessible from a sidebar - **Mod management** — install mods by ID, reorder, toggle, and browse CurseForge from within the app -- **Scheduled automation** — cron-based schedules for backups, updates, restarts, and RCON broadcasts -- **Backup and restore** — create, restore, and prune ZIP backups per server with retention settings +- **Scheduled automation** — cron-based schedules for backups, updates, restarts, and RCON broadcasts; runs fully in the background even when the window is hidden +- **TimeShift backups** — server, player, and full-install backups with hourly/daily/weekly/monthly retention tiers, automatic pruning, and restore support +- **Player connection tracking** — log player logins with optional per-login player backups - **Cluster support** — group servers into clusters with a shared directory -- **Notifications** — Discord webhooks, email (SMTP), and desktop notifications for server events +- **Notifications** — Discord webhooks, email (SMTP), desktop OS notifications, and in-app toasts for server events including backups, crashes, updates, and more - **Proton-GE** — automatic detection and download on Linux for running the Windows server binary -- **System tray** — minimizes to tray; server processes keep running while the window is hidden -- **Auto-update** — checks for app updates and installs them in the background +- **System tray** — minimizes to tray; server processes and scheduled tasks keep running while the window is hidden +- **Auto-update** — checks for app updates and installs them in the background (AppImage, `.deb`, and `.rpm` builds); PKGBUILD users are notified to rebuild manually +- **Firewall management** — optional firewall rule helpers for server ports +- **Graceful restart** — countdown restart with configurable warning broadcasts to online players --- @@ -28,13 +31,66 @@ Built with Tauri v2, Next.js, and Rust. No web browser required, no monthly subs Pre-built installers are on the [Releases](https://github.com/LokiRothbrook/LokiASAM/releases) page. -**Linux:** Download the `.AppImage`, make it executable, and run it. +### Debian / Ubuntu / Linux Mint + +Download and install the `.deb` package: + +```bash +sudo dpkg -i LokiASAM_*_amd64.deb +sudo apt-get install -f # pull in any missing dependencies +``` + +### Fedora / openSUSE / RHEL-based + +Download and install the `.rpm` package: + +```bash +sudo rpm -i LokiASAM_*_x86_64.rpm +# or with dnf: +sudo dnf install ./LokiASAM_*_x86_64.rpm +``` + +### Arch Linux / CachyOS / Manjaro + +AppImage and pre-built binaries do not work reliably on rolling-release distros due to bundled library conflicts. Build from source instead: + +```bash +git clone https://github.com/LokiRothbrook/LokiASAM.git +cd LokiASAM/packaging/arch +makepkg -si +``` + +`makepkg -si` builds the app using your system's native libraries and installs it via pacman — icons, the `.desktop` entry, and shell integration all work correctly out of the box. + +To uninstall: + +```bash +sudo pacman -R lokiasam +``` + +To update, pull the latest source and rebuild: + +```bash +cd LokiASAM +git pull +cd packaging/arch +makepkg -si +``` + +### Generic Linux (AppImage) + +> **Note:** AppImage does not work on Arch-based systems (Arch, CachyOS, Manjaro). Use the PKGBUILD method above instead. + ```bash chmod +x LokiASAM_*.AppImage ./LokiASAM_*.AppImage ``` -**Windows:** Run the `LokiASAM_*_x64-setup.exe` installer. +On first run you will be prompted to register the app in your application menu. Accepting writes the `.desktop` file and icon to `~/.local/share/` so the launcher and taskbar icon work correctly. + +### Windows + +Run the `LokiASAM_*_x64-setup.exe` installer. --- @@ -45,7 +101,7 @@ chmod +x LokiASAM_*.AppImage - [Rust](https://rustup.rs/) (stable) - [Node.js](https://nodejs.org/) 22+ - [pnpm](https://pnpm.io/) 9+ -- Linux: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf` +- Linux: `webkit2gtk-4.1`, `libappindicator-gtk3`, `librsvg`, `patchelf` - Windows: WebView2 (ships with Windows 11; installer available for Windows 10) **Steps** diff --git a/package.json b/package.json index 4220a28..82e5305 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "lokiasam", - "version": "0.10.1", + "version": "0.13.0", "private": true, "scripts": { "dev": "next dev", diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD new file mode 100644 index 0000000..c07585e --- /dev/null +++ b/packaging/arch/PKGBUILD @@ -0,0 +1,67 @@ +# Maintainer: Arron Ohnemus +pkgname=lokiasam +pkgver=0.13.0 +pkgrel=1 +pkgdesc="Loki ARK Survival Ascended Server Manager — a desktop app for managing dedicated ASA servers" +arch=("x86_64") +url="https://github.com/LokiRothbrook/LokiASAM" +license=("GPL3") +depends=( + "webkit2gtk-4.1" + "gtk3" + "libappindicator-gtk3" + "librsvg" + "xdg-utils" +) +makedepends=( + "rust" + "cargo" + "nodejs" + "pnpm" + "git" +) +install=lokiasam.install +source=("$pkgname-$pkgver::git+$url.git#tag=v$pkgver") +sha256sums=("SKIP") + +build() { + cd "$srcdir/$pkgname-$pkgver" + pnpm install --frozen-lockfile + pnpm tauri build --bundles none +} + +package() { + cd "$srcdir/$pkgname-$pkgver" + + # Binary + install -Dm755 "src-tauri/target/release/lokiasam" "$pkgdir/usr/bin/lokiasam" + + # Icons + for size in 32x32 128x128 256x256 512x512; do + local src="src-tauri/icons/${size}.png" + if [[ -f "$src" ]]; then + install -Dm644 "$src" \ + "$pkgdir/usr/share/icons/hicolor/${size}/apps/xyz.lokisoft.lokiasam.png" + fi + done + + # .desktop file + install -Dm644 /dev/stdin \ + "$pkgdir/usr/share/applications/xyz.lokisoft.lokiasam.desktop" </dev/null || true + gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null || true +} + +post_upgrade() { + post_install +} + +post_remove() { + update-desktop-database -q 2>/dev/null || true + gtk-update-icon-cache -q -t /usr/share/icons/hicolor 2>/dev/null || true +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 883a68c..821c3f6 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2727,7 +2727,7 @@ dependencies = [ [[package]] name = "lokiasam" -version = "0.11.0" +version = "0.13.0" dependencies = [ "configparser", "flate2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 9854dc7..b300fd2 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lokiasam" -version = "0.11.0" +version = "0.13.0" description = "Loki Ark Survival Ascended Server Manager" authors = ["Loki"] license = "GPL-3.0-or-later" diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index 610a168..c6ab372 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -5,7 +5,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, State}; use tokio::sync::oneshot; -use tokio::time::{timeout, Duration}; +use tokio::time::{timeout, sleep, Duration}; use uuid::Uuid; use sevenz_rust::{SevenZWriter, SevenZArchiveEntry}; @@ -84,12 +84,89 @@ fn days_to_ymd(mut days: u64) -> (u64, u64, u64) { (y, m, d) } +fn fmt_size(bytes: u64) -> String { + if bytes >= 1_073_741_824 { + format!("{:.1} GB", bytes as f64 / 1_073_741_824.0) + } else if bytes >= 1_048_576 { + format!("{:.1} MB", bytes as f64 / 1_048_576.0) + } else { + format!("{:.1} KB", bytes as f64 / 1_024.0) + } +} + fn sanitize_name(name: &str) -> String { name.chars() .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) .collect() } +/// Build a filename tier suffix like "-DH" from a tiers string like "D,H" or "H". +/// Tiers are sorted in canonical priority order (M W D H). +fn tier_suffix(tiers: &str) -> String { + if tiers.is_empty() { + return String::new(); + } + const ORDER: &[char] = &['M', 'W', 'D', 'H']; + let flags: Vec = tiers.split(',') + .filter_map(|t| t.trim().chars().next()) + .filter(|c| ORDER.contains(c)) + .collect(); + if flags.is_empty() { + return String::new(); + } + let mut sorted: Vec = ORDER.iter().copied().filter(|c| flags.contains(c)).collect(); + sorted.dedup(); + format!("-{}", sorted.iter().collect::()) +} + +/// Find and parse a `YYYY-MM-DD_HH-MM-SS` timestamp embedded in a filename stem. +/// Returns `(ts_iso, tiers_str)` where `tiers_str` may be empty for files without +/// the tier suffix (e.g. manual backups or pre-tier-feature archives). +pub fn parse_backup_filename(stem: &str) -> Option<(String, String)> { + let bytes = stem.as_bytes(); + let len = bytes.len(); + if len < 19 { return None; } + + for i in 0..=(len - 19) { + let candidate = &stem[i..i + 19]; + if is_timestamp(candidate.as_bytes()) { + let after = &stem[i + 19..]; + // After timestamp: either empty, or "-{MWDH letters}", or something else (no tier) + let tiers = if let Some(rest) = after.strip_prefix('-') { + if !rest.is_empty() && rest.chars().all(|c| matches!(c, 'M' | 'W' | 'D' | 'H')) { + rest.to_string() + } else { + String::new() + } + } else { + String::new() + }; + // Convert YYYY-MM-DD_HH-MM-SS → YYYY-MM-DDTHH:MM:SSZ + let ts_iso = format!( + "{}T{}:{}:{}Z", + &candidate[..10], + &candidate[11..13], + &candidate[14..16], + &candidate[17..19], + ); + return Some((ts_iso, tiers)); + } + } + None +} + +fn is_timestamp(b: &[u8]) -> bool { + if b.len() != 19 { return false; } + b[4] == b'-' && b[7] == b'-' && b[10] == b'_' && + b[13] == b'-' && b[16] == b'-' && + b[..4].iter().all(|c| c.is_ascii_digit()) && + b[5..7].iter().all(|c| c.is_ascii_digit()) && + b[8..10].iter().all(|c| c.is_ascii_digit()) && + b[11..13].iter().all(|c| c.is_ascii_digit())&& + b[14..16].iter().all(|c| c.is_ascii_digit())&& + b[17..19].iter().all(|c| c.is_ascii_digit()) +} + /// Recursively collect all file paths under `dir`. fn collect_files(dir: &Path, out: &mut Vec) -> std::io::Result<()> { for entry in fs::read_dir(dir)? { @@ -116,7 +193,7 @@ fn emit_progress(app: &AppHandle, server_id: &str, percent: f32, file: &str, lab /// Send SaveWorld through the managed RCON connection if one is live. /// Falls back silently if RCON is not connected. -async fn rcon_save_world(pool: &RconPool, server_id: &str) -> Result<(), String> { +pub async fn rcon_save_world(pool: &RconPool, server_id: &str) -> Result<(), String> { let tx = { let guard = pool.cmd_channels.lock().await; guard.get(server_id).filter(|(tx, _)| !tx.is_closed()).map(|(tx, _)| tx.clone()) @@ -143,6 +220,9 @@ async fn rcon_save_world(pool: &RconPool, server_id: &str) -> Result<(), String> /// Write `files` into a 7z archive at `dest_path`. /// `root` is stripped from each file path to produce the archive entry name. /// Emits progress events keyed on `server_id`. +/// Returns Ok(skipped_count) on success. A non-zero skipped_count means some +/// files disappeared between enumeration and compression — the caller should +/// consider retrying with a fresh file list. fn compress_to_7z( app: &AppHandle, server_id: &str, @@ -150,9 +230,10 @@ fn compress_to_7z( root: &Path, dest_path: &Path, label: &str, -) -> Result<(), String> { +) -> Result { let total = files.len().max(1) as f32; let mut writer = SevenZWriter::create(dest_path).map_err(|e| e.to_string())?; + let mut skipped = 0usize; for (idx, file_path) in files.iter().enumerate() { let rel = file_path @@ -163,7 +244,17 @@ fn compress_to_7z( let pct = (idx as f32 / total * 99.0).min(99.0); emit_progress(app, server_id, pct, &entry_name, label); - let file = File::open(file_path).map_err(|e| e.to_string())?; + // Skip files that disappeared between enumeration and compression (ASA + // uses delete+rename atomic writes, which creates a brief window where + // the file doesn't exist). Count skips so callers can retry. + let file = match File::open(file_path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + skipped += 1; + continue; + } + Err(e) => return Err(e.to_string()), + }; let metadata = file.metadata().map_err(|e| e.to_string())?; let mut entry = SevenZArchiveEntry::new(); entry.name = entry_name.clone(); @@ -175,17 +266,21 @@ fn compress_to_7z( } writer.finish().map_err(|e| e.to_string())?; - Ok(()) + Ok(skipped) } // --------------------------------------------------------------------------- // Cleanup: delete ARK's own auto-generated backup files // --------------------------------------------------------------------------- -/// Delete all `{mapPath}-*.ark` timestamped backup files and `*.profilebak` -/// files from the SavedArks/{mapPath} directory. Only removes ARK's own -/// rolling copies — never touches the live `{mapPath}.ark` save or the -/// `_AntiCorruptionBackup.bak` ARK integrity file. +/// Delete ARK's own auto-generated rolling copies from SavedArks/{mapPath}: +/// - `{mapPath}_*.ark` — ARK's own timestamped world-save backups +/// - `{mapPath}_*.arkrbf` — ASA rollback files +/// - `*.profilebak` — ARK player-profile backups +/// - `*.tribebak` — ARK tribe backups +/// +/// Never touches the live `{mapPath}.ark`, `_AntiCorruptionBackup.bak`, +/// `*.arkprofile`, or `*.arktribe` files. /// /// Returns the number of files deleted. #[tauri::command] @@ -204,7 +299,8 @@ pub async fn cleanup_ark_own_backups( } let mut deleted = 0u32; - let prefix = format!("{map_path}-"); + // ASA uses underscore as separator: Astraeos_WP_11.06.2026_09.37.13.ark + let prefix = format!("{map_path}_"); let entries = fs::read_dir(&saved_dir).map_err(|e| e.to_string())?; for entry in entries { @@ -216,10 +312,12 @@ pub async fn cleanup_ark_own_backups( .and_then(|n| n.to_str()) .unwrap_or(""); - let is_ark_timestamped = fname.starts_with(&prefix) && fname.ends_with(".ark"); - let is_profilebak = fname.ends_with(".profilebak"); + let is_ark_rolling = fname.starts_with(&prefix) + && (fname.ends_with(".ark") || fname.ends_with(".arkrbf")); + let is_profilebak = fname.ends_with(".profilebak"); + let is_tribebak = fname.ends_with(".tribebak"); - if is_ark_timestamped || is_profilebak { + if is_ark_rolling || is_profilebak || is_tribebak { if fs::remove_file(&path).is_ok() { deleted += 1; } @@ -233,12 +331,29 @@ pub async fn cleanup_ark_own_backups( // Server backup (SavedArks + SaveGames → .7z) // --------------------------------------------------------------------------- -/// Create a Server backup: SaveWorld via RCON → cleanup ARK own backups → -/// 7z SavedArks/{mapPath} + SaveGames into {backup_dir}/{server_id}/server/. +/// Inner implementation for server backup — callable from both the Tauri command +/// and the Rust backup_manager tick handler (which cannot use State<'_> wrappers). /// -/// Emits `backup://progress/{server_id}` events during compression. -/// If the server is stopped (no RCON), SaveWorld is skipped and existing saves -/// are compressed as-is. +/// `skip_world_save`: pass `true` when the caller has already issued SaveWorld +/// (e.g. the scheduler tick that consolidates the save across backup types). +/// Pass `false` for manual/UI-triggered backups so they save on their own. +pub async fn create_server_backup_inner( + app: &AppHandle, + server_id: &str, + server_name: &str, + install_path: &str, + map_path: &str, + map_id: &str, + backup_dir: &str, + triggered_by: &str, + tier: &str, + pool: &RconPool, + skip_world_save: bool, +) -> Result { + create_server_backup_impl(app, server_id, server_name, install_path, map_path, map_id, backup_dir, triggered_by, tier, pool, skip_world_save).await +} + +/// Tauri command: exposed to the frontend for manual/UI-triggered backups. #[tauri::command] pub async fn create_server_backup( app: AppHandle, @@ -249,83 +364,197 @@ pub async fn create_server_backup( map_id: String, backup_dir: String, triggered_by: String, + tier: String, pool: State<'_, RconPool>, ) -> Result { - // SaveWorld (best-effort — server may be stopped) - emit_progress(&app, &server_id, 0.0, "", "Saving world…"); - let _ = rcon_save_world(&pool, &server_id).await; + let result = create_server_backup_inner(&app, &server_id, &server_name, &install_path, &map_path, &map_id, &backup_dir, &triggered_by, &tier, &pool, false).await; + if let Ok(ref rec) = result { + let size = fmt_size(rec.file_size_bytes); + crate::commands::notifications::dispatch_notification( + &app, "backup_completed", Some(&server_id), &server_name, + "Backup Complete", &format!("Server backup completed ({size})"), "success", + ).await; + } + result +} - // Cleanup ARK's own backup files before we zip - emit_progress(&app, &server_id, 2.0, "", "Cleaning ARK backups…"); - let _ = cleanup_ark_own_backups(install_path.clone(), map_path.clone()).await; +async fn create_server_backup_impl( + app: &AppHandle, + server_id: &str, + server_name: &str, + install_path: &str, + map_path: &str, + map_id: &str, + backup_dir: &str, + triggered_by: &str, + tier: &str, + pool: &RconPool, + skip_world_save: bool, +) -> Result { + const MAX_ATTEMPTS: u32 = 3; + const RETRY_DELAY_SECS: u64 = 15; + const POST_SAVE_WAIT_SECS: u64 = 5; + + if !skip_world_save { + // SaveWorld (best-effort — server may be stopped) + emit_progress(&app, &server_id, 0.0, "", "Saving world…"); + let _ = rcon_save_world(&pool, &server_id).await; + + // ASA acknowledges SaveWorld via RCON before finishing all file I/O. + // Wait briefly so atomic save writes (delete → rename patterns) complete + // before we enumerate the directory. + sleep(Duration::from_secs(POST_SAVE_WAIT_SECS)).await; + } let saved_arks = PathBuf::from(&install_path) .join("ShooterGame").join("Saved").join("SavedArks").join(&map_path); let save_games = PathBuf::from(&install_path) .join("ShooterGame").join("Saved").join("SaveGames"); - - let mut all_files: Vec = Vec::new(); - if saved_arks.exists() { - collect_files(&saved_arks, &mut all_files).map_err(|e| e.to_string())?; - } - if save_games.exists() { - collect_files(&save_games, &mut all_files).map_err(|e| e.to_string())?; - } - if all_files.is_empty() { - return Err("No save files found to back up".to_string()); - } + let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); let out_dir = PathBuf::from(&backup_dir).join(&server_id).join("server"); fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?; - let (ts_file, ts_iso) = now_timestamp(); let safe_name = sanitize_name(&server_name); - let archive_name = format!("{safe_name}-{ts_file}.7z"); - let archive_path = out_dir.join(&archive_name); + let suffix = tier_suffix(&tier); + let mut last_error = String::new(); + + for attempt in 0..MAX_ATTEMPTS { + if attempt > 0 { + emit_progress(&app, &server_id, 0.0, "", + &format!("Retrying backup (attempt {}/{MAX_ATTEMPTS})…", attempt + 1)); + sleep(Duration::from_secs(RETRY_DELAY_SECS)).await; + } - // Root for relative paths inside the archive = ShooterGame/Saved - let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + // Fresh cleanup and enumeration on every attempt so each retry gets a + // stable snapshot after ASA has finished writing. + emit_progress(&app, &server_id, 2.0, "", "Cleaning ARK backups…"); + let _ = cleanup_ark_own_backups(install_path.to_string(), map_path.to_string()).await; - let app_c = app.clone(); - let sid = server_id.clone(); - let files = all_files.clone(); - let root = saved_root.clone(); - let dest = archive_path.clone(); - tokio::task::spawn_blocking(move || { - compress_to_7z(&app_c, &sid, &files, &root, &dest, "Creating server backup…") - }) - .await - .map_err(|e| format!("Backup task panicked: {e}"))??; - - emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); + let mut all_files: Vec = Vec::new(); + if saved_arks.exists() { + collect_files(&saved_arks, &mut all_files).map_err(|e| e.to_string())?; + } + if save_games.exists() { + collect_files(&save_games, &mut all_files).map_err(|e| e.to_string())?; + } + if all_files.is_empty() { + return Err("No save files found to back up".to_string()); + } - let file_size = fs::metadata(&archive_path) - .map_err(|e| e.to_string())? - .len(); + let (ts_file, ts_iso) = now_timestamp(); + let archive_name = format!("{safe_name}-{ts_file}{suffix}.7z"); + let archive_path = out_dir.join(&archive_name); + + let app_c = app.clone(); + let sid = server_id.to_string(); + let files = all_files; + let root = saved_root.clone(); + let dest = archive_path.clone(); + let compress_result = tokio::task::spawn_blocking(move || { + compress_to_7z(&app_c, &sid, &files, &root, &dest, "Creating server backup…") + }) + .await + .map_err(|e| format!("Backup task panicked: {e}"))?; + + match compress_result { + Ok(skipped) => { + let is_last = attempt == MAX_ATTEMPTS - 1; + if skipped > 0 && !is_last { + // Files disappeared mid-compression — retry with fresh snapshot + let _ = tokio::fs::remove_file(&archive_path).await; + continue; + } + // Clean run, or last attempt — accept the archive + emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); + let file_size = fs::metadata(&archive_path) + .map_err(|e| e.to_string())? + .len(); + return Ok(BackupRecord { + id: Uuid::new_v4().to_string(), + server_id: server_id.to_string(), + file_path: archive_path.to_string_lossy().to_string(), + file_size_bytes: file_size, + map_id: map_id.to_string(), + triggered_by: triggered_by.to_string(), + created_at: ts_iso, + backup_type: "server".to_string(), + tiers: String::new(), + player_eosid: None, + player_name: None, + }); + } + Err(e) => { + let _ = tokio::fs::remove_file(&archive_path).await; + last_error = e; + // Will retry if attempts remain + } + } + } - Ok(BackupRecord { - id: Uuid::new_v4().to_string(), - server_id, - file_path: archive_path.to_string_lossy().to_string(), - file_size_bytes: file_size, - map_id, - triggered_by, - created_at: ts_iso, - backup_type: "server".to_string(), - tiers: String::new(), - player_eosid: None, - player_name: None, - }) + Err(last_error) } // --------------------------------------------------------------------------- -// Player backup (single .arkprofile → .7z) +// All-players manual backup // --------------------------------------------------------------------------- -/// Back up a single player's .arkprofile into -/// {backup_dir}/{server_id}/player/{eos_id}/. +/// Inner implementation for all-players backup — callable from both the Tauri +/// command and the Rust backup_manager tick handler. +pub async fn backup_all_players_inner( + app: &AppHandle, + server_id: &str, + server_name: &str, + install_path: &str, + map_path: &str, + map_id: &str, + backup_dir: &str, + triggered_by: &str, +) -> Result, String> { + let saved_dir = PathBuf::from(install_path) + .join("ShooterGame").join("Saved") + .join("SavedArks").join(map_path); + + if !saved_dir.exists() { + return Ok(vec![]); + } + + let profiles: Vec = fs::read_dir(&saved_dir) + .map_err(|e| e.to_string())? + .filter_map(|e| e.ok()) + .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("arkprofile")) + .filter_map(|e| { + e.path().file_stem() + .and_then(|s| s.to_str()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + }) + .collect(); + + let mut records = Vec::new(); + for eos_id in &profiles { + if let Ok(rec) = create_player_backup_inner( + app, + server_id, + server_name, + install_path, + map_path, + map_id, + backup_dir, + eos_id, + eos_id, + triggered_by, + "", + ).await { + records.push(rec); + } + } + Ok(records) +} + +/// Tauri command: back up every .arkprofile (UI-triggered or scheduled from frontend). #[tauri::command] -pub async fn create_player_backup( +pub async fn backup_all_players( app: AppHandle, server_id: String, server_name: String, @@ -333,63 +562,127 @@ pub async fn create_player_backup( map_path: String, map_id: String, backup_dir: String, - eos_id: String, - player_name: String, triggered_by: String, +) -> Result, String> { + let result = backup_all_players_inner(&app, &server_id, &server_name, &install_path, &map_path, &map_id, &backup_dir, &triggered_by).await; + if let Ok(ref recs) = result { + let count = recs.len(); + if count > 0 { + crate::commands::notifications::dispatch_notification( + &app, "backup_completed", Some(&server_id), &server_name, + "Backup Complete", &format!("Player backups completed ({count} players)"), "success", + ).await; + } + } + result +} + +// --------------------------------------------------------------------------- +// Player backup (single .arkprofile → .7z) +// --------------------------------------------------------------------------- + +/// Inner implementation for single-player backup — callable without Tauri State wrappers. +pub async fn create_player_backup_inner( + app: &AppHandle, + server_id: &str, + server_name: &str, + install_path: &str, + map_path: &str, + map_id: &str, + backup_dir: &str, + eos_id: &str, + player_name: &str, + triggered_by: &str, + tier: &str, ) -> Result { - let profile_file = PathBuf::from(&install_path) + let profile_file = PathBuf::from(install_path) .join("ShooterGame").join("Saved") - .join("SavedArks").join(&map_path) + .join("SavedArks").join(map_path) .join(format!("{eos_id}.arkprofile")); if !profile_file.exists() { return Err(format!("Profile not found: {}", profile_file.display())); } - let out_dir = PathBuf::from(&backup_dir) - .join(&server_id).join("player").join(&eos_id); + let out_dir = PathBuf::from(backup_dir) + .join(server_id).join("player").join(eos_id); fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?; let (ts_file, ts_iso) = now_timestamp(); - let safe_server = sanitize_name(&server_name); - let safe_player = sanitize_name(&player_name); - let archive_name = format!("{safe_server}-{safe_player}-{ts_file}.7z"); + let safe_server = sanitize_name(server_name); + let safe_player = sanitize_name(player_name); + let suffix = tier_suffix(tier); + let archive_name = format!("{safe_server}-{safe_player}-{ts_file}{suffix}.7z"); let archive_path = out_dir.join(&archive_name); - emit_progress(&app, &server_id, 0.0, "", &format!("Backing up {player_name}…")); + emit_progress(app, server_id, 0.0, "", &format!("Backing up {player_name}…")); let root = profile_file.parent().unwrap().to_path_buf(); let files = vec![profile_file.clone()]; let app_c = app.clone(); - let sid = server_id.clone(); + let sid = server_id.to_string(); let dest = archive_path.clone(); - tokio::task::spawn_blocking(move || { + let result = tokio::task::spawn_blocking(move || { compress_to_7z(&app_c, &sid, &files, &root, &dest, "Creating player backup…") }) .await - .map_err(|e| format!("Backup task panicked: {e}"))??; + .map_err(|e| format!("Backup task panicked: {e}"))?; + if let Err(e) = result { + let _ = fs::remove_file(&archive_path); + return Err(e); + } - emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); + emit_progress(app, server_id, 100.0, &archive_name, "Done"); let file_size = fs::metadata(&archive_path) .map_err(|e| e.to_string())? .len(); Ok(BackupRecord { - id: Uuid::new_v4().to_string(), - server_id, - file_path: archive_path.to_string_lossy().to_string(), + id: Uuid::new_v4().to_string(), + server_id: server_id.to_string(), + file_path: archive_path.to_string_lossy().to_string(), file_size_bytes: file_size, - map_id, - triggered_by, - created_at: ts_iso, - backup_type: "player".to_string(), - tiers: String::new(), - player_eosid: Some(eos_id), - player_name: Some(player_name), + map_id: map_id.to_string(), + triggered_by: triggered_by.to_string(), + created_at: ts_iso, + backup_type: "player".to_string(), + tiers: String::new(), + player_eosid: Some(eos_id.to_string()), + player_name: Some(player_name.to_string()), }) } +/// Tauri command: back up a single player's .arkprofile. +#[tauri::command] +pub async fn create_player_backup( + app: AppHandle, + server_id: String, + server_name: String, + install_path: String, + map_path: String, + map_id: String, + backup_dir: String, + eos_id: String, + player_name: String, + triggered_by: String, + tier: String, +) -> Result { + let result = create_player_backup_inner( + &app, &server_id, &server_name, &install_path, &map_path, + &map_id, &backup_dir, &eos_id, &player_name, &triggered_by, &tier, + ).await; + if let Ok(ref rec) = result { + let size = fmt_size(rec.file_size_bytes); + let display_name = rec.player_name.as_deref().unwrap_or(&eos_id); + crate::commands::notifications::dispatch_notification( + &app, "backup_completed", Some(&server_id), &server_name, + "Backup Complete", &format!("Player backup for {display_name} completed ({size})"), "success", + ).await; + } + result +} + // --------------------------------------------------------------------------- // INI backup (loose files in a timestamped folder) // --------------------------------------------------------------------------- @@ -496,6 +789,7 @@ pub async fn create_full_backup( map_id: String, backup_dir: String, triggered_by: String, + tier: String, ) -> Result { let install_dir = PathBuf::from(&install_path); if !install_dir.exists() { @@ -507,7 +801,8 @@ pub async fn create_full_backup( let (ts_file, ts_iso) = now_timestamp(); let safe_name = sanitize_name(&server_name); - let archive_name = format!("{safe_name}-full-{ts_file}.7z"); + let suffix = tier_suffix(&tier); + let archive_name = format!("{safe_name}-full-{ts_file}{suffix}.7z"); let archive_path = out_dir.join(&archive_name); emit_progress(&app, &server_id, 0.0, "", "Collecting files for full backup…"); @@ -519,11 +814,15 @@ pub async fn create_full_backup( let sid = server_id.clone(); let dest = archive_path.clone(); let root = install_dir.clone(); - tokio::task::spawn_blocking(move || { + let result = tokio::task::spawn_blocking(move || { compress_to_7z(&app_c, &sid, &all_files, &root, &dest, "Creating full backup…") }) .await - .map_err(|e| format!("Full backup task panicked: {e}"))??; + .map_err(|e| format!("Full backup task panicked: {e}"))?; + if let Err(e) = result { + let _ = fs::remove_file(&archive_path); + return Err(e); + } emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); @@ -531,7 +830,7 @@ pub async fn create_full_backup( .map_err(|e| e.to_string())? .len(); - Ok(BackupRecord { + let rec = BackupRecord { id: Uuid::new_v4().to_string(), server_id, file_path: archive_path.to_string_lossy().to_string(), @@ -543,7 +842,13 @@ pub async fn create_full_backup( tiers: String::new(), player_eosid: None, player_name: None, - }) + }; + let size = fmt_size(rec.file_size_bytes); + crate::commands::notifications::dispatch_notification( + &app, "backup_completed", Some(&rec.server_id), &server_name, + "Backup Complete", &format!("Full backup completed ({size})"), "success", + ).await; + Ok(rec) } // --------------------------------------------------------------------------- @@ -685,3 +990,112 @@ pub async fn estimate_dir_size(dir_path: String) -> Result { } Ok(total) } + +// --------------------------------------------------------------------------- +// Rename file (used when tier flags change) +// --------------------------------------------------------------------------- + +/// Rename a backup file on disk and return the new path. +/// Used by the frontend when tier flags are promoted/stripped. +#[tauri::command] +pub async fn rename_backup_file(old_path: String, new_path: String) -> Result<(), String> { + fs::rename(&old_path, &new_path).map_err(|e| e.to_string()) +} + +// --------------------------------------------------------------------------- +// File exists check +// --------------------------------------------------------------------------- + +#[tauri::command] +pub async fn backup_file_exists(file_path: String) -> bool { + PathBuf::from(&file_path).exists() +} + +// --------------------------------------------------------------------------- +// Scan backup directory (Sync from Disk) +// --------------------------------------------------------------------------- + +/// Scan a server's backup subdirectory tree and return every .7z found as a +/// BackupRecord. The caller diffs against the DB and imports what's missing. +#[tauri::command] +pub async fn scan_backup_dir( + server_id: String, + backup_dir: String, + map_id: String, +) -> Result, String> { + let base = PathBuf::from(&backup_dir).join(&server_id); + let mut records: Vec = Vec::new(); + + // server/ + scan_type_dir(&base.join("server"), &server_id, &map_id, "server", None, &mut records); + // player/{eos_id}/ + let player_root = base.join("player"); + if player_root.exists() { + if let Ok(rd) = fs::read_dir(&player_root) { + for entry in rd.flatten() { + let eos_dir = entry.path(); + if eos_dir.is_dir() { + let eos_id = eos_dir.file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_string(); + scan_type_dir(&eos_dir, &server_id, &map_id, "player", Some(&eos_id), &mut records); + } + } + } + } + // full/ + scan_type_dir(&base.join("full"), &server_id, &map_id, "full", None, &mut records); + + Ok(records) +} + +fn scan_type_dir( + dir: &Path, + server_id: &str, + map_id: &str, + backup_type: &str, + eos_id: Option<&str>, + out: &mut Vec, +) { + if !dir.exists() { return; } + let Ok(rd) = fs::read_dir(dir) else { return }; + + for entry in rd.flatten() { + let path = entry.path(); + if !path.is_file() { continue; } + let fname = match path.file_name().and_then(|n| n.to_str()) { + Some(n) if n.ends_with(".7z") => n.to_string(), + _ => continue, + }; + + let stem = fname.trim_end_matches(".7z"); + let (ts_iso, tiers) = parse_backup_filename(stem).unwrap_or_else(|| { + // Fallback: use file mtime + let secs = path.metadata().ok() + .and_then(|m| m.modified().ok()) + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()) + .unwrap_or(0); + let (y, mo, d, h, min, s) = crate::state::log_manager::epoch_to_ymdhms(secs); + (format!("{y:04}-{mo:02}-{d:02}T{h:02}:{min:02}:{s:02}Z"), String::new()) + }); + + let file_size = path.metadata().map(|m| m.len()).unwrap_or(0); + let eos_str = eos_id.unwrap_or("").to_string(); + + out.push(BackupRecord { + id: Uuid::new_v4().to_string(), + server_id: server_id.to_string(), + file_path: path.to_string_lossy().to_string(), + file_size_bytes: file_size, + map_id: map_id.to_string(), + triggered_by: "disk_import".to_string(), + created_at: ts_iso, + backup_type: backup_type.to_string(), + tiers, + player_eosid: if eos_str.is_empty() { None } else { Some(eos_str.clone()) }, + player_name: if eos_str.is_empty() { None } else { Some(eos_str) }, + }); + } +} diff --git a/src-tauri/src/commands/backup_manager.rs b/src-tauri/src/commands/backup_manager.rs new file mode 100644 index 0000000..69b2656 --- /dev/null +++ b/src-tauri/src/commands/backup_manager.rs @@ -0,0 +1,595 @@ +/// backup_manager.rs — Rust-side hourly backup tick handler. +/// +/// Replaces the frontend SchedulerManager's `backup://tick` handler so that +/// scheduled backups are created and recorded in SQLite even when the WebKit +/// webview is throttled (window hidden in the system tray). +/// +/// Called once per hour from the background tick task in lib.rs. +/// For each running server that has a backup schedule enabled, this module: +/// 1. Creates the 7z archive via the existing backup commands. +/// 2. Computes which TimeShift tiers are due (H/D/W/M). +/// 3. Renames the archive to embed the tier suffix. +/// 4. Inserts the record into SQLite. +/// 5. Prunes old archives beyond each tier's keep-count. +/// 6. Emits `backup://completed/{serverId}` so the UI can refresh. + +use std::collections::HashMap; +use tauri::{AppHandle, Emitter, Manager}; + +use crate::db; +use crate::state::AppState; +use crate::state::rcon_pool::RconPool; + +use super::backup::{ + create_server_backup_inner, backup_all_players_inner, create_player_backup_inner, + rcon_save_world, BackupRecord, +}; + +fn fmt_size(bytes: u64) -> String { + if bytes >= 1_073_741_824 { + format!("{:.1} GB", bytes as f64 / 1_073_741_824.0) + } else if bytes >= 1_048_576 { + format!("{:.1} MB", bytes as f64 / 1_048_576.0) + } else { + format!("{:.1} KB", bytes as f64 / 1_024.0) + } +} + +// --------------------------------------------------------------------------- +// Map ID → ASA map path (matches ARK_MAPS in game-data.ts) +// --------------------------------------------------------------------------- + +fn map_id_to_path(map_id: &str) -> &'static str { + match map_id { + "theisland" => "TheIsland_WP", + "thecenter" => "TheCenter_WP", + "ragnarok" => "Ragnarok_WP", + "valguero" => "Valguero_WP", + "scorched" => "ScorchedEarth_WP", + "aberration" => "Aberration_WP", + "extinction" => "Extinction_WP", + "astraeos" => "Astraeos_WP", + "lostcolony" => "LostColony_WP", + "genesis1" => "Genesis_WP", + "genesis2" => "Gen2_WP", + "lostisland" => "LostIsland_WP", + "fjordur" => "Fjordur_WP", + "crystalisles"=> "CrystalIsles_WP", + "amissa" => "Amissa_WP", + "svartalfheim"=> "Svartalfheim_WP", + "clubark" => "ClubARK_WP", + _ => "TheIsland_WP", + } +} + +// --------------------------------------------------------------------------- +// Tier configuration +// --------------------------------------------------------------------------- + +/// Tier priority order: most important first. +const TIERS: [(char, &str, u64); 4] = [ + ('M', "monthly", 30 * 24 * 3600), + ('W', "weekly", 7 * 24 * 3600), + ('D', "daily", 24 * 3600), + ('H', "hourly", 0), +]; + +const TIER_DEFAULT_KEEP: [(char, u32); 4] = [ + ('M', 3), + ('W', 4), + ('D', 7), + ('H', 24), +]; + +#[derive(Debug, Default, Clone, Copy)] +struct TierCfg { + enabled: bool, + keep: u32, +} + +type TierConfig = HashMap; + +fn parse_tier_config(config_json: &str) -> TierConfig { + let mut cfg = TierConfig::new(); + let v: serde_json::Value = serde_json::from_str(config_json).unwrap_or_default(); + + // New unified format: { hourly: { enabled, keep }, daily: ..., weekly: ..., monthly: ... } + for (tier_char, key, _) in &TIERS { + if let Some(obj) = v.get(key) { + let enabled = obj.get("enabled").and_then(|e| e.as_bool()).unwrap_or(false); + let default_keep = TIER_DEFAULT_KEEP.iter() + .find(|(c, _)| c == tier_char) + .map(|(_, k)| *k) + .unwrap_or(24); + let keep = obj.get("keep") + .and_then(|k| k.as_u64()) + .map(|k| k as u32) + .unwrap_or(default_keep); + cfg.insert(*tier_char, TierCfg { enabled, keep }); + } + } + + // Legacy single-tier format: { tier: "H", keep: 24 } + if cfg.is_empty() { + if let Some(tier_str) = v.get("tier").and_then(|t| t.as_str()) { + let tier_char = tier_str.chars().next().map(|c| c.to_ascii_uppercase()).unwrap_or('H'); + let default_keep = TIER_DEFAULT_KEEP.iter() + .find(|(c, _)| *c == tier_char) + .map(|(_, k)| *k) + .unwrap_or(24); + let keep = v.get("keep").and_then(|k| k.as_u64()).map(|k| k as u32).unwrap_or(default_keep); + cfg.insert(tier_char, TierCfg { enabled: true, keep }); + } + } + + cfg +} + +fn tier_config_any_enabled(cfg: &TierConfig) -> bool { + cfg.values().any(|c| c.enabled) +} + +// --------------------------------------------------------------------------- +// Path helpers (mirrors computeRenamedPath from SchedulerManager.tsx) +// --------------------------------------------------------------------------- + +/// Build a tier suffix string like "-MWD" from a comma-separated tiers string like "M,W,D". +fn tier_suffix(tiers: &str) -> String { + if tiers.is_empty() { + return String::new(); + } + const ORDER: [char; 4] = ['M', 'W', 'D', 'H']; + let flags: Vec = tiers + .split(',') + .filter_map(|t| t.trim().chars().next()) + .collect(); + let sorted: String = ORDER.iter().filter(|c| flags.contains(c)).collect(); + if sorted.is_empty() { String::new() } else { format!("-{sorted}") } +} + +/// Rename a backup file path to embed the new tier suffix. +/// "server-2024-01-15_10-00-00.7z" → "server-2024-01-15_10-00-00-DH.7z" +/// "server-2024-01-15_10-00-00-H.7z" + "D,H" → "server-2024-01-15_10-00-00-DH.7z" +fn compute_renamed_path(file_path: &str, new_tiers: &str) -> String { + let sep = if file_path.contains('\\') { '\\' } else { '/' }; + let last_sep = file_path.rfind(sep).map(|i| i + 1).unwrap_or(0); + let dir = &file_path[..last_sep]; + let fname = &file_path[last_sep..]; + + if !fname.ends_with(".7z") { + return file_path.to_string(); + } + + let stem = &fname[..fname.len() - 3]; // strip ".7z" + + // Strip existing tier suffix: if the last "-XXXX" segment is all tier chars, remove it. + let base_stem = if let Some(hyphen) = stem.rfind('-') { + let after = &stem[hyphen + 1..]; + if !after.is_empty() && after.chars().all(|c| matches!(c, 'M' | 'W' | 'D' | 'H')) { + &stem[..hyphen] + } else { + stem + } + } else { + stem + }; + + let new_suffix = tier_suffix(new_tiers); + format!("{dir}{base_stem}{new_suffix}.7z") +} + +/// Remove a single tier letter from a comma-separated tiers string. +fn remove_tier(tiers: &str, tier: char) -> String { + tiers + .split(',') + .filter(|t| !t.trim().is_empty() && t.trim() != &tier.to_string()) + .collect::>() + .join(",") +} + +// --------------------------------------------------------------------------- +// Core backup-record handler (handles one archive: tier assignment + DB + prune) +// --------------------------------------------------------------------------- + +/// Determine which tiers are due for `rec`, rename the file, insert into DB, and prune. +/// `eos_id = None` for server backups, `Some(id)` for player backups. +fn handle_backup_record( + conn: &rusqlite::Connection, + rec: &BackupRecord, + cfg: &TierConfig, + backup_type: &str, + eos_id: Option<&str>, +) { + let now_secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + + let all_backups = db::get_server_backups_by_type(conn, &rec.server_id, backup_type); + + // For player backups, only consider backups for this specific player. + let relevant: Vec<&db::BackupRow> = all_backups.iter() + .filter(|b| eos_id.map_or(true, |id| b.player_eosid.as_deref() == Some(id))) + .collect(); + + let mut due_tiers: Vec = Vec::new(); + + for (tier_char, _, threshold_secs) in &TIERS { + let t_cfg = match cfg.get(tier_char) { + Some(c) if c.enabled => *c, + _ => continue, + }; + let _ = t_cfg; // keep alive + + if *threshold_secs == 0 { + // Hourly: always due when the tick fires. + due_tiers.push(*tier_char); + continue; + } + + // Find the most recent backup with this tier. + let last_secs = relevant.iter() + .filter(|b| b.tiers.split(',').any(|t| t.trim() == tier_char.to_string())) + .map(|b| db::iso_to_unix_secs(&b.created_at)) + .max() + .unwrap_or(0); + + if now_secs.saturating_sub(last_secs) >= *threshold_secs { + due_tiers.push(*tier_char); + } + } + + if due_tiers.is_empty() { + // No tier is due — discard the archive. + let _ = std::fs::remove_file(&rec.file_path); + return; + } + + // Build canonical tier string (M,W,D,H priority order). + let const_order = ['M', 'W', 'D', 'H']; + let tiers_string: String = const_order.iter() + .filter(|c| due_tiers.contains(c)) + .map(|c| c.to_string()) + .collect::>() + .join(","); + + // Rename file to include tier suffix. + let renamed_path = compute_renamed_path(&rec.file_path, &tiers_string); + if renamed_path != rec.file_path { + let _ = std::fs::rename(&rec.file_path, &renamed_path); + } + + // Insert into DB. + let _ = db::insert_backup(conn, &db::BackupInsert { + id: &rec.id, + server_id: &rec.server_id, + file_path: &renamed_path, + file_size_bytes: rec.file_size_bytes, + map_id: &rec.map_id, + triggered_by: &rec.triggered_by, + created_at: &rec.created_at, + backup_type, + tiers: &tiers_string, + player_eosid: eos_id, + player_name: rec.player_name.as_deref(), + }); + + // Prune each due tier. + for tier_char in &due_tiers { + let keep = cfg.get(tier_char) + .map(|c| c.keep) + .unwrap_or_else(|| TIER_DEFAULT_KEEP.iter() + .find(|(c, _)| c == tier_char) + .map(|(_, k)| *k) + .unwrap_or(24)); + prune_by_tier(conn, &rec.server_id, backup_type, *tier_char, keep, eos_id); + } +} + +/// Remove excess archives for a tier, keeping at most `keep_count`. +fn prune_by_tier( + conn: &rusqlite::Connection, + server_id: &str, + backup_type: &str, + tier: char, + keep_count: u32, + eos_id: Option<&str>, +) { + let all = db::get_server_backups_by_type(conn, server_id, backup_type); + let tier_str = tier.to_string(); + + let with_tier: Vec<&db::BackupRow> = all.iter() + .filter(|b| { + if !b.tiers.split(',').any(|t| t.trim() == tier_str) { return false; } + if let Some(id) = eos_id { + b.player_eosid.as_deref() == Some(id) + } else { + true + } + }) + .collect(); + + if with_tier.len() <= keep_count as usize { + return; + } + + // `with_tier` is already sorted oldest-first (ORDER BY created_at ASC in query). + let excess_count = with_tier.len() - keep_count as usize; + for b in with_tier.iter().take(excess_count) { + let new_tiers = remove_tier(&b.tiers, tier); + if new_tiers.is_empty() { + // Last tier — delete file and record. + let _ = std::fs::remove_file(&b.file_path); + let _ = db::delete_backup_record(conn, &b.id); + } else { + // Still has other tiers — rename and update DB. + let new_path = compute_renamed_path(&b.file_path, &new_tiers); + if new_path != b.file_path { + let _ = std::fs::rename(&b.file_path, &new_path); + let _ = db::update_backup_file_path(conn, &b.id, &new_path); + } + let _ = db::update_backup_tiers(conn, &b.id, &new_tiers); + } + } +} + +// --------------------------------------------------------------------------- +// Main entry point: execute_tick +// --------------------------------------------------------------------------- + +// --------------------------------------------------------------------------- +// Login backup handler — called from log_manager when a player login is detected +// --------------------------------------------------------------------------- + +/// Called from the log watcher when a player login line is detected. +/// Records the player_connections row and, if login backups are configured, +/// creates an archive and prunes old ones — all without touching the webview. +pub async fn handle_player_login(app: &AppHandle, server_id: &str, eos_id: &str, ip: &str) { + let db_path = { + let state = app.state::(); + match state.get_db_path() { + Some(p) => p, + None => return, + } + }; + + let conn = match db::open(&db_path) { + Ok(c) => c, + Err(e) => { + eprintln!("[backup_manager] handle_player_login: DB open failed: {e}"); + return; + } + }; + + // Always record the connection, regardless of backup settings. + let _ = db::insert_player_connection(&conn, server_id, eos_id, ip); + + // Check if login backups are enabled for this server. + let keep_str = db::get_app_setting(&conn, &format!("login_backup_keep_{server_id}")); + let keep: usize = keep_str + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + if keep == 0 { + return; + } + + // Look up server info needed to create the archive. + let server = match db::get_server(&conn, server_id) { + Some(s) => s, + None => { + eprintln!("[backup_manager] handle_player_login: server {server_id} not found"); + return; + } + }; + + let backup_dir = match db::get_app_setting(&conn, "backup_dir") { + Some(d) if !d.is_empty() => d, + _ => return, + }; + + let map_path = map_id_to_path(&server.map_id); + + // Create the archive (eos_id used as player_name for the filename). + let rec = match create_player_backup_inner( + app, + server_id, + &server.name, + &server.install_path, + map_path, + &server.map_id, + &backup_dir, + eos_id, + eos_id, + "login", + "", + ).await { + Ok(r) => r, + Err(e) => { + eprintln!("[backup_manager] Login backup failed for {eos_id}@{server_id}: {e}"); + return; + } + }; + + // Insert into DB. + let _ = db::insert_backup(&conn, &db::BackupInsert { + id: &rec.id, + server_id, + file_path: &rec.file_path, + file_size_bytes: rec.file_size_bytes, + map_id: &rec.map_id, + triggered_by: "login", + created_at: &rec.created_at, + backup_type: "player", + tiers: "", + player_eosid: Some(eos_id), + player_name: Some(eos_id), + }); + + // Prune: keep at most `keep` login backups for this player. + let existing = db::get_player_login_backups(&conn, server_id, eos_id); + if existing.len() > keep { + let excess = existing.len() - keep; + for b in existing.iter().take(excess) { + let _ = std::fs::remove_file(&b.file_path); + let _ = db::delete_backup_record(&conn, &b.id); + } + } +} + +// --------------------------------------------------------------------------- + +/// Called from lib.rs once per hour at each :00:00 boundary. +/// Handles all scheduled backup logic entirely in Rust so it works even when +/// the WebKit webview is throttled in the system tray. +pub async fn execute_tick(app: &AppHandle) { + let db_path = { + let state = app.state::(); + match state.get_db_path() { + Some(p) => p, + None => { + // DB not initialized yet (setup not complete) — skip tick. + return; + } + } + }; + + let running_ids: Vec = { + let state = app.state::(); + let ids: Vec = state.running_servers.lock().unwrap().keys().cloned().collect(); + ids + }; + + if running_ids.is_empty() { + return; + } + + let conn = match db::open(&db_path) { + Ok(c) => c, + Err(e) => { + eprintln!("[backup_manager] Failed to open DB: {e}"); + return; + } + }; + + let backup_dir = match db::get_app_setting(&conn, "backup_dir") { + Some(d) if !d.is_empty() => d, + _ => { + eprintln!("[backup_manager] backup_dir not configured — skipping tick"); + return; + } + }; + + let servers = db::get_servers(&conn); + let pool = app.state::(); + + for server in &servers { + if !running_ids.contains(&server.id) { + continue; + } + + let schedules = db::get_server_schedules(&conn, &server.id); + let map_path = map_id_to_path(&server.map_id); + + // Parse both schedule configs up front so we can decide whether a + // world save is needed before starting either backup. + let server_cfg = schedules.iter() + .find(|s| s.schedule_type == "backup_server" && s.enabled == 1) + .map(|s| parse_tier_config(&s.config_json)); + let player_cfg = schedules.iter() + .find(|s| s.schedule_type == "backup_player" && s.enabled == 1) + .map(|s| parse_tier_config(&s.config_json)); + + let server_active = server_cfg.as_ref().map_or(false, tier_config_any_enabled); + let player_active = player_cfg.as_ref().map_or(false, tier_config_any_enabled); + + // ── Single world save for the whole tick ─────────────────────────── + // Issue SaveWorld once if any backup type is going to run, so both + // server and player backups read from the same flushed on-disk state. + if server_active || player_active { + let _ = rcon_save_world(&pool, &server.id).await; + // ASA confirms SaveWorld via RCON before all file I/O is done; + // wait for atomic writes (delete → rename) to settle. + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + } + + // ── Server backup ────────────────────────────────────────────────── + if server_active { + if let Some(cfg) = server_cfg { + match create_server_backup_inner( + app, + &server.id, + &server.name, + &server.install_path, + map_path, + &server.map_id, + &backup_dir, + "schedule", + "", // tier assigned after tier computation + &pool, + true, // world save already done above + ).await { + Ok(rec) => { + handle_backup_record(&conn, &rec, &cfg, "server", None); + let size = fmt_size(rec.file_size_bytes); + crate::commands::notifications::dispatch_notification( + app, "backup_completed", Some(&server.id), &server.name, + "Backup Complete", &format!("Scheduled server backup completed ({size})"), "success", + ).await; + let _ = app.emit( + &format!("backup://completed/{}", server.id), + serde_json::json!({ "serverId": server.id }), + ); + } + Err(e) => { + eprintln!("[backup_manager] Server backup failed for {}: {e}", server.name); + crate::commands::notifications::dispatch_notification( + app, "backup_failed", Some(&server.id), &server.name, + "Backup Failed", &format!("Scheduled server backup failed: {e}"), "error", + ).await; + let _ = app.emit( + &format!("backup://completed/{}", server.id), + serde_json::json!({ "serverId": server.id, "error": e }), + ); + } + } + } + } + + // ── Player backup ────────────────────────────────────────────────── + if player_active { + if let Some(cfg) = player_cfg { + match backup_all_players_inner( + app, + &server.id, + &server.name, + &server.install_path, + map_path, + &server.map_id, + &backup_dir, + "schedule", + ).await { + Ok(recs) => { + let count = recs.len(); + for rec in &recs { + let eos_id = rec.player_eosid.as_deref(); + handle_backup_record(&conn, rec, &cfg, "player", eos_id); + } + if count > 0 { + crate::commands::notifications::dispatch_notification( + app, "backup_completed", Some(&server.id), &server.name, + "Backup Complete", &format!("Scheduled player backups completed ({count} players)"), "success", + ).await; + } + } + Err(e) => { + eprintln!("[backup_manager] Player backup failed for {}: {e}", server.name); + crate::commands::notifications::dispatch_notification( + app, "backup_failed", Some(&server.id), &server.name, + "Backup Failed", &format!("Scheduled player backup failed: {e}"), "error", + ).await; + } + } + } + } + } +} diff --git a/src-tauri/src/commands/countdown.rs b/src-tauri/src/commands/countdown.rs new file mode 100644 index 0000000..bc9f770 --- /dev/null +++ b/src-tauri/src/commands/countdown.rs @@ -0,0 +1,472 @@ +use tauri::{AppHandle, Emitter, Manager, State}; +use tokio::sync::mpsc; +use tokio::time::{sleep, Duration}; +use serde::{Deserialize, Serialize}; + +use crate::state::AppState; +use crate::state::CountdownSignal; +use super::server::{inner_stop_server, inner_start_server, StartServerParams}; + +// --------------------------------------------------------------------------- +// Tauri event payload +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CountdownPayload { + pub server_id: String, + /// "restart" | "update" | null (null = countdown cleared) + pub action: Option, + pub remaining_secs: u64, + pub total_secs: u64, +} + +const COUNTDOWN_EVENT: &str = "server://countdown"; + +// --------------------------------------------------------------------------- +// RCON helper (fire-and-forget, never blocks the countdown) +// --------------------------------------------------------------------------- + +async fn rcon_send(rcon_port: u16, rcon_password: &str, cmd: &str) { + let _ = super::rcon::transient_rcon_command(rcon_port, rcon_password, cmd).await; +} + +// --------------------------------------------------------------------------- +// Result type returned by run_countdown +// --------------------------------------------------------------------------- + +pub enum CountdownResult { + Proceed, + Cancel, +} + +// --------------------------------------------------------------------------- +// Format a duration into "Xh Ym", "Xm Ys", or "Xs" for the RCON message. +// --------------------------------------------------------------------------- + +fn format_time(secs: u64) -> String { + if secs >= 3600 { + let h = secs / 3600; + let m = (secs % 3600) / 60; + if m == 0 { + format!("{h} hour{}", if h == 1 { "" } else { "s" }) + } else { + format!("{h}h {m}m") + } + } else if secs >= 60 { + let m = secs / 60; + let s = secs % 60; + if s == 0 { + format!("{m} minute{}", if m == 1 { "" } else { "s" }) + } else { + format!("{m}m {s}s") + } + } else { + format!("{secs} second{}", if secs == 1 { "" } else { "s" }) + } +} + +/// Seconds at which an in-game broadcast reminder is sent. +const BROADCAST_AT: &[u64] = &[3600, 1800, 900, 600, 300, 120, 60, 30, 10, 5]; + +// --------------------------------------------------------------------------- +// Core countdown logic — shared by manual commands and the scheduler. +// +// Returns Proceed when the countdown expired or ProceedNow was signalled. +// Returns Cancel when Cancel was signalled. +// +// If total_secs == 0 OR no players are online, returns Proceed immediately +// without sending any RCON messages. +// --------------------------------------------------------------------------- + +pub async fn run_countdown( + app: &AppHandle, + server_id: &str, + total_secs: u64, + rcon_port: u16, + rcon_password: &str, + message_template: &str, + cancel_message: &str, + action_label: &str, + rx: &mut mpsc::Receiver, +) -> CountdownResult { + // ── Check for players — skip countdown if none are online ──────────────── + if total_secs > 0 { + let player_resp = super::rcon::transient_rcon_command(rcon_port, rcon_password, "listplayers") + .await + .unwrap_or_default(); + let has_players = !player_resp.trim().is_empty() + && !player_resp.to_lowercase().contains("no players"); + + if !has_players { + // Emit a zero-remaining event so the frontend shows the action is + // starting immediately, then clear. + let _ = app.emit(COUNTDOWN_EVENT, CountdownPayload { + server_id: server_id.to_string(), + action: Some(action_label.to_string()), + remaining_secs: 0, + total_secs, + }); + emit_clear(app, server_id); + return CountdownResult::Proceed; + } + } else { + emit_clear(app, server_id); + return CountdownResult::Proceed; + } + + // ── Send initial broadcast and emit first countdown event ──────────────── + let initial_msg = message_template.replace("{time}", &format_time(total_secs)); + rcon_send(rcon_port, rcon_password, &format!("ServerChat {initial_msg}")).await; + + let _ = app.emit(COUNTDOWN_EVENT, CountdownPayload { + server_id: server_id.to_string(), + action: Some(action_label.to_string()), + remaining_secs: total_secs, + total_secs, + }); + + // ── Countdown loop ─────────────────────────────────────────────────────── + let mut remaining = total_secs; + + loop { + tokio::select! { + _ = sleep(Duration::from_secs(1)) => { + if remaining == 0 { + break; + } + remaining -= 1; + + // Emit UI update every second for live countdown display. + let _ = app.emit(COUNTDOWN_EVENT, CountdownPayload { + server_id: server_id.to_string(), + action: Some(action_label.to_string()), + remaining_secs: remaining, + total_secs, + }); + + // Send RCON broadcast at configured thresholds. + if BROADCAST_AT.contains(&remaining) { + let msg = message_template.replace("{time}", &format_time(remaining)); + rcon_send(rcon_port, rcon_password, &format!("ServerChat {msg}")).await; + } + + if remaining == 0 { + break; + } + } + signal = rx.recv() => { + match signal { + Some(CountdownSignal::ProceedNow) => { + emit_clear(app, server_id); + return CountdownResult::Proceed; + } + Some(CountdownSignal::Cancel) | None => { + // Notify players the action was cancelled. + if !cancel_message.is_empty() { + rcon_send(rcon_port, rcon_password, &format!("ServerChat {cancel_message}")).await; + } + emit_clear(app, server_id); + return CountdownResult::Cancel; + } + } + } + } + } + + emit_clear(app, server_id); + CountdownResult::Proceed +} + +fn emit_clear(app: &AppHandle, server_id: &str) { + let _ = app.emit(COUNTDOWN_EVENT, CountdownPayload { + server_id: server_id.to_string(), + action: None, + remaining_secs: 0, + total_secs: 0, + }); +} + +// --------------------------------------------------------------------------- +// Register / deregister countdown channels in AppState +// --------------------------------------------------------------------------- + +fn register_countdown(state: &AppState, server_id: &str) -> mpsc::Receiver { + let (tx, rx) = mpsc::channel::(1); + state.countdowns.lock().unwrap().insert(server_id.to_string(), tx); + rx +} + +fn deregister_countdown(state: &AppState, server_id: &str) { + state.countdowns.lock().unwrap().remove(server_id); +} + +// --------------------------------------------------------------------------- +// Tauri command: start_graceful_restart +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GracefulRestartParams { + pub server_id: String, + pub warn_seconds: u64, + pub rcon_port: u16, + pub rcon_password: String, + pub message: String, + pub cancel_message: String, + pub start_params: StartServerParams, +} + +#[tauri::command] +pub async fn start_graceful_restart( + app: AppHandle, + state: State<'_, AppState>, + params: GracefulRestartParams, +) -> Result<(), String> { + // Guard: only if actually running. + { + let reg = state.running_servers.lock().unwrap(); + if !reg.contains_key(¶ms.server_id) { + return Err(format!("Server {} is not running", params.server_id)); + } + } + + // Guard: no concurrent countdown. + { + let cd = state.countdowns.lock().unwrap(); + if cd.contains_key(¶ms.server_id) { + return Err("A countdown is already in progress for this server".into()); + } + } + + let mut rx = register_countdown(&state, ¶ms.server_id); + let app2 = app.clone(); + + // Spawn so the command returns immediately. + tauri::async_runtime::spawn(async move { + let state2 = app2.state::(); + let result = run_countdown( + &app2, + ¶ms.server_id, + params.warn_seconds, + params.rcon_port, + ¶ms.rcon_password, + ¶ms.message, + ¶ms.cancel_message, + "restart", + &mut rx, + ).await; + + deregister_countdown(&state2, ¶ms.server_id); + + if matches!(result, CountdownResult::Proceed) { + // saveworld → doexit → wait → restart + let _ = super::rcon::transient_rcon_command( + params.rcon_port, ¶ms.rcon_password, "saveworld" + ).await; + sleep(Duration::from_secs(3)).await; + let _ = super::rcon::transient_rcon_command( + params.rcon_port, ¶ms.rcon_password, "doexit" + ).await; + + // Wait up to 30s for graceful exit. + for _ in 0..60 { + sleep(Duration::from_millis(500)).await; + let still_running = state2.running_servers.lock().unwrap().contains_key(¶ms.server_id); + if !still_running { break; } + } + // Force-kill if still alive. + let _ = inner_stop_server(&app2, ¶ms.server_id, false); + + let _ = inner_start_server(app2, params.start_params).await; + } + }); + + Ok(()) +} + +// --------------------------------------------------------------------------- +// Tauri command: start_graceful_update +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GracefulUpdateParams { + pub server_id: String, + pub server_name: String, + pub warn_seconds: u64, + pub rcon_port: u16, + pub rcon_password: String, + pub message: String, + pub cancel_message: String, + pub install_path: String, + pub cache_dir: String, + pub steamcmd_path: String, + pub restart_after: bool, + pub start_params: Option, +} + +#[tauri::command] +pub async fn start_graceful_update( + app: AppHandle, + state: State<'_, AppState>, + params: GracefulUpdateParams, +) -> Result<(), String> { + // Guard: no concurrent countdown. + { + let cd = state.countdowns.lock().unwrap(); + if cd.contains_key(¶ms.server_id) { + return Err("A countdown is already in progress for this server".into()); + } + } + + let was_running = state.running_servers.lock().unwrap().contains_key(¶ms.server_id); + let mut rx = register_countdown(&state, ¶ms.server_id); + let app2 = app.clone(); + + tauri::async_runtime::spawn(async move { + let state2 = app2.state::(); + // Only run countdown if server is actually running. + let proceed = if was_running { + let r = run_countdown( + &app2, + ¶ms.server_id, + params.warn_seconds, + params.rcon_port, + ¶ms.rcon_password, + ¶ms.message, + ¶ms.cancel_message, + "update", + &mut rx, + ).await; + matches!(r, CountdownResult::Proceed) + } else { + true + }; + + deregister_countdown(&state2, ¶ms.server_id); + + if !proceed { return; } + + // Stop the server gracefully if it was running. + if was_running { + let _ = super::rcon::transient_rcon_command( + params.rcon_port, ¶ms.rcon_password, "saveworld" + ).await; + sleep(Duration::from_secs(3)).await; + let _ = super::rcon::transient_rcon_command( + params.rcon_port, ¶ms.rcon_password, "doexit" + ).await; + + for _ in 0..60 { + sleep(Duration::from_millis(500)).await; + let still = state2.running_servers.lock().unwrap().contains_key(¶ms.server_id); + if !still { break; } + } + let _ = inner_stop_server(&app2, ¶ms.server_id, false); + } + + // Emit "updating" status so server card shows spinner. + use crate::commands::server::emit_status; + use crate::commands::server::ServerStatus; + emit_status(&app2, &ServerStatus { + server_id: params.server_id.clone(), + status: "updating".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + + // Run SteamCMD update. + let channel = format!("steamcmd://output/{}", params.server_id); + if let Err(e) = tokio::fs::create_dir_all(¶ms.cache_dir).await { + eprintln!("Failed to create cache dir: {e}"); + } + + let update_result = crate::commands::steamcmd::steamcmd_app_update( + &app2, + ¶ms.steamcmd_path, + ¶ms.cache_dir, + false, + &channel, + None, + ).await; + + if let Err(e) = update_result { + eprintln!("Scheduled update SteamCMD failed: {e}"); + emit_status(&app2, &ServerStatus { + server_id: params.server_id.clone(), + status: "stopped".into(), + pid: None, + uptime_seconds: None, + error: Some(e), + }); + return; + } + + // Sync updated cache to server directory. + let cache_path = std::path::PathBuf::from(¶ms.cache_dir); + let server_path = std::path::PathBuf::from(¶ms.install_path); + if let Err(e) = tokio::task::spawn_blocking(move || { + crate::commands::steamcmd::sync_cache_to_server(&cache_path, &server_path) + }).await.map_err(|e| e.to_string()).and_then(|r| r.map_err(|e| e.to_string())) { + eprintln!("Cache sync failed: {e}"); + } + + // Emit update-available cleared. + let _ = app2.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ + "updateApplied": true, + "serverId": params.server_id, + })); + + // Restart if requested and we have start params. + if params.restart_after { + if let Some(sp) = params.start_params { + let _ = inner_start_server(app2, sp).await; + return; + } + } + + emit_status(&app2, &ServerStatus { + server_id: params.server_id.clone(), + status: "stopped".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + }); + + Ok(()) +} + +// --------------------------------------------------------------------------- +// Tauri command: cancel_countdown +// --------------------------------------------------------------------------- + +#[tauri::command] +pub async fn cancel_countdown( + state: State<'_, AppState>, + server_id: String, +) -> Result<(), String> { + let tx = state.countdowns.lock().unwrap().get(&server_id).cloned(); + match tx { + Some(tx) => tx.send(CountdownSignal::Cancel).await.map_err(|e| e.to_string()), + None => Err(format!("No countdown in progress for server {server_id}")), + } +} + +// --------------------------------------------------------------------------- +// Tauri command: proceed_now +// --------------------------------------------------------------------------- + +#[tauri::command] +pub async fn proceed_now( + state: State<'_, AppState>, + server_id: String, +) -> Result<(), String> { + let tx = state.countdowns.lock().unwrap().get(&server_id).cloned(); + match tx { + Some(tx) => tx.send(CountdownSignal::ProceedNow).await.map_err(|e| e.to_string()), + None => Err(format!("No countdown in progress for server {server_id}")), + } +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 970d0f9..e265a43 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -1,4 +1,6 @@ pub mod backup; +pub mod backup_manager; +pub mod countdown; pub mod certs; pub mod firewall; pub mod cluster; diff --git a/src-tauri/src/commands/notifications.rs b/src-tauri/src/commands/notifications.rs index 029f5b5..b4f14f7 100644 --- a/src-tauri/src/commands/notifications.rs +++ b/src-tauri/src/commands/notifications.rs @@ -1,4 +1,163 @@ use serde::{Deserialize, Serialize}; +use tauri::{Emitter, Manager}; + +use crate::db; +use crate::state::AppState; + +// --------------------------------------------------------------------------- +// Rust-side notification dispatcher +// --------------------------------------------------------------------------- + +/// Dispatch a notification from Rust — works even when the WebKit webview is +/// throttled in the system tray. +/// +/// For each enabled channel config: +/// - "desktop": fires an OS desktop notification +/// - "discord": POSTs an embed to the configured webhook +/// - "email": sends via SMTP (best-effort) +/// +/// Always logs the notification to `in_app_notifications` in SQLite so the +/// in-app notification center is complete even if the frontend missed the event. +/// +/// Emits two events for the frontend: +/// - `notification://toast` → frontend shows a Sonner toast (if window visible) +/// - `notification://logged` → frontend updates the bell badge unread count +pub async fn dispatch_notification( + app: &tauri::AppHandle, + event_type: &str, + server_id: Option<&str>, + server_name: &str, + title: &str, + body: &str, + severity: &str, +) { + // ── Load DB connection ───────────────────────────────────────────────── + let db_path = { + let state = app.state::(); + match state.get_db_path() { + Some(p) => p, + None => return, // DB not ready yet + } + }; + let conn = match db::open(&db_path) { + Ok(c) => c, + Err(e) => { + eprintln!("[notify] Failed to open DB: {e}"); + return; + } + }; + + // ── Load notification configs ────────────────────────────────────────── + let configs = db::get_notification_configs(&conn, server_id); + + // Track which channels we've processed (per-server configs take precedence). + let mut seen_channels = std::collections::HashSet::new(); + + let mut in_app_enabled = true; // default: show toast + let mut bell_enabled = true; // default: show unread badge + let mut desktop_active = false; + + for cfg in &configs { + let channel = cfg.channel.as_str(); + if seen_channels.contains(channel) { continue; } + // Per-server configs "own" the channel; global configs only apply if no per-server row. + if cfg.server_id.is_some() { seen_channels.insert(channel.to_string()); } + + if !event_enabled(&cfg.events_json, event_type) { continue; } + + match channel { + "in_app" => { + in_app_enabled = cfg.enabled == 1; + } + "bell" => { + bell_enabled = cfg.enabled == 1; + } + "desktop" if cfg.enabled == 1 => { + desktop_active = true; + let app2 = app.clone(); + let title = title.to_string(); + let body = body.to_string(); + tauri::async_runtime::spawn(async move { + use tauri_plugin_notification::NotificationExt; + let _ = app2.notification() + .builder() + .title(&title) + .body(&body) + .show(); + }); + } + "discord" if cfg.enabled == 1 => { + let cfg_json: serde_json::Value = + serde_json::from_str(&cfg.config_json).unwrap_or_default(); + if let Some(url) = cfg_json.get("webhookUrl").and_then(|u| u.as_str()) { + let state = app.state::(); + let payload = serde_json::json!({ + "embeds": [{ + "title": title, + "description": body, + "color": severity_color(severity), + "fields": [ + { "name": "Event", "value": event_type, "inline": true }, + { "name": "Server", "value": server_name, "inline": true } + ], + "footer": { "text": "LokiASAM" } + }] + }); + let client = state.http_client.clone(); + let url = url.to_string(); + tauri::async_runtime::spawn(async move { + let _ = client.post(&url).json(&payload).send().await; + }); + } + } + _ => {} + } + } + + // ── Log to in_app_notifications ──────────────────────────────────────── + let visible_channel_active = in_app_enabled || desktop_active; + let show_unread = bell_enabled && visible_channel_active; + + let id = uuid::Uuid::new_v4().to_string(); + let _ = db::log_notification(&conn, &db::NotifInsert { + id: &id, + server_id, + event_type, + title, + body, + severity, + read: if show_unread { 0 } else { 1 }, + }); + + // ── Signal the frontend ──────────────────────────────────────────────── + // Toast: show when window is visible + if in_app_enabled { + let _ = app.emit("notification://toast", serde_json::json!({ + "severity": severity, + "title": title, + "body": body, + })); + } + // Bell badge: always emit so the badge stays accurate even after restore from tray + let _ = app.emit("notification://logged", serde_json::json!({ + "serverId": server_id, + "unread": show_unread, + })); +} + +fn severity_color(severity: &str) -> u32 { + match severity { + "success" => 0x00ff88, + "warning" => 0xffaa00, + "error" => 0xff0055, + _ => 0x00ffff, + } +} + +fn event_enabled(events_json: &str, event_type: &str) -> bool { + let events: Vec = serde_json::from_str(events_json).unwrap_or_default(); + events.is_empty() || events.iter().any(|e| e == event_type) +} #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index beebd8a..e4b0e1c 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -5,6 +5,7 @@ use tokio::sync::{mpsc, oneshot}; use tokio::time::{timeout, Duration, interval, MissedTickBehavior}; use crate::state::{ + AppState, log_manager::LogManagerState, rcon_pool::{ bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, @@ -121,7 +122,7 @@ async fn exec_cmd( /// Owns the TCP connection for one server. Runs a select! loop that: /// • Processes commands from the mpsc channel (user commands, player refresh) /// • Polls listplayers every 30 s -/// • Polls GetChat every 5 s (only when chat_poll_active) +/// • Polls GetChat every 5 s (always — buffered in memory for the RCON page) /// /// All RCON I/O is serialized — nothing competes for the connection. /// On any fatal I/O error the task exits, emits rcon://status disconnected, @@ -199,6 +200,14 @@ async fn run_rcon_manager( pool.player_cache.lock().await .insert(server_id.clone(), players.clone()); } + // Upsert player names in SQLite — works even when webview is throttled. + if let Some(db_path) = app.state::().get_db_path() { + if let Ok(db_conn) = crate::db::open(&db_path) { + for p in &players { + let _ = crate::db::upsert_player_name(&db_conn, &server_id, &p.player_id, &p.name); + } + } + } let _ = app.emit(&format!("rcon://players/{server_id}"), &players); let _ = app.emit("rcon://players-any", serde_json::json!({ "serverId": server_id, "players": players })); let _ = response_tx.send(Ok(players)); @@ -225,6 +234,14 @@ async fn run_rcon_manager( pool.player_cache.lock().await .insert(server_id.clone(), players.clone()); } + // Upsert player names in SQLite — works even when webview is throttled. + if let Some(db_path) = app.state::().get_db_path() { + if let Ok(db_conn) = crate::db::open(&db_path) { + for p in &players { + let _ = crate::db::upsert_player_name(&db_conn, &server_id, &p.player_id, &p.name); + } + } + } let _ = app.emit(&format!("rcon://players/{server_id}"), &players); let _ = app.emit("rcon://players-any", serde_json::json!({ "serverId": server_id, "players": players })); } @@ -233,14 +250,8 @@ async fn run_rcon_manager( } } - // ── Periodic chat poll (every 5 s, only when tab is open) ───── + // ── Periodic chat poll (every 5 s) ─────────────────────────── _ = chat_tick.tick() => { - let active = app.state::() - .chat_poll_active.lock().await - .contains(&server_id); - - if !active { continue; } - match exec_cmd(&mut conn, "GetChat", 3_000).await { Ok(raw) => { for line in raw.lines().map(|l| l.trim()).filter(|l| !l.is_empty()) { @@ -486,6 +497,7 @@ pub async fn rcon_send( } /// Signal the manager task to close the connection and remove it from the pool. +/// Also clears the log buffer so the next server start gets a fresh console. #[tauri::command] pub async fn rcon_disconnect( server_id: String, @@ -494,6 +506,7 @@ pub async fn rcon_disconnect( if let Some((tx, _)) = pool.cmd_channels.lock().await.remove(&server_id) { let _ = tx.send(RconCmd::Disconnect).await; } + pool.log_buffer.lock().await.remove(&server_id); Ok(()) } @@ -565,26 +578,6 @@ pub async fn rcon_clear_log( Ok(()) } -/// Enable GetChat polling for this server (called when RCON tab opens). -#[tauri::command] -pub async fn rcon_enable_chat_poll( - server_id: String, - pool: State<'_, RconPool>, -) -> Result<(), String> { - pool.chat_poll_active.lock().await.insert(server_id); - Ok(()) -} - -/// Disable GetChat polling for this server (called when RCON tab closes). -#[tauri::command] -pub async fn rcon_disable_chat_poll( - server_id: String, - pool: State<'_, RconPool>, -) -> Result<(), String> { - pool.chat_poll_active.lock().await.remove(&server_id); - Ok(()) -} - /// Read the server's BanList.txt and return a list of EOS IDs. #[tauri::command] pub async fn rcon_read_ban_list(install_path: String) -> Result, String> { diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index 04b7b47..b6e175d 100644 --- a/src-tauri/src/commands/scheduler.rs +++ b/src-tauri/src/commands/scheduler.rs @@ -1,4 +1,4 @@ -use crate::state::{scheduler::SchedulerState, AppState, rcon_pool::RconPool}; +use crate::state::{scheduler::SchedulerState, AppState}; use serde::{Deserialize, Serialize}; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Emitter, Manager}; @@ -31,8 +31,8 @@ pub struct SchedulerFiredPayload { pub schedule_type: String, pub success: bool, pub error: Option, - /// Set when schedule_type == "backup" so the frontend can INSERT the record into SQLite. - pub backup_record: Option, + /// All backup records created by this firing (player backups produce one per player). + pub backup_records: Vec, } // --------------------------------------------------------------------------- @@ -63,13 +63,27 @@ pub async fn toggle_schedule(_schedule_id: String, _enabled: bool) -> Result<(), /// Called by the frontend whenever schedules are created, updated, toggled, or deleted, /// and once on startup after the DB is ready. Rust fires entries purely based on /// `next_run_ms` — cron parsing lives entirely in the frontend (cron-parser). +/// +/// Preserves `u64::MAX` for any entry that is currently in-flight (still running a +/// backup). The frontend may push a stale `next_run_ms` for such entries before it +/// has had a chance to update the DB; overwriting `u64::MAX` would cause an immediate +/// re-fire on the next tick. #[tauri::command] pub async fn sync_schedules( entries: Vec, state: tauri::State<'_, SchedulerState>, ) -> Result<(), String> { let mut store = state.entries.lock().unwrap(); - *store = entries; + let mut updated = entries; + for entry in updated.iter_mut() { + if let Some(existing) = store.iter().find(|e| e.schedule_id == entry.schedule_id) { + if existing.next_run_ms == u64::MAX { + // Entry is currently in-flight — don't overwrite the guard. + entry.next_run_ms = u64::MAX; + } + } + } + *store = updated; Ok(()) } @@ -132,48 +146,50 @@ async fn fire_broadcast(app: &AppHandle, entry: &crate::state::scheduler::Schedu } async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { - let is_running = { + if !is_server_running(app, &entry.server_id) { + return Ok(()); + } + + let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); + let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; + let message = cfg["message"].as_str().unwrap_or("Server restarting in {time}.").to_string(); + let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); + + let (tx, mut rx) = tokio::sync::mpsc::channel::(1); + { let state = app.state::(); - let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); - r - }; + state.countdowns.lock().unwrap().insert(entry.server_id.clone(), tx); + } - if !is_running { - return Ok(()); + let result = super::countdown::run_countdown( + app, + &entry.server_id, + warn_minutes * 60, + entry.rcon_port, + &entry.rcon_password, + &message, + &cancel_msg, + "restart", + &mut rx, + ).await; + + { + let state = app.state::(); + state.countdowns.lock().unwrap().remove(&entry.server_id); } - let cfg: serde_json::Value = - serde_json::from_str(&entry.config_json).unwrap_or_default(); - let broadcast_warning = cfg["broadcastWarning"].as_bool().unwrap_or(false); - let warning_minutes = cfg["warningMinutes"].as_u64().unwrap_or(0); - - if broadcast_warning && warning_minutes > 0 { - let template = cfg["message"] - .as_str() - .unwrap_or("Server restarting in {minutes} minutes.") - .to_string(); - let msg = template.replace("{minutes}", &warning_minutes.to_string()); - transient_rcon_send(entry.rcon_port, &entry.rcon_password, &format!("ServerChat {msg}")).await; - sleep(Duration::from_secs(warning_minutes * 60)).await; + if matches!(result, super::countdown::CountdownResult::Cancel) { + return Ok(()); } - // Clean shutdown via RCON: save then exit. transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; - sleep(Duration::from_secs(2)).await; + sleep(Duration::from_secs(3)).await; transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; - // Wait up to 30 s for the process to exit gracefully. for _ in 0..60 { sleep(Duration::from_millis(500)).await; - let still_running = { - let state = app.state::(); - let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); - r - }; - if !still_running { break; } + if !is_server_running(app, &entry.server_id) { break; } } - - // Force-kill if still alive. let _ = inner_stop_server(app, &entry.server_id, false); let params = entry_to_start_params(entry); @@ -223,93 +239,80 @@ async fn fire_global_update_check( } async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { - let cfg: serde_json::Value = - serde_json::from_str(&entry.config_json).unwrap_or_default(); + let cfg: serde_json::Value = serde_json::from_str(&entry.config_json).unwrap_or_default(); let sep = if entry.base_dir.contains('\\') { '\\' } else { '/' }; let cache_dir = format!("{}{sep}lokiasam{sep}cache{sep}asa-server", entry.base_dir); - // ── Check & Apply mode ──────────────────────────────────────────────────── - let is_running = { - let state = app.state::(); - let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); - r - }; - - let broadcast_warning = cfg["broadcastWarning"].as_bool().unwrap_or(false); - let warning_minutes = cfg["warningMinutes"].as_u64().unwrap_or(0); - let skip_if_players = cfg["skipIfPlayersOnline"].as_bool().unwrap_or(false); - let restart_after = cfg["restartAfterUpdate"].as_bool().unwrap_or(true); + let is_running = is_server_running(app, &entry.server_id); + let warn_minutes = if cfg["broadcastWarning"].as_bool().unwrap_or(false) { cfg["warningMinutes"].as_u64().unwrap_or(0) } else { 0 }; + let skip_if_players = cfg["skipIfPlayersOnline"].as_bool().unwrap_or(false); + let restart_after = cfg["restartAfterUpdate"].as_bool().unwrap_or(true); + let message = cfg["message"].as_str().unwrap_or("Server going down for update in {time}.").to_string(); + let cancel_msg = cfg["cancelMessage"].as_str().unwrap_or("").to_string(); - // Skip if players are online. + // Skip entirely if players are online and the schedule says to. if is_running && skip_if_players { - use crate::state::rcon_pool::{RconConn, RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND}; - use tokio::net::TcpStream; - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], entry.rcon_port)); - if let Ok(Ok(stream)) = tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(addr)).await { - let _ = stream.set_nodelay(true); - let mut conn = RconConn { stream, next_id: 1 }; - if conn.send_packet(1, RCON_AUTH, &entry.rcon_password).await.is_ok() { - for _ in 0..3 { - match tokio::time::timeout(Duration::from_secs(3), conn.recv_packet()).await { - Ok(Ok((_, t, _))) if t == RCON_AUTH_RESPONSE => break, - Ok(Err(_)) | Err(_) => break, - _ => {} - } - } - if let Ok(Ok(response)) = tokio::time::timeout( - Duration::from_secs(5), - conn.send_packet(2, RCON_EXECCOMMAND, "ListPlayers"), - ).await { - let _ = response; - // Wait briefly for the response then read it - if let Ok(Ok((_, _, body))) = tokio::time::timeout( - Duration::from_secs(5), - conn.recv_packet(), - ).await { - // "No Players Connected" or a list of players - if !body.trim().is_empty() && !body.contains("No Players Connected") { - return Ok(()); // players online — skip update - } - } - } - } + let resp = super::rcon::transient_rcon_command(entry.rcon_port, &entry.rcon_password, "listplayers") + .await + .unwrap_or_default(); + let has_players = !resp.trim().is_empty() && !resp.to_lowercase().contains("no players"); + if has_players { + return Ok(()); } } - // Broadcast warning before stopping the server. - if is_running && broadcast_warning && warning_minutes > 0 { - let template = cfg["message"] - .as_str() - .unwrap_or("Server updating in {minutes} minutes.") - .to_string(); - let msg = template.replace("{minutes}", &warning_minutes.to_string()); - transient_rcon_send(entry.rcon_port, &entry.rcon_password, &format!("ServerChat {msg}")).await; - sleep(Duration::from_secs(warning_minutes * 60)).await; - } - if is_running { - // Clean shutdown via RCON: save then exit. + let (tx, mut rx) = tokio::sync::mpsc::channel::(1); + { + let state = app.state::(); + state.countdowns.lock().unwrap().insert(entry.server_id.clone(), tx); + } + + let result = super::countdown::run_countdown( + app, + &entry.server_id, + warn_minutes * 60, + entry.rcon_port, + &entry.rcon_password, + &message, + &cancel_msg, + "update", + &mut rx, + ).await; + + { + let state = app.state::(); + state.countdowns.lock().unwrap().remove(&entry.server_id); + } + + if matches!(result, super::countdown::CountdownResult::Cancel) { + return Ok(()); + } + transient_rcon_send(entry.rcon_port, &entry.rcon_password, "saveworld").await; - sleep(Duration::from_secs(2)).await; + sleep(Duration::from_secs(3)).await; transient_rcon_send(entry.rcon_port, &entry.rcon_password, "doexit").await; for _ in 0..60 { sleep(Duration::from_millis(500)).await; - let still_running = { - let state = app.state::(); - let r = state.running_servers.lock().unwrap().contains_key(&entry.server_id); - r - }; - if !still_running { break; } + if !is_server_running(app, &entry.server_id) { break; } } - - // Force-kill if still alive. let _ = inner_stop_server(app, &entry.server_id, false); } + // Emit "updating" so the server card shows the spinner. + use crate::commands::server::{emit_status, ServerStatus}; + emit_status(app, &ServerStatus { + server_id: entry.server_id.clone(), + status: "updating".into(), + pid: None, + uptime_seconds: None, + error: None, + }); + // Update shared cache via SteamCMD. - let channel = format!("schedule://update/{}", entry.server_id); + let channel = format!("steamcmd://output/{}", entry.server_id); tokio::fs::create_dir_all(&cache_dir) .await .map_err(|e| format!("Failed to create cache dir: {e}"))?; @@ -328,7 +331,6 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE .map_err(|e| format!("Sync task panicked: {e}"))? .map_err(|e| format!("Failed to sync server files: {e}"))?; - // Emit update-applied event so the frontend can refresh the cached build ID. let _ = app.emit(crate::events::ASA_UPDATE_CHECK, serde_json::json!({ "updateApplied": true, "serverId": entry.server_id, @@ -368,117 +370,6 @@ fn is_server_running(app: &AppHandle, server_id: &str) -> bool { .contains_key(server_id) } -/// Fire a Server backup: cleanup ARK own files → SaveWorld → 7z SavedArks+SaveGames. -/// Skips silently if the server is stopped (scheduled runs only back up live servers). -async fn fire_server_backup( - app: &AppHandle, - entry: &crate::state::scheduler::ScheduleEntry, -) -> Result, String> { - // Scheduled server backups only run when the server is live. - if !is_server_running(app, &entry.server_id) { - return Ok(None); - } - - let pool = app.state::(); - crate::commands::backup::create_server_backup( - app.clone(), - entry.server_id.clone(), - entry.server_name.clone(), - entry.install_path.clone(), - entry.map_path.clone(), - entry.map_id.clone(), - entry.backup_dir.clone(), - "schedule".to_string(), - pool, - ) - .await - .map(Some) -} - -/// Fire a Player backup for all known .arkprofile files. -/// Reads the config_json for optional eos_id filter; defaults to all players. -/// Skips silently if the server is stopped. -async fn fire_player_backup( - app: &AppHandle, - entry: &crate::state::scheduler::ScheduleEntry, -) -> Result, String> { - if !is_server_running(app, &entry.server_id) { - return Ok(None); - } - - // Enumerate all .arkprofile files and zip each one. - // Returns the record for the last successful player backup (the count is - // captured in the frontend via per-player BackupRecord events). - let saved_dir = std::path::PathBuf::from(&entry.install_path) - .join("ShooterGame").join("Saved") - .join("SavedArks").join(&entry.map_path); - - if !saved_dir.exists() { - return Ok(None); - } - - let profiles: Vec<(String, std::path::PathBuf)> = std::fs::read_dir(&saved_dir) - .map_err(|e| e.to_string())? - .filter_map(|e| e.ok()) - .filter(|e| { - e.path().extension().and_then(|x| x.to_str()) == Some("arkprofile") - }) - .map(|e| { - let path = e.path(); - let eos_id = path.file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_string(); - (eos_id, path) - }) - .filter(|(id, _)| !id.is_empty()) - .collect(); - - if profiles.is_empty() { - return Ok(None); - } - - let mut last_record: Option = None; - for (eos_id, _) in &profiles { - match crate::commands::backup::create_player_backup( - app.clone(), - entry.server_id.clone(), - entry.server_name.clone(), - entry.install_path.clone(), - entry.map_path.clone(), - entry.map_id.clone(), - entry.backup_dir.clone(), - eos_id.clone(), - eos_id.clone(), // frontend resolves to display name; eos_id as fallback - "schedule".to_string(), - ) - .await - { - Ok(rec) => last_record = Some(rec), - Err(_) => {} // best-effort per player - } - } - Ok(last_record) -} - -/// Fire a Full backup. No server-running check — full backups may run any time. -async fn fire_full_backup( - app: &AppHandle, - entry: &crate::state::scheduler::ScheduleEntry, -) -> Result, String> { - crate::commands::backup::create_full_backup( - app.clone(), - entry.server_id.clone(), - entry.server_name.clone(), - entry.install_path.clone(), - entry.map_id.clone(), - entry.backup_dir.clone(), - "schedule".to_string(), - ) - .await - .map(Some) -} - /// Called by the background scheduler loop in lib.rs. /// Checks for due entries, fires them in separate spawned tasks, and marks them /// as fired (next_run_ms = u64::MAX) to prevent double-fire until the frontend resyncs. @@ -506,36 +397,24 @@ pub fn tick_scheduler(app: &AppHandle) { let server_id = entry.server_id.clone(); let server_name = entry.server_name.clone(); - let (success, error, backup_record) = match schedule_type.as_str() { + let (success, error, backup_records) = match schedule_type.as_str() { "broadcast" => match fire_broadcast(&app, &entry).await { - Ok(_) => (true, None, None), - Err(e) => (false, Some(e), None), - }, - "backup_server" => match fire_server_backup(&app, &entry).await { - Ok(rec) => (true, None, rec), - Err(e) => (false, Some(e), None), - }, - "backup_player" => match fire_player_backup(&app, &entry).await { - Ok(rec) => (true, None, rec), - Err(e) => (false, Some(e), None), - }, - "backup_full" => match fire_full_backup(&app, &entry).await { - Ok(rec) => (true, None, rec), - Err(e) => (false, Some(e), None), + Ok(_) => (true, None, vec![]), + Err(e) => (false, Some(e), vec![]), }, "restart" => match fire_restart(&app, &entry).await { - Ok(_) => (true, None, None), - Err(e) => (false, Some(e), None), + Ok(_) => (true, None, vec![]), + Err(e) => (false, Some(e), vec![]), }, "update" => match fire_update(&app, &entry).await { - Ok(_) => (true, None, None), - Err(e) => (false, Some(e), None), + Ok(_) => (true, None, vec![]), + Err(e) => (false, Some(e), vec![]), }, "global_update_check" => match fire_global_update_check(&app, &entry).await { - Ok(_) => (true, None, None), - Err(e) => (false, Some(e), None), + Ok(_) => (true, None, vec![]), + Err(e) => (false, Some(e), vec![]), }, - _ => (false, Some(format!("Unknown schedule type: {schedule_type}")), None), + _ => (false, Some(format!("Unknown schedule type: {schedule_type}")), vec![]), }; let _ = app.emit( @@ -547,7 +426,7 @@ pub fn tick_scheduler(app: &AppHandle) { schedule_type, success, error, - backup_record, + backup_records, }, ); }); diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 8dba940..619f0aa 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -120,7 +120,7 @@ pub struct StartServerParams { // --------------------------------------------------------------------------- /// Emit both the per-server and global status-change events. -fn emit_status(app: &tauri::AppHandle, status: &ServerStatus) { +pub(crate) fn emit_status(app: &tauri::AppHandle, status: &ServerStatus) { let _ = app.emit( &events::server_event(events::SERVER_STATUS, &status.server_id), status.clone(), @@ -384,6 +384,7 @@ async fn inner_start_server_with_state( let handle_clone = app_handle.clone(); let confirmed_clone = Arc::clone(&confirmed_running); let cfcore_clone = Arc::clone(&cfcore_unreachable); + let server_name_notif = params.server_name.clone(); tauri::async_runtime::spawn(async move { let (_, raw_stderr) = tokio::join!( child.wait(), @@ -411,6 +412,10 @@ async fn inner_start_server_with_state( if was_intentional { app_state.running_servers.lock().unwrap().remove(&sid); LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; + crate::commands::notifications::dispatch_notification( + &handle_clone, "server_stopped", Some(&sid), &server_name_notif, + &format!("{} stopped", server_name_notif), "Server has shut down.", "info", + ).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "stopped".into(), pid: None, uptime_seconds: None, error: None, @@ -422,6 +427,11 @@ async fn inner_start_server_with_state( if confirmed_clone.load(Ordering::Relaxed) { app_state.running_servers.lock().unwrap().remove(&sid); LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; + crate::commands::notifications::dispatch_notification( + &handle_clone, "server_crashed", Some(&sid), &server_name_notif, + &format!("{} crashed", server_name_notif), + "The server process crashed unexpectedly.", "error", + ).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "crashed".into(), pid: None, uptime_seconds: None, error: None, @@ -478,6 +488,15 @@ async fn inner_start_server_with_state( } else { filtered }; + let err_body = if trimmed.is_empty() { + "Server failed to start.".to_string() + } else { + trimmed.clone() + }; + crate::commands::notifications::dispatch_notification( + &handle_clone, "server_start_failed", Some(&sid), &server_name_notif, + &format!("{} failed to start", server_name_notif), &err_body, "error", + ).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "start-failed".into(), @@ -563,10 +582,11 @@ async fn inner_start_server_with_state( // Falls back to emitting "running" after 15 minutes if the message is // never seen (e.g. log location changed, log disabled) so the server // doesn't stay in "starting" forever. - let sid2 = params.server_id.clone(); - let handle2 = app_handle.clone(); - let query_port2 = params.query_port; - let log_path2 = format!( + let sid2 = params.server_id.clone(); + let handle2 = app_handle.clone(); + let query_port2 = params.query_port; + let server_name_ready = params.server_name.clone(); + let log_path2 = format!( "{}/ShooterGame/Saved/Logs/ShooterGame.log", params.install_path ); @@ -611,6 +631,15 @@ async fn inner_start_server_with_state( error: None, }, ); + let handle_n = handle.clone(); + let sid_n = sid.to_string(); + let name_n = server_name_ready.clone(); + tauri::async_runtime::spawn(async move { + crate::commands::notifications::dispatch_notification( + &handle_n, "server_started", Some(&sid_n), &name_n, + &format!("{name_n} is online"), "Players can now connect.", "success", + ).await; + }); true }; @@ -1182,7 +1211,7 @@ pub async fn graceful_stop_server( state.stopping_servers.lock().unwrap().remove(&server_id); state.running_servers.lock().unwrap().remove(&server_id); pool.cmd_channels.lock().await.remove(&server_id); - pool.chat_poll_active.lock().await.remove(&server_id); + pool.log_buffer.lock().await.remove(&server_id); pool.player_cache.lock().await.remove(&server_id); // Rotate logs now that the process is confirmed dead. Covers servers that diff --git a/src-tauri/src/commands/stats.rs b/src-tauri/src/commands/stats.rs index 81081b5..8105d98 100644 --- a/src-tauri/src/commands/stats.rs +++ b/src-tauri/src/commands/stats.rs @@ -1,13 +1,16 @@ use crate::state::stats_recorder::StatsRecorderState; +use crate::state::AppState; /// Called by the frontend once the JS-side `initDb(dbPath)` has run all migrations. -/// Opens a separate rusqlite connection for the background recorder task and -/// immediately runs the first rollup (pruning old raw samples and old daily rows). +/// Opens a separate rusqlite connection for the background recorder task, runs the +/// first rollup, and stores the db_path in AppState for Rust-side business logic. #[tauri::command] pub async fn init_stats_recorder( db_path: String, recorder: tauri::State<'_, StatsRecorderState>, + app_state: tauri::State<'_, AppState>, ) -> Result<(), String> { + app_state.set_db_path(&db_path); recorder.init(&db_path)?; let now_ms = std::time::SystemTime::now() diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index a10e6b0..cb5c11d 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -790,6 +790,23 @@ fn read_cstring(data: &[u8], cursor: &mut usize) -> Result { const APP_INTEGRATION_ID: &str = "xyz.lokisoft.lokiasam"; const APP_ICON_PNG: &[u8] = include_bytes!("../../icons/icon.png"); +/// Detect how the application was installed. +/// Returns one of: "appimage" | "pkgbuild" | "binary" +/// +/// - "appimage" — $APPIMAGE env var is set (running inside an AppImage) +/// - "pkgbuild" — marker file written by the PKGBUILD .install hook exists +/// - "binary" — raw executable, deb, or rpm (auto-updater works normally) +#[tauri::command] +pub fn get_install_method() -> &'static str { + if std::env::var_os("APPIMAGE").is_some() { + return "appimage"; + } + if std::path::Path::new("/usr/lib/lokiasam/install-method").exists() { + return "pkgbuild"; + } + "binary" +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AppImageIntegrationStatus { diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs new file mode 100644 index 0000000..4a8574b --- /dev/null +++ b/src-tauri/src/db.rs @@ -0,0 +1,400 @@ +// db.rs — direct rusqlite helpers for Rust-side business logic. +// Separate from the frontend's @tauri-apps/plugin-sql connection. +// Functions open a fresh connection per call using the db_path stored in AppState. + +use rusqlite::Connection; + +// --------------------------------------------------------------------------- +// Connection helper +// --------------------------------------------------------------------------- + +pub fn open(db_path: &str) -> Result { + let conn = Connection::open(db_path) + .map_err(|e| format!("Failed to open DB at {db_path}: {e}"))?; + conn.execute_batch( + "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;", + ) + .map_err(|e| format!("DB PRAGMA failed: {e}"))?; + Ok(conn) +} + +// --------------------------------------------------------------------------- +// Timestamp parsing — ISO "YYYY-MM-DDTHH:MM:SSZ" → Unix seconds +// Uses the Howard Hinnant civil-calendar algorithm (no external crate needed). +// --------------------------------------------------------------------------- + +pub fn iso_to_unix_secs(ts: &str) -> u64 { + let s = ts.trim_end_matches('Z'); + let t_pos = s.find('T').unwrap_or(s.len()); + let date = &s[..t_pos]; + let time = if t_pos < s.len() { &s[t_pos + 1..] } else { "0:0:0" }; + + let mut dp = date.split('-').filter_map(|x| x.parse::().ok()); + let mut tp = time.split(':').filter_map(|x| x.parse::().ok()); + + let y = dp.next().unwrap_or(1970); + let m = dp.next().unwrap_or(1); + let d = dp.next().unwrap_or(1); + let h = tp.next().unwrap_or(0); + let min = tp.next().unwrap_or(0); + let sec = tp.next().unwrap_or(0); + + let days = ymd_to_days_since_epoch(y, m, d); + let total = days.saturating_mul(86400) as u64 + h * 3600 + min * 60 + sec; + total +} + +fn ymd_to_days_since_epoch(y: i64, m: i64, d: i64) -> i64 { + // Howard Hinnant algorithm: https://howardhinnant.github.io/date_algorithms.html + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let m2 = if m > 2 { m - 3 } else { m + 9 }; + let doy = (153 * m2 + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +// --------------------------------------------------------------------------- +// app_settings +// --------------------------------------------------------------------------- + +pub fn get_app_setting(conn: &Connection, key: &str) -> Option { + conn.query_row( + "SELECT value FROM app_settings WHERE key = ?1", + [key], + |row| row.get::<_, String>(0), + ) + .ok() +} + +// --------------------------------------------------------------------------- +// servers +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct ServerRow { + pub id: String, + pub name: String, + pub map_id: String, + pub install_path: String, +} + +pub fn get_server(conn: &Connection, server_id: &str) -> Option { + conn.query_row( + "SELECT id, name, map_id, install_path FROM servers WHERE id = ?1", + [server_id], + |row| { + Ok(ServerRow { + id: row.get(0)?, + name: row.get(1)?, + map_id: row.get(2)?, + install_path: row.get(3)?, + }) + }, + ) + .ok() +} + +pub fn get_servers(conn: &Connection) -> Vec { + let mut stmt = match conn.prepare( + "SELECT id, name, map_id, install_path FROM servers", + ) { + Ok(s) => s, + Err(e) => { + eprintln!("[db] get_servers prepare failed: {e}"); + return vec![]; + } + }; + stmt.query_map([], |row| { + Ok(ServerRow { + id: row.get(0)?, + name: row.get(1)?, + map_id: row.get(2)?, + install_path: row.get(3)?, + }) + }) + .map(|rows| rows.filter_map(|r| r.ok()).collect()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// schedules +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct ScheduleRow { + pub schedule_type: String, + pub enabled: i64, + pub config_json: String, +} + +pub fn get_server_schedules(conn: &Connection, server_id: &str) -> Vec { + let mut stmt = match conn.prepare( + "SELECT schedule_type, enabled, config_json FROM schedules WHERE server_id = ?1", + ) { + Ok(s) => s, + Err(e) => { + eprintln!("[db] get_server_schedules prepare failed: {e}"); + return vec![]; + } + }; + stmt.query_map([server_id], |row| { + Ok(ScheduleRow { + schedule_type: row.get(0)?, + enabled: row.get(1)?, + config_json: row.get(2)?, + }) + }) + .map(|rows| rows.filter_map(|r| r.ok()).collect()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// backups +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct BackupRow { + pub id: String, + pub file_path: String, + pub created_at: String, + pub tiers: String, + pub player_eosid: Option, +} + +/// Returns all backups for a server+type, sorted oldest-first. +pub fn get_server_backups_by_type( + conn: &Connection, + server_id: &str, + backup_type: &str, +) -> Vec { + let mut stmt = match conn.prepare( + "SELECT id, file_path, created_at, tiers, player_eosid \ + FROM backups \ + WHERE server_id = ?1 AND backup_type = ?2 \ + ORDER BY created_at ASC", + ) { + Ok(s) => s, + Err(e) => { + eprintln!("[db] get_server_backups_by_type prepare failed: {e}"); + return vec![]; + } + }; + stmt.query_map([server_id, backup_type], |row| { + Ok(BackupRow { + id: row.get(0)?, + file_path: row.get(1)?, + created_at: row.get(2)?, + tiers: row.get(3)?, + player_eosid: row.get(4)?, + }) + }) + .map(|rows| rows.filter_map(|r| r.ok()).collect()) + .unwrap_or_default() +} + +pub struct BackupInsert<'a> { + pub id: &'a str, + pub server_id: &'a str, + pub file_path: &'a str, + pub file_size_bytes: u64, + pub map_id: &'a str, + pub triggered_by: &'a str, + pub created_at: &'a str, + pub backup_type: &'a str, + pub tiers: &'a str, + pub player_eosid: Option<&'a str>, + pub player_name: Option<&'a str>, +} + +pub fn insert_backup(conn: &Connection, b: &BackupInsert) -> Result<(), String> { + conn.execute( + "INSERT INTO backups \ + (id, server_id, file_path, file_size_bytes, map_id, triggered_by, \ + created_at, backup_type, tiers, player_eosid, player_name) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + rusqlite::params![ + b.id, + b.server_id, + b.file_path, + b.file_size_bytes as i64, + b.map_id, + b.triggered_by, + b.created_at, + b.backup_type, + b.tiers, + b.player_eosid, + b.player_name, + ], + ) + .map_err(|e| format!("insert_backup failed: {e}"))?; + Ok(()) +} + +pub fn update_backup_tiers(conn: &Connection, id: &str, tiers: &str) -> Result<(), String> { + conn.execute("UPDATE backups SET tiers = ?1 WHERE id = ?2", [tiers, id]) + .map_err(|e| format!("update_backup_tiers failed: {e}"))?; + Ok(()) +} + +pub fn update_backup_file_path(conn: &Connection, id: &str, path: &str) -> Result<(), String> { + conn.execute("UPDATE backups SET file_path = ?1 WHERE id = ?2", [path, id]) + .map_err(|e| format!("update_backup_file_path failed: {e}"))?; + Ok(()) +} + +pub fn delete_backup_record(conn: &Connection, id: &str) -> Result<(), String> { + conn.execute("DELETE FROM backups WHERE id = ?1", [id]) + .map_err(|e| format!("delete_backup_record failed: {e}"))?; + Ok(()) +} + +/// Returns all login backups for a player, oldest-first. +pub fn get_player_login_backups( + conn: &Connection, + server_id: &str, + eos_id: &str, +) -> Vec { + let mut stmt = match conn.prepare( + "SELECT id, file_path, created_at, tiers, player_eosid \ + FROM backups \ + WHERE server_id = ?1 AND backup_type = 'player' AND player_eosid = ?2 \ + AND triggered_by = 'login' \ + ORDER BY created_at ASC", + ) { + Ok(s) => s, + Err(e) => { + eprintln!("[db] get_player_login_backups prepare failed: {e}"); + return vec![]; + } + }; + stmt.query_map([server_id, eos_id], |row| { + Ok(BackupRow { + id: row.get(0)?, + file_path: row.get(1)?, + created_at: row.get(2)?, + tiers: row.get(3)?, + player_eosid: row.get(4)?, + }) + }) + .map(|rows| rows.filter_map(|r| r.ok()).collect()) + .unwrap_or_default() +} + +pub fn insert_player_connection( + conn: &Connection, + server_id: &str, + eos_id: &str, + ip: &str, +) -> Result<(), String> { + conn.execute( + "INSERT INTO player_connections (id, server_id, eos_id, ip_address, connected_at) \ + VALUES (?1, ?2, ?3, ?4, datetime('now'))", + rusqlite::params![uuid::Uuid::new_v4().to_string(), server_id, eos_id, ip], + ) + .map_err(|e| format!("insert_player_connection failed: {e}"))?; + Ok(()) +} + +pub fn upsert_player_name( + conn: &Connection, + server_id: &str, + eos_id: &str, + name: &str, +) -> Result<(), String> { + conn.execute( + "INSERT INTO player_name_map (server_id, eos_id, player_name, last_seen) \ + VALUES (?1, ?2, ?3, datetime('now')) \ + ON CONFLICT(server_id, eos_id) DO UPDATE \ + SET player_name = excluded.player_name, last_seen = excluded.last_seen", + [server_id, eos_id, name], + ) + .map_err(|e| format!("upsert_player_name failed: {e}"))?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// notifications +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +pub struct NotificationConfig { + pub server_id: Option, + pub channel: String, + pub enabled: i64, + pub config_json: String, + pub events_json: String, +} + +/// Returns notification configs, per-server rows first (so dispatch logic can +/// apply per-server channel settings before falling back to global). +pub fn get_notification_configs( + conn: &Connection, + server_id: Option<&str>, +) -> Vec { + let mut results: Vec = Vec::new(); + + // Per-server configs + if let Some(sid) = server_id { + if let Ok(mut stmt) = conn.prepare( + "SELECT server_id, channel, enabled, config_json, events_json \ + FROM notification_configs WHERE server_id = ?1", + ) { + if let Ok(rows) = stmt.query_map([sid], |row| { + Ok(NotificationConfig { + server_id: row.get(0)?, + channel: row.get(1)?, + enabled: row.get(2)?, + config_json: row.get(3)?, + events_json: row.get(4)?, + }) + }) { + results.extend(rows.filter_map(|r| r.ok())); + } + } + } + + // Global configs (server_id IS NULL) + if let Ok(mut stmt) = conn.prepare( + "SELECT server_id, channel, enabled, config_json, events_json \ + FROM notification_configs WHERE server_id IS NULL", + ) { + if let Ok(rows) = stmt.query_map([], |row| { + Ok(NotificationConfig { + server_id: row.get(0)?, + channel: row.get(1)?, + enabled: row.get(2)?, + config_json: row.get(3)?, + events_json: row.get(4)?, + }) + }) { + results.extend(rows.filter_map(|r| r.ok())); + } + } + + results +} + +pub struct NotifInsert<'a> { + pub id: &'a str, + pub server_id: Option<&'a str>, + pub event_type: &'a str, + pub title: &'a str, + pub body: &'a str, + pub severity: &'a str, + pub read: i64, +} + +pub fn log_notification(conn: &Connection, n: &NotifInsert) -> Result<(), String> { + conn.execute( + "INSERT INTO in_app_notifications \ + (id, server_id, event_type, title, body, severity, read) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + rusqlite::params![ + n.id, n.server_id, n.event_type, n.title, n.body, n.severity, n.read, + ], + ) + .map_err(|e| format!("log_notification failed: {e}"))?; + Ok(()) +} diff --git a/src-tauri/src/events/mod.rs b/src-tauri/src/events/mod.rs index 4b648a9..ac4dd0d 100644 --- a/src-tauri/src/events/mod.rs +++ b/src-tauri/src/events/mod.rs @@ -16,6 +16,11 @@ pub const LOG_BACKFILL: &str = "log://backfill"; pub const BACKUP_PROGRESS: &str = "backup://progress"; /// ASA update check result (or update-applied notification). pub const ASA_UPDATE_CHECK: &str = "asa://update-check"; +/// Player login detected from ShooterGame.log — carries { eosId, ip }. +/// Emitted on the per-server channel `player://login/{server_id}`. +pub const PLAYER_LOGIN: &str = "player://login"; +/// Same login event broadcast globally — carries { serverId, eosId, ip }. +pub const PLAYER_LOGIN_ANY: &str = "player://login-any"; /// Build a namespaced event name for a specific server. /// e.g. `server_event("server://status", "abc-123")` → `"server://status/abc-123"` diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 523334d..c9f119e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ mod commands; +mod db; mod events; mod state; @@ -237,6 +238,27 @@ pub fn run() { } }); + // ── Hourly backup tick ───────────────────────────────────────── + // Fires at each wall-clock hour boundary (7:00, 8:00, …) so backup + // checks are predictable and independent of when the app started. + let backup_tick_handle = app.handle().clone(); + tauri::async_runtime::spawn(async move { + use std::time::{SystemTime, UNIX_EPOCH}; + + // Sleep until the next :00:00 boundary. + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let secs_until_next_hour = 3600 - (now_secs % 3600); + tokio::time::sleep(tokio::time::Duration::from_secs(secs_until_next_hour)).await; + + loop { + crate::commands::backup_manager::execute_tick(&backup_tick_handle).await; + tokio::time::sleep(tokio::time::Duration::from_secs(3600)).await; + } + }); + // ── Stats recorder background task ───────────────────────────── // Polls all running servers every 5 s. On every poll: // - Emits "stats://live" so the frontend live buffer stays current. @@ -398,6 +420,11 @@ pub fn run() { commands::server::stop_server, commands::server::restart_server, commands::server::graceful_stop_server, + // Graceful countdown (restart / update with player warning) + commands::countdown::start_graceful_restart, + commands::countdown::start_graceful_update, + commands::countdown::cancel_countdown, + commands::countdown::proceed_now, commands::server::get_server_status, commands::server::scan_running_servers, commands::server::clone_server, @@ -432,8 +459,6 @@ pub fn run() { commands::rcon::rcon_get_cached_players, commands::rcon::rcon_get_log, commands::rcon::rcon_clear_log, - commands::rcon::rcon_enable_chat_poll, - commands::rcon::rcon_disable_chat_poll, commands::rcon::rcon_read_ban_list, commands::rcon::rcon_read_whitelist, // Log watcher + archive + crash + chat @@ -459,6 +484,7 @@ pub fn run() { // Backups commands::backup::create_server_backup, commands::backup::create_player_backup, + commands::backup::backup_all_players, commands::backup::create_ini_backup, commands::backup::create_full_backup, commands::backup::list_ini_backups, @@ -469,6 +495,9 @@ pub fn run() { commands::backup::delete_backup, commands::backup::cleanup_ark_own_backups, commands::backup::estimate_dir_size, + commands::backup::rename_backup_file, + commands::backup::backup_file_exists, + commands::backup::scan_backup_dir, // Mods (Phase 5) commands::mods::install_mods, commands::mods::open_mod_browser, @@ -481,6 +510,7 @@ pub fn run() { commands::system::check_appimage_integration, commands::system::install_appimage_integration, commands::system::uninstall_appimage_integration, + commands::system::get_install_method, commands::system::check_dir, commands::system::check_file_exists, commands::system::delete_directory, diff --git a/src-tauri/src/state/log_manager.rs b/src-tauri/src/state/log_manager.rs index 000f17d..e066419 100644 --- a/src-tauri/src/state/log_manager.rs +++ b/src-tauri/src/state/log_manager.rs @@ -305,7 +305,8 @@ async fn tail_log_with_backfill( let _ = file.seek(SeekFrom::End(0)).await; // ── Tail: stream new lines as they arrive ──────────────────────────────── - let line_event = format!("{}/{server_id}", events::LOG_LINE); + let line_event = format!("{}/{server_id}", events::LOG_LINE); + let login_event = format!("{}/{server_id}", events::PLAYER_LOGIN); let mut reader = BufReader::new(file); let mut line_buf = String::new(); @@ -321,7 +322,22 @@ async fn tail_log_with_backfill( let trimmed = line_buf.trim_end_matches(['\n', '\r']).to_string(); if !trimmed.is_empty() { let level = classify_level(&trimmed).to_string(); - let _ = app.emit(&line_event, LogLine { line: trimmed, level }); + let _ = app.emit(&line_event, LogLine { line: trimmed.clone(), level }); + if let Some((eos_id, ip)) = parse_player_login(&trimmed) { + let _ = app.emit(&login_event, serde_json::json!({ "eosId": eos_id, "ip": ip })); + let _ = app.emit( + crate::events::PLAYER_LOGIN_ANY, + serde_json::json!({ "serverId": server_id, "eosId": eos_id, "ip": ip }), + ); + // Record connection + login backup in Rust (works even in tray). + let app2 = app.clone(); + let sid2 = server_id.clone(); + tauri::async_runtime::spawn(async move { + crate::commands::backup_manager::handle_player_login( + &app2, &sid2, &eos_id, &ip, + ).await; + }); + } } line_buf.clear(); } @@ -330,6 +346,23 @@ async fn tail_log_with_backfill( } } +/// Parse "IP for incoming account {EOS_ID} - IP {IP}" from a log line. +/// Returns (eos_id, ip) if matched. +fn parse_player_login(line: &str) -> Option<(String, String)> { + let prefix = "IP for incoming account "; + let sep = " - IP "; + let start = line.find(prefix)?; + let after = &line[start + prefix.len()..]; + let mid = after.find(sep)?; + let eos_id = after[..mid].trim().to_string(); + let ip = after[mid + sep.len()..].trim().to_string(); + if eos_id.chars().all(|c| c.is_ascii_hexdigit()) && !eos_id.is_empty() && !ip.is_empty() { + Some((eos_id, ip)) + } else { + None + } +} + // --------------------------------------------------------------------------- // Time helpers (no external crate, manual calculation) // --------------------------------------------------------------------------- diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 40b5398..73f8fcc 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -7,6 +7,12 @@ use std::collections::{HashMap, HashSet}; use std::sync::{atomic::AtomicBool, Arc, Mutex}; use std::time::Instant; +/// Signal sent to an in-progress countdown task. +pub enum CountdownSignal { + Cancel, + ProceedNow, +} + /// A server process currently tracked by this app session. pub struct RunningServer { /// OS process ID. @@ -43,6 +49,14 @@ pub struct AppState { /// Per-operation abort flags. Key examples: "steamcmd_install", "proton_download", /// "server_{id}". Set to true to request cancellation; commands clear their key on exit. pub abort_flags: Mutex>>, + /// Active countdown tasks keyed by server_id. Sending a signal cancels or + /// short-circuits the running countdown. + pub countdowns: Mutex>>, + /// Absolute filesystem path to the SQLite database file. + /// Set by `init_stats_recorder` (the first Rust-side DB init call from the frontend). + /// Used by Rust-side business logic (backup manager, notification dispatch) to open + /// their own rusqlite connections without blocking the Tauri plugin-sql connection. + pub db_path: Mutex>, } impl AppState { @@ -58,9 +72,21 @@ impl AppState { .build() .expect("Failed to build shared HTTP client"), abort_flags: Mutex::new(HashMap::new()), + countdowns: Mutex::new(HashMap::new()), + db_path: Mutex::new(None), } } + /// Store the database file path (called from init_stats_recorder). + pub fn set_db_path(&self, path: &str) { + *self.db_path.lock().unwrap() = Some(path.to_string()); + } + + /// Retrieve the database file path, if set. + pub fn get_db_path(&self) -> Option { + self.db_path.lock().unwrap().clone() + } + /// Register a new abort flag for `op_id` and return a clone of it. /// Replaces any existing flag for the same key. pub fn register_abort(&self, op_id: &str) -> Arc { diff --git a/src-tauri/src/state/rcon_pool.rs b/src-tauri/src/state/rcon_pool.rs index 7955d99..d8a0744 100644 --- a/src-tauri/src/state/rcon_pool.rs +++ b/src-tauri/src/state/rcon_pool.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashMap, VecDeque}; use std::sync::atomic::{AtomicU64, Ordering}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; @@ -116,8 +116,6 @@ pub struct RconPool { pub cmd_channels: Mutex, u64)>>, /// Rolling console log buffer per server, capped at 500 lines. pub log_buffer: Mutex>>, - /// Server IDs that have an active GetChat poll subscriber (RCON tab open). - pub chat_poll_active: Mutex>, /// Last-known player list per server. A missing key means no data yet /// (never connected this session); an empty Vec means 0 players online. pub player_cache: Mutex>>, @@ -130,7 +128,6 @@ impl RconPool { Self { cmd_channels: Mutex::new(HashMap::new()), log_buffer: Mutex::new(HashMap::new()), - chat_poll_active: Mutex::new(HashSet::new()), player_cache: Mutex::new(HashMap::new()), next_conn_id: AtomicU64::new(1), } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1194aab..0cb0f72 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "LokiASAM", - "version": "0.12.0", + "version": "0.13.0", "identifier": "xyz.lokisoft.lokiasam", "build": { "frontendDist": "../out", diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx index 04ce1a1..03f2b9f 100644 --- a/src/components/layout/AppShell.tsx +++ b/src/components/layout/AppShell.tsx @@ -12,10 +12,12 @@ import { NotificationManager } from "@/components/layout/NotificationManager"; import { UpdateManager } from "@/components/layout/UpdateManager"; import { CloseWarningManager } from "@/components/layout/CloseWarningManager"; import { RconManager } from "@/components/layout/RconManager"; +import { LogWatcherManager } from "@/components/layout/LogWatcherManager"; import { StartupReconciliationManager } from "@/components/layout/StartupReconciliationManager"; import { StartupQueueManager } from "@/components/layout/StartupQueueManager"; import { StartupRecoveryManager } from "@/components/layout/StartupRecoveryManager"; import { CfcoreRetryManager } from "@/components/layout/CfcoreRetryManager"; +import CountdownManager from "@/components/layout/CountdownManager"; import { ServerStatsRecorderProvider } from "@/providers/ServerStatsRecorderProvider"; import { Toaster } from "sonner"; @@ -39,9 +41,11 @@ export function AppShell({ children }: { children: React.ReactNode }) { + +
diff --git a/src/components/layout/CountdownManager.tsx b/src/components/layout/CountdownManager.tsx new file mode 100644 index 0000000..a3a82a7 --- /dev/null +++ b/src/components/layout/CountdownManager.tsx @@ -0,0 +1,33 @@ +"use client"; + +import { useEffect } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { useAppStore } from "@/store/useAppStore"; + +interface CountdownPayload { + serverId: string; + action: "restart" | "update" | null; + remainingSecs: number; + totalSecs: number; +} + +export default function CountdownManager() { + const setCountdown = useAppStore((s) => s.setCountdown); + + useEffect(() => { + const unlisten = listen("server://countdown", (ev) => { + const { serverId, action, remainingSecs, totalSecs } = ev.payload; + if (!action) { + setCountdown(serverId, null); + } else { + setCountdown(serverId, { action, remainingSecs, totalSecs }); + } + }); + + return () => { + unlisten.then((fn) => fn()); + }; + }, [setCountdown]); + + return null; +} diff --git a/src/components/layout/LogWatcherManager.tsx b/src/components/layout/LogWatcherManager.tsx new file mode 100644 index 0000000..dc229f3 --- /dev/null +++ b/src/components/layout/LogWatcherManager.tsx @@ -0,0 +1,59 @@ +"use client"; + +/** + * LogWatcherManager — global side-effect component that tails ShooterGame.log + * for all running servers. + * + * Ensures player://login-any events are emitted even when the Logs tab is never + * opened, so login backups and player activity tracking work in the background. + * + * LogsTab may restart the watcher (for backfill) when it mounts — that's fine. + * This manager re-owns the watcher once the tab unmounts or after server restart. + */ + +import { useEffect } from "react"; +import { getServers } from "@/lib/db"; +import { tauriCmd, type ServerStatus } from "@/lib/tauri-commands"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; + +function logPath(installPath: string): string { + const sep = installPath.includes("\\") ? "\\" : "/"; + return `${installPath}${sep}ShooterGame${sep}Saved${sep}Logs${sep}ShooterGame.log`; +} + +async function startWatcher(serverId: string, installPath: string) { + try { + await tauriCmd.watchServerLog(serverId, logPath(installPath)); + } catch { + // Not ready yet — next status event will retry. + } +} + +export function LogWatcherManager() { + // ── Start watchers for all running/starting servers on mount ───────────── + useEffect(() => { + getServers().then((servers) => { + for (const s of servers) { + if (s.status === "running" || s.status === "starting") { + startWatcher(s.id, s.install_path); + } + } + }).catch(() => null); + }, []); + + // ── React to server lifecycle changes ──────────────────────────────────── + useTauriEvent("server://any-change", (payload) => { + if (payload.status === "running" || payload.status === "starting") { + getServers().then((servers) => { + const s = servers.find((srv) => srv.id === payload.serverId); + if (s) startWatcher(s.id, s.install_path); + }).catch(() => null); + } + + if (["stopped", "crashed", "start-failed"].includes(payload.status)) { + tauriCmd.stopLogWatch(payload.serverId).catch(() => null); + } + }); + + return null; +} diff --git a/src/components/layout/NotificationManager.tsx b/src/components/layout/NotificationManager.tsx index 03964df..bd9a34f 100644 --- a/src/components/layout/NotificationManager.tsx +++ b/src/components/layout/NotificationManager.tsx @@ -3,78 +3,36 @@ /** * NotificationManager — mounts once in the root layout. * - * Subscribes to `server://any-change` Tauri events and fires - * `dispatchNotification` for status transitions worth notifying about: - * - server started → success - * - server stopped → info - * - server crashed → error + * Server status notifications are now dispatched from Rust (dispatch_notification + * in notifications.rs), so they fire even when the WebKit webview is throttled + * in the system tray. This component just handles the two frontend-facing events: * - * The dispatch function persists the event to SQLite, bumps the Zustand - * unread counter (so the bell icon refreshes), and fires any configured - * external channels (OS toast, Discord, email). + * - `notification://toast` → show a Sonner toast when the window is visible + * - `notification://logged` → bump the bell badge unread counter */ -import { useRef } from "react"; +import { toast } from "sonner"; import { useTauriEvent } from "@/hooks/useTauriEvent"; -import { dispatchNotification } from "@/lib/notifications"; -import { getServer } from "@/lib/db"; -import { NOTIFICATION_EVENTS } from "@/data/game-data"; -import type { ServerStatus } from "@/lib/tauri-commands"; +import { useAppStore } from "@/store/useAppStore"; export function NotificationManager() { - // Debounce: track the last status per server so we don't emit duplicate - // notifications when the crash-monitor fires after the per-server watcher - // already handled the same transition. - const lastStatusRef = useRef>(new Map()); - - useTauriEvent("server://any-change", async (status) => { - const prev = lastStatusRef.current.get(status.serverId); - if (prev === status.status) return; - lastStatusRef.current.set(status.serverId, status.status); - - const server = await getServer(status.serverId).catch(() => null); - const serverName = server?.name ?? status.serverId.slice(0, 8); + useTauriEvent<{ severity: string; title: string; body: string }>( + "notification://toast", + ({ severity, title, body }) => { + const msg = body ? `${title} — ${body}` : title; + if (severity === "success") toast.success(msg); + else if (severity === "warning") toast.warning(msg); + else if (severity === "error") toast.error(msg); + else toast(msg); + } + ); - if (status.status === "running") { - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.SERVER_STARTED, - serverId: status.serverId, - serverName, - title: `${serverName} started`, - body: `Server is online${status.pid ? ` (PID ${status.pid})` : ""}.`, - severity: "success", - }); - } else if (status.status === "stopped") { - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.SERVER_STOPPED, - serverId: status.serverId, - serverName, - title: `${serverName} stopped`, - body: "Server has shut down.", - severity: "info", - }); - } else if (status.status === "crashed") { - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.SERVER_CRASHED, - serverId: status.serverId, - serverName, - title: `${serverName} crashed`, - body: "Server process exited unexpectedly. Check the Logs tab for details.", - severity: "error", - }); - } else if (status.status === "start-failed") { - const body = status.error - ?? "Server failed to start. Verify that Proton-GE is configured correctly, the server files are intact, and all required ports are available."; - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, - serverId: status.serverId, - serverName, - title: `${serverName} failed to start`, - body, - severity: "error", - }); + useTauriEvent<{ serverId?: string; unread: boolean }>( + "notification://logged", + ({ unread }) => { + if (unread) useAppStore.getState().incrementUnread(); } - }); + ); return null; } diff --git a/src/components/layout/SchedulerManager.tsx b/src/components/layout/SchedulerManager.tsx index 02426ab..2881b7c 100644 --- a/src/components/layout/SchedulerManager.tsx +++ b/src/components/layout/SchedulerManager.tsx @@ -4,133 +4,22 @@ * SchedulerManager — bridges the Rust scheduler and SQLite. * * On mount: hydrates the Rust scheduler from SQLite via syncSchedulesToRust(). - * On `scheduler://fired`: persists last_run / next_run to SQLite, inserts - * backup records (with TimeShift tier logic), runs retention pruning, re-syncs. - * On `rcon://players/{id}`: updates the player_name_map so player backups can - * display human-readable names. + * On `scheduler://fired`: persists last_run / next_run for non-backup schedules. + * + * Hourly backup ticks, player name tracking, login backup, and player connection + * recording are all handled in Rust (backup_manager.rs, rcon.rs, log_manager.rs). */ import { useEffect } from "react"; import { toast } from "sonner"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import { - insertBackup, updateScheduleRun, getScheduleById, setAppSetting, - getServerBackupsByType, updateBackupTiers, deleteBackupRecord, - upsertPlayerNames, - type BackupRow, + updateScheduleRun, getScheduleById, setAppSetting, } from "@/lib/db"; -import { tauriCmd } from "@/lib/tauri-commands"; import { getNextCronDate } from "@/components/shared/CronBuilder"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; -import { ARK_MAPS } from "@/data/game-data"; import type { SchedulerFiredPayload } from "@/lib/tauri-commands"; -// --------------------------------------------------------------------------- -// TimeShift helpers -// --------------------------------------------------------------------------- - -type Tier = "H" | "D" | "W" | "M"; - -/** Parse config_json for the tier flag for this schedule entry. */ -function parseTier(configJson: string): Tier { - try { - const cfg = JSON.parse(configJson) as { tier?: string }; - const t = (cfg.tier ?? "H").toUpperCase(); - if (t === "D" || t === "W" || t === "M") return t as Tier; - } catch { /* fall through */ } - return "H"; -} - -/** Parse keep count from config_json. */ -function parseKeep(configJson: string, defaultKeep = 5): number { - try { - const cfg = JSON.parse(configJson) as { keep?: number }; - return typeof cfg.keep === "number" && cfg.keep > 0 ? cfg.keep : defaultKeep; - } catch { return defaultKeep; } -} - -/** Add a tier flag to a comma-separated tiers string without duplicating. */ -function addTier(existing: string, tier: Tier): string { - const flags = existing ? existing.split(",").filter(Boolean) : []; - if (!flags.includes(tier)) flags.push(tier); - return flags.sort().join(","); -} - -/** Remove a tier flag from a comma-separated tiers string. */ -function removeTier(existing: string, tier: Tier): string { - return (existing ? existing.split(",").filter(Boolean) : []) - .filter((f) => f !== tier) - .join(","); -} - -/** - * TimeShift retention prune. - * - * For the given tier, if the count exceeds `keepCount`, strip the tier flag - * from the oldest excess backups. If a backup then has no tier flags at all, - * delete the file and DB record. - */ -async function pruneByTier( - serverId: string, - backupType: string, - tier: Tier, - keepCount: number, -): Promise { - const backups = await getServerBackupsByType(serverId, backupType); - // Only backups that carry this tier flag, oldest first. - const withTier = backups - .filter((b) => b.tiers.split(",").includes(tier)) - .sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()); - - if (withTier.length <= keepCount) return; - - const excess = withTier.slice(0, withTier.length - keepCount); - for (const b of excess) { - const newTiers = removeTier(b.tiers, tier); - if (!newTiers) { - // No tier flags remain — physically delete. - try { await tauriCmd.deleteBackup(b.file_path); } catch { /* best-effort */ } - await deleteBackupRecord(b.id); - } else { - await updateBackupTiers(b.id, newTiers); - } - } -} - -/** - * Try to promote an existing backup to a higher tier instead of creating a new - * archive. Promotion succeeds if there is a backup of the given type whose - * creation timestamp falls within `windowMs` of now. - * - * Returns the promoted backup (with updated tiers) or null if none found. - */ -async function tryPromote( - serverId: string, - backupType: string, - tier: Tier, - windowMs: number, -): Promise { - const backups = await getServerBackupsByType(serverId, backupType); - // Most-recent backup that was created recently enough. - const candidate = backups - .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) - .find((b) => Date.now() - new Date(b.created_at).getTime() <= windowMs); - - if (!candidate) return null; - - const newTiers = addTier(candidate.tiers, tier); - await updateBackupTiers(candidate.id, newTiers); - return { ...candidate, tiers: newTiers }; -} - -// Promotion window per tier — how recent must an existing backup be to count? -const PROMOTE_WINDOW: Record = { - H: 0, // never promote — always create new hourly - D: 6 * 3600_000, // promote if there's a backup within 6h - W: 24 * 3600_000, // promote if there's a backup within 24h - M: 48 * 3600_000, // promote if there's a backup within 48h -}; - // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- @@ -140,22 +29,10 @@ export function SchedulerManager() { syncSchedulesToRust(); }, []); - // Update player_name_map whenever RCON refreshes the player list. - useTauriEvent<{ serverId?: string; players?: { name: string; playerId: string }[] }>( - "rcon://players-any", - async (payload) => { - if (!payload.serverId || !payload.players?.length) return; - await upsertPlayerNames( - payload.serverId, - payload.players.map((p) => ({ eosId: p.playerId, name: p.name })), - ).catch(() => {}); - } - ); - + // Non-backup scheduler events: restart, broadcast, update, global_update_check. useTauriEvent("scheduler://fired", async (payload) => { - const { scheduleId, serverName, scheduleType, success, error, backupRecord } = payload; + const { scheduleId, serverId, serverName, scheduleType, success, error } = payload; - // ── Global update check ───────────────────────────────────────────────── if (scheduleType === "global_update_check") { await setAppSetting("asa_last_checked", new Date().toISOString()); if (!success) toast.error(`Auto update check failed: ${error ?? "unknown error"}`); @@ -163,86 +40,20 @@ export function SchedulerManager() { return; } - // ── Backup schedule types ─────────────────────────────────────────────── - const isBackup = scheduleType === "backup_server" - || scheduleType === "backup_player" - || scheduleType === "backup_full"; - - if (isBackup && success && backupRecord) { - const row = await getScheduleById(scheduleId); - const configJson = row?.config_json ?? "{}"; - const tier = parseTier(configJson); - const keep = parseKeep(configJson, 5); - const bType = backupRecord.backupType; - - // Determine final tiers for the new backup. - let tiers = tier; - - // For D/W/M: if we can promote an existing backup, don't need the one - // Rust just created (it was a "new backup" case, not promotion). - // The Rust always creates a new file; we just tag it accordingly. - if (tier !== "H") { - const window = PROMOTE_WINDOW[tier]; - const promoted = await tryPromote(payload.serverId, bType, tier, window); - if (promoted) { - // A recent backup was promoted — delete the redundant new file Rust created. - try { await tauriCmd.deleteBackup(backupRecord.filePath); } catch { /* ok */ } - // Prune and re-sync without inserting the new record. - await pruneByTier(payload.serverId, bType, tier, keep); - const lastRun = new Date().toISOString(); - const nextDate = row ? getNextCronDate(row.cron_expression) : null; - await updateScheduleRun(scheduleId, lastRun, nextDate?.toISOString() ?? null); - syncSchedulesToRust(); - toast.success(`[${serverName}] ${tier}-tier backup promoted.`); - return; - } - // No recent backup to promote — keep the new file Rust created. - tiers = tier; - } - - try { - await insertBackup({ - id: backupRecord.id, - server_id: backupRecord.serverId, - file_path: backupRecord.filePath, - file_size_bytes: backupRecord.fileSizeBytes, - map_id: backupRecord.mapId, - triggered_by: backupRecord.triggeredBy, - created_at: backupRecord.createdAt, - backup_type: bType, - tiers, - player_eosid: backupRecord.playerEosid ?? null, - player_name: backupRecord.playerName ?? null, - }); - } catch { - // Non-fatal — backup file exists even if DB insert failed. - } - - await pruneByTier(payload.serverId, bType, tier, keep); - } - - // ── Update last_run / next_run ────────────────────────────────────────── const lastRun = new Date().toISOString(); try { - const row = await getScheduleById(scheduleId); + const row = await getScheduleById(scheduleId); const nextDate = row ? getNextCronDate(row.cron_expression) : null; await updateScheduleRun(scheduleId, lastRun, nextDate?.toISOString() ?? null); } catch { /* non-fatal */ } if (success) { - // Skipped-because-server-stopped: success=true but no backupRecord. - // Don't toast — this is expected behaviour, not an event worth surfacing. - const wasSkipped = isBackup && !backupRecord; - if (!wasSkipped) { - const labels: Record = { - backup_server: "Server backup completed", - backup_player: "Player backups completed", - backup_full: "Full backup completed", - restart: "Scheduled restart completed", - update: "Scheduled update completed", - broadcast: "Scheduled broadcast sent", - }; - toast.success(`[${serverName}] ${labels[scheduleType] ?? "Schedule fired"}.`); + const labels: Record = { + restart: "Scheduled restart completed", + update: "Scheduled update completed", + }; + if (labels[scheduleType]) { + toast.success(`[${serverName}] ${labels[scheduleType]}.`); } } else { toast.error(`[${serverName}] Scheduled ${scheduleType} failed: ${error ?? "unknown error"}`); diff --git a/src/components/layout/UpdateManager.tsx b/src/components/layout/UpdateManager.tsx index 0be7ceb..24fba89 100644 --- a/src/components/layout/UpdateManager.tsx +++ b/src/components/layout/UpdateManager.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef } from "react"; import { check } from "@tauri-apps/plugin-updater"; +import { invoke } from "@tauri-apps/api/core"; import { toast } from "sonner"; import { getAppSetting } from "@/lib/db"; @@ -14,15 +15,28 @@ export function UpdateManager() { if (checkingRef.current) return; checkingRef.current = true; try { + const installMethod = await invoke("get_install_method").catch(() => "binary"); const update = await check(); if (!update) return; const toastId = `app-update-${update.version}`; - // Trim release notes to the first line so the toast stays readable. const firstLine = (update.body ?? "").split("\n").find((l) => l.trim()) ?? ""; const description = firstLine.length > 120 ? firstLine.slice(0, 120) + "…" : firstLine || "A new version is ready to install."; + + if (installMethod === "pkgbuild") { + // pkgbuild installs are not managed by the Tauri updater — pacman owns the binary. + // Show the version notice but direct the user to rebuild manually. + toast.info(`LokiASAM ${update.version} is available`, { + id: toastId, + description: "To update: git pull in your LokiASAM folder, then re-run makepkg -si", + duration: Infinity, + cancel: { label: "Dismiss", onClick: () => {} }, + }); + return; + } + toast.info(`LokiASAM ${update.version} is available`, { id: toastId, description, diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index fa60dd8..3808e44 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -1,7 +1,7 @@ "use client"; import { useState, useEffect } from "react"; -import { MoreVertical, Trash2, Copy, FolderOpen, HardDrive, Loader2 } from "lucide-react"; +import { MoreVertical, Trash2, Copy, FolderOpen, HardDrive, Loader2, ToggleLeft, ToggleRight } from "lucide-react"; import { DropdownMenu, DropdownMenuContent, @@ -36,6 +36,7 @@ import { getAppSetting, isServerNameTaken, insertBackup, + pruneManualBackups, getServers, } from "@/lib/db"; import { useQueryClient } from "@tanstack/react-query"; @@ -100,7 +101,7 @@ function DeleteDialog({ return ( !v && onClose()}> - + e.stopPropagation()}> Delete “{server.name}”? @@ -111,36 +112,46 @@ function DeleteDialog({
- +
+
+

Also delete server files on disk

+

{server.install_path}

+
+ +
{exclusivePorts.length > 0 && ( - +
+
+

Also remove firewall rules for ports {exclusivePortList}

+

Only ports not used by any other server will be removed

+
+ +
)}
@@ -287,7 +298,7 @@ function CloneDialog({ return ( !v && !cloning && onClose()}> - + e.stopPropagation()}> Clone “{server.name}” @@ -388,13 +399,15 @@ export function ServerActionMenu({ server }: Props) { file_path: record.filePath, file_size_bytes: record.fileSizeBytes, map_id: record.mapId, - triggered_by: record.triggeredBy, + triggered_by: "manual", created_at: record.createdAt, backup_type: "server", tiers: "", player_eosid: null, player_name: null, }); + const keep = parseInt(await getAppSetting(`manual_backup_keep_${server.id}`) ?? "5", 10); + await pruneManualBackups(server.id, "server", isNaN(keep) ? 5 : keep); toast.success(`Backup of "${server.name}" completed.`); } catch (err) { toast.error(`Backup failed: ${err}`); diff --git a/src/components/server/ServerCard.tsx b/src/components/server/ServerCard.tsx index 7e8da70..6ed53ea 100644 --- a/src/components/server/ServerCard.tsx +++ b/src/components/server/ServerCard.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState, useEffect } from "react"; +import { useState, useEffect, useRef } from "react"; import { useTauriEvent } from "@/hooks/useTauriEvent"; import Link from "next/link"; import { useRouter } from "next/navigation"; @@ -23,6 +23,8 @@ import { Loader2, X, Ban, + ToggleLeft, + ToggleRight, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; @@ -34,8 +36,6 @@ import { DialogTitle, DialogFooter, } from "@/components/ui/dialog"; -import { Switch } from "@/components/ui/switch"; -import { Label } from "@/components/ui/label"; import { CommandOutputPanel, clearOutputBuffer } from "@/components/shared/CommandOutputPanel"; import { ServerStatusBadge } from "./ServerStatusBadge"; import { ServerActionMenu } from "./ServerActionMenu"; @@ -48,6 +48,7 @@ import { getServerMods, getLastBackupTime, getNextScheduledRestart, + getHasBackupEnabled, getAppSetting, resetServersFromStatus, } from "@/lib/db"; @@ -66,6 +67,19 @@ interface Props { // ── Utility helpers ────────────────────────────────────────────────────────── +function formatCountdown(secs: number): string { + if (secs >= 3600) { + const h = Math.floor(secs / 3600); + const m = Math.floor((secs % 3600) / 60); + return `${h}h ${m}m`; + } + const m = Math.floor(secs / 60); + const s = secs % 60; + if (m > 0 && s > 0) return `${m}m ${s}s`; + if (m > 0) return `${m}m`; + return `${s}s`; +} + function formatUptime(startMs: number): string { const elapsed = Date.now() - startMs; if (elapsed < 0) return "0m"; @@ -87,17 +101,11 @@ function formatRelativeTime(iso: string | null): string { return `${Math.floor(h / 24)}d ago`; } -function formatFutureTime(iso: string | null): string { +function formatClockTime(iso: string | null): string { if (!iso) return "Not scheduled"; const d = new Date(iso); if (isNaN(d.getTime())) return "—"; - const diffMs = d.getTime() - Date.now(); - if (diffMs < 0) return "Overdue"; - const diffMins = Math.floor(diffMs / 60_000); - if (diffMins < 60) return `in ${diffMins}m`; - const h = Math.floor(diffMins / 60); - if (h < 24) return `in ${h}h`; - return `in ${Math.floor(h / 24)}d`; + return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); } // ── Main component ─────────────────────────────────────────────────────────── @@ -111,10 +119,12 @@ export function ServerCard({ server }: Props) { const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); const clearNoRetryServer = useAppStore((s) => s.clearNoRetryServer); const isServerScanPending = useAppStore((s) => s.isServerScanPending); + const countdown = useAppStore((s) => s.countdowns[server.id] ?? null); const [modCount, setModCount] = useState(null); const [lastBackup, setLastBackup] = useState(null); const [nextRestart, setNextRestart] = useState(null); + const [backupEnabled, setBackupEnabled] = useState(null); const [actionPending, setActionPending] = useState(false); const [showProgress, setShowProgress] = useState(false); const [showUpdateConfirm, setShowUpdateConfirm] = useState(false); @@ -123,13 +133,34 @@ export function ServerCard({ server }: Props) { const [backupProgress, setBackupProgress] = useState<{ active: boolean; percent: number; label: string }>({ active: false, percent: 0, label: "", }); + const backupProgressUpdatedAt = useRef(0); const removeFromStartupQueue = useAppStore((s) => s.removeFromStartupQueue); useTauriEvent<{ percent: number; currentFile: string; label: string }>( `backup://progress/${server.id}`, - (p) => setBackupProgress({ active: p.percent < 100, percent: p.percent, label: p.label }) + (p) => { + backupProgressUpdatedAt.current = Date.now(); + // Keep active=true even at 100% — SchedulerManager's backup:completed clears it + setBackupProgress({ active: true, percent: p.percent, label: p.label }); + } ); + // Clear progress bar when Rust confirms the backup is fully recorded in DB. + useTauriEvent(`backup://completed/${server.id}`, () => { + setBackupProgress({ active: false, percent: 0, label: "" }); + }); + + // Fallback: clear stale progress bar if no update received in 30s. + useEffect(() => { + if (!backupProgress.active) return; + const id = setInterval(() => { + if (backupProgressUpdatedAt.current > 0 && Date.now() - backupProgressUpdatedAt.current > 30_000) { + setBackupProgress({ active: false, percent: 0, label: "" }); + } + }, 5_000); + return () => clearInterval(id); + }, [backupProgress.active]); + const hasUpdateAvailable = server.update_available === 1; const isUpdateQueued = server.status === "update_queued"; const isStartupQueued = server.status === "startup_queued"; @@ -159,16 +190,18 @@ export function ServerCard({ server }: Props) { useEffect(() => { let cancelled = false; (async () => { - const [mc, lb, nr, autoHours] = await Promise.all([ + const [mc, lb, nr, be, autoHours] = await Promise.all([ getServerModCount(server.id), getLastBackupTime(server.id), getNextScheduledRestart(server.id), + getHasBackupEnabled(server.id), getAppSetting("asa_auto_check_hours"), ]); if (!cancelled) { setModCount(mc); setLastBackup(lb); setNextRestart(nr); + setBackupEnabled(be); setAutoCheckEnabled((autoHours ?? "0") !== "0"); } })(); @@ -292,6 +325,20 @@ export function ServerCard({ server }: Props) { }; const handleRestart = async () => { + if (server.restart_warn_players) { + const startParams = await buildStartParams(); + tauriCmd.startGracefulRestart({ + serverId: server.id, + warnSeconds: (server.restart_warn_minutes ?? 5) * 60, + rconPort: server.rcon_port, + rconPassword: server.rcon_password, + message: server.restart_message || "Server restarting in {time}.", + cancelMessage: server.restart_cancel_message || "Restart has been canceled.", + startParams, + }).catch((err) => toast.error(`Restart failed: ${err}`)); + return; + } + setActionPending(true); try { await updateServerStatus(server.id, "stopping", server.pid); @@ -313,6 +360,34 @@ export function ServerCard({ server }: Props) { const handleApplyUpdate = async () => { setShowUpdateConfirm(false); + + if (server.update_warn_players && isRunning) { + const [baseDir, steamcmdPath] = await Promise.all([ + getAppSetting("base_dir"), + getAppSetting("steamcmd_path"), + ]); + if (!baseDir || !steamcmdPath) return; + const sep = baseDir.includes("\\") ? "\\" : "/"; + const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + const startParams = restartAfterUpdate ? await buildStartParams() : null; + + tauriCmd.startGracefulUpdate({ + serverId: server.id, + serverName: server.name, + warnSeconds: (server.update_warn_minutes ?? 5) * 60, + rconPort: server.rcon_port, + rconPassword: server.rcon_password, + message: server.update_message || "Server going down for update in {time}.", + cancelMessage: server.update_cancel_message || "Update has been canceled.", + installPath: server.install_path, + cacheDir, + steamcmdPath, + restartAfter: restartAfterUpdate, + startParams, + }).catch((err) => toast.error(`Update failed: ${err}`)); + return; + } + setActionPending(true); try { const wasRunning = isRunning; @@ -324,6 +399,8 @@ export function ServerCard({ server }: Props) { wasRunning, restartAfterUpdate, (msg) => toast.info(msg), + server.rcon_port, + server.rcon_password, ); } catch (err) { if (err && typeof err === "object" && "restartNeeded" in err) { @@ -404,7 +481,7 @@ export function ServerCard({ server }: Props) { : undefined, }} onClick={(e) => { - if (!(e.target as HTMLElement).closest('button, a, [role="menuitem"], [data-radix-collection-item]')) { + if (!(e.target as HTMLElement).closest('button, a, [role="menuitem"], [data-radix-collection-item], [role="dialog"], [role="alertdialog"]')) { router.push(`/servers/detail?id=${server.id}`); } }} @@ -419,7 +496,14 @@ export function ServerCard({ server }: Props) { > {server.name} - + {hasUpdateAvailable && ( - - {backupProgress.active ? backupProgress.label || "Backing up…" : "Backup"} - + Backup - {backupProgress.active - ? `${backupProgress.percent.toFixed(0)}%` - : formatRelativeTime(lastBackup) - } + {formatRelativeTime(lastBackup)}
{backupProgress.active && ( -
-
+
+
+
+
+ + {backupProgress.percent.toFixed(0)}% +
)}
- {/* Next restart */} - {nextRestart && ( -

- Next restart:{" "} - - {formatFutureTime(nextRestart)} - -

+ {/* Next restart · Backup status */} + {(nextRestart || backupEnabled !== null || backupProgress.active) && ( +
+ {nextRestart && ( + + Next restart:{" "} + {formatClockTime(nextRestart)} + + )} + {nextRestart && (backupEnabled !== null || backupProgress.active) && ( + · + )} + {(backupEnabled !== null || backupProgress.active) && ( + + {backupProgress.active + ? Backup in progress + : backupEnabled + ? Backup enabled + : Backup disabled + } + + )} +
)} {/* ── Action buttons ── */} @@ -552,7 +651,28 @@ export function ServerCard({ server }: Props) { {/* Left: all status-dependent actions */}
- {isActiveInstall ? ( + {countdown ? ( + <> + + + + ) : isActiveInstall ? ( <>
)} diff --git a/src/components/server/ServerStatusBadge.tsx b/src/components/server/ServerStatusBadge.tsx index 9966578..1effcac 100644 --- a/src/components/server/ServerStatusBadge.tsx +++ b/src/components/server/ServerStatusBadge.tsx @@ -41,28 +41,34 @@ interface Props { status: string; /** Render a slightly larger badge. Defaults to false. */ large?: boolean; + /** When set, overrides the label with a live countdown string and uses an orange pulsing style. */ + countdownLabel?: string; } -export function ServerStatusBadge({ status, large = false }: Props) { +export function ServerStatusBadge({ status, large = false, countdownLabel }: Props) { const cfg = STATUS_MAP[status as ServerStatusValue] ?? STATUS_MAP.stopped; const size = large ? "text-sm px-3 py-1" : "text-xs px-2 py-0.5"; + const color = countdownLabel ? "#ff8c00" : cfg.color; + const pulse = countdownLabel ? true : cfg.pulse; + const label = countdownLabel ?? cfg.label; + return ( {/* Pulsing dot for active states */} - {cfg.label} + {label} ); } diff --git a/src/components/server/rcon/RconConsole.tsx b/src/components/server/rcon/RconConsole.tsx index 7cd8ff9..1ad757e 100644 --- a/src/components/server/rcon/RconConsole.tsx +++ b/src/components/server/rcon/RconConsole.tsx @@ -138,12 +138,6 @@ export function RconConsole({ server }: Props) { }).catch(() => null); }, [server.id]); - // ── Enable chat poll on mount, disable on unmount ───────────────────────── - useEffect(() => { - tauriCmd.rconEnableChatPoll(server.id).catch(() => null); - return () => { tauriCmd.rconDisableChatPoll(server.id).catch(() => null); }; - }, [server.id]); - // ── Load players, ban list, whitelist ──────────────────────────────────── const refreshPlayers = useCallback(async () => { if (!connected) return; diff --git a/src/components/server/tabs/AutomationTab.tsx b/src/components/server/tabs/AutomationTab.tsx index 7d7ab87..25c77e1 100644 --- a/src/components/server/tabs/AutomationTab.tsx +++ b/src/components/server/tabs/AutomationTab.tsx @@ -19,7 +19,7 @@ import { type ScheduleRow, type CreateScheduleInput, type UpdateAutomation, } from "@/lib/db"; -import { getAppSetting } from "@/lib/db"; +import { getAppSetting, setAppSetting } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; import { syncSchedulesToRust } from "@/lib/scheduler-sync"; import type { ServerRow } from "@/lib/db"; @@ -504,11 +504,12 @@ function ScheduleCard({ serverId, type, icon: Icon, title, description, existing type BackupTier = "H" | "D" | "W" | "M"; type BackupScheduleType = "backup_server" | "backup_player" | "backup_full"; -const TIER_FIXED_CRON: Record = { - M: "0 4 1 * *", - W: "0 3 * * 0", - D: "0 2 * * *", - H: "0 */6 * * *", +// Maps tier letter to the key used in the unified config_json +const TIER_TO_CONFIG_KEY: Record = { + H: "hourly", + D: "daily", + W: "weekly", + M: "monthly", }; const TIER_DEFAULT_KEEP: Record = { M: 3, W: 4, D: 7, H: 24 }; @@ -516,12 +517,18 @@ const TIER_LABEL: Record = { M: "monthly", W: "weekly", D: " const TIER_ORDER: BackupTier[] = ["M", "W", "D", "H"]; type TierState = { keep: number; enabled: boolean }; -function findTierSchedule(schedules: ScheduleRow[], type: BackupScheduleType, tier: BackupTier): ScheduleRow | null { - return schedules.find((s) => { - if (s.schedule_type !== type) return false; - try { return (JSON.parse(s.config_json ?? "{}").tier ?? "H") === tier; } - catch { return false; } - }) ?? null; +/** Compute the cron that should run — hourly if H enabled, otherwise the lowest-frequency tier. */ +function effectiveCron(tiers: Record): string { + if (tiers.H.enabled) return "0 * * * *"; + if (tiers.D.enabled) return "0 2 * * *"; + if (tiers.W.enabled) return "0 3 * * 0"; + if (tiers.M.enabled) return "0 4 1 * *"; + return "0 * * * *"; +} + +/** Find the single consolidated backup schedule row for a given type. */ +function findBackupSchedule(schedules: ScheduleRow[], type: BackupScheduleType): ScheduleRow | null { + return schedules.find((s) => s.schedule_type === type) ?? null; } function findFullSchedule(schedules: ScheduleRow[]): ScheduleRow | null { @@ -545,9 +552,34 @@ function BackupTypeSection({ const buildState = (): Record => { const s = {} as Record; for (const tier of TIER_ORDER) { - const row = findTierSchedule(schedules, scheduleType, tier); - const cfg = row?.config_json ? parseCfg(row.config_json) : {}; - s[tier] = { keep: (cfg.keep as number) ?? TIER_DEFAULT_KEEP[tier], enabled: row ? row.enabled === 1 : false }; + s[tier] = { keep: TIER_DEFAULT_KEEP[tier], enabled: false }; + } + // Merge all rows for this type (handles legacy multi-row and new single-row formats) + const rows = schedules.filter((r) => r.schedule_type === scheduleType); + for (const row of rows) { + const cfg = parseCfg(row.config_json); + if (cfg.hourly !== undefined || cfg.daily !== undefined || cfg.weekly !== undefined || cfg.monthly !== undefined) { + // New unified format + for (const tier of TIER_ORDER) { + const key = TIER_TO_CONFIG_KEY[tier]; + const tc = cfg[key] as { enabled?: boolean; keep?: number } | undefined; + if (tc) { + s[tier] = { + keep: typeof tc.keep === "number" && tc.keep > 0 ? tc.keep : TIER_DEFAULT_KEEP[tier], + enabled: tc.enabled === true && row.enabled === 1, + }; + } + } + } else if (typeof cfg.tier === "string") { + // Legacy single-tier format: { tier: "H", keep: N } + const t = (cfg.tier as string).toUpperCase() as BackupTier; + if (TIER_ORDER.includes(t)) { + s[t] = { + keep: typeof cfg.keep === "number" && cfg.keep > 0 ? cfg.keep : TIER_DEFAULT_KEEP[t], + enabled: row.enabled === 1, + }; + } + } } return s; }; @@ -564,21 +596,38 @@ function BackupTypeSection({ async function handleSave() { setSaving(true); try { - for (const tier of TIER_ORDER) { - const { keep, enabled } = tiers[tier]; - const existing = findTierSchedule(schedules, scheduleType, tier); - const configJson = JSON.stringify({ tier, keep }); - const cron = TIER_FIXED_CRON[tier]; - const nextIso = getNextCronDate(cron)?.toISOString() ?? new Date().toISOString(); - if (existing) { - await updateScheduleConfig(existing.id, cron, configJson, nextIso); - if (enabled !== (existing.enabled === 1)) await updateScheduleEnabled(existing.id, enabled); - } else if (enabled) { - const newId = await tauriCmd.createSchedule({ serverId, scheduleType, cronExpression: cron, configJson }); - await createSchedule({ id: newId, serverId, scheduleType, cronExpression: cron, enabled: true, configJson }); - await updateScheduleConfig(newId, cron, configJson, nextIso); - } + const anyEnabled = TIER_ORDER.some((t) => tiers[t].enabled); + const configJson = JSON.stringify( + Object.fromEntries(TIER_ORDER.map((t) => [ + TIER_TO_CONFIG_KEY[t], + { enabled: tiers[t].enabled, keep: tiers[t].keep }, + ])) + ); + const cron = effectiveCron(tiers); + const nextIso = anyEnabled + ? (getNextCronDate(cron)?.toISOString() ?? new Date().toISOString()) + : new Date().toISOString(); + + // Collect all existing rows for this type; migration 012 should have consolidated + // them already, but handle the legacy multi-row case gracefully. + const allExisting = schedules.filter((r) => r.schedule_type === scheduleType); + const primary = allExisting[0] ?? null; + + // Delete any extra rows left over from the old per-tier format + for (const row of allExisting.slice(1)) { + await tauriCmd.deleteSchedule(row.id); + await deleteScheduleRecord(row.id); } + + if (primary) { + await updateScheduleConfig(primary.id, cron, configJson, nextIso); + if (anyEnabled !== (primary.enabled === 1)) await updateScheduleEnabled(primary.id, anyEnabled); + } else if (anyEnabled) { + const newId = await tauriCmd.createSchedule({ serverId, scheduleType, cronExpression: cron, configJson }); + await createSchedule({ id: newId, serverId, scheduleType, cronExpression: cron, enabled: true, configJson }); + await updateScheduleConfig(newId, cron, configJson, nextIso); + } + setSaved(true); setTimeout(() => setSaved(false), 2000); onRefresh(); @@ -729,6 +778,156 @@ function FullBackupScheduleSection({ serverId, schedules, onRefresh }: { ); } +// --------------------------------------------------------------------------- +// LoginBackupRow — per-server login backup keep-N setting (app_setting) +// --------------------------------------------------------------------------- + +function LoginBackupRow({ serverId }: { serverId: string }) { + const [keep, setKeep] = useState(3); + const [enabled, setEnabled] = useState(false); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + useEffect(() => { + getAppSetting(`login_backup_keep_${serverId}`).then((v) => { + const n = parseInt(v ?? "0", 10); + setEnabled(n > 0); + setKeep(n > 0 ? n : 3); + }).catch(() => {}); + }, [serverId]); + + async function handleSave() { + setSaving(true); + try { + await setAppSetting(`login_backup_keep_${serverId}`, enabled ? String(keep) : "0"); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save login backup config: ${e}`); + } finally { + setSaving(false); + } + } + + return ( +
+
+ setKeep(Math.max(1, parseInt(e.target.value, 10) || 1))} + className="w-16 h-8 text-sm text-center shrink-0" + style={{ + background: "rgba(0,0,0,0.4)", + border: `1px solid ${enabled ? "rgba(0,255,255,0.35)" : "rgba(var(--neon-purple-rgb),0.15)"}`, + color: "var(--text-primary)", + }} + /> +
+ login backups to keep +

+ Triggered when a player connects. No tier flags. Independent rotation. +

+
+ +
+ +
+ ); +} + +// --------------------------------------------------------------------------- +// ManualBackupRow — keep-N setting for manual (on-demand) backups +// --------------------------------------------------------------------------- + +function ManualBackupRow({ serverId }: { serverId: string }) { + const [keep, setKeep] = useState(5); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + useEffect(() => { + getAppSetting(`manual_backup_keep_${serverId}`).then((v) => { + const n = parseInt(v ?? "5", 10); + setKeep(isNaN(n) || n < 1 ? 5 : n); + }).catch(() => {}); + }, [serverId]); + + async function handleSave() { + setSaving(true); + try { + await setAppSetting(`manual_backup_keep_${serverId}`, String(Math.max(1, keep))); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save manual backup config: ${e}`); + } finally { + setSaving(false); + } + } + + return ( +
+
+ setKeep(Math.max(1, parseInt(e.target.value, 10) || 1))} + className="w-16 h-8 text-sm text-center shrink-0" + style={{ + background: "rgba(0,0,0,0.4)", + border: "1px solid rgba(var(--neon-purple-rgb),0.35)", + color: "var(--text-primary)", + }} + /> +
+ manual backups to keep +

+ Applies to on-demand backups triggered by the Backup Now buttons. +

+
+
+ +
+ ); +} + // --------------------------------------------------------------------------- // BackupScheduleSection // --------------------------------------------------------------------------- @@ -761,6 +960,8 @@ function BackupScheduleSection({ serverId, schedules, onRefresh }: { + +
diff --git a/src/components/server/tabs/BackupsTab.tsx b/src/components/server/tabs/BackupsTab.tsx index d7a3458..cd8b60f 100644 --- a/src/components/server/tabs/BackupsTab.tsx +++ b/src/components/server/tabs/BackupsTab.tsx @@ -9,7 +9,7 @@ import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { getServerBackupsByType, insertBackup, deleteBackupRecord, - getAppSetting, setAppSetting, getKnownPlayers, + pruneManualBackups, getAppSetting, setAppSetting, getKnownPlayers, type BackupRow, } from "@/lib/db"; import { tauriCmd } from "@/lib/tauri-commands"; @@ -76,6 +76,17 @@ function TierTag({ tier }: { tier: string }) { ); } +function LoginTag() { + return ( + + Login + + ); +} + // --------------------------------------------------------------------------- // Progress overlay // --------------------------------------------------------------------------- @@ -208,7 +219,8 @@ function BackupRowCard({ onDelete: (b: BackupRow) => void; restoreDisabled: boolean; }) { - const tiers = backup.tiers ? backup.tiers.split(",").filter(Boolean) : []; + const isLogin = backup.triggered_by === "login"; + const tiers = !isLogin && backup.tiers ? backup.tiers.split(",").filter(Boolean) : []; const fname = backup.file_path.split(/[\\/]/).pop() ?? backup.file_path; const displayName = backup.backup_type === "player" && backup.player_name ? backup.player_name @@ -222,7 +234,7 @@ function BackupRowCard({
{/* Tier tags + date */}
- {tiers.map((t) => )} + {isLogin ? : tiers.map((t) => )} {formatHumanDate(backup.created_at)} @@ -390,7 +402,8 @@ function PlayerBackupSection({ onEditSchedules?: () => void; onManualBackup: () => void; }) { - const [knownPlayers, setKnownPlayers] = useState<{ eosId: string; playerName: string }[]>([]); + const [knownPlayers, setKnownPlayers] = useState<{ eosId: string; playerName: string }[]>([]); + const [selectedEosId, setSelectedEosId] = useState("all"); useEffect(() => { getKnownPlayers(serverId).then(setKnownPlayers).catch(() => {}); @@ -402,34 +415,91 @@ function PlayerBackupSection({ (byPlayer[id] ??= []).push(b); } - const playerIds = Object.keys(byPlayer).filter((id) => (byPlayer[id]?.length ?? 0) > 0); + const playersWithBackups = Object.keys(byPlayer).filter((id) => (byPlayer[id]?.length ?? 0) > 0); + + // Union of players with backups + known players (deduped) + const allOptions: { eosId: string; name: string }[] = [ + ...playersWithBackups.map((id) => ({ + eosId: id, + name: knownPlayers.find((p) => p.eosId === id)?.playerName + ?? playerBackups.find((b) => b.player_eosid === id)?.player_name + ?? id, + })), + ...knownPlayers + .filter((p) => !playersWithBackups.includes(p.eosId)) + .map((p) => ({ eosId: p.eosId, name: p.playerName })), + ]; + const uniqueOptions = Array.from(new Map(allOptions.map((p) => [p.eosId, p])).values()); - const nameFor = (eosId: string): string => - knownPlayers.find((p) => p.eosId === eosId)?.playerName - ?? playerBackups.find((b) => b.player_eosid === eosId)?.player_name - ?? eosId; + const nameFor = (eosId: string) => + uniqueOptions.find((p) => p.eosId === eosId)?.name ?? eosId; + + const selectedBackups = + selectedEosId === "all" + ? null + : (byPlayer[selectedEosId] ?? []).sort( + (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() + ); return (
+ + {/* Player filter dropdown */} + {uniqueOptions.length > 0 && ( +
+ +
+ )} +
{loading ? (
- ) : playerIds.length === 0 ? ( + ) : selectedEosId !== "all" ? ( + // Single-player view + (selectedBackups ?? []).length === 0 ? ( +

+ No backups yet +

+ ) : ( +
+ {(selectedBackups ?? []).map((b) => ( + + ))} +
+ ) + ) : playersWithBackups.length === 0 ? (

No player backups yet

) : ( + // All-players grouped view
- {playerIds.map((eosId) => { + {playersWithBackups.map((eosId) => { const pBackups = (byPlayer[eosId] ?? []).sort( (a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ); @@ -440,10 +510,8 @@ function PlayerBackupSection({

{pBackups.map((b) => ( - + ))}
@@ -575,6 +643,54 @@ function IniBackupSection({ ); } +// --------------------------------------------------------------------------- +// SyncConfirmDialog +// --------------------------------------------------------------------------- + +function SyncConfirmDialog({ + importCount, onConfirm, onCancel, +}: { + importCount: number; + onConfirm: () => void; + onCancel: () => void; +}) { + return ( +
+
+
+
+ +
+

+ Sync from Disk +

+
+

+ Found{" "} + + {importCount} file{importCount !== 1 ? "s" : ""} + {" "} + to import. +

+
+ + +
+
+
+ ); +} + // --------------------------------------------------------------------------- // BackupsTab — main component // --------------------------------------------------------------------------- @@ -599,6 +715,8 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { const [showFullWarning, setShowFullWarning] = useState(false); const [fullEstimate, setFullEstimate] = useState(0); const [backupDir, setBackupDir] = useState(""); + const [syncPending, setSyncPending] = useState<{ toImport: BackupRecord[] } | null>(null); + const [syncing, setSyncing] = useState(false); const loadAll = useCallback(async () => { setLoading(true); @@ -636,6 +754,9 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { } ); + // Rust scheduler emits this after inserting the DB record — reload the list. + useTauriEvent(`backup://completed/${server.id}`, () => { loadAll(); }); + // ── Manual backup helpers ──────────────────────────────────────────────── async function handleServerBackup() { @@ -648,9 +769,11 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { await insertBackup({ id: rec.id, server_id: rec.serverId, file_path: rec.filePath, file_size_bytes: rec.fileSizeBytes, map_id: rec.mapId, - triggered_by: rec.triggeredBy, created_at: rec.createdAt, + triggered_by: "manual", created_at: rec.createdAt, backup_type: "server", tiers: "", player_eosid: null, player_name: null, }); + const keep = parseInt(await getAppSetting(`manual_backup_keep_${server.id}`) ?? "5", 10); + await pruneManualBackups(server.id, "server", isNaN(keep) ? 5 : keep); toast.success("Server backup created."); await loadAll(); } catch (e) { @@ -660,6 +783,41 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { } } + async function handleAllPlayersBackup() { + if (!backupDir) { toast.error("Backup directory not configured."); return; } + setProgress({ active: true, percent: 0, currentFile: "", label: "Starting player backups…" }); + try { + const records = await tauriCmd.backupAllPlayers( + server.id, server.name, server.install_path, mapPath, server.map_id, backupDir, "manual" + ); + if (records.length === 0) { + toast.info("No player profiles found to back up."); + return; + } + const keep = parseInt(await getAppSetting(`manual_backup_keep_${server.id}`) ?? "5", 10); + const keepN = isNaN(keep) ? 5 : keep; + for (const rec of records) { + await insertBackup({ + id: rec.id, server_id: rec.serverId, file_path: rec.filePath, + file_size_bytes: rec.fileSizeBytes, map_id: rec.mapId, + triggered_by: "manual", created_at: rec.createdAt, + backup_type: "player", tiers: "", + player_eosid: rec.playerEosid ?? null, + player_name: rec.playerName ?? null, + }); + if (rec.playerEosid) { + await pruneManualBackups(server.id, "player", keepN); + } + } + toast.success(`Backed up ${records.length} player profile${records.length === 1 ? "" : "s"}.`); + await loadAll(); + } catch (e) { + toast.error(`Player backup failed: ${e}`); + } finally { + setProgress((p) => ({ ...p, active: false })); + } + } + async function handleFullBackupClick() { if (!backupDir) { toast.error("Backup directory not configured."); return; } const dismissed = await getAppSetting("full_backup_warning_dismissed"); @@ -682,9 +840,11 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { await insertBackup({ id: rec.id, server_id: rec.serverId, file_path: rec.filePath, file_size_bytes: rec.fileSizeBytes, map_id: rec.mapId, - triggered_by: rec.triggeredBy, created_at: rec.createdAt, + triggered_by: "manual", created_at: rec.createdAt, backup_type: "full", tiers: "", player_eosid: null, player_name: null, }); + const keep = parseInt(await getAppSetting(`manual_backup_keep_${server.id}`) ?? "5", 10); + await pruneManualBackups(server.id, "full", isNaN(keep) ? 5 : keep); toast.success("Full backup created."); await loadAll(); } catch (e) { @@ -735,6 +895,115 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { } } + // ── Sync from Disk ────────────────────────────────────────────────────────── + + async function handleSyncFromDisk() { + if (!backupDir) { toast.error("Backup directory not configured."); return; } + setSyncing(true); + try { + const diskRecords = await tauriCmd.scanBackupDir(server.id, backupDir, server.map_id); + const [dbServer, dbPlayer, dbFull] = await Promise.all([ + getServerBackupsByType(server.id, "server"), + getServerBackupsByType(server.id, "player"), + getServerBackupsByType(server.id, "full"), + ]); + const allDb = [...dbServer, ...dbPlayer, ...dbFull]; + + const diskPaths = new Set(diskRecords.map((r) => r.filePath)); + const dbPaths = new Set(allDb.map((r) => r.file_path)); + + // Silently remove stale DB records (files no longer on disk). + for (const dbRec of allDb) { + if (!diskPaths.has(dbRec.file_path)) { + await deleteBackupRecord(dbRec.id).catch(() => {}); + } + } + + // Find disk files not yet in DB. + const toImport = diskRecords.filter((r) => !dbPaths.has(r.filePath)); + + if (toImport.length === 0) { + toast.info("Backups are up to date."); + await loadAll(); + return; + } + + setSyncPending({ toImport }); + } catch (e) { + toast.error(`Scan failed: ${e}`); + } finally { + setSyncing(false); + } + } + + async function handleSyncConfirmed() { + if (!syncPending) return; + const { toImport } = syncPending; + setSyncPending(null); + setSyncing(true); + try { + // Load existing records so we know which higher tiers are already covered. + const [dbSrv, dbPlr, dbFul] = await Promise.all([ + getServerBackupsByType(server.id, "server"), + getServerBackupsByType(server.id, "player"), + getServerBackupsByType(server.id, "full"), + ]); + // Track which tiers each type already has (across existing DB + this import batch). + const seenByType: Record> = { + server: new Set(dbSrv.flatMap((b) => b.tiers.split(",").filter(Boolean))), + player: new Set(dbPlr.flatMap((b) => b.tiers.split(",").filter(Boolean))), + full: new Set(dbFul.flatMap((b) => b.tiers.split(",").filter(Boolean))), + }; + + // Process oldest-first: the earliest backup inherits the highest-tier slots. + const TIER_ORDER = ["M", "W", "D", "H"] as const; + const sorted = [...toImport].sort( + (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() + ); + + for (const rec of sorted) { + const seen = seenByType[rec.backupType] ?? new Set(); + let tiersStr = rec.tiers ?? ""; + + // For files that already carry a tier suffix (scheduled backups), promote + // them to cover any D/W/M slots not yet held by an existing backup. + // Files without a suffix (manual backups) keep tiers = "" as normal. + if (tiersStr && rec.triggeredBy !== "login") { + const tiers = new Set(tiersStr.split(",").filter(Boolean)); + for (const t of ["M", "W", "D"] as const) { + if (!seen.has(t)) tiers.add(t); + } + tiersStr = TIER_ORDER.filter((t) => tiers.has(t)).join(","); + } + + await insertBackup({ + id: rec.id, + server_id: rec.serverId, + file_path: rec.filePath, + file_size_bytes: rec.fileSizeBytes, + map_id: rec.mapId, + triggered_by: rec.triggeredBy, + created_at: rec.createdAt, + backup_type: rec.backupType, + tiers: tiersStr, + player_eosid: rec.playerEosid ?? null, + player_name: rec.playerName ?? null, + }).catch(() => {}); + + // Update seen so later backups in this batch don't also inherit these tiers. + for (const t of tiersStr.split(",").filter(Boolean)) seen.add(t); + seenByType[rec.backupType] = seen; + } + + toast.success(`Imported ${toImport.length} backup${toImport.length !== 1 ? "s" : ""}.`); + await loadAll(); + } catch (e) { + toast.error(`Import failed: ${e}`); + } finally { + setSyncing(false); + } + } + // ── Navigation helper — switch to automation tab then scroll to backup section function handleEditSchedule() { onNavigateToAutomation?.(); @@ -822,7 +1091,7 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { serverId={server.id} playerBackups={playerBackups} loading={loading} onRestore={setRestoreTarget} onDelete={handleDelete} - onManualBackup={() => toast.info("Player backups are triggered automatically by the scheduler.")} + onManualBackup={handleAllPlayersBackup} onEditSchedules={editScheduleBtn} restoreDisabled={isBusy} /> @@ -838,6 +1107,23 @@ export function BackupsTab({ server, onNavigateToAutomation }: Props) { backupLabel="Backup Full Now" /> + {/* Sync from Disk */} + {backupDir && ( +
+ +
+ )} + {restoreTarget && ( setShowFullWarning(false)} /> )} + + {syncPending && ( + setSyncPending(null)} + /> + )}
); } diff --git a/src/components/server/tabs/ConfigTab.tsx b/src/components/server/tabs/ConfigTab.tsx index afc0230..b7c0a61 100644 --- a/src/components/server/tabs/ConfigTab.tsx +++ b/src/components/server/tabs/ConfigTab.tsx @@ -10,7 +10,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { tauriCmd, type ServerConfigJson } from "@/lib/tauri-commands"; import { INI_FIELD_GROUPS, LAUNCH_PARAMETERS, type IniFieldDef, type LaunchParameter } from "@/data/game-data"; -import { getServerConfig, saveServerConfig, updateServerShutdownSettings, getAppSetting, type ServerRow } from "@/lib/db"; +import { getServerConfig, saveServerConfig, updateServerShutdownSettings, updateServerRestartSettings, updateServerUpdateSettings, getAppSetting, type ServerRow } from "@/lib/db"; import { toast } from "sonner"; import { NumberField } from "@/components/shared/NumberField"; @@ -521,6 +521,204 @@ function ShutdownSettingsCard({ server }: { server: ServerRow }) { ); } +// --------------------------------------------------------------------------- +// Restart Warning Settings Card +// --------------------------------------------------------------------------- + +function RestartSettingsCard({ server }: { server: ServerRow }) { + const [warnPlayers, setWarnPlayers] = useState(server.restart_warn_players !== 0); + const [warnMinutes, setWarnMinutes] = useState(server.restart_warn_minutes ?? 5); + const [message, setMessage] = useState(server.restart_message || "Server restarting in {time}."); + const [cancelMessage, setCancelMessage] = useState(server.restart_cancel_message || "Restart has been canceled."); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + const handleSave = async () => { + setSaving(true); + try { + await updateServerRestartSettings(server.id, warnPlayers, warnMinutes, message, cancelMessage); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save restart settings: ${e}`); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ +

Restart Warning

+
+ + + +
+
+ + setWarnMinutes(parseInt(e.target.value, 10) || 5)} + className="h-7 w-24 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + setMessage(e.target.value)} + placeholder="Server restarting in {time}." + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + setCancelMessage(e.target.value)} + placeholder="Restart has been canceled." + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + +
+ ); +} + +// --------------------------------------------------------------------------- +// Update Warning Settings Card +// --------------------------------------------------------------------------- + +function UpdateSettingsCard({ server }: { server: ServerRow }) { + const [warnPlayers, setWarnPlayers] = useState(server.update_warn_players !== 0); + const [warnMinutes, setWarnMinutes] = useState(server.update_warn_minutes ?? 5); + const [message, setMessage] = useState(server.update_message || "Server going down for update in {time}."); + const [cancelMessage, setCancelMessage] = useState(server.update_cancel_message || "Update has been canceled."); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + + const handleSave = async () => { + setSaving(true); + try { + await updateServerUpdateSettings(server.id, warnPlayers, warnMinutes, message, cancelMessage); + setSaved(true); + setTimeout(() => setSaved(false), 2000); + } catch (e) { + toast.error(`Failed to save update settings: ${e}`); + } finally { + setSaving(false); + } + }; + + return ( +
+
+ +

Update Warning

+
+ + + +
+
+ + setWarnMinutes(parseInt(e.target.value, 10) || 5)} + className="h-7 w-24 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + setMessage(e.target.value)} + placeholder="Server going down for update in {time}." + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + setCancelMessage(e.target.value)} + placeholder="Update has been canceled." + className="h-7 text-xs" + style={{ background: "rgba(0,0,0,0.4)", borderColor: "rgba(var(--neon-purple-rgb),0.2)", color: "var(--text-primary)" }} + /> +
+
+ + +
+ ); +} + export function ConfigTab({ server }: Props) { const [config, setConfig] = useState(null); const [rawGus, setRawGus] = useState(""); @@ -763,8 +961,10 @@ export function ConfigTab({ server }: Props) {
)} - {/* Graceful shutdown settings */} + {/* Graceful shutdown / restart / update warning settings */} + + {/* Full INI Editor modal */} {showFullModal && config && ( diff --git a/src/components/server/tabs/LogsTab.tsx b/src/components/server/tabs/LogsTab.tsx index d46b64d..8a6419d 100644 --- a/src/components/server/tabs/LogsTab.tsx +++ b/src/components/server/tabs/LogsTab.tsx @@ -8,11 +8,14 @@ import { import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { tauriCmd } from "@/lib/tauri-commands"; -import { useTauriEvent } from "@/hooks/useTauriEvent"; import type { ServerRow } from "@/lib/db"; import type { ArchivedLogInfo, CrashInfo, CrashReport, ChatLogInfo, OtherLogInfo, } from "@/lib/tauri-commands"; +import { + getKnownPlayers, getPlayerKnownIps, getPlayerConnectionHistory, getPossibleAlts, + type PlayerConnectionRow, +} from "@/lib/db"; interface Props { server: ServerRow; @@ -25,7 +28,7 @@ interface LogLine { } type LevelFilter = "all" | "info" | "warning" | "error"; -type LogView = "live" | "archive" | "crashes" | "chat"; +type LogView = "live" | "archive" | "crashes" | "chat" | "players"; let _id = 0; @@ -152,7 +155,7 @@ function LivePanel({ server }: { server: ServerRow }) { setLines([]); return; } - const latest = archives[archives.length - 1]; + const latest = archives[0]; // sorted newest-first by Rust setLastSessionFilename(latest.filename); const content = await tauriCmd.readArchivedLog(server.id, latest.filename, 0, 0); setLines(content.map((line) => ({ id: ++_id, line, level: classifyLine(line) }))); @@ -162,32 +165,60 @@ function LivePanel({ server }: { server: ServerRow }) { } }, [server.id]); - useTauriEvent<{ line: string; level: string }[]>(`log://backfill/${server.id}`, (payload) => { - const newLines = payload.map((item) => ({ - id: ++_id, - line: item.line, - level: (item.level as LogLine["level"]) ?? "info", - })); - setLines(newLines.slice(-4000)); - setReady(true); - }); - - useTauriEvent<{ line: string; level: string }>(`log://line/${server.id}`, (payload) => { - setReady(true); - setLines((prev) => [ - ...prev.slice(-3999), - { id: ++_id, line: payload.line, level: (payload.level as LogLine["level"]) ?? "info" }, - ]); - }); - - // Manage watcher vs last-session display based on whether the server is active. + // Single effect that registers both event listeners BEFORE starting the watcher. + // This eliminates a race where the Rust watcher emits the backfill event before + // the frontend listeners are ready (the Tauri listen() IPC is async/microtask, + // so a synchronous watchServerLog call would arrive at Rust first, causing the + // backfill to be emitted with no registered listeners and silently dropped). useEffect(() => { if (isActive) { setLastSessionFilename(null); setLines([]); setReady(false); - tauriCmd.watchServerLog(server.id, logPath(server.install_path)).catch(() => null); - return () => { tauriCmd.stopLogWatch(server.id).catch(() => null); }; + + let cancelled = false; + let unlistenBackfill: (() => void) | undefined; + let unlistenLine: (() => void) | undefined; + + import("@tauri-apps/api/event").then(async ({ listen }) => { + if (cancelled) return; + try { + [unlistenBackfill, unlistenLine] = await Promise.all([ + listen<{ line: string; level: string }[]>(`log://backfill/${server.id}`, (e) => { + const newLines = (e.payload ?? []).map((item) => ({ + id: ++_id, + line: item.line, + level: (item.level as LogLine["level"]) ?? "info", + })); + setLines(newLines.slice(-4000)); + setReady(true); + }), + listen<{ line: string; level: string }>(`log://line/${server.id}`, (e) => { + setReady(true); + setLines((prev) => [ + ...prev.slice(-3999), + { id: ++_id, line: e.payload.line, level: (e.payload.level as LogLine["level"]) ?? "info" }, + ]); + }), + ]); + } catch { + return; + } + if (cancelled) { + unlistenBackfill?.(); + unlistenLine?.(); + return; + } + // Both listeners are now registered in Rust — safe to start the watcher. + // Backfill will be emitted only after this point, so nothing is dropped. + tauriCmd.watchServerLog(server.id, logPath(server.install_path)).catch(() => null); + }); + + return () => { + cancelled = true; + unlistenBackfill?.(); + unlistenLine?.(); + }; } else { tauriCmd.stopLogWatch(server.id).catch(() => null); loadLastSession(); @@ -583,9 +614,14 @@ function CrashesPanel({ server }: { server: ServerRow }) { {selected.folderName} - +
+ + +
{loadingReport ? (
@@ -717,9 +753,16 @@ function ChatPanel({ server }: { server: ServerRow }) { )) )} - +
+ {selected && ( + + )} + +
{selected && ( @@ -756,6 +799,151 @@ function ChatPanel({ server }: { server: ServerRow }) { ); } +// --------------------------------------------------------------------------- +// PlayersPanel +// --------------------------------------------------------------------------- + +function formatDate(iso: string): string { + const d = new Date(iso); + if (isNaN(d.getTime())) return iso; + return d.toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" }); +} + +function PlayersPanel({ server }: { server: ServerRow }) { + const [knownPlayers, setKnownPlayers] = useState<{ eosId: string; playerName: string }[]>([]); + const [selectedEosId, setSelectedEosId] = useState(""); + const [knownIps, setKnownIps] = useState<{ ip: string; lastSeen: string }[]>([]); + const [history, setHistory] = useState([]); + const [alts, setAlts] = useState<{ eosId: string; sharedIps: string[] }[]>([]); + const [loading, setLoading] = useState(false); + + useEffect(() => { + getKnownPlayers(server.id).then(setKnownPlayers).catch(() => {}); + }, [server.id]); + + useEffect(() => { + if (!selectedEosId) { setKnownIps([]); setHistory([]); setAlts([]); return; } + setLoading(true); + Promise.all([ + getPlayerKnownIps(server.id, selectedEosId), + getPlayerConnectionHistory(server.id, selectedEosId, 200), + getPossibleAlts(server.id, selectedEosId), + ]).then(([ips, hist, altList]) => { + setKnownIps(ips); + setHistory(hist); + setAlts(altList); + }).catch(() => {}).finally(() => setLoading(false)); + }, [server.id, selectedEosId]); + + const nameFor = (eosId: string) => + knownPlayers.find((p) => p.eosId === eosId)?.playerName ?? eosId; + + return ( +
+ {/* Player selector */} +
+ +
+ + {!selectedEosId ? ( +

+ Select a player above to view their connection history. +

+ ) : loading ? ( +
+ + Loading… +
+ ) : ( +
+ + {/* Known IPs */} +
+
+

Known IPs

+
+
+ {knownIps.length === 0 ? ( +

No IPs recorded.

+ ) : knownIps.map(({ ip, lastSeen }) => ( +
+ {ip} + {formatDate(lastSeen)} +
+ ))} +
+
+ + {/* Connection History */} +
+
+

+ Connection History + {history.length >= 200 && ( + (last 200) + )} +

+
+
+ {history.length === 0 ? ( +

No connections recorded.

+ ) : history.map((row) => ( +
+ {row.ip_address} + {formatDate(row.connected_at)} +
+ ))} +
+
+ + {/* Possible Alts */} +
+
+

Possible Alts

+
+
+

+ Accounts that connected from the same IP(s). May include household members or VPN users. +

+ {alts.length === 0 ? ( +

No shared IPs detected.

+ ) : alts.map(({ eosId, sharedIps }) => ( +
+

+ {nameFor(eosId)} +

+

+ {sharedIps.join(", ")} +

+
+ ))} +
+
+ +
+ )} +
+ ); +} + // --------------------------------------------------------------------------- // Main LogsTab // --------------------------------------------------------------------------- @@ -765,6 +953,7 @@ const VIEW_TABS: { value: LogView; label: string; icon: React.ComponentType<{ cl { value: "archive", label: "Archive", icon: Archive }, { value: "crashes", label: "Crashes", icon: AlertTriangle }, { value: "chat", label: "Chat", icon: MessageSquare }, + { value: "players", label: "Players", icon: Search }, ]; export function LogsTab({ server }: Props) { @@ -805,6 +994,7 @@ export function LogsTab({ server }: Props) { {view === "archive" && } {view === "crashes" && } {view === "chat" && } + {view === "players" && }
); diff --git a/src/components/server/tabs/OverviewTab.tsx b/src/components/server/tabs/OverviewTab.tsx index 215eadc..351594b 100644 --- a/src/components/server/tabs/OverviewTab.tsx +++ b/src/components/server/tabs/OverviewTab.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useCallback, useRef } from "react"; import { useRouter } from "next/navigation"; import { Play, Square, RotateCcw, Users, Cpu, MemoryStick, Clock, @@ -27,8 +27,8 @@ import { tauriCmd, type StartServerParams, type ArkPlayer } from "@/lib/tauri-co import { useAppStore } from "@/store/useAppStore"; import { updateServerStatus, getServerConfig, getServerModCount, getServerMods, - getLastBackupTime, getNextScheduledRestart, getAppSetting, insertBackup, - setServerAutoStart, + getLastBackupTime, getNextScheduledRestart, getHasBackupEnabled, getAppSetting, insertBackup, + pruneManualBackups, setServerAutoStart, } from "@/lib/db"; import { applyUpdateToServer } from "@/lib/update-utils"; import { warnIfFirewallMissing } from "@/lib/firewall-utils"; @@ -38,6 +38,7 @@ import { toast } from "sonner"; import { ARK_MAPS, LAUNCH_PARAMETERS, NOTIFICATION_EVENTS } from "@/data/game-data"; import { dispatchNotification } from "@/lib/notifications"; import { useQueryClient } from "@tanstack/react-query"; +import { useTauriEvent } from "@/hooks/useTauriEvent"; interface Props { server: ServerRow; @@ -55,6 +56,19 @@ const METRIC_CONFIG = { // ── Helpers ─────────────────────────────────────────────────────────────────── +function formatCountdown(secs: number): string { + if (secs >= 3600) { + const h = Math.floor(secs / 3600); + const m = Math.floor((secs % 3600) / 60); + return `${h}h ${m}m`; + } + const m = Math.floor(secs / 60); + const s = secs % 60; + if (m > 0 && s > 0) return `${m}m ${s}s`; + if (m > 0) return `${m}m`; + return `${s}s`; +} + function formatUptime(startMs: number): string { const elapsed = Date.now() - startMs; if (elapsed < 0) return "0m"; @@ -286,17 +300,11 @@ function StatChart({ // ── ServerSummaryPanel ──────────────────────────────────────────────────────── -function formatFutureTime(iso: string | null): string { +function formatClockTime(iso: string | null): string { if (!iso) return "Not scheduled"; const d = new Date(iso); if (isNaN(d.getTime())) return "—"; - const diffMs = d.getTime() - Date.now(); - if (diffMs < 0) return "Overdue"; - const diffMins = Math.floor(diffMs / 60_000); - if (diffMins < 60) return `in ${diffMins}m`; - const h = Math.floor(diffMins / 60); - if (h < 24) return `in ${h}h`; - return `in ${Math.floor(h / 24)}d`; + return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }); } function ServerSummaryPanel({ @@ -305,6 +313,7 @@ function ServerSummaryPanel({ modCount, lastBackup, nextRestart, + backupEnabled, onAutoStartChange, }: { server: ServerRow; @@ -312,11 +321,33 @@ function ServerSummaryPanel({ modCount: number | null; lastBackup: string | null; nextRestart: string | null; + backupEnabled: boolean | null; onAutoStartChange: (v: boolean) => void; }) { const isRunning = server.status === "running" || server.status === "starting"; const currentStartMs = startTime ?? (isRunning ? new Date(server.updated_at).getTime() : null); + const [backupActive, setBackupActive] = useState(false); + const backupUpdatedAt = useRef(0); + + useTauriEvent<{ percent: number; currentFile: string; label: string }>( + `backup://progress/${server.id}`, + (p) => { + backupUpdatedAt.current = Date.now(); + setBackupActive(p.percent < 100); + } + ); + + useEffect(() => { + if (!backupActive) return; + const id = setInterval(() => { + if (backupUpdatedAt.current > 0 && Date.now() - backupUpdatedAt.current > 30_000) { + setBackupActive(false); + } + }, 5_000); + return () => clearInterval(id); + }, [backupActive]); + const fmtDate = (ms: number) => new Date(ms).toLocaleString([], { month: "short", day: "numeric", @@ -330,7 +361,8 @@ function ServerSummaryPanel({ { label: "Map", value: mapDisplay }, { label: "Mods", value: modCount !== null ? String(modCount) : "—" }, { label: "Last Backup", value: formatRelativeTime(lastBackup) }, - { label: "Next Restart", value: formatFutureTime(nextRestart) }, + { label: "Backup", value: backupActive ? "In progress…" : backupEnabled === null ? "—" : backupEnabled ? "Enabled" : "Disabled" }, + { label: "Next Restart", value: formatClockTime(nextRestart) }, ]; return ( @@ -435,10 +467,12 @@ export function OverviewTab({ server }: Props) { const stats = useServerStats(server); const startTime = useAppStore((s) => s.serverStartTimes[server.id]); const isServerScanPending = useAppStore((s) => s.isServerScanPending); + const countdown = useAppStore((s) => s.countdowns[server.id] ?? null); const [modCount, setModCount] = useState(null); - const [lastBackup, setLastBackup] = useState(null); - const [nextRestart, setNextRestart] = useState(null); + const [lastBackup, setLastBackup] = useState(null); + const [nextRestart, setNextRestart] = useState(null); + const [backupEnabled, setBackupEnabled] = useState(null); const [actionPending, setActionPending] = useState(false); const [players, setPlayers] = useState(null); const [playersLoading, setPlayersLoading] = useState(false); @@ -470,16 +504,18 @@ export function OverviewTab({ server }: Props) { useEffect(() => { let cancelled = false; (async () => { - const [mc, lb, nr, autoHours] = await Promise.all([ + const [mc, lb, nr, be, autoHours] = await Promise.all([ getServerModCount(server.id), getLastBackupTime(server.id), getNextScheduledRestart(server.id), + getHasBackupEnabled(server.id), getAppSetting("asa_auto_check_hours"), ]); if (!cancelled) { setModCount(mc); setLastBackup(lb); setNextRestart(nr); + setBackupEnabled(be); setAutoCheckEnabled((autoHours ?? "0") !== "0"); } })(); @@ -583,6 +619,20 @@ export function OverviewTab({ server }: Props) { }; const handleRestart = async () => { + if (server.restart_warn_players) { + const startParams = await buildStartParams(); + tauriCmd.startGracefulRestart({ + serverId: server.id, + warnSeconds: (server.restart_warn_minutes ?? 5) * 60, + rconPort: server.rcon_port, + rconPassword: server.rcon_password, + message: server.restart_message || "Server restarting in {time}.", + cancelMessage: server.restart_cancel_message || "Restart has been canceled.", + startParams, + }).catch((err) => toast.error(`Restart failed: ${err}`)); + return; + } + setActionPending(true); try { await updateServerStatus(server.id, "stopping", null); @@ -601,6 +651,34 @@ export function OverviewTab({ server }: Props) { const handleApplyUpdate = async () => { setShowUpdateConfirm(false); + + if (server.update_warn_players && isRunning) { + const [baseDir, steamcmdPath] = await Promise.all([ + getAppSetting("base_dir"), + getAppSetting("steamcmd_path"), + ]); + if (!baseDir || !steamcmdPath) return; + const sep = baseDir.includes("\\") ? "\\" : "/"; + const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; + const startParams = restartAfterUpdate ? await buildStartParams() : null; + + tauriCmd.startGracefulUpdate({ + serverId: server.id, + serverName: server.name, + warnSeconds: (server.update_warn_minutes ?? 5) * 60, + rconPort: server.rcon_port, + rconPassword: server.rcon_password, + message: server.update_message || "Server going down for update in {time}.", + cancelMessage: server.update_cancel_message || "Update has been canceled.", + installPath: server.install_path, + cacheDir, + steamcmdPath, + restartAfter: restartAfterUpdate, + startParams, + }).catch((err) => toast.error(`Update failed: ${err}`)); + return; + } + setApplyingUpdate(true); try { const wasRunning = isRunning; @@ -612,6 +690,8 @@ export function OverviewTab({ server }: Props) { wasRunning, restartAfterUpdate, (msg) => toast.info(msg), + server.rcon_port, + server.rcon_password, ); } catch (err) { if (err && typeof err === "object" && "restartNeeded" in err) { @@ -651,7 +731,7 @@ export function OverviewTab({ server }: Props) { } }; - const refreshPlayers = async () => { + const refreshPlayers = useCallback(async () => { setPlayersLoading(true); try { const list = await tauriCmd.rconGetPlayers(server.id); @@ -662,7 +742,19 @@ export function OverviewTab({ server }: Props) { } finally { setPlayersLoading(false); } - }; + }, [server.id]); + + // Fetch player list on mount/server-change if running. + useEffect(() => { + if (server.status === "running") refreshPlayers(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [server.id]); + + // The per-server event emits the players array directly as payload. + useTauriEvent( + `rcon://players/${server.id}`, + (list) => setPlayers(list) + ); // ── Render ────────────────────────────────────────────────────────────────── @@ -682,7 +774,33 @@ export function OverviewTab({ server }: Props) { {/* Left group — status-dependent buttons */}
- {isServerScanPending ? ( + {countdown ? ( + <> + + {countdown.action === "restart" + ? `Restarting in ${formatCountdown(countdown.remainingSecs)}` + : `Updating in ${formatCountdown(countdown.remainingSecs)}`} + + + + + ) : isServerScanPending ? ( )} - {isRunning && !isServerScanPending && ( + {isRunning && !isServerScanPending && !countdown && ( @@ -770,9 +888,11 @@ export function OverviewTab({ server }: Props) { await insertBackup({ id: record.id, server_id: record.serverId, file_path: record.filePath, file_size_bytes: record.fileSizeBytes, map_id: record.mapId, - triggered_by: record.triggeredBy, created_at: record.createdAt, + triggered_by: "manual", created_at: record.createdAt, backup_type: "server", tiers: "", player_eosid: null, player_name: null, }); + const keep = parseInt(await getAppSetting(`manual_backup_keep_${server.id}`) ?? "5", 10); + await pruneManualBackups(server.id, "server", isNaN(keep) ? 5 : keep); }) .catch(() => null); }} @@ -804,6 +924,7 @@ export function OverviewTab({ server }: Props) { modCount={modCount} lastBackup={lastBackup} nextRestart={nextRestart} + backupEnabled={backupEnabled} onAutoStartChange={async (v) => { await setServerAutoStart(server.id, v); queryClient.invalidateQueries({ queryKey: ["servers"] }); diff --git a/src/components/shared/NotificationMatrix.tsx b/src/components/shared/NotificationMatrix.tsx index 0e41c4d..d83ecbd 100644 --- a/src/components/shared/NotificationMatrix.tsx +++ b/src/components/shared/NotificationMatrix.tsx @@ -49,7 +49,7 @@ const ALL_EVENTS = Object.values(NOTIFICATION_EVENTS) as NotificationEventType[] const CHANNEL_DEFAULTS: Record = { in_app: ALL_EVENTS, bell: ALL_EVENTS, - desktop: ["server_started", "server_crashed", "update_available", "update_started", "update_failed"], + desktop: ["server_started", "server_crashed", "update_available", "update_started", "update_failed", "backup_completed", "backup_failed"], discord: ALL_EVENTS, email: ALL_EVENTS, }; diff --git a/src/data/game-data.ts b/src/data/game-data.ts index c1518f4..37c8fa5 100644 --- a/src/data/game-data.ts +++ b/src/data/game-data.ts @@ -907,7 +907,7 @@ export const INI_FIELD_GROUPS: IniFieldGroup[] = [ { section: "gus", iniSection: "ServerSettings", key: "GlobalSpoilingTimeMultiplier", label: "Spoiling Time", type: "number", min: 0, max: 10, step: 0.1, defaultValue: 1.0, description: "Higher = food/items spoil slower." }, { section: "gus", iniSection: "ServerSettings", key: "GlobalItemDecompositionTimeMultiplier", label: "Item Decay Time", type: "number", min: 0, max: 10, step: 0.1, defaultValue: 1.0 }, { section: "gus", iniSection: "ServerSettings", key: "GlobalCorpseDecompositionTimeMultiplier", label: "Corpse Decay Time", type: "number", min: 0, max: 10, step: 0.1, defaultValue: 1.0 }, - { section: "gus", iniSection: "ServerSettings", key: "AutoSavePeriodMinutes", label: "Auto-Save Interval (min)", type: "number", min: 1, max: 120, defaultValue: 15, description: "How often the server saves to disk." }, + { section: "gus", iniSection: "ServerSettings", key: "AutoSavePeriodMinutes", label: "Auto-Save Interval (min)", type: "number", min: 0, max: 120, defaultValue: 15, description: "How often the server saves to disk. Set to 0 to disable ARK's auto-save and manage saves manually via RCON." }, ], }, { diff --git a/src/lib/db.ts b/src/lib/db.ts index c687c17..beb9451 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -7,6 +7,7 @@ */ import Database from "@tauri-apps/plugin-sql"; +import { CronExpressionParser } from "cron-parser"; // Singleton DB connection — populated by initDb(). let _db: Database | null = null; @@ -249,6 +250,16 @@ async function runMigrations(db: Database): Promise { await db.execute("ALTER TABLE servers ADD COLUMN auto_start INTEGER NOT NULL DEFAULT 0"); } catch { /* already exists */ } + // ── Migration 014: restart / update warning settings ───────────────────── + try { await db.execute("ALTER TABLE servers ADD COLUMN restart_warn_players INTEGER NOT NULL DEFAULT 0"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN restart_warn_minutes INTEGER NOT NULL DEFAULT 5"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN restart_message TEXT NOT NULL DEFAULT 'Server restarting in {time}.'"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN restart_cancel_message TEXT NOT NULL DEFAULT 'Restart has been canceled.'"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN update_warn_players INTEGER NOT NULL DEFAULT 0"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN update_warn_minutes INTEGER NOT NULL DEFAULT 5"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN update_message TEXT NOT NULL DEFAULT 'Server going down for update in {time}.'"); } catch { /* exists */ } + try { await db.execute("ALTER TABLE servers ADD COLUMN update_cancel_message TEXT NOT NULL DEFAULT 'Update has been canceled.'"); } catch { /* exists */ } + // Reset partial "updating" status — the update did not complete and must be re-triggered. // update_available remains 1 so the badge shows. // startup_queued and update_queued are intentionally preserved — StartupRecoveryManager @@ -325,6 +336,143 @@ async function runMigrations(db: Database): Promise { added_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (port, protocol) )`); + + // ── Migration 010: player connection history ───────────────────────────── + await db.execute(`CREATE TABLE IF NOT EXISTS player_connections ( + id TEXT PRIMARY KEY, + server_id TEXT NOT NULL, + eos_id TEXT NOT NULL, + ip_address TEXT NOT NULL, + connected_at DATETIME NOT NULL + )`); + await db.execute( + "CREATE INDEX IF NOT EXISTS idx_player_connections_server_eos ON player_connections(server_id, eos_id)" + ); + await db.execute( + "CREATE INDEX IF NOT EXISTS idx_player_connections_ip ON player_connections(server_id, ip_address)" + ); + + // ── Migration 011: fix hourly backup cron (was every 6h, now every 1h) ─── + await db.execute( + "UPDATE schedules SET cron_expression = '0 * * * *' WHERE schedule_type IN ('backup_server','backup_player') AND cron_expression = '0 */6 * * *'" + ); + + // ── Migration 012: consolidate per-tier schedule rows into single rows ──── + // Old format: up to 4 rows per (server, type) each with { tier: "H"|"D"|"W"|"M", keep: N } + // New format: 1 row per (server, type) with all tiers in config_json: + // { hourly: { enabled, keep }, daily: { enabled, keep }, weekly: { enabled, keep }, monthly: { enabled, keep } } + { + const done = await db.select<{ value: string }[]>( + "SELECT value FROM app_settings WHERE key = 'migration_012_done'" + ); + if (!done.length || done[0]?.value !== "true") { + type OldRow = { id: string; server_id: string; schedule_type: string; config_json: string; enabled: number }; + const rows = await db.select( + "SELECT id, server_id, schedule_type, config_json, enabled FROM schedules WHERE schedule_type IN ('backup_server','backup_player') ORDER BY rowid ASC" + ); + + const groups = new Map(); + for (const row of rows) { + const key = `${row.server_id}:${row.schedule_type}`; + if (!groups.has(key)) groups.set(key, []); + groups.get(key)!.push(row); + } + + const tierMap: Record = { H: "hourly", D: "daily", W: "weekly", M: "monthly" }; + const keepDefaults: Record = { hourly: 24, daily: 7, weekly: 4, monthly: 3 }; + + for (const [, groupRows] of groups) { + const merged: Record = { + hourly: { enabled: false, keep: keepDefaults.hourly }, + daily: { enabled: false, keep: keepDefaults.daily }, + weekly: { enabled: false, keep: keepDefaults.weekly }, + monthly: { enabled: false, keep: keepDefaults.monthly }, + }; + + let needsUpdate = false; + for (const row of groupRows) { + try { + const cfg = JSON.parse(row.config_json ?? "{}") as Record; + if (typeof cfg.tier === "string") { + // Old single-tier format + needsUpdate = true; + const key = tierMap[(cfg.tier as string).toUpperCase()]; + if (key) { + merged[key] = { + enabled: row.enabled === 1, + keep: typeof cfg.keep === "number" && cfg.keep > 0 ? cfg.keep : keepDefaults[key], + }; + } + } else if (cfg.hourly !== undefined || cfg.daily !== undefined || cfg.weekly !== undefined || cfg.monthly !== undefined) { + // Already new format — still merge in case of multiple new-format rows + for (const k of ["hourly", "daily", "weekly", "monthly"]) { + const tc = cfg[k] as { enabled?: boolean; keep?: number } | undefined; + if (tc) merged[k] = { enabled: tc.enabled ?? false, keep: tc.keep ?? keepDefaults[k] }; + } + } + } catch { /* skip malformed rows */ } + } + + if (!needsUpdate && groupRows.length <= 1) continue; + + const anyEnabled = Object.values(merged).some((v) => v.enabled); + const cron = merged.hourly.enabled ? "0 * * * *" + : merged.daily.enabled ? "0 2 * * *" + : merged.weekly.enabled ? "0 3 * * 0" + : "0 4 1 * *"; + + await db.execute( + "UPDATE schedules SET config_json = ?, cron_expression = ?, enabled = ? WHERE id = ?", + [JSON.stringify(merged), cron, anyEnabled ? 1 : 0, groupRows[0].id] + ); + + for (const row of groupRows.slice(1)) { + await db.execute("DELETE FROM schedules WHERE id = ?", [row.id]); + } + } + + await db.execute( + "INSERT OR REPLACE INTO app_settings (key, value) VALUES ('migration_012_done', 'true')" + ); + } + } + + // ── Migration 013: convert ancient {"retention":N} backup config to tier format ── + // Pre-tier-system rows had { "retention": N } with no hourly/daily/weekly/monthly keys. + // Convert them so the new hourly backup tick can handle them correctly. + { + const done = await db.select<{ value: string }[]>( + "SELECT value FROM app_settings WHERE key = 'migration_013_done'" + ); + if (!done.length || done[0]?.value !== "true") { + type Row = { id: string; config_json: string }; + const rows = await db.select( + "SELECT id, config_json FROM schedules WHERE schedule_type IN ('backup_server','backup_player','backup_full')" + ); + for (const row of rows) { + try { + const cfg = JSON.parse(row.config_json ?? "{}") as Record; + if (cfg.retention !== undefined && cfg.hourly === undefined) { + const keep = typeof cfg.retention === "number" && cfg.retention > 0 + ? cfg.retention : 24; + const newCfg = { + hourly: { enabled: true, keep }, + daily: { enabled: false, keep: 7 }, + weekly: { enabled: false, keep: 4 }, + monthly: { enabled: false, keep: 3 }, + }; + await db.execute( + "UPDATE schedules SET config_json = ?, cron_expression = '0 * * * *' WHERE id = ?", + [JSON.stringify(newCfg), row.id] + ); + } + } catch { /* skip malformed */ } + } + await db.execute( + "INSERT OR REPLACE INTO app_settings (key, value) VALUES ('migration_013_done', 'true')" + ); + } + } } // --------------------------------------------------------------------------- @@ -349,10 +497,18 @@ export interface ServerRow { pid: number | null; update_available: number; // 0 | 1 — set by global update check update_automation_json: string; // UpdateAutomation JSON blob - shutdown_warn_players: number; // 0 | 1 - shutdown_warn_minutes: number; // default 5 - shutdown_message: string; // template with {time} placeholder - auto_start: number; // 0 | 1 — always start on app launch + shutdown_warn_players: number; // 0 | 1 + shutdown_warn_minutes: number; // default 5 + shutdown_message: string; // template with {time} placeholder + restart_warn_players: number; // 0 | 1 + restart_warn_minutes: number; // default 5 + restart_message: string; // template with {time} placeholder + restart_cancel_message: string; + update_warn_players: number; // 0 | 1 + update_warn_minutes: number; // default 5 + update_message: string; // template with {time} placeholder + update_cancel_message: string; + auto_start: number; // 0 | 1 — always start on app launch created_at: string; updated_at: string; } @@ -707,6 +863,34 @@ export async function updateServerShutdownSettings( ); } +export async function updateServerRestartSettings( + id: string, + warnPlayers: boolean, + warnMinutes: number, + message: string, + cancelMessage: string, +): Promise { + const db = await getDb(); + await db.execute( + "UPDATE servers SET restart_warn_players = ?, restart_warn_minutes = ?, restart_message = ?, restart_cancel_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + [warnPlayers ? 1 : 0, warnMinutes, message, cancelMessage, id] + ); +} + +export async function updateServerUpdateSettings( + id: string, + warnPlayers: boolean, + warnMinutes: number, + message: string, + cancelMessage: string, +): Promise { + const db = await getDb(); + await db.execute( + "UPDATE servers SET update_warn_players = ?, update_warn_minutes = ?, update_message = ?, update_cancel_message = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", + [warnPlayers ? 1 : 0, warnMinutes, message, cancelMessage, id] + ); +} + /** Set the auto_start flag for a server. */ export async function setServerAutoStart(id: string, autoStart: boolean): Promise { const db = await getDb(); @@ -959,6 +1143,32 @@ export async function deleteBackupRecord(backupId: string): Promise { await db.execute("DELETE FROM backups WHERE id = ?", [backupId]); } +/** + * Prune manual backups for a server+type down to `keep` most recent. + * Called after every manual backup insertion. + */ +export async function pruneManualBackups( + serverId: string, + backupType: string, + keep: number, +): Promise { + if (keep <= 0) return; + const db = await getDb(); + const rows = await db.select<{ id: string; file_path: string }[]>( + `SELECT id, file_path FROM backups + WHERE server_id = ? AND backup_type = ? AND triggered_by = 'manual' + ORDER BY created_at DESC`, + [serverId, backupType], + ); + const toDelete = rows.slice(keep); + for (const row of toDelete) { + await import("@/lib/tauri-commands").then(({ tauriCmd }) => + tauriCmd.deleteBackup(row.file_path).catch(() => {}) + ); + await db.execute("DELETE FROM backups WHERE id = ?", [row.id]); + } +} + // --------------------------------------------------------------------------- // Player name map // --------------------------------------------------------------------------- @@ -1076,16 +1286,161 @@ export async function getLastBackupTime(serverId: string): Promise Date.now()) return nextRun; + } + if (!cronExpr) return nextRun; + try { + const next = CronExpressionParser.parse(cronExpr).next().toDate(); + return next.toISOString(); + } catch { + return nextRun; + } +} + /** Return the next_run ISO timestamp for the restart/update schedule, or null. */ export async function getNextScheduledRestart(serverId: string): Promise { const db = await getDb(); - const rows = await db.select<{ next_run: string | null }[]>( - `SELECT next_run FROM schedules + const rows = await db.select<{ next_run: string | null; cron_expression: string | null }[]>( + `SELECT next_run, cron_expression FROM schedules WHERE server_id = ? AND schedule_type IN ('restart', 'update') AND enabled = 1 ORDER BY next_run ASC LIMIT 1`, [serverId] ); - return rows[0]?.next_run ?? null; + if (!rows[0]) return null; + return resolveNextRun(rows[0].next_run, rows[0].cron_expression); +} + +/** Return true if any backup schedule row is enabled and has at least one tier active. */ +export async function getHasBackupEnabled(serverId: string): Promise { + const db = await getDb(); + const rows = await db.select<{ config_json: string }[]>( + `SELECT config_json FROM schedules + WHERE server_id = ? AND schedule_type IN ('backup_server', 'backup_player', 'backup_full') AND enabled = 1`, + [serverId] + ); + return rows.some((row) => { + try { + const cfg = JSON.parse(row.config_json ?? "{}") as Record; + return Object.values(cfg).some( + (v) => typeof v === "object" && v !== null && (v as { enabled?: boolean }).enabled === true + ); + } catch { return false; } + }); +} + +// --------------------------------------------------------------------------- +// Player connections +// --------------------------------------------------------------------------- + +export interface PlayerConnectionRow { + id: string; + server_id: string; + eos_id: string; + ip_address: string; + connected_at: string; +} + +export async function insertPlayerConnection( + serverId: string, + eosId: string, + ip: string +): Promise { + const db = await getDb(); + await db.execute( + "INSERT INTO player_connections (id, server_id, eos_id, ip_address, connected_at) VALUES (?, ?, ?, ?, datetime('now'))", + [crypto.randomUUID(), serverId, eosId, ip] + ); +} + +/** All unique IPs a player has connected from, most recently seen first. */ +export async function getPlayerKnownIps( + serverId: string, + eosId: string +): Promise<{ ip: string; lastSeen: string }[]> { + const db = await getDb(); + return db.select<{ ip: string; lastSeen: string }[]>( + `SELECT ip_address AS ip, MAX(connected_at) AS lastSeen + FROM player_connections + WHERE server_id = ? AND eos_id = ? + GROUP BY ip_address + ORDER BY lastSeen DESC`, + [serverId, eosId] + ); +} + +/** Full connection history for a player, newest first (capped at 200 for display). */ +export async function getPlayerConnectionHistory( + serverId: string, + eosId: string, + limit = 200 +): Promise { + const db = await getDb(); + return db.select( + "SELECT * FROM player_connections WHERE server_id = ? AND eos_id = ? ORDER BY connected_at DESC LIMIT ?", + [serverId, eosId, limit] + ); +} + +/** Other EOS IDs that have connected from any of the same IPs as this player. */ +export async function getPossibleAlts( + serverId: string, + eosId: string +): Promise<{ eosId: string; sharedIps: string[] }[]> { + const db = await getDb(); + const rows = await db.select<{ eos_id: string; ip_address: string }[]>( + `SELECT DISTINCT p2.eos_id, p2.ip_address + FROM player_connections p1 + JOIN player_connections p2 + ON p1.server_id = p2.server_id AND p1.ip_address = p2.ip_address + WHERE p1.server_id = ? AND p1.eos_id = ? AND p2.eos_id != ? + ORDER BY p2.eos_id`, + [serverId, eosId, eosId] + ); + const map = new Map(); + for (const r of rows) { + if (!map.has(r.eos_id)) map.set(r.eos_id, []); + map.get(r.eos_id)!.push(r.ip_address); + } + return [...map.entries()].map(([id, ips]) => ({ eosId: id, sharedIps: [...new Set(ips)] })); +} + +/** Count of login backups for a specific player (used for prune logic). */ +export async function getLoginBackupCount( + serverId: string, + eosId: string +): Promise { + const db = await getDb(); + const rows = await db.select<{ n: number }[]>( + "SELECT COUNT(*) AS n FROM backups WHERE server_id = ? AND player_eosid = ? AND triggered_by = 'login'", + [serverId, eosId] + ); + return rows[0]?.n ?? 0; +} + +/** Oldest login backup for a player — used to prune when over the keep limit. */ +export async function getOldestLoginBackup( + serverId: string, + eosId: string +): Promise { + const db = await getDb(); + const rows = await db.select( + "SELECT * FROM backups WHERE server_id = ? AND player_eosid = ? AND triggered_by = 'login' ORDER BY created_at ASC LIMIT 1", + [serverId, eosId] + ); + return rows[0] ?? null; +} + +/** Update the file_path for a backup record (used after tier-rename on disk). */ +export async function updateBackupFilePath( + backupId: string, + newFilePath: string +): Promise { + const db = await getDb(); + await db.execute("UPDATE backups SET file_path = ? WHERE id = ?", [newFilePath, backupId]); } // --------------------------------------------------------------------------- diff --git a/src/lib/scheduler-sync.ts b/src/lib/scheduler-sync.ts index b64e752..b540654 100644 --- a/src/lib/scheduler-sync.ts +++ b/src/lib/scheduler-sync.ts @@ -72,17 +72,25 @@ export async function syncSchedulesToRust(): Promise { const map = ARK_MAPS.find((m) => m.id === server.map_id); const mapPath = map?.mapPath ?? "TheIsland_WP"; - // Exclude backup schedule types that don't use the standard cron approach. - // backup_server / backup_player / backup_full are included normally below. + // Backup schedules are handled by the hourly backup://tick task in Rust, + // NOT by the cron scheduler. Skip them here so they never double-fire. + const BACKUP_TYPES = new Set(["backup_server", "backup_player", "backup_full"]); + for (const schedule of enabled) { + if (BACKUP_TYPES.has(schedule.schedule_type)) continue; // Compute next_run_ms from either the stored ISO date or fresh from cron. + // IMPORTANT: never push a past timestamp — that causes Rust to fire immediately, + // which re-fires backups that are still in progress (erases the u64::MAX guard). let nextRunMs: number; - if (schedule.next_run) { - const stored = new Date(schedule.next_run).getTime(); - nextRunMs = isNaN(stored) ? Date.now() : stored; + const storedTime = schedule.next_run + ? new Date(schedule.next_run).getTime() + : NaN; + if (!isNaN(storedTime) && storedTime > Date.now()) { + nextRunMs = storedTime; } else { + // Stale, missing, or past — compute next strictly-future occurrence. const next = getNextCronDate(schedule.cron_expression); - nextRunMs = next ? next.getTime() : Date.now(); + nextRunMs = next ? next.getTime() : Date.now() + 3_600_000; } entries.push({ diff --git a/src/lib/tauri-commands.ts b/src/lib/tauri-commands.ts index 41659ee..df87a6f 100644 --- a/src/lib/tauri-commands.ts +++ b/src/lib/tauri-commands.ts @@ -314,7 +314,8 @@ export interface SchedulerFiredPayload { scheduleType: string; success: boolean; error?: string; - backupRecord?: BackupRecord; + /** All backup records created by this firing (player backups produce one per player). */ + backupRecords: BackupRecord[]; } // --------------------------------------------------------------------------- @@ -419,9 +420,6 @@ export const tauriCmd = { rconGetPlayers: (serverId: string) => invoke("rcon_get_players", { serverId }), /** null = no RCON connection established yet; [] = connected but 0 players online. */ rconGetCachedPlayers: (serverId: string) => invoke("rcon_get_cached_players", { serverId }), - // RCON — chat (polling is now internal to the Rust manager task) - rconEnableChatPoll: (serverId: string) => invoke("rcon_enable_chat_poll", { serverId }), - rconDisableChatPoll: (serverId: string) => invoke("rcon_disable_chat_poll", { serverId }), // RCON — log buffer rconGetLog: (serverId: string) => invoke("rcon_get_log", { serverId }), rconClearLog: (serverId: string) => invoke("rcon_clear_log", { serverId }), @@ -438,6 +436,38 @@ export const tauriCmd = { warnMessage: string, ) => invoke("graceful_stop_server", { serverId, rconPort, rconPassword, warnPlayers, warnMinutes, warnMessage }), + // Graceful countdown restart / update + startGracefulRestart: (params: { + serverId: string; + warnSeconds: number; + rconPort: number; + rconPassword: string; + message: string; + cancelMessage: string; + startParams: StartServerParams; + }) => invoke("start_graceful_restart", { params }), + + startGracefulUpdate: (params: { + serverId: string; + serverName: string; + warnSeconds: number; + rconPort: number; + rconPassword: string; + message: string; + cancelMessage: string; + installPath: string; + cacheDir: string; + steamcmdPath: string; + restartAfter: boolean; + startParams: StartServerParams | null; + }) => invoke("start_graceful_update", { params }), + + cancelCountdown: (serverId: string) => + invoke("cancel_countdown", { serverId }), + + proceedNow: (serverId: string) => + invoke("proceed_now", { serverId }), + // Log watcher watchServerLog: (serverId: string, logPath: string) => invoke("watch_server_log", { serverId, logPath }), @@ -494,14 +524,20 @@ export const tauriCmd = { /** Server backup: SaveWorld → cleanup ARK files → 7z SavedArks+SaveGames. */ createServerBackup: ( serverId: string, serverName: string, installPath: string, mapPath: string, - mapId: string, backupDir: string, triggeredBy: string, - ) => invoke("create_server_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy }), + mapId: string, backupDir: string, triggeredBy: string, tier = "", + ) => invoke("create_server_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy, tier }), /** Player backup: 7z a single .arkprofile file. */ createPlayerBackup: ( serverId: string, serverName: string, installPath: string, mapPath: string, - mapId: string, backupDir: string, eosId: string, playerName: string, triggeredBy: string, - ) => invoke("create_player_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, eosId, playerName, triggeredBy }), + mapId: string, backupDir: string, eosId: string, playerName: string, triggeredBy: string, tier = "", + ) => invoke("create_player_backup", { serverId, serverName, installPath, mapPath, mapId, backupDir, eosId, playerName, triggeredBy, tier }), + + /** Back up every .arkprofile in SavedArks/{mapPath}/ in one call. */ + backupAllPlayers: ( + serverId: string, serverName: string, installPath: string, mapPath: string, + mapId: string, backupDir: string, triggeredBy: string, + ) => invoke("backup_all_players", { serverId, serverName, installPath, mapPath, mapId, backupDir, triggeredBy }), /** INI backup: copy loose INI files into a rotating timestamped folder. */ createIniBackup: (serverId: string, installPath: string, backupDir: string, platform: string) => @@ -510,8 +546,8 @@ export const tauriCmd = { /** Full backup: 7z the entire install_path directory. */ createFullBackup: ( serverId: string, serverName: string, installPath: string, mapId: string, - backupDir: string, triggeredBy: string, - ) => invoke("create_full_backup", { serverId, serverName, installPath, mapId, backupDir, triggeredBy }), + backupDir: string, triggeredBy: string, tier = "", + ) => invoke("create_full_backup", { serverId, serverName, installPath, mapId, backupDir, triggeredBy, tier }), /** List timestamped INI snapshot folder names for a server, newest first. */ listIniBackups: (serverId: string, backupDir: string) => @@ -543,6 +579,17 @@ export const tauriCmd = { /** Estimate total uncompressed size of a directory in bytes. */ estimateDirSize: (dirPath: string) => invoke("estimate_dir_size", { dirPath }), + /** Rename a backup file on disk (used when tier flags change). */ + renameBackupFile: (oldPath: string, newPath: string) => + invoke("rename_backup_file", { oldPath, newPath }), + + /** Check whether a backup file still exists on disk. */ + backupFileExists: (filePath: string) => invoke("backup_file_exists", { filePath }), + + /** Scan the server's backup directory tree and return all discovered .7z files. */ + scanBackupDir: (serverId: string, backupDir: string, mapId: string) => + invoke("scan_backup_dir", { serverId, backupDir, mapId }), + // Mods /** * Download all listed mods via SteamCMD, cache them, and copy to the server. diff --git a/src/lib/update-utils.ts b/src/lib/update-utils.ts index 2407ed2..9849929 100644 --- a/src/lib/update-utils.ts +++ b/src/lib/update-utils.ts @@ -134,6 +134,8 @@ export async function applyUpdateToServer( wasRunning: boolean, restartAfterUpdate: boolean, onStatusChange?: (msg: string) => void, + rconPort?: number, + rconPassword?: string, ): Promise { const [cacheBase, steamcmdPath] = await Promise.all([ getAppSetting("base_dir"), @@ -156,8 +158,12 @@ export async function applyUpdateToServer( try { if (wasRunning) { onStatusChange?.("Stopping server…"); - await tauriCmd.stopServer(serverId, false); - await new Promise((r) => setTimeout(r, 3000)); + if (rconPort !== undefined && rconPassword !== undefined) { + await tauriCmd.gracefulStopServer(serverId, rconPort, rconPassword, false, 0, ""); + } else { + await tauriCmd.stopServer(serverId, false); + await new Promise((r) => setTimeout(r, 3000)); + } } onStatusChange?.("Applying update…"); diff --git a/src/store/useAppStore.ts b/src/store/useAppStore.ts index 235c6ba..c18b42b 100644 --- a/src/store/useAppStore.ts +++ b/src/store/useAppStore.ts @@ -113,6 +113,10 @@ interface AppState { statsLiveBuffers: Record; addLiveSample: (serverId: string, point: ChartPoint) => void; clearLiveBuffer: (serverId: string) => void; + + /** Active countdown info keyed by server ID. Null means no countdown running. */ + countdowns: Record; + setCountdown: (serverId: string, entry: { action: 'restart' | 'update'; remainingSecs: number; totalSecs: number } | null) => void; } export const useAppStore = create((set) => ({ @@ -197,4 +201,8 @@ export const useAppStore = create((set) => ({ delete next[serverId]; return { statsLiveBuffers: next }; }), + + countdowns: {}, + setCountdown: (serverId, entry) => + set((s) => ({ countdowns: { ...s.countdowns, [serverId]: entry } })), }));