diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 30a1b35..2a98b98 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -68,40 +68,41 @@ jobs: LokiASAM is a desktop application for managing Ark Survival Ascended dedicated servers on Linux and Windows. - ### What's new in v0.11.0 + ### What's new in v0.12.0 - **Server stats history** - CPU and RAM usage are now recorded to a local database in the background. The Overview tab shows live charts of resource usage over time so you can see how your server behaves across a session, not just at a single moment. + **Firewall management** + LokiASAM can now detect your system firewall (UFW, firewalld, iptables on Linux; Windows Defender Firewall on Windows) and open the required ports for each server with a single elevation prompt. A dedicated Firewall step in the server creation wizard checks port status and offers to fix missing rules before you ever try to start. A non-blocking warning notification is shown at startup if a rule is missing. You can also check and repair rules for all servers at any time from Settings → Tools → Firewall Rules. When deleting a server, you're offered the option to clean up firewall rules for ports that no longer have any server behind them. - **Server status on startup** - The app now scans running OS processes on launch to determine which servers are actually running, rather than relying on stored state. If a server crashed or was stopped while the app was closed, the status will be correct immediately on next open. + **Amazon Root CA certificate install** + Servers with mods can fail to start with a CurseForge API TLS error when the Amazon Root CA 1 certificate is missing from the Wine/Windows cert store. The setup wizard now includes a certificate install step that fixes this automatically. The same action is available under Settings → Tools → Amazon Root CA for reinstallation at any time. - **Launch parameters** - You can now configure per-server launch arguments through the UI — both in the setup wizard and the server config tab — without editing config files manually. + **CurseForge API auto-retry** + When a server exits immediately after logging the CurseForge "serverUnreachable" error, LokiASAM now automatically retries the launch up to three times before declaring start-failed. This handles the common case where the CurseForge API is briefly rate-limiting or slow at startup. If all three attempts fail, a detailed notification explains the cause and suggests next steps. - **Graceful shutdown settings** - Servers now have configurable graceful shutdown behaviour, letting you control how the shutdown sequence is handled per server. + **Expanded backup system** + Backups now support three types: full server backups, player save backups (per player EOS ID), and INI config backups. Player backups can be restored individually. The backup tab and scheduler have been updated to reflect the new options. - **Per-server update automation** - Update automation is now configured per server rather than globally, with in-app notifications when updates are available for the server's installed version. + **Logs page** + A dedicated Logs page is now accessible from the sidebar. It provides four views: Live (tail of the current ShooterGame.log), Archive (past session logs), Crashes (crash dump files), and Chat (chat log history). Logs are automatically archived when a server stops or crashes so previous sessions are always accessible. Old logs are cleaned up automatically based on retention settings. - **New game settings** - - PvP friendly fire toggle added - - Cryo sickness handling option added + **Auto-start on launch** + Each server now has an auto-start toggle. Servers marked for auto-start will be queued and started sequentially when the app launches, one at a time to avoid overloading the host. - ### Improvements + **Quick Start Guide** + A `?` button in the sidebar opens the Quick Start Guide from anywhere in the app. The guide now includes a slide covering port forwarding and VPN services for players connecting from outside your home network. Clicking "Quick Start Guide" on the setup wizard completion screen takes you directly to the dashboard with the guide already open. - - **RCON** — improved tab layout, scrolling behaviour, and reliability. IO errors and timeouts are now distinguished and reported separately. Player list updates are handled via events. - - **Log handling** — ShooterGame.log is now rotated on server startup so the log viewer always starts from a clean slate for that session. - - **UI controls** — toggle switches replaced with icon buttons for better clarity. Numeric settings now use a combined number field and slider control. - - **Setup wizard** — improved visual effects and theme handling. + **Updated application icons** + New icon set with improved clarity at all sizes. Linux builds include adaptive launcher icons. - ### Bug fixes + ### Improvements - - **Linux/Arch/CachyOS: blank screen on launch** — modern distros with newer GPU drivers could get a blank white window due to a WebKit DMA-BUF renderer incompatibility. Fixed. - - **Linux/KDE: title bar buttons stop working** — minimising and restoring the window on KDE could leave the decoration buttons unresponsive. Fixed. - - **Startup: Steam error output** — noisy Steam deprecation warnings are no longer surfaced as server errors in the log. - - **Startup: missing executable** — clearer error notification when the server binary can't be found at launch. + - **Setup wizard** — auto-update settings are now configured during first-time setup. The wizard completion screen includes a Quick Start Guide button that opens the tour on the dashboard. + - **Server creation wizard** — added a Firewall step and a port forwarding info card in the Network step. + - **Logs tab** — the per-server Logs tab now loads the last session's log on open, even when the server is stopped. Logs are archived automatically on server state changes. + - **Mods tab** — added a note reminding users that a server restart is required for mod changes to take effect. + - **Sidebar** — Logs and Backups are now top-level navigation items. Tooltip backgrounds and contrast improved across all nav items. + - **Theme** — updated built-in theme presets and accent colours for improved consistency. + - **Settings** — Tools section now includes rows for certificate install/reinstall and firewall rule check/repair. ### Installation @@ -114,11 +115,11 @@ jobs: | `.rpm` | Yes | Installs via `rpm`, prompts for your password | ```bash - chmod +x LokiASAM_0.11.0_amd64.AppImage - ./LokiASAM_0.11.0_amd64.AppImage + chmod +x LokiASAM_0.12.0_amd64.AppImage + ./LokiASAM_0.12.0_amd64.AppImage ``` - **Windows:** Download and run `LokiASAM_0.11.0_x64-setup.exe` from the assets below. + **Windows:** Download and run `LokiASAM_0.12.0_x64-setup.exe` from the assets below. ### Notes - This is a public beta — bugs are expected. Please report them on the [Issues](https://github.com/LokiRothbrook/LokiASAM/issues) page. diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index d03cb9d..883a68c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + [[package]] name = "adler2" version = "2.0.1" @@ -315,6 +324,21 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link 0.2.1", +] + [[package]] name = "base64" version = "0.21.7" @@ -333,15 +357,30 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bit-set" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0481a0e032742109b1133a095184ee93d88f3dc9e0d28a5d033dc77a073f44f" +dependencies = [ + "bit-vec 0.7.0", +] + [[package]] name = "bit-set" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ - "bit-vec", + "bit-vec 0.8.0", ] +[[package]] +name = "bit-vec" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c54ff287cfc0a34f38a6b832ea1bd8e448a330b3e40a50859e6488bee07f22" + [[package]] name = "bit-vec" version = "0.8.0" @@ -1102,7 +1141,7 @@ version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521e380c0c8afb8d9a1e83a1822ee03556fc3e3e7dbc1fd30be14e37f9cb3f89" dependencies = [ - "bit-set", + "bit-set 0.8.0", "cssparser", "foldhash 0.2.0", "html5ever", @@ -1330,6 +1369,15 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "failure" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" +dependencies = [ + "backtrace", +] + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -1392,6 +1440,17 @@ dependencies = [ "libc", ] +[[package]] +name = "filetime_creation" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25b5d475550e559de5b0c0084761c65325444e3b6c9e298af9cefe7a9ef3a5f" +dependencies = [ + "cfg-if", + "filetime", + "windows-sys 0.52.0", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -1740,6 +1799,12 @@ dependencies = [ "wasip3", ] +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + [[package]] name = "gio" version = "0.18.4" @@ -2670,9 +2735,11 @@ dependencies = [ "log", "procfs", "reqwest 0.12.28", + "runas", "rusqlite", "serde", "serde_json", + "sevenz-rust", "sysinfo", "tar", "tauri", @@ -2708,6 +2775,15 @@ dependencies = [ "crc", ] +[[package]] +name = "lzma-rust" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baab2bbbd7d75a144d671e9ff79270e903957d92fb7386fd39034c709bd2661" +dependencies = [ + "byteorder", +] + [[package]] name = "lzma-sys" version = "0.1.20" @@ -2884,6 +2960,16 @@ dependencies = [ "zbus", ] +[[package]] +name = "nt-time" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de419e64947cd8830e66beb584acc3fb42ed411d103e3c794dda355d1b374b5" +dependencies = [ + "chrono", + "time", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -3185,6 +3271,15 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -4099,6 +4194,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "runas" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a620b0994a180cdfa25c0439e6d58c0628272571501880d626ffff58e96a0799" +dependencies = [ + "cc", + "which", +] + [[package]] name = "rusqlite" version = "0.32.1" @@ -4130,6 +4235,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "rustc-demangle" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" + [[package]] name = "rustc-hash" version = "2.1.2" @@ -4561,6 +4672,23 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "sevenz-rust" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26482cf1ecce4540dc782fc70019eba89ffc4d87b3717eb5ec524b5db6fdefef" +dependencies = [ + "bit-set 0.6.0", + "byteorder", + "crc", + "filetime_creation", + "js-sys", + "lzma-rust", + "nt-time", + "sha2", + "wasm-bindgen", +] + [[package]] name = "sha1" version = "0.10.6" @@ -6596,6 +6724,16 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]] +name = "which" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d011071ae14a2f6671d0b74080ae0cd8ebf3a6f8c9589a2cd45f23126fe29724" +dependencies = [ + "failure", + "libc", +] + [[package]] name = "whoami" version = "1.6.1" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index d5e3ada..9854dc7 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -42,8 +42,8 @@ uuid = { version = "1", features = ["v4", "serde"] } # HTTP client (Discord webhooks, update checks) reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false } -# ZIP compression for backups -zip = { version = "2" } +# 7z compression for backups (pure Rust LZMA2, no external binary required) +sevenz-rust = { version = "0.6", features = ["compress"] } # Email / SMTP notifications lettre = { version = "0.11", features = ["tokio1", "tokio1-rustls-tls", "builder", "smtp-transport"], default-features = false } @@ -54,7 +54,8 @@ sysinfo = { version = "0.32" } # INI file parsing configparser = { version = "3" } -# Linux .tar.gz extraction for SteamCMD download +# Archive extraction for SteamCMD download (zip on Windows, tar.gz on Linux) +zip = { version = "2" } flate2 = { version = "1" } tar = { version = "0.4" } @@ -72,3 +73,8 @@ rusqlite = { version = "0.32", features = ["bundled"] } # Replaces hand-rolled /proc string parsing with a tested, maintained library. [target.'cfg(target_os = "linux")'.dependencies] procfs = { version = "0.17", default-features = false } + +# Windows elevation: spawn a child process with "runas" verb (UAC prompt). +# Used for netsh firewall rule management which requires admin rights. +[target.'cfg(target_os = "windows")'.dependencies] +runas = { version = "0.2" } diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png index b834284..b7449f0 100644 Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ diff --git a/src-tauri/icons/128x128@2x.png b/src-tauri/icons/128x128@2x.png index 77d87ac..194b3d0 100644 Binary files a/src-tauri/icons/128x128@2x.png and b/src-tauri/icons/128x128@2x.png differ diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png index 04f4401..094ad7d 100644 Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png new file mode 100644 index 0000000..d0af363 Binary files /dev/null and b/src-tauri/icons/64x64.png differ diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png index 4c3d0fe..564364a 100644 Binary files a/src-tauri/icons/Square107x107Logo.png and b/src-tauri/icons/Square107x107Logo.png differ diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png index c63678b..467face 100644 Binary files a/src-tauri/icons/Square142x142Logo.png and b/src-tauri/icons/Square142x142Logo.png differ diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png index e94250e..d987f30 100644 Binary files a/src-tauri/icons/Square150x150Logo.png and b/src-tauri/icons/Square150x150Logo.png differ diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png index da89bdf..37ec2aa 100644 Binary files a/src-tauri/icons/Square284x284Logo.png and b/src-tauri/icons/Square284x284Logo.png differ diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png index 86f9add..dc83bc5 100644 Binary files a/src-tauri/icons/Square30x30Logo.png and b/src-tauri/icons/Square30x30Logo.png differ diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png index 83b72e7..88042a4 100644 Binary files a/src-tauri/icons/Square310x310Logo.png and b/src-tauri/icons/Square310x310Logo.png differ diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png index f0c5bd6..7e2f552 100644 Binary files a/src-tauri/icons/Square44x44Logo.png and b/src-tauri/icons/Square44x44Logo.png differ diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png index 681533b..143c4cc 100644 Binary files a/src-tauri/icons/Square71x71Logo.png and b/src-tauri/icons/Square71x71Logo.png differ diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png index 69086dd..46c1e09 100644 Binary files a/src-tauri/icons/Square89x89Logo.png and b/src-tauri/icons/Square89x89Logo.png differ diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png index 15bc090..aa63635 100644 Binary files a/src-tauri/icons/StoreLogo.png and b/src-tauri/icons/StoreLogo.png differ diff --git a/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml b/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..2ffbf24 --- /dev/null +++ b/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..f64a7f8 Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png differ diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..6255a9c Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..724e03e Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png differ diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..8186715 Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png differ diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..95ec19e Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..0cfe329 Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png differ diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..72251ed Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png differ diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..17cbbe6 Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..41f2cd1 Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..7f72b08 Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png differ diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..646e6ba Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a2c08c6 Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..910b92f Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..931e622 Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a0a0bcc Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/src-tauri/icons/android/values/ic_launcher_background.xml b/src-tauri/icons/android/values/ic_launcher_background.xml new file mode 100644 index 0000000..ea9c223 --- /dev/null +++ b/src-tauri/icons/android/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #fff + \ No newline at end of file diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns index 5c68a6f..c9a028f 100644 Binary files a/src-tauri/icons/icon.icns and b/src-tauri/icons/icon.icns differ diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico index ce081d6..c9acb98 100644 Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png index 5e1e47d..3f48b86 100644 Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ diff --git a/src-tauri/icons/ios/AppIcon-20x20@1x.png b/src-tauri/icons/ios/AppIcon-20x20@1x.png new file mode 100644 index 0000000..864401b Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-20x20@1x.png differ diff --git a/src-tauri/icons/ios/AppIcon-20x20@2x-1.png b/src-tauri/icons/ios/AppIcon-20x20@2x-1.png new file mode 100644 index 0000000..74d6540 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-20x20@2x-1.png differ diff --git a/src-tauri/icons/ios/AppIcon-20x20@2x.png b/src-tauri/icons/ios/AppIcon-20x20@2x.png new file mode 100644 index 0000000..74d6540 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-20x20@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-20x20@3x.png b/src-tauri/icons/ios/AppIcon-20x20@3x.png new file mode 100644 index 0000000..35704da Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-20x20@3x.png differ diff --git a/src-tauri/icons/ios/AppIcon-29x29@1x.png b/src-tauri/icons/ios/AppIcon-29x29@1x.png new file mode 100644 index 0000000..8f48a8b Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-29x29@1x.png differ diff --git a/src-tauri/icons/ios/AppIcon-29x29@2x-1.png b/src-tauri/icons/ios/AppIcon-29x29@2x-1.png new file mode 100644 index 0000000..fedb1d6 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-29x29@2x-1.png differ diff --git a/src-tauri/icons/ios/AppIcon-29x29@2x.png b/src-tauri/icons/ios/AppIcon-29x29@2x.png new file mode 100644 index 0000000..fedb1d6 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-29x29@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-29x29@3x.png b/src-tauri/icons/ios/AppIcon-29x29@3x.png new file mode 100644 index 0000000..7288964 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-29x29@3x.png differ diff --git a/src-tauri/icons/ios/AppIcon-40x40@1x.png b/src-tauri/icons/ios/AppIcon-40x40@1x.png new file mode 100644 index 0000000..74d6540 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-40x40@1x.png differ diff --git a/src-tauri/icons/ios/AppIcon-40x40@2x-1.png b/src-tauri/icons/ios/AppIcon-40x40@2x-1.png new file mode 100644 index 0000000..7d58f6a Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-40x40@2x-1.png differ diff --git a/src-tauri/icons/ios/AppIcon-40x40@2x.png b/src-tauri/icons/ios/AppIcon-40x40@2x.png new file mode 100644 index 0000000..7d58f6a Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-40x40@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-40x40@3x.png b/src-tauri/icons/ios/AppIcon-40x40@3x.png new file mode 100644 index 0000000..a2e5dcb Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-40x40@3x.png differ diff --git a/src-tauri/icons/ios/AppIcon-512@2x.png b/src-tauri/icons/ios/AppIcon-512@2x.png new file mode 100644 index 0000000..3759cc1 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-512@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-60x60@2x.png b/src-tauri/icons/ios/AppIcon-60x60@2x.png new file mode 100644 index 0000000..a2e5dcb Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-60x60@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-60x60@3x.png b/src-tauri/icons/ios/AppIcon-60x60@3x.png new file mode 100644 index 0000000..1994c2c Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-60x60@3x.png differ diff --git a/src-tauri/icons/ios/AppIcon-76x76@1x.png b/src-tauri/icons/ios/AppIcon-76x76@1x.png new file mode 100644 index 0000000..2c4a915 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-76x76@1x.png differ diff --git a/src-tauri/icons/ios/AppIcon-76x76@2x.png b/src-tauri/icons/ios/AppIcon-76x76@2x.png new file mode 100644 index 0000000..e8af0f6 Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-76x76@2x.png differ diff --git a/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png b/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png new file mode 100644 index 0000000..4605bce Binary files /dev/null and b/src-tauri/icons/ios/AppIcon-83.5x83.5@2x.png differ diff --git a/src-tauri/migrations/003_backups_v2.sql b/src-tauri/migrations/003_backups_v2.sql new file mode 100644 index 0000000..a526f0f --- /dev/null +++ b/src-tauri/migrations/003_backups_v2.sql @@ -0,0 +1,26 @@ +-- Migration 003: Backup system v2 +-- Expands the backups table with type/tier/player columns, +-- adds player_name_map for EOS ID → display name resolution, +-- and renames the old generic "backup" schedule type to "backup_server". + +-- Rename existing backup schedule rows to the new type name. +UPDATE schedules SET schedule_type = 'backup_server' WHERE schedule_type = 'backup'; + +-- Add backup_type column (server|player|full|ini). +ALTER TABLE backups ADD COLUMN backup_type TEXT NOT NULL DEFAULT 'server'; + +-- Add tiers column (comma-separated H/D/W/M flags, or empty for manual/full). +ALTER TABLE backups ADD COLUMN tiers TEXT NOT NULL DEFAULT ''; + +-- Add player columns (only populated for player backups). +ALTER TABLE backups ADD COLUMN player_eosid TEXT; +ALTER TABLE backups ADD COLUMN player_name TEXT; + +-- EOS ID → display name cache, updated from listplayers RCON polls. +CREATE TABLE IF NOT EXISTS player_name_map ( + server_id TEXT NOT NULL, + eos_id TEXT NOT NULL, + player_name TEXT NOT NULL, + last_seen TEXT NOT NULL, + PRIMARY KEY (server_id, eos_id) +); diff --git a/src-tauri/migrations/004_firewall_rules.sql b/src-tauri/migrations/004_firewall_rules.sql new file mode 100644 index 0000000..ef20a03 --- /dev/null +++ b/src-tauri/migrations/004_firewall_rules.sql @@ -0,0 +1,11 @@ +-- Migration 004: firewall port rule tracking +-- Used as fallback state for Linux iptables/nftables where non-root +-- reads of live firewall state are not available. For ufw and firewalld, +-- state is derived directly from the system (ufw profile file / firewall-cmd). + +CREATE TABLE IF NOT EXISTS firewall_rules ( + port INTEGER NOT NULL, + protocol TEXT NOT NULL CHECK(protocol IN ('tcp', 'udp')), + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (port, protocol) +); diff --git a/src-tauri/src/commands/backup.rs b/src-tauri/src/commands/backup.rs index 5f888e9..610a168 100644 --- a/src-tauri/src/commands/backup.rs +++ b/src-tauri/src/commands/backup.rs @@ -1,14 +1,20 @@ use std::fs::{self, File}; -use std::io::BufWriter; +use std::io::BufReader; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; -use tauri::{AppHandle, Emitter}; +use tauri::{AppHandle, Emitter, State}; +use tokio::sync::oneshot; +use tokio::time::{timeout, Duration}; use uuid::Uuid; -use zip::write::{SimpleFileOptions, ZipWriter}; -use zip::CompressionMethod; +use sevenz_rust::{SevenZWriter, SevenZArchiveEntry}; use crate::events; +use crate::state::rcon_pool::{RconCmd, RconPool}; + +// --------------------------------------------------------------------------- +// Shared types +// --------------------------------------------------------------------------- #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] @@ -20,6 +26,12 @@ pub struct BackupRecord { pub map_id: String, pub triggered_by: String, pub created_at: String, + /// server | player | full | ini + pub backup_type: String, + /// Comma-separated tier flags: H, D, W, M — assigned by the frontend after creation. + pub tiers: String, + pub player_eosid: Option, + pub player_name: Option, } #[derive(Debug, Serialize, Deserialize, Clone)] @@ -27,23 +39,57 @@ pub struct BackupRecord { pub struct BackupProgress { pub percent: f32, pub current_file: String, + pub label: String, +} + +// --------------------------------------------------------------------------- +// Internal helpers +// --------------------------------------------------------------------------- + +/// Build a human-readable timestamp string for file/folder names. +/// Format: YYYY-MM-DD_HH-MM-SS +fn now_timestamp() -> (String, String) { + let now_secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (year, month, day, hh, mm, ss) = secs_to_parts(now_secs); + let ts_file = format!("{year:04}-{month:02}-{day:02}_{hh:02}-{mm:02}-{ss:02}"); + let ts_iso = format!("{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z"); + (ts_file, ts_iso) +} + +fn secs_to_parts(now_secs: u64) -> (u64, u64, u64, u64, u64, u64) { + let secs_per_day = 86_400u64; + let days = now_secs / secs_per_day; + let day_secs = now_secs % secs_per_day; + let (year, month, day) = days_to_ymd(days); + let hh = day_secs / 3600; + let mm = (day_secs % 3600) / 60; + let ss = day_secs % 60; + (year, month, day, hh, mm, ss) } -/// Convert days since Unix epoch to (year, month, day). fn days_to_ymd(mut days: u64) -> (u64, u64, u64) { days += 719_468; let era = days / 146_097; let doe = days % 146_097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe + era * 400; + let y = yoe + era * 400; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if m <= 2 { y + 1 } else { y }; + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; (y, m, d) } +fn sanitize_name(name: &str) -> String { + name.chars() + .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) + .collect() +} + /// 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)? { @@ -57,198 +103,585 @@ fn collect_files(dir: &Path, out: &mut Vec) -> std::io::Result<()> { Ok(()) } -/// Create a ZIP backup of the server's ShooterGame/Saved directory. +fn emit_progress(app: &AppHandle, server_id: &str, percent: f32, file: &str, label: &str) { + let _ = app.emit( + &format!("{}/{}", events::BACKUP_PROGRESS, server_id), + BackupProgress { + percent, + current_file: file.to_string(), + label: label.to_string(), + }, + ); +} + +/// 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> { + let tx = { + let guard = pool.cmd_channels.lock().await; + guard.get(server_id).filter(|(tx, _)| !tx.is_closed()).map(|(tx, _)| tx.clone()) + }; + let Some(tx) = tx else { return Ok(()); }; + + let (resp_tx, resp_rx) = oneshot::channel(); + tx.send(RconCmd::Execute { + command: "SaveWorld".to_string(), + suppress_cmd: true, + suppress_resp: true, + response_tx: resp_tx, + }) + .await + .map_err(|_| "RCON channel closed before SaveWorld".to_string())?; + + match timeout(Duration::from_secs(60), resp_rx).await { + Ok(Ok(_)) => Ok(()), + Ok(Err(_)) => Err("SaveWorld response channel dropped".to_string()), + Err(_) => Err("SaveWorld timed out after 60s".to_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`. +fn compress_to_7z( + app: &AppHandle, + server_id: &str, + files: &[PathBuf], + root: &Path, + dest_path: &Path, + label: &str, +) -> Result<(), String> { + let total = files.len().max(1) as f32; + let mut writer = SevenZWriter::create(dest_path).map_err(|e| e.to_string())?; + + for (idx, file_path) in files.iter().enumerate() { + let rel = file_path + .strip_prefix(root) + .map_err(|e| e.to_string())?; + let entry_name = rel.to_string_lossy().replace('\\', "/"); + + 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())?; + let metadata = file.metadata().map_err(|e| e.to_string())?; + let mut entry = SevenZArchiveEntry::new(); + entry.name = entry_name.clone(); + entry.size = metadata.len(); + entry.is_directory = false; + writer + .push_archive_entry::>(entry, Some(BufReader::new(file))) + .map_err(|e| e.to_string())?; + } + + writer.finish().map_err(|e| e.to_string())?; + Ok(()) +} + +// --------------------------------------------------------------------------- +// 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. +/// +/// Returns the number of files deleted. +#[tauri::command] +pub async fn cleanup_ark_own_backups( + install_path: String, + map_path: String, +) -> Result { + let saved_dir = PathBuf::from(&install_path) + .join("ShooterGame") + .join("Saved") + .join("SavedArks") + .join(&map_path); + + if !saved_dir.exists() { + return Ok(0); + } + + let mut deleted = 0u32; + let prefix = format!("{map_path}-"); + + let entries = fs::read_dir(&saved_dir).map_err(|e| e.to_string())?; + for entry in entries { + let entry = entry.map_err(|e| e.to_string())?; + let path = entry.path(); + if !path.is_file() { continue; } + + let fname = path.file_name() + .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"); + + if is_ark_timestamped || is_profilebak { + if fs::remove_file(&path).is_ok() { + deleted += 1; + } + } + } + + Ok(deleted) +} + +// --------------------------------------------------------------------------- +// 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/. /// -/// Files are streamed into the zip with `std::io::copy` — no full-file buffers. -/// The heavy zip work runs in `spawn_blocking` so the async runtime is not blocked. -/// Emits `backup://progress/{server_id}` events while zipping. +/// 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. #[tauri::command] -pub async fn create_backup( +pub async fn create_server_backup( app: AppHandle, server_id: String, server_name: String, install_path: String, + map_path: String, + map_id: String, backup_dir: String, + triggered_by: 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; + + // 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; + + 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 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); + + // Root for relative paths inside the archive = ShooterGame/Saved + let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + + 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 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(), + 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, + }) +} + +// --------------------------------------------------------------------------- +// Player backup (single .arkprofile → .7z) +// --------------------------------------------------------------------------- + +/// Back up a single player's .arkprofile into +/// {backup_dir}/{server_id}/player/{eos_id}/. +#[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, ) -> Result { - let saved_dir = PathBuf::from(&install_path) - .join("ShooterGame") - .join("Saved"); - if !saved_dir.exists() { - return Err(format!( - "Save directory not found: {}", - saved_dir.display() - )); + let profile_file = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved") + .join("SavedArks").join(&map_path) + .join(format!("{eos_id}.arkprofile")); + + if !profile_file.exists() { + return Err(format!("Profile not found: {}", profile_file.display())); } - fs::create_dir_all(&backup_dir).map_err(|e| e.to_string())?; + 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 archive_path = out_dir.join(&archive_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 dest = archive_path.clone(); + 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}"))??; - let now_secs = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - let secs_per_day = 86_400u64; - let days = now_secs / secs_per_day; - let day_secs = now_secs % secs_per_day; - let (year, month, day) = days_to_ymd(days); - let hh = day_secs / 3600; - let mm = (day_secs % 3600) / 60; - let ss = day_secs % 60; - let timestamp = format!("{year:04}{month:02}{day:02}-{hh:02}{mm:02}{ss:02}"); + emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); - let safe_name: String = server_name - .chars() - .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) + 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(), + 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), + }) +} + +// --------------------------------------------------------------------------- +// INI backup (loose files in a timestamped folder) +// --------------------------------------------------------------------------- + +#[derive(Debug, Serialize, Deserialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct IniBackupRecord { + pub id: String, + pub server_id: String, + pub folder_path: String, + pub created_at: String, +} + +/// Back up GameUserSettings.ini and Game.ini to a timestamped subfolder of +/// {backup_dir}/{server_id}/ini/. The folder named "current" always holds +/// the latest backup; on each save the previous "current" is renamed to a +/// timestamp folder and a new "current" copy is written. +#[tauri::command] +pub async fn create_ini_backup( + server_id: String, + install_path: String, + backup_dir: String, + platform: String, +) -> Result { + let config_dir = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved").join("Config").join(&platform); + + let ini_files = ["GameUserSettings.ini", "Game.ini"]; + let sources: Vec = ini_files.iter() + .map(|f| config_dir.join(f)) + .filter(|p| p.exists()) .collect(); - let zip_filename = format!("{safe_name}-{timestamp}.zip"); - let zip_path = PathBuf::from(&backup_dir).join(&zip_filename); - // Collect file list before spawning so we know the total count. - let mut all_files: Vec = Vec::new(); - collect_files(&saved_dir, &mut all_files).map_err(|e| e.to_string())?; - let total_files = all_files.len().max(1) as f32; + if sources.is_empty() { + return Err("No INI files found to back up".to_string()); + } - // Run the blocking zip work on a dedicated thread. - // AppHandle is Clone + Send so we can move it in for progress events. - let app_clone = app.clone(); - let sid_clone = server_id.clone(); - let zip_path_clone = zip_path.clone(); - let saved_dir_clone = saved_dir.clone(); + let ini_base = PathBuf::from(&backup_dir).join(&server_id).join("ini"); + let current = ini_base.join("current"); - tokio::task::spawn_blocking(move || -> Result<(), String> { - let zip_file = File::create(&zip_path_clone).map_err(|e| e.to_string())?; - let mut zip = ZipWriter::new(BufWriter::new(zip_file)); - let options = SimpleFileOptions::default() - .compression_method(CompressionMethod::Deflated); - - for (idx, file_path) in all_files.iter().enumerate() { - let rel = file_path - .strip_prefix(&saved_dir_clone) - .map_err(|e| e.to_string())?; - let entry_name = rel.to_string_lossy().replace('\\', "/"); - - let pct = (idx as f32 / total_files * 99.0).min(99.0); - let _ = app_clone.emit( - &format!("{}/{}", events::BACKUP_PROGRESS, sid_clone), - BackupProgress { percent: pct, current_file: entry_name.clone() }, - ); - - zip.start_file(&entry_name, options).map_err(|e| e.to_string())?; - let mut src = File::open(file_path).map_err(|e| e.to_string())?; - std::io::copy(&mut src, &mut zip).map_err(|e| e.to_string())?; + // If "current" already exists, rename it to a timestamp folder. + if current.exists() { + let (ts_file, _) = now_timestamp(); + let archive_folder = ini_base.join(&ts_file); + fs::rename(¤t, &archive_folder).map_err(|e| e.to_string())?; + } + + fs::create_dir_all(¤t).map_err(|e| e.to_string())?; + + for src in &sources { + if let Some(fname) = src.file_name() { + fs::copy(src, current.join(fname)).map_err(|e| e.to_string())?; } + } - zip.finish().map_err(|e| e.to_string())?; - Ok(()) + let (_, ts_iso) = now_timestamp(); + Ok(IniBackupRecord { + id: Uuid::new_v4().to_string(), + server_id, + folder_path: current.to_string_lossy().to_string(), + created_at: ts_iso, + }) +} + +/// List timestamped INI snapshot folders for a server (newest first). +#[tauri::command] +pub async fn list_ini_backups( + server_id: String, + backup_dir: String, +) -> Result, String> { + let ini_base = PathBuf::from(&backup_dir).join(&server_id).join("ini"); + if !ini_base.exists() { + return Ok(vec![]); + } + + let mut folders: Vec = fs::read_dir(&ini_base) + .map_err(|e| e.to_string())? + .filter_map(|e| e.ok()) + .filter(|e| { + e.path().is_dir() + && e.file_name().to_string_lossy() != "current" + }) + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + + // Timestamps sort lexicographically as newest last; reverse for newest first. + folders.sort(); + folders.reverse(); + Ok(folders) +} + +// --------------------------------------------------------------------------- +// Full backup (entire install_path → .7z) +// --------------------------------------------------------------------------- + +/// Create a Full backup of the entire server installation directory. +/// This can be very large — warn the user before calling this. +#[tauri::command] +pub async fn create_full_backup( + app: AppHandle, + server_id: String, + server_name: String, + install_path: String, + map_id: String, + backup_dir: String, + triggered_by: String, +) -> Result { + let install_dir = PathBuf::from(&install_path); + if !install_dir.exists() { + return Err(format!("Install path not found: {install_path}")); + } + + let out_dir = PathBuf::from(&backup_dir).join(&server_id).join("full"); + 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}-full-{ts_file}.7z"); + let archive_path = out_dir.join(&archive_name); + + emit_progress(&app, &server_id, 0.0, "", "Collecting files for full backup…"); + + let mut all_files: Vec = Vec::new(); + collect_files(&install_dir, &mut all_files).map_err(|e| e.to_string())?; + + let app_c = app.clone(); + let sid = server_id.clone(); + let dest = archive_path.clone(); + let root = install_dir.clone(); + tokio::task::spawn_blocking(move || { + compress_to_7z(&app_c, &sid, &all_files, &root, &dest, "Creating full backup…") }) .await - .map_err(|e| format!("Backup task panicked: {e}"))??; + .map_err(|e| format!("Full backup task panicked: {e}"))??; - let _ = app.emit( - &format!("{}/{}", events::BACKUP_PROGRESS, server_id), - BackupProgress { percent: 100.0, current_file: zip_filename.clone() }, - ); + emit_progress(&app, &server_id, 100.0, &archive_name, "Done"); - let file_size = fs::metadata(&zip_path) + let file_size = fs::metadata(&archive_path) .map_err(|e| e.to_string())? .len(); - let created_at = format!( - "{year:04}-{month:02}-{day:02}T{hh:02}:{mm:02}:{ss:02}Z" - ); - Ok(BackupRecord { id: Uuid::new_v4().to_string(), server_id, - file_path: zip_path.to_string_lossy().to_string(), + file_path: archive_path.to_string_lossy().to_string(), file_size_bytes: file_size, map_id, triggered_by, - created_at, + created_at: ts_iso, + backup_type: "full".to_string(), + tiers: String::new(), + player_eosid: None, + player_name: None, }) } -/// Restore a backup by extracting the zip over ShooterGame/Saved. -/// -/// Files are streamed from the zip entry with `std::io::copy` — no full-file buffers. -/// The frontend stops the server before calling this and restarts it after. +// --------------------------------------------------------------------------- +// Restore +// --------------------------------------------------------------------------- + +/// Restore a Server backup: extract 7z over SavedArks/{mapPath} and SaveGames. #[tauri::command] -pub async fn restore_backup( +pub async fn restore_server_backup( app: AppHandle, server_id: String, backup_file_path: String, install_path: String, ) -> Result<(), String> { - let zip_path = PathBuf::from(&backup_file_path); - if !zip_path.exists() { - return Err(format!("Backup file not found: {}", zip_path.display())); - } - - let saved_dir = PathBuf::from(&install_path) - .join("ShooterGame") - .join("Saved"); + let saved_root = PathBuf::from(&install_path).join("ShooterGame").join("Saved"); + extract_7z_with_progress(&app, &server_id, &backup_file_path, &saved_root, "Restoring server backup…").await +} - let app_clone = app.clone(); - let sid_clone = server_id.clone(); +/// Restore a Player backup: extract 7z into SavedArks/{mapPath}. +#[tauri::command] +pub async fn restore_player_backup( + app: AppHandle, + server_id: String, + backup_file_path: String, + install_path: String, + map_path: String, +) -> Result<(), String> { + let target = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved") + .join("SavedArks").join(&map_path); + fs::create_dir_all(&target).map_err(|e| e.to_string())?; + extract_7z_with_progress(&app, &server_id, &backup_file_path, &target, "Restoring player backup…").await +} - tokio::task::spawn_blocking(move || -> Result<(), String> { - if saved_dir.exists() { - fs::remove_dir_all(&saved_dir).map_err(|e| e.to_string())?; +/// Restore an INI backup from a snapshot folder. +#[tauri::command] +pub async fn restore_ini_backup( + backup_folder_path: String, + install_path: String, + platform: String, +) -> Result<(), String> { + let src_dir = PathBuf::from(&backup_folder_path); + let dst_dir = PathBuf::from(&install_path) + .join("ShooterGame").join("Saved").join("Config").join(&platform); + + fs::create_dir_all(&dst_dir).map_err(|e| e.to_string())?; + + for entry in fs::read_dir(&src_dir).map_err(|e| e.to_string())? { + let entry = entry.map_err(|e| e.to_string())?; + let src = entry.path(); + if src.is_file() { + if let Some(fname) = src.file_name() { + fs::copy(&src, dst_dir.join(fname)).map_err(|e| e.to_string())?; + } } - fs::create_dir_all(&saved_dir).map_err(|e| e.to_string())?; + } + Ok(()) +} - let file = std::fs::File::open(&zip_path).map_err(|e| e.to_string())?; - let mut archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - let total = archive.len().max(1) as f32; +/// Restore a Full backup: extract 7z over the entire install_path. +#[tauri::command] +pub async fn restore_full_backup( + app: AppHandle, + server_id: String, + backup_file_path: String, + install_path: String, +) -> Result<(), String> { + let target = PathBuf::from(&install_path); + extract_7z_with_progress(&app, &server_id, &backup_file_path, &target, "Restoring full backup…").await +} - for i in 0..archive.len() { - let mut entry = archive.by_index(i).map_err(|e| e.to_string())?; - let entry_name = entry.name().to_string(); +async fn extract_7z_with_progress( + app: &AppHandle, + server_id: &str, + archive_path: &str, + dest_root: &Path, + label: &str, +) -> Result<(), String> { + let archive_path = archive_path.to_string(); + let dest_root = dest_root.to_path_buf(); + let app_c = app.clone(); + let sid = server_id.to_string(); + let lbl = label.to_string(); - // Guard against path traversal. - if entry_name.contains("..") || Path::new(&entry_name).is_absolute() { - return Err(format!("Unsafe path in backup archive: {entry_name}")); - } + emit_progress(app, server_id, 0.0, "", label); - let out_path = saved_dir.join(&entry_name); + tokio::task::spawn_blocking(move || -> Result<(), String> { + fs::create_dir_all(&dest_root).map_err(|e| e.to_string())?; - if entry_name.ends_with('/') { - fs::create_dir_all(&out_path).map_err(|e| e.to_string())?; - } else { - if let Some(parent) = out_path.parent() { - fs::create_dir_all(parent).map_err(|e| e.to_string())?; - } - let mut out = std::fs::File::create(&out_path).map_err(|e| e.to_string())?; - std::io::copy(&mut entry, &mut out).map_err(|e| e.to_string())?; - } + sevenz_rust::decompress_file(&archive_path, &dest_root) + .map_err(|e| e.to_string())?; - let pct = ((i + 1) as f32 / total * 100.0).min(100.0); - let _ = app_clone.emit( - &format!("{}/{}", events::BACKUP_PROGRESS, sid_clone), - BackupProgress { percent: pct, current_file: entry_name }, - ); - } + emit_progress(&app_c, &sid, 100.0, "", &lbl); Ok(()) }) .await - .map_err(|e| format!("Restore task panicked: {e}"))??; - - Ok(()) + .map_err(|e| format!("Restore task panicked: {e}"))? } -/// Delete a backup zip from disk. The caller removes the SQLite record. +// --------------------------------------------------------------------------- +// Delete +// --------------------------------------------------------------------------- + +/// Delete a backup archive or INI folder from disk. #[tauri::command] pub async fn delete_backup(file_path: String) -> Result<(), String> { let path = PathBuf::from(&file_path); - if path.exists() { + if !path.exists() { + return Ok(()); + } + if path.is_dir() { + fs::remove_dir_all(&path).map_err(|e| e.to_string())?; + } else { fs::remove_file(&path).map_err(|e| e.to_string())?; } Ok(()) } -/// No-op stub — backup pruning is handled by the frontend via individual delete calls. +/// Estimate the uncompressed size of the install directory (for full backup warning). #[tauri::command] -pub async fn prune_backups(_server_id: String) -> Result { - Ok(0) +pub async fn estimate_dir_size(dir_path: String) -> Result { + let path = PathBuf::from(&dir_path); + if !path.exists() { + return Ok(0); + } + let mut total = 0u64; + let mut stack = vec![path]; + while let Some(d) = stack.pop() { + if let Ok(rd) = fs::read_dir(&d) { + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + stack.push(p); + } else if let Ok(meta) = fs::metadata(&p) { + total += meta.len(); + } + } + } + } + Ok(total) } diff --git a/src-tauri/src/commands/certs.rs b/src-tauri/src/commands/certs.rs new file mode 100644 index 0000000..eb19ce1 --- /dev/null +++ b/src-tauri/src/commands/certs.rs @@ -0,0 +1,202 @@ +use std::path::PathBuf; +use tokio::process::Command; + +const AMAZON_ROOT_CA1_URL: &str = + "https://www.amazontrust.com/repository/AmazonRootCA1.cer"; + +const CERT_MARKER_FILENAME: &str = ".amazon_root_ca_installed"; + +// ── Download ───────────────────────────────────────────────────────────────── + +/// Downloads the Amazon Root CA 1 certificate to `{temp_dir}/AmazonRootCA1.cer` +/// and returns the full path to the saved file. +#[tauri::command] +pub async fn download_amazon_root_ca(temp_dir: String) -> Result { + let client = reqwest::Client::builder() + .user_agent("LokiASAM/0.1") + .build() + .map_err(|e| format!("Failed to build HTTP client: {e}"))?; + + let bytes = client + .get(AMAZON_ROOT_CA1_URL) + .send() + .await + .map_err(|e| format!("Failed to download certificate: {e}"))? + .error_for_status() + .map_err(|e| format!("Certificate download returned error: {e}"))? + .bytes() + .await + .map_err(|e| format!("Failed to read certificate bytes: {e}"))?; + + tokio::fs::create_dir_all(&temp_dir) + .await + .map_err(|e| format!("Failed to create temp directory: {e}"))?; + + let cert_path = PathBuf::from(&temp_dir).join("AmazonRootCA1.cer"); + tokio::fs::write(&cert_path, &bytes) + .await + .map_err(|e| format!("Failed to write certificate file: {e}"))?; + + cert_path + .to_str() + .map(|s| s.to_string()) + .ok_or_else(|| "Certificate path contains invalid characters".to_string()) +} + +// ── Install ─────────────────────────────────────────────────────────────────── + +/// Installs the downloaded certificate into the system/Wine certificate store. +/// +/// - Windows: installs into `CurrentUser\Root` via `certutil`. Windows will +/// show its standard trust-confirmation dialog; no elevation is needed. +/// - Linux: initialises the Proton Wine prefix if required, then installs via +/// the `wine64` binary bundled with Proton-GE. +/// +/// On success, writes a marker file so `check_amazon_root_ca_installed` can +/// detect the installation without repeating the cert-store query. +#[tauri::command] +pub async fn install_amazon_root_ca( + cert_path: String, + proton_path: Option, + prefix_path: Option, +) -> Result<(), String> { + #[cfg(target_os = "windows")] + { + install_windows(&cert_path).await?; + } + + #[cfg(target_os = "linux")] + { + let proton = proton_path + .as_deref() + .filter(|s| !s.is_empty()) + .ok_or("Proton-GE path is required on Linux")?; + let prefix = prefix_path + .as_deref() + .filter(|s| !s.is_empty()) + .ok_or("Wine prefix path is required on Linux")?; + install_linux(&cert_path, proton, prefix).await?; + } + + // Suppress "unused variable" warnings on each platform. + let _ = (&cert_path, &proton_path, &prefix_path); + + Ok(()) +} + +#[cfg(target_os = "windows")] +async fn install_windows(cert_path: &str) -> Result<(), String> { + let status = Command::new("certutil") + .args(["-addstore", "-user", "Root", cert_path]) + .status() + .await + .map_err(|e| format!("Failed to run certutil: {e}"))?; + + if !status.success() { + return Err(format!( + "certutil exited with code {}", + status.code().unwrap_or(-1) + )); + } + Ok(()) +} + +#[cfg(target_os = "linux")] +async fn install_linux(cert_path: &str, proton_path: &str, prefix_path: &str) -> Result<(), String> { + let wine_bin = format!("{proton_path}/files/bin/wine64"); + let wine_pfx = format!("{prefix_path}/pfx"); + let marker = PathBuf::from(prefix_path).join(CERT_MARKER_FILENAME); + + // Initialise the Wine prefix if it has not been set up yet. wineboot -u + // creates the fake C: drive, registry hives, etc. without blocking on + // Mono/Gecko downloads. This can take up to ~30 s on first run. + let system_reg = format!("{wine_pfx}/system.reg"); + if !tokio::fs::try_exists(&system_reg).await.unwrap_or(false) { + let status = Command::new(&wine_bin) + .args(["wineboot", "-u"]) + .env("WINEPREFIX", &wine_pfx) + .env("WINEDLLOVERRIDES", "mscoree,mshtml=") + .env("WINEDEBUG", "-all") + .status() + .await + .map_err(|e| format!("Failed to run wineboot: {e}"))?; + + if !status.success() { + return Err(format!( + "wineboot exited with code {}", + status.code().unwrap_or(-1) + )); + } + } + + // Install the certificate into Wine's CurrentUser\Root store. + let status = Command::new(&wine_bin) + .args(["certutil", "-addstore", "Root", cert_path]) + .env("WINEPREFIX", &wine_pfx) + .env("WINEDEBUG", "-all") + .status() + .await + .map_err(|e| format!("Failed to run wine certutil: {e}"))?; + + if !status.success() { + return Err(format!( + "wine certutil exited with code {}", + status.code().unwrap_or(-1) + )); + } + + // Write marker so future checks are instant. + let _ = tokio::fs::write(&marker, b"1").await; + + Ok(()) +} + +// ── Check ───────────────────────────────────────────────────────────────────── + +/// Returns `true` if the Amazon Root CA 1 certificate is already installed. +/// +/// - Windows: queries the `CurrentUser\Root` store for the cert subject. +/// - Linux: checks for the marker file written by a previous successful install. +#[tauri::command] +pub async fn check_amazon_root_ca_installed( + proton_path: Option, + prefix_path: Option, +) -> Result { + #[cfg(target_os = "windows")] + { + let _ = (&proton_path, &prefix_path); + return check_windows().await; + } + + #[cfg(target_os = "linux")] + { + let prefix = prefix_path.as_deref().filter(|s| !s.is_empty()); + let _ = &proton_path; + return check_linux(prefix).await; + } + + #[allow(unreachable_code)] + Ok(false) +} + +#[cfg(target_os = "windows")] +async fn check_windows() -> Result { + // List CurrentUser\Root store and search for Amazon Root CA 1 subject. + let output = Command::new("certutil") + .args(["-store", "-user", "Root"]) + .output() + .await + .map_err(|e| format!("Failed to run certutil: {e}"))?; + + let stdout = String::from_utf8_lossy(&output.stdout); + Ok(stdout.contains("Amazon Root CA 1")) +} + +#[cfg(target_os = "linux")] +async fn check_linux(prefix_path: Option<&str>) -> Result { + let Some(prefix) = prefix_path else { + return Ok(false); + }; + let marker = PathBuf::from(prefix).join(CERT_MARKER_FILENAME); + Ok(tokio::fs::try_exists(&marker).await.unwrap_or(false)) +} diff --git a/src-tauri/src/commands/firewall.rs b/src-tauri/src/commands/firewall.rs new file mode 100644 index 0000000..e54a55d --- /dev/null +++ b/src-tauri/src/commands/firewall.rs @@ -0,0 +1,614 @@ +use serde::{Deserialize, Serialize}; +use tokio::process::Command; + +// --------------------------------------------------------------------------- +// Shared types +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PortDef { + pub port: u16, + pub protocol: String, // "tcp" | "udp" +} + +#[derive(Debug, Serialize)] +pub struct PortStatus { + pub port: u16, + pub protocol: String, + pub covered: bool, +} + +#[derive(Debug, Serialize)] +pub struct FirewallStatus { + /// "none" | "ufw" | "firewalld" | "iptables" | "nftables" | "windows" + pub firewall_type: String, + /// false means no active firewall — no rules needed + pub active: bool, + pub ports: Vec, +} + +// --------------------------------------------------------------------------- +// Platform: Windows +// --------------------------------------------------------------------------- + +#[cfg(target_os = "windows")] +mod windows_impl { + use super::*; + + fn rule_name(port: u16, protocol: &str) -> String { + format!("LokiASAM-{port}-{protocol}") + } + + pub async fn check_ports(ports: &[PortDef]) -> FirewallStatus { + let mut statuses = Vec::new(); + for p in ports { + let name = rule_name(p.port, &p.protocol); + let covered = Command::new("netsh") + .args(["advfirewall", "firewall", "show", "rule", &format!("name={name}"), "dir=in"]) + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false); + statuses.push(PortStatus { port: p.port, protocol: p.protocol.clone(), covered }); + } + FirewallStatus { firewall_type: "windows".into(), active: true, ports: statuses } + } + + pub async fn add_rules(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let name = rule_name(p.port, &p.protocol); + let proto = p.protocol.to_uppercase(); + let port_str = p.port.to_string(); + + // Check first — skip if already present + let exists = Command::new("netsh") + .args(["advfirewall", "firewall", "show", "rule", &format!("name={name}"), "dir=in"]) + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false); + + if exists { + continue; + } + + let status = runas::Command::new("netsh") + .args(&[ + "advfirewall", "firewall", "add", "rule", + &format!("name={name}"), + "dir=in", "action=allow", + &format!("protocol={proto}"), + &format!("localport={port_str}"), + ]) + .status() + .map_err(|e| format!("Failed to run elevated netsh for port {}: {e}", p.port))?; + + if !status.success() { + return Err(format!( + "netsh exited with code {} for port {}", + status.code().unwrap_or(-1), + p.port + )); + } + } + Ok(()) + } + + pub async fn remove_rules(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let name = rule_name(p.port, &p.protocol); + let status = runas::Command::new("netsh") + .args(&[ + "advfirewall", "firewall", "delete", "rule", + &format!("name={name}"), + ]) + .status() + .map_err(|e| format!("Failed to run elevated netsh delete for port {}: {e}", p.port))?; + + if !status.success() { + // Non-fatal: rule may already be gone + log::warn!("netsh delete exited {} for port {}", status.code().unwrap_or(-1), p.port); + } + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Platform: Linux +// --------------------------------------------------------------------------- + +#[cfg(target_os = "linux")] +mod linux_impl { + use super::*; + use std::path::Path; + + // ── Firewall detection ─────────────────────────────────────────────────── + + pub enum FirewallKind { + Ufw, + Firewalld, + Iptables, + None, + } + + pub async fn detect() -> FirewallKind { + // Check firewalld first (most specific D-Bus interface) + if which("firewall-cmd").await && service_active("firewalld").await { + return FirewallKind::Firewalld; + } + // Then ufw + if which("ufw").await { + // ufw can be installed but inactive; we handle both cases in check_ports + return FirewallKind::Ufw; + } + // Fall back to iptables + if which("iptables").await { + return FirewallKind::Iptables; + } + FirewallKind::None + } + + async fn which(cmd: &str) -> bool { + Command::new("which") + .arg(cmd) + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false) + } + + async fn service_active(name: &str) -> bool { + Command::new("systemctl") + .args(["is-active", "--quiet", name]) + .status() + .await + .map(|s| s.success()) + .unwrap_or(false) + } + + async fn ufw_is_active() -> bool { + // Try reading ufw status without root; ufw status itself requires root, + // but we can check if the profile file was written by us (world-readable). + // For the "is active" question we spawn ufw with pkexec only when needed. + // Cheap heuristic: profile file exists → we set it up → treat as active. + Path::new("/etc/ufw/applications.d/lokiasam").exists() + || service_active("ufw").await + } + + // ── UFW ───────────────────────────────────────────────────────────────── + + const UFW_PROFILE_PATH: &str = "/etc/ufw/applications.d/lokiasam"; + const UFW_APP_NAME: &str = "LokiASAM"; + + /// Parse the ports line from the lokiasam ufw profile. + /// Returns a set of "port/proto" strings like {"7777/udp", "27020/tcp"}. + pub fn parse_ufw_profile() -> std::collections::HashSet { + let Ok(content) = std::fs::read_to_string(UFW_PROFILE_PATH) else { + return Default::default(); + }; + let mut set = std::collections::HashSet::new(); + for line in content.lines() { + let line = line.trim(); + if !line.starts_with("ports=") { + continue; + } + // Format: ports=7777,7778/udp|27015/udp|27020/tcp + // Each segment is either "port/proto" or "p1,p2/proto" + let segments = line.trim_start_matches("ports="); + for segment in segments.split('|') { + let segment = segment.trim(); + if let Some(slash) = segment.rfind('/') { + let proto = &segment[slash + 1..]; + let ports_part = &segment[..slash]; + for p in ports_part.split(',') { + set.insert(format!("{}/{}", p.trim(), proto)); + } + } + } + } + set + } + + /// Build the ports= line for the ufw profile from a list of PortDef. + fn build_ufw_ports_line(ports: &[PortDef]) -> String { + // Group by protocol + let mut udp: Vec = ports.iter().filter(|p| p.protocol == "udp").map(|p| p.port).collect(); + let mut tcp: Vec = ports.iter().filter(|p| p.protocol == "tcp").map(|p| p.port).collect(); + udp.sort_unstable(); + udp.dedup(); + tcp.sort_unstable(); + tcp.dedup(); + + let mut segments = Vec::new(); + if !udp.is_empty() { + let ports_str = udp.iter().map(|p| p.to_string()).collect::>().join(","); + segments.push(format!("{ports_str}/udp")); + } + if !tcp.is_empty() { + let ports_str = tcp.iter().map(|p| p.to_string()).collect::>().join(","); + segments.push(format!("{ports_str}/tcp")); + } + segments.join("|") + } + + fn build_ufw_profile(ports: &[PortDef]) -> String { + let ports_line = build_ufw_ports_line(ports); + format!( + "[{UFW_APP_NAME}]\ntitle=LokiASAM ARK Server\ndescription=ARK Survival Ascended Server Ports\nports={ports_line}\n" + ) + } + + pub async fn check_ufw(ports: &[PortDef]) -> FirewallStatus { + let active = ufw_is_active().await; + if !active { + let statuses = ports.iter().map(|p| PortStatus { + port: p.port, protocol: p.protocol.clone(), covered: false, + }).collect(); + return FirewallStatus { firewall_type: "ufw".into(), active: false, ports: statuses }; + } + + let covered_set = parse_ufw_profile(); + let statuses = ports.iter().map(|p| { + let key = format!("{}/{}", p.port, p.protocol); + PortStatus { port: p.port, protocol: p.protocol.clone(), covered: covered_set.contains(&key) } + }).collect(); + FirewallStatus { firewall_type: "ufw".into(), active: true, ports: statuses } + } + + pub async fn add_ufw(new_ports: &[PortDef], existing_covered: &std::collections::HashSet) -> Result<(), String> { + // Read current profile ports, merge with new ones + let current = parse_ufw_profile(); + let mut all_ports: Vec = Vec::new(); + + // Keep existing covered ports that are already in the profile + for entry in ¤t { + if let Some(slash) = entry.rfind('/') { + if let Ok(p) = entry[..slash].parse::() { + let proto = entry[slash + 1..].to_string(); + all_ports.push(PortDef { port: p, protocol: proto }); + } + } + } + // Add new ports (dedup handled by build) + for p in new_ports { + let key = format!("{}/{}", p.port, p.protocol); + if !existing_covered.contains(&key) { + all_ports.push(p.clone()); + } + } + // Also include uncovered ones from the original new_ports list + for p in new_ports { + if !all_ports.iter().any(|e| e.port == p.port && e.protocol == p.protocol) { + all_ports.push(p.clone()); + } + } + + let profile_content = build_ufw_profile(&all_ports); + + // Write profile with pkexec tee + let mut child = Command::new("pkexec") + .args(["tee", UFW_PROFILE_PATH]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; + + if let Some(mut stdin) = child.stdin.take() { + use tokio::io::AsyncWriteExt; + stdin.write_all(profile_content.as_bytes()).await + .map_err(|e| format!("Failed to write profile: {e}"))?; + } + + let output = child.wait_with_output().await + .map_err(|e| format!("pkexec tee failed: {e}"))?; + + if !output.status.success() { + return Err(format!("pkexec tee exited {}", output.status.code().unwrap_or(-1))); + } + + // Activate the rule + let allow_status = Command::new("pkexec") + .args(["ufw", "allow", UFW_APP_NAME]) + .status() + .await + .map_err(|e| format!("Failed to run pkexec ufw allow: {e}"))?; + + if !allow_status.success() { + return Err(format!("pkexec ufw allow exited {}", allow_status.code().unwrap_or(-1))); + } + Ok(()) + } + + pub async fn remove_ufw(ports_to_remove: &[PortDef]) -> Result<(), String> { + let current = parse_ufw_profile(); + let remove_set: std::collections::HashSet = ports_to_remove + .iter().map(|p| format!("{}/{}", p.port, p.protocol)).collect(); + + let remaining: Vec = current.iter() + .filter(|k| !remove_set.contains(*k)) + .filter_map(|entry| { + let slash = entry.rfind('/')?; + let p = entry[..slash].parse::().ok()?; + Some(PortDef { port: p, protocol: entry[slash + 1..].to_string() }) + }) + .collect(); + + let profile_content = if remaining.is_empty() { + // Delete the profile and the rule + let _ = Command::new("pkexec") + .args(["ufw", "delete", "allow", UFW_APP_NAME]) + .status().await; + let _ = Command::new("pkexec") + .args(["rm", "-f", UFW_PROFILE_PATH]) + .status().await; + return Ok(()); + } else { + build_ufw_profile(&remaining) + }; + + // Rewrite profile + let mut child = Command::new("pkexec") + .args(["tee", UFW_PROFILE_PATH]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::null()) + .spawn() + .map_err(|e| format!("Failed to spawn pkexec tee: {e}"))?; + + if let Some(mut stdin) = child.stdin.take() { + use tokio::io::AsyncWriteExt; + stdin.write_all(profile_content.as_bytes()).await + .map_err(|e| format!("Failed to write profile: {e}"))?; + } + let out = child.wait_with_output().await + .map_err(|e| format!("pkexec tee failed: {e}"))?; + if !out.status.success() { + return Err(format!("pkexec tee exited {}", out.status.code().unwrap_or(-1))); + } + + // Re-apply + let _ = Command::new("pkexec") + .args(["ufw", "allow", UFW_APP_NAME]) + .status().await; + Ok(()) + } + + // ── firewalld ──────────────────────────────────────────────────────────── + + pub async fn check_firewalld(ports: &[PortDef]) -> FirewallStatus { + let mut statuses = Vec::new(); + for p in ports { + let arg = format!("{}/{}", p.port, p.protocol); + let covered = Command::new("firewall-cmd") + .args(["--query-port", &arg]) + .status() + .await + .map(|s| s.success()) + .unwrap_or(false); + statuses.push(PortStatus { port: p.port, protocol: p.protocol.clone(), covered }); + } + FirewallStatus { firewall_type: "firewalld".into(), active: true, ports: statuses } + } + + pub async fn add_firewalld(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let arg = format!("{}/{}", p.port, p.protocol); + let already = Command::new("firewall-cmd") + .args(["--query-port", &arg]) + .status().await + .map(|s| s.success()).unwrap_or(false); + if already { continue; } + + let s = Command::new("pkexec") + .args(["firewall-cmd", "--permanent", &format!("--add-port={arg}")]) + .status().await + .map_err(|e| format!("pkexec firewall-cmd failed: {e}"))?; + if !s.success() { + return Err(format!("firewall-cmd --add-port exited {}", s.code().unwrap_or(-1))); + } + } + // Reload once after all ports added + let _ = Command::new("pkexec") + .args(["firewall-cmd", "--reload"]) + .status().await; + Ok(()) + } + + pub async fn remove_firewalld(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let arg = format!("{}/{}", p.port, p.protocol); + let _ = Command::new("pkexec") + .args(["firewall-cmd", "--permanent", &format!("--remove-port={arg}")]) + .status().await; + } + let _ = Command::new("pkexec") + .args(["firewall-cmd", "--reload"]) + .status().await; + Ok(()) + } + + // ── iptables (DB-backed fallback) ──────────────────────────────────────── + + pub async fn add_iptables(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let proto = &p.protocol; + let port_str = p.port.to_string(); + let s = Command::new("pkexec") + .args(["iptables", "-A", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) + .status().await + .map_err(|e| format!("pkexec iptables failed: {e}"))?; + if !s.success() { + return Err(format!("iptables -A exited {} for port {}", s.code().unwrap_or(-1), p.port)); + } + } + Ok(()) + } + + pub async fn remove_iptables(ports: &[PortDef]) -> Result<(), String> { + for p in ports { + let proto = &p.protocol; + let port_str = p.port.to_string(); + let _ = Command::new("pkexec") + .args(["iptables", "-D", "INPUT", "-p", proto, "--dport", &port_str, "-j", "ACCEPT"]) + .status().await; + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Tauri commands +// --------------------------------------------------------------------------- + +/// Check firewall status for the given ports. Non-elevated on all platforms. +#[tauri::command] +pub async fn check_firewall_ports(ports: Vec) -> Result { + #[cfg(target_os = "windows")] + { + Ok(windows_impl::check_ports(&ports).await) + } + + #[cfg(target_os = "linux")] + { + use linux_impl::*; + match detect().await { + FirewallKind::Ufw => Ok(check_ufw(&ports).await), + FirewallKind::Firewalld => Ok(check_firewalld(&ports).await), + FirewallKind::Iptables | FirewallKind::None => { + // For iptables we rely on DB state (checked by the frontend). + // Return active:false so the frontend falls back to DB. + let statuses = ports.iter().map(|p| PortStatus { + port: p.port, protocol: p.protocol.clone(), covered: false, + }).collect(); + Ok(FirewallStatus { + firewall_type: if matches!(detect().await, FirewallKind::Iptables) { + "iptables".into() + } else { + "none".into() + }, + active: false, + ports: statuses, + }) + } + } + } + + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + { + let statuses = ports.iter().map(|p| PortStatus { + port: p.port, protocol: p.protocol.clone(), covered: false, + }).collect(); + Ok(FirewallStatus { firewall_type: "none".into(), active: false, ports: statuses }) + } +} + +/// Add firewall rules for the given ports. Triggers elevation (UAC / pkexec). +#[tauri::command] +pub async fn add_firewall_rules(ports: Vec, _proton_path: Option) -> Result<(), String> { + #[cfg(target_os = "windows")] + { + windows_impl::add_rules(&ports).await + } + + #[cfg(target_os = "linux")] + { + use linux_impl::*; + match detect().await { + FirewallKind::Ufw => { + let current = parse_ufw_profile(); + add_ufw(&ports, ¤t).await + } + FirewallKind::Firewalld => add_firewalld(&ports).await, + FirewallKind::Iptables => add_iptables(&ports).await, + FirewallKind::None => Ok(()), // nothing to do + } + } + + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + { + Ok(()) + } +} + +/// Remove firewall rules. Called only when the user opts in during server deletion. +#[tauri::command] +pub async fn remove_firewall_rules(ports: Vec) -> Result<(), String> { + #[cfg(target_os = "windows")] + { + windows_impl::remove_rules(&ports).await + } + + #[cfg(target_os = "linux")] + { + use linux_impl::*; + match detect().await { + FirewallKind::Ufw => remove_ufw(&ports).await, + FirewallKind::Firewalld => remove_firewalld(&ports).await, + FirewallKind::Iptables => remove_iptables(&ports).await, + FirewallKind::None => Ok(()), + } + } + + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + { + Ok(()) + } +} + +/// Returns currently tracked UFW profile ports (world-readable on Linux). +/// On Windows returns the same list derived from netsh (non-elevated). +/// Used to compute exclusive ports when deleting a server. +#[tauri::command] +pub async fn get_all_firewall_ports() -> Result, String> { + #[cfg(target_os = "windows")] + { + // Parse netsh output to find LokiASAM-* rules + let output = Command::new("netsh") + .args(["advfirewall", "firewall", "show", "rule", "name=all", "dir=in"]) + .output() + .await + .map_err(|e| format!("netsh failed: {e}"))?; + + let text = String::from_utf8_lossy(&output.stdout); + let mut ports = Vec::new(); + let mut current_name = String::new(); + let mut current_proto = String::new(); + + for line in text.lines() { + let line = line.trim(); + if line.starts_with("Rule Name:") { + current_name = line.trim_start_matches("Rule Name:").trim().to_string(); + current_proto.clear(); + } else if line.starts_with("Protocol:") { + current_proto = line.trim_start_matches("Protocol:").trim().to_lowercase(); + } else if line.starts_with("LocalPort:") && current_name.starts_with("LokiASAM-") { + let port_str = line.trim_start_matches("LocalPort:").trim(); + if let Ok(port) = port_str.parse::() { + if current_proto == "tcp" || current_proto == "udp" { + ports.push(PortDef { port, protocol: current_proto.clone() }); + } + } + } + } + Ok(ports) + } + + #[cfg(target_os = "linux")] + { + use linux_impl::parse_ufw_profile; + let set = parse_ufw_profile(); + let ports = set.iter() + .filter_map(|entry| { + let slash = entry.rfind('/')?; + let p = entry[..slash].parse::().ok()?; + Some(PortDef { port: p, protocol: entry[slash + 1..].to_string() }) + }) + .collect(); + Ok(ports) + } + + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + { + Ok(vec![]) + } +} diff --git a/src-tauri/src/commands/logs.rs b/src-tauri/src/commands/logs.rs index 37948da..17d61e1 100644 --- a/src-tauri/src/commands/logs.rs +++ b/src-tauri/src/commands/logs.rs @@ -1,114 +1,640 @@ -use std::io::SeekFrom; -use std::sync::{atomic::Ordering, Arc}; -use tauri::{Emitter, State}; -use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; - -use crate::{events, state::log_watcher::LogWatcherState}; - -/// Begin tailing `log_path` for `server_id`. -/// A background tokio task polls the file every 200 ms, seeking to the current -/// end on start so only new lines are emitted. Each new line fires the event -/// `log://line/{server_id}` with a `LogLine` payload. -/// -/// Calling this again for the same `server_id` replaces the previous watcher. +use serde::{Deserialize, Serialize}; +use tauri::State; + +use crate::state::log_manager::LogManagerState; + +// --------------------------------------------------------------------------- +// Public types (mirrored on the frontend) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchivedLogInfo { + pub filename: String, + pub size_bytes: u64, + /// ISO timestamp derived from the filename (YYYY-MM-DD_HH-MM-SS). + pub timestamp: String, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashInfo { + pub folder_name: String, + pub timestamp: String, + pub has_call_stack: bool, + pub files: Vec, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashFile { + pub name: String, + pub content: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CrashReport { + pub folder_name: String, + pub files: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ChatLogInfo { + pub filename: String, + pub date: String, + pub size_bytes: u64, + pub full_path: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LogStats { + pub shootergame_archive_count: u32, + pub shootergame_total_bytes: u64, + pub chat_log_count: u32, + pub chat_total_bytes: u64, + pub crash_count: u32, + pub storage_root: String, +} + +// --------------------------------------------------------------------------- +// Watch commands +// --------------------------------------------------------------------------- + +/// Start tailing ShooterGame.log for `server_id`. +/// Emits `log://backfill/{server_id}` with existing content then +/// `log://line/{server_id}` for each new line. #[tauri::command] pub async fn watch_server_log( app: tauri::AppHandle, server_id: String, log_path: String, - state: State<'_, LogWatcherState>, + state: State<'_, LogManagerState>, ) -> Result<(), String> { - let stop_flag = state.start(&server_id).await; - let event_name = format!("{}/{server_id}", events::LOG_LINE); - - tauri::async_runtime::spawn(async move { - tail_log(app, event_name, log_path, stop_flag).await; - }); - + state.start_watcher(&server_id, log_path, app).await; Ok(()) } -/// Stop the log watcher for `server_id` (no-op if not watching). +/// Stop the log watcher for `server_id`. #[tauri::command] pub async fn stop_log_watch( server_id: String, - state: State<'_, LogWatcherState>, + state: State<'_, LogManagerState>, ) -> Result<(), String> { - state.stop(&server_id).await; + state.stop_watcher(&server_id).await; Ok(()) } -#[derive(Clone, serde::Serialize)] -pub struct LogLine { - pub line: String, - pub level: String, +// --------------------------------------------------------------------------- +// Archive commands +// --------------------------------------------------------------------------- + +/// List all archived ShooterGame log files for a server, newest first. +#[tauri::command] +pub async fn list_archived_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read log archive dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let timestamp = extract_timestamp_from_filename(&name); + entries.push(ArchivedLogInfo { + filename: name, + size_bytes: meta.len(), + timestamp, + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + // Sort newest first by filename (ISO timestamp sorts lexicographically). + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) } -/// Classify an ASA log line into a rough severity level. -fn classify_level(line: &str) -> &'static str { - let lower = line.to_ascii_lowercase(); - if lower.contains("error") || lower.contains("fatal") || lower.contains("critical") { - "error" - } else if lower.contains("warning") || lower.contains("warn") { - "warning" - } else { - "info" +/// Read lines from an archived log file, with pagination. +/// `offset` is line index (0-based); `limit` is max lines to return. +/// Pass limit=0 to get all lines. +#[tauri::command] +pub async fn read_archived_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + .ok_or("Log storage not configured")?; + + // Validate filename — no path traversal + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); } + + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) } -async fn tail_log( +/// Delete an archived log file. +#[tauri::command] +pub async fn delete_archived_log( app: tauri::AppHandle, - event_name: String, - log_path: String, - stop_flag: Arc, -) { - use tokio::fs::File; - - // Wait for the log file to exist (server may not have started yet). - let mut file = { - let mut attempts = 0u32; - loop { - if stop_flag.load(Ordering::Relaxed) { - return; - } - match File::open(&log_path).await { - Ok(f) => break f, - Err(_) => { - attempts += 1; - if attempts >= 60 { - return; - } - tokio::time::sleep(std::time::Duration::from_secs(1)).await; + server_id: String, + filename: String, +) -> Result<(), String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } + + tokio::fs::remove_file(dir.join(&filename)) + .await + .map_err(|e| format!("Failed to delete log: {e}")) +} + +// --------------------------------------------------------------------------- +// Crash commands +// --------------------------------------------------------------------------- + +/// List crash reports from the server's central crash storage. +#[tauri::command] +pub async fn list_crashes( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut crashes: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read crashes dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + if !meta.is_dir() { + continue; + } + + let folder_name = entry.file_name().to_string_lossy().to_string(); + let full_path = entry.path().to_string_lossy().to_string(); + + let mut files: Vec = Vec::new(); + let mut has_call_stack = false; + + if let Ok(mut inner) = tokio::fs::read_dir(entry.path()).await { + while let Ok(Some(f)) = inner.next_entry().await { + let fname = f.file_name().to_string_lossy().to_string(); + let fl = fname.to_lowercase(); + if fl.contains("callstack") || fl.contains("stack") { + has_call_stack = true; } + files.push(fname); } } + files.sort(); + + let timestamp = folder_name_to_timestamp(&folder_name); + crashes.push(CrashInfo { folder_name, timestamp, has_call_stack, files, full_path }); + } + + crashes.sort_by(|a, b| b.folder_name.cmp(&a.folder_name)); + Ok(crashes) +} + +/// Read all readable (non-binary) files from a crash folder in central storage. +#[tauri::command] +pub async fn read_crash_report( + app: tauri::AppHandle, + server_id: String, + folder_name: String, +) -> Result { + if folder_name.contains('/') || folder_name.contains('\\') || folder_name.contains("..") { + return Err("Invalid folder name".to_string()); + } + + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + .ok_or("Log storage not configured")?; + + let folder_path = dir.join(&folder_name); + if !folder_path.exists() { + return Err("Crash folder not found".to_string()); + } + + let mut files: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&folder_path) + .await + .map_err(|e| format!("Failed to read crash folder: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + let lower = name.to_lowercase(); + if lower.ends_with(".dmp") || lower.ends_with(".png") || lower.ends_with(".jpg") || lower.ends_with(".bin") { + continue; + } + let content = tokio::fs::read_to_string(entry.path()) + .await + .unwrap_or_else(|_| "[binary or unreadable file]".to_string()); + files.push(CrashFile { name, content }); + } + + files.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(CrashReport { folder_name, files }) +} + +/// Delete a crash report folder from central storage. +#[tauri::command] +pub async fn delete_crash_report( + app: tauri::AppHandle, + server_id: String, + folder_name: String, +) -> Result<(), String> { + if folder_name.contains('/') || folder_name.contains('\\') || folder_name.contains("..") { + return Err("Invalid folder name".to_string()); + } + + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("crashes")) + .ok_or("Log storage not configured")?; + + tokio::fs::remove_dir_all(dir.join(&folder_name)) + .await + .map_err(|e| format!("Failed to delete crash report: {e}")) +} + +// --------------------------------------------------------------------------- +// Other log commands (secondary engine logs collected at server start) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OtherLogInfo { + pub filename: String, + pub size_bytes: u64, + pub timestamp: String, + pub full_path: String, +} + +/// List secondary log files collected to central storage (non-ShooterGame logs). +#[tauri::command] +pub async fn list_other_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("other")) + { + Some(d) => d, + None => return Ok(vec![]), }; - // Seek to end so we only tail new content from this point. - let _ = file.seek(SeekFrom::End(0)).await; + if !dir.exists() { + return Ok(vec![]); + } - let mut reader = BufReader::new(file); - let mut line_buf = String::new(); + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read other logs dir: {e}"))?; - loop { - if stop_flag.load(Ordering::Relaxed) { - break; + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let timestamp = extract_timestamp_from_filename(&name); + entries.push(OtherLogInfo { + filename: name, + size_bytes: meta.len(), + timestamp, + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) +} + +/// Read lines from an other log file. +#[tauri::command] +pub async fn read_other_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("other")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } + + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) +} + +// --------------------------------------------------------------------------- +// Chat log commands +// --------------------------------------------------------------------------- + +/// List all chat log files for a server, newest first. +#[tauri::command] +pub async fn list_chat_logs( + app: tauri::AppHandle, + server_id: String, +) -> Result, String> { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("chat")) + { + Some(d) => d, + None => return Ok(vec![]), + }; + + if !dir.exists() { + return Ok(vec![]); + } + + let mut entries: Vec = Vec::new(); + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read chat log dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + // filename: chat_YYYY-MM-DD.log → date: YYYY-MM-DD + let date = name + .strip_prefix("chat_") + .and_then(|s| s.strip_suffix(".log")) + .unwrap_or(&name) + .to_string(); + entries.push(ChatLogInfo { + filename: name, + date, + size_bytes: meta.len(), + full_path: entry.path().to_string_lossy().to_string(), + }); + } + + entries.sort_by(|a, b| b.filename.cmp(&a.filename)); + Ok(entries) +} + +/// Read lines from a chat log file. +#[tauri::command] +pub async fn read_chat_log( + app: tauri::AppHandle, + server_id: String, + filename: String, + offset: usize, + limit: usize, +) -> Result, String> { + let dir = LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("chat")) + .ok_or("Log storage not configured")?; + + if filename.contains('/') || filename.contains('\\') || filename.contains("..") { + return Err("Invalid filename".to_string()); + } - match reader.read_line(&mut line_buf).await { - Ok(0) => { - // No new data — sleep before next poll. - tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let path = dir.join(&filename); + let content = tokio::fs::read_to_string(&path) + .await + .map_err(|e| format!("Failed to read chat log: {e}"))?; + + let lines: Vec = content + .lines() + .skip(offset) + .take(if limit == 0 { usize::MAX } else { limit }) + .map(|l| l.to_string()) + .collect(); + + Ok(lines) +} + +// --------------------------------------------------------------------------- +// Cleanup + stats +// --------------------------------------------------------------------------- + +/// Delete all archived ShooterGame logs older than `older_than_days` days. +/// Returns the number of files deleted. +#[tauri::command] +pub async fn cleanup_logs( + app: tauri::AppHandle, + server_id: String, + older_than_days: u32, +) -> Result { + let dir = match LogManagerState::server_logs_dir(&app, &server_id) + .map(|d| d.join("shootergame")) + { + Some(d) => d, + None => return Ok(0), + }; + + if !dir.exists() { + return Ok(0); + } + + let cutoff_secs = { + use std::time::{SystemTime, UNIX_EPOCH}; + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .saturating_sub(older_than_days as u64 * 86_400) + }; + + let mut deleted = 0u32; + let mut read_dir = tokio::fs::read_dir(&dir) + .await + .map_err(|e| format!("Failed to read log dir: {e}"))?; + + while let Some(entry) = read_dir.next_entry().await.map_err(|e| e.to_string())? { + let name = entry.file_name().to_string_lossy().to_string(); + if !name.ends_with(".log") { + continue; + } + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + let modified_secs = meta + .modified() + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()) + .unwrap_or(0); + + if modified_secs < cutoff_secs { + if tokio::fs::remove_file(entry.path()).await.is_ok() { + deleted += 1; } - Ok(_) => { - 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(&event_name, LogLine { line: trimmed, level }); + } + } + + Ok(deleted) +} + +/// Get log storage statistics for a server. +#[tauri::command] +pub async fn get_log_stats( + app: tauri::AppHandle, + server_id: String, +) -> Result { + let root = LogManagerState::server_logs_dir(&app, &server_id); + let storage_root = root + .as_ref() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + + let sg_dir = root.as_ref().map(|d| d.join("shootergame")); + let chat_dir = root.as_ref().map(|d| d.join("chat")); + let crash_dir = root.as_ref().map(|d| { + // crashes live in the install dir, but we reference them from here + d.clone() + }); + let _ = crash_dir; // placeholder until we store crashes centrally + + let (sg_count, sg_bytes) = count_dir(sg_dir.as_deref()).await; + let (chat_count, chat_bytes) = count_dir(chat_dir.as_deref()).await; + + Ok(LogStats { + shootergame_archive_count: sg_count, + shootergame_total_bytes: sg_bytes, + chat_log_count: chat_count, + chat_total_bytes: chat_bytes, + crash_count: 0, // populated by list_crashes on demand + storage_root, + }) +} + +/// Return the path to the central logs storage root (for display in UI). +#[tauri::command] +pub fn get_log_storage_root(app: tauri::AppHandle) -> String { + LogManagerState::logs_root(&app) + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default() +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +async fn count_dir(dir: Option<&std::path::Path>) -> (u32, u64) { + let dir = match dir { + Some(d) if d.exists() => d, + _ => return (0, 0), + }; + let mut count = 0u32; + let mut bytes = 0u64; + if let Ok(mut rd) = tokio::fs::read_dir(dir).await { + while let Ok(Some(entry)) = rd.next_entry().await { + if let Ok(meta) = entry.metadata().await { + if meta.is_file() { + count += 1; + bytes += meta.len(); } - line_buf.clear(); } - Err(_) => break, } } + (count, bytes) +} + +/// Extract the timestamp string from a filename like `ShooterGame_2026-06-08_14-30-00.log`. +fn extract_timestamp_from_filename(name: &str) -> String { + // ShooterGame_YYYY-MM-DD_HH-MM-SS.log + name.trim_start_matches("ShooterGame_") + .trim_end_matches(".log") + .replace('_', " ") + .replace('-', if name.contains("_") { "-" } else { "-" }) + .to_string() +} + +/// Convert a UE5 crash folder name (e.g. `UE5-ShooterGame-Win64-2026.06.08-14.30.00`) to a readable string. +fn folder_name_to_timestamp(folder: &str) -> String { + // Try to extract any date-like portion. + // Common patterns: 2026.06.08-14.30.00 or 2026-06-08_14-30-00 + for part in folder.split('-') { + if part.len() >= 4 && part.chars().next().map_or(false, |c| c.is_ascii_digit()) { + return part.replace('.', "-"); + } + } + folder.to_string() } diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 50d9bcd..970d0f9 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -1,4 +1,6 @@ pub mod backup; +pub mod certs; +pub mod firewall; pub mod cluster; pub mod config; pub mod logs; diff --git a/src-tauri/src/commands/proton.rs b/src-tauri/src/commands/proton.rs index c97efc8..ba3e306 100644 --- a/src-tauri/src/commands/proton.rs +++ b/src-tauri/src/commands/proton.rs @@ -37,7 +37,7 @@ fn emit_download_line(app: &AppHandle, msg: &str) { ); } -/// Scan well-known Steam compatibilitytools.d locations and {base_dir}/proton/ +/// Scan well-known Steam compatibilitytools.d locations and {base_dir}/lokiasam/proton/ /// for valid GE-Proton installations. #[tauri::command] pub async fn scan_for_proton(base_dir: String) -> Result, String> { @@ -47,7 +47,7 @@ pub async fn scan_for_proton(base_dir: String) -> Result, Strin home.join(".steam/steam/compatibilitytools.d"), home.join(".local/share/Steam/compatibilitytools.d"), home.join(".var/app/com.valvesoftware.Steam/.local/share/Steam/compatibilitytools.d"), - PathBuf::from(&base_dir).join("proton"), + PathBuf::from(&base_dir).join("lokiasam").join("proton"), ]; let mut results = Vec::new(); diff --git a/src-tauri/src/commands/rcon.rs b/src-tauri/src/commands/rcon.rs index bf35821..beebd8a 100644 --- a/src-tauri/src/commands/rcon.rs +++ b/src-tauri/src/commands/rcon.rs @@ -4,9 +4,12 @@ use tauri::{Emitter, Manager, State}; use tokio::sync::{mpsc, oneshot}; use tokio::time::{timeout, Duration, interval, MissedTickBehavior}; -use crate::state::rcon_pool::{ - bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, - RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND, parse_player_list, +use crate::state::{ + log_manager::LogManagerState, + rcon_pool::{ + bin_subdir, CachedPlayer, RconCmd, RconConn, RconLogLine, RconPool, + RCON_AUTH, RCON_AUTH_RESPONSE, RCON_EXECCOMMAND, parse_player_list, + }, }; // Re-export CachedPlayer as ArkPlayer for backwards-compat with existing frontend calls. @@ -197,6 +200,7 @@ async fn run_rcon_manager( .insert(server_id.clone(), players.clone()); } 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)); } Err(e) => { @@ -222,6 +226,7 @@ async fn run_rcon_manager( .insert(server_id.clone(), players.clone()); } let _ = app.emit(&format!("rcon://players/{server_id}"), &players); + let _ = app.emit("rcon://players-any", serde_json::json!({ "serverId": server_id, "players": players })); } Err(ExecError::Io(_)) => break, // TCP dead Err(ExecError::Timeout) => {} // server slow; skip this poll cycle @@ -245,6 +250,7 @@ async fn run_rcon_manager( // Drop SERVER: prefix lines — these are echoes of admin // broadcasts (e.g. ServerChat) that the user already saw. if line.starts_with("SERVER: ") { continue; } + LogManagerState::append_chat_line(&app, &server_id, line).await; emit_log(&app, &server_id, RconLogLine { timestamp_ms: now_ms(), text: line.to_string(), diff --git a/src-tauri/src/commands/scheduler.rs b/src-tauri/src/commands/scheduler.rs index e3a9c7a..04b7b47 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}; +use crate::state::{scheduler::SchedulerState, AppState, rcon_pool::RconPool}; use serde::{Deserialize, Serialize}; use std::time::{SystemTime, UNIX_EPOCH}; use tauri::{AppHandle, Emitter, Manager}; @@ -131,20 +131,6 @@ async fn fire_broadcast(app: &AppHandle, entry: &crate::state::scheduler::Schedu Ok(()) } -async fn fire_backup(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result, String> { - crate::commands::backup::create_backup( - app.clone(), - entry.server_id.clone(), - entry.server_name.clone(), - entry.install_path.clone(), - entry.backup_dir.clone(), - entry.map_id.clone(), - "schedule".to_string(), - ) - .await - .map(Some) -} - async fn fire_restart(app: &AppHandle, entry: &crate::state::scheduler::ScheduleEntry) -> Result<(), String> { let is_running = { let state = app.state::(); @@ -360,6 +346,7 @@ async fn fire_update(app: &AppHandle, entry: &crate::state::scheduler::ScheduleE fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> StartServerParams { StartServerParams { server_id: entry.server_id.clone(), + server_name: entry.server_name.clone(), install_path: entry.install_path.clone(), map_path: entry.map_path.clone(), port: entry.port, @@ -372,6 +359,126 @@ fn entry_to_start_params(entry: &crate::state::scheduler::ScheduleEntry) -> Star } } +/// Returns true if a server is currently running (checked via AppState). +fn is_server_running(app: &AppHandle, server_id: &str) -> bool { + app.state::() + .running_servers + .lock() + .unwrap() + .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. @@ -404,7 +511,15 @@ pub fn tick_scheduler(app: &AppHandle) { Ok(_) => (true, None, None), Err(e) => (false, Some(e), None), }, - "backup" => match fire_backup(&app, &entry).await { + "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), }, diff --git a/src-tauri/src/commands/server.rs b/src-tauri/src/commands/server.rs index 16a51c0..8dba940 100644 --- a/src-tauri/src/commands/server.rs +++ b/src-tauri/src/commands/server.rs @@ -1,4 +1,4 @@ -use crate::{events, state::{AppState, rcon_pool::RconPool}}; +use crate::{events, state::{AppState, log_manager::LogManagerState, rcon_pool::RconPool}}; use serde::{Deserialize, Serialize}; use std::sync::{ atomic::{AtomicBool, Ordering}, @@ -92,6 +92,8 @@ fn filter_steam_noise(s: &str) -> String { #[serde(rename_all = "camelCase")] pub struct StartServerParams { pub server_id: String, + /// Human-readable server name — used only for log archiving context. + pub server_name: String, /// Absolute path to the server install directory. pub install_path: String, /// ASA map identifier, e.g. "TheIsland_WP". @@ -319,53 +321,6 @@ async fn inner_start_server_with_state( cmd.env_remove("PYTHONPATH"); } - // Rotate any existing ShooterGame.log before launching. We own log rotation - // from here on — archiving the old file ourselves so the fresh log starts at - // byte 0 and the readiness watcher below never has to deal with inodes. - let current_log_path = format!( - "{}/ShooterGame/Saved/Logs/ShooterGame.log", - params.install_path - ); - let did_rotate: bool = if tokio::fs::metadata(¤t_log_path).await.is_ok() { - use std::time::{SystemTime, UNIX_EPOCH}; - let now_secs = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - let (year, month, day, hh, mm, ss) = { - let secs_per_day = 86_400u64; - let days = now_secs / secs_per_day; - let day_secs = now_secs % secs_per_day; - let mut d = days; - let mut y = 1970u64; - loop { - let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); - let days_in_year = if leap { 366 } else { 365 }; - if d < days_in_year { break; } - d -= days_in_year; - y += 1; - } - let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); - let days_in_month = [31u64, if leap { 29 } else { 28 }, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - let mut mo = 0usize; - while mo < 12 && d >= days_in_month[mo] { d -= days_in_month[mo]; mo += 1; } - (y, (mo + 1) as u64, d + 1, day_secs / 3600, (day_secs % 3600) / 60, day_secs % 60) - }; - let archive_path = format!( - "{}/ShooterGame/Saved/Logs/ShooterGame_{year:04}-{month:02}-{day:02}_{hh:02}-{mm:02}-{ss:02}.log", - params.install_path - ); - // Rename preferred; fall back to delete so we always start with a clean slate. - if tokio::fs::rename(¤t_log_path, &archive_path).await.is_ok() { - true - } else { - tokio::fs::remove_file(¤t_log_path).await.is_ok() - } - } else { - // No pre-existing log — fresh install or first ever start. - true - }; - let mut child = match cmd.spawn() { Ok(c) => c, Err(e) => { @@ -389,6 +344,10 @@ async fn inner_start_server_with_state( // The watcher task reads this on exit to distinguish a startup failure // (process died before ever being ready) from a runtime crash. let confirmed_running = Arc::new(AtomicBool::new(false)); + // Set to true by the readiness task if the CurseForge mod API unreachable + // error is seen in the log. The watcher task emits a dedicated retry event + // instead of "start-failed" so the frontend can auto-retry silently. + let cfcore_unreachable = Arc::new(AtomicBool::new(false)); // Register in the running map. { @@ -424,6 +383,7 @@ async fn inner_start_server_with_state( let install_path_watcher = params.install_path.clone(); let handle_clone = app_handle.clone(); let confirmed_clone = Arc::clone(&confirmed_running); + let cfcore_clone = Arc::clone(&cfcore_unreachable); tauri::async_runtime::spawn(async move { let (_, raw_stderr) = tokio::join!( child.wait(), @@ -450,6 +410,7 @@ async fn inner_start_server_with_state( // ── Intentional stop ───────────────────────────────────────────────── if was_intentional { app_state.running_servers.lock().unwrap().remove(&sid); + LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "stopped".into(), pid: None, uptime_seconds: None, error: None, @@ -460,6 +421,7 @@ async fn inner_start_server_with_state( // ── Runtime crash (was confirmed running) ──────────────────────────── 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; emit_status(&handle_clone, &ServerStatus { server_id: sid, status: "crashed".into(), pid: None, uptime_seconds: None, error: None, @@ -498,6 +460,17 @@ async fn inner_start_server_with_state( // ── Genuine start failure ───────────────────────────────────────────── app_state.running_servers.lock().unwrap().remove(&sid); + LogManagerState::archive_all_server_logs(&handle_clone, &sid, &install_path_watcher).await; + + // CurseForge mod API was unreachable — this is almost always a transient + // network issue. Emit a dedicated event so CfcoreRetryManager can silently + // retry up to 3 times before surfacing a failure to the user. The server + // status stays "starting" in the DB (no start-failed event emitted here). + if cfcore_clone.load(Ordering::Relaxed) { + let _ = handle_clone.emit("server://cfcore-error", serde_json::json!({ "serverId": sid })); + return; + } + let cleaned = strip_ansi(raw_stderr.trim()); let filtered = filter_steam_noise(&cleaned); let trimmed = if filtered.len() > 800 { @@ -598,7 +571,8 @@ async fn inner_start_server_with_state( params.install_path ); - let confirmed2 = Arc::clone(&confirmed_running); + let confirmed2 = Arc::clone(&confirmed_running); + let cfcore2 = Arc::clone(&cfcore_unreachable); tauri::async_runtime::spawn(async move { use std::io::SeekFrom; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, BufReader}; @@ -641,11 +615,8 @@ async fn inner_start_server_with_state( }; // ── Wait for the fresh log file to appear ──────────────────────────── - // We rotated any pre-existing ShooterGame.log before spawning, so the - // first file to appear at this path belongs to the current session. - // Read from byte 0 — no need for inode detection or seek-to-end. - // If rotation failed (permissions, locked file), did_rotate is false - // and we seek to end to skip stale content from the previous session. + // Rotation happens on stop/crash/startup, so by the time the server + // starts there is no pre-existing ShooterGame.log. Read from byte 0. let file = loop { if Instant::now() >= deadline { return; } @@ -663,12 +634,6 @@ async fn inner_start_server_with_state( } }; - let mut file = file; - if !did_rotate { - // Rotation failed — old file is still in place. Seek past stale - // content so we don't false-positive on a READY_MSG from a prior run. - let _ = file.seek(SeekFrom::End(0)).await; - } let mut reader = BufReader::new(file); let mut buf = String::new(); @@ -694,6 +659,9 @@ async fn inner_start_server_with_state( confirm_running(&handle2, &sid2); return; } + if buf.contains("Error querying server mods: ApiError: Failed (serverUnreachable)") { + cfcore2.store(true, Ordering::Relaxed); + } buf.clear(); } Err(_) => sleep(Duration::from_millis(200)).await, @@ -899,11 +867,14 @@ pub async fn scan_running_servers( servers: Vec, ) -> Result, String> { let mut results = Vec::new(); + let mut to_rotate: Vec<(String, String)> = Vec::new(); for entry in servers { let pid = find_server_process(&entry.install_path); if let Some(pid) = pid { + // Keep a copy of install_path for the watcher closure before it's moved. + let install_path_watcher = entry.install_path.clone(); { let mut registry = state.running_servers.lock().unwrap(); registry.insert( @@ -939,6 +910,10 @@ pub async fn scan_running_servers( app_state.running_servers.lock().unwrap().remove(&sid); + // Rotate logs before announcing the status change so the + // frontend can display the archived last-session log immediately. + LogManagerState::archive_all_server_logs(&handle, &sid, &install_path_watcher).await; + let status = if was_intentional { "stopped" } else { "crashed" }; let payload = ServerStatus { server_id: sid.clone(), @@ -957,11 +932,20 @@ pub async fn scan_running_servers( } } }); + } else { + // Not running — schedule for startup rotation. + to_rotate.push((entry.server_id.clone(), entry.install_path.clone())); } results.push(ScanResult { server_id: entry.server_id, pid }); } + // Rotate all stopped servers before returning so the scan-complete signal + // only reaches the frontend after logs are already in central storage. + for (server_id, install_path) in to_rotate { + LogManagerState::archive_all_server_logs(&app_handle, &server_id, &install_path).await; + } + Ok(results) } @@ -1201,6 +1185,11 @@ pub async fn graceful_stop_server( pool.chat_poll_active.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 + // were found running at startup (watched by the scan watcher which exits + // cleanly when running_servers is cleared above, bypassing its rotation). + LogManagerState::archive_all_server_logs(&app_handle, &server_id, &install_path).await; + emit_status(&app_handle, &ServerStatus { server_id, status: "stopped".into(), @@ -1211,3 +1200,22 @@ pub async fn graceful_stop_server( Ok(()) } + +/// Called by CfcoreRetryManager after all 3 auto-retry attempts have failed. +/// Emits the standard "start-failed" status event with a user-friendly +/// explanation so the UI and NotificationManager treat it as a normal failure. +#[tauri::command] +pub async fn force_server_start_failed( + server_id: String, + error: String, + app: tauri::AppHandle, +) -> Result<(), String> { + emit_status(&app, &ServerStatus { + server_id, + status: "start-failed".into(), + pid: None, + uptime_seconds: None, + error: Some(error), + }); + Ok(()) +} diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs index 47aa5a7..a10e6b0 100644 --- a/src-tauri/src/commands/system.rs +++ b/src-tauri/src/commands/system.rs @@ -444,7 +444,7 @@ pub fn get_platform() -> String { pub async fn open_folder(path: String) -> Result<(), String> { let p = std::path::Path::new(&path); if !p.exists() { - return Err(format!("Path does not exist: {path}")); + std::fs::create_dir_all(p).map_err(|e| format!("Could not create directory: {e}"))?; } #[cfg(target_os = "linux")] diff --git a/src-tauri/src/events/mod.rs b/src-tauri/src/events/mod.rs index 895d24d..4b648a9 100644 --- a/src-tauri/src/events/mod.rs +++ b/src-tauri/src/events/mod.rs @@ -8,8 +8,10 @@ pub const SERVER_STATUS: &str = "server://status"; pub const SERVER_ANY_CHANGE: &str = "server://any-change"; /// SteamCMD stdout/stderr lines streamed during install / update / validate. pub const STEAMCMD_OUTPUT: &str = "steamcmd://output"; -/// ASA server log lines streamed from the ShooterGame.log file watcher. +/// ASA server log lines streamed from the ShooterGame.log file watcher (new lines only). pub const LOG_LINE: &str = "log://line"; +/// Batch of existing log lines sent once when the watcher first opens a file (backfill). +pub const LOG_BACKFILL: &str = "log://backfill"; /// Backup progress update. pub const BACKUP_PROGRESS: &str = "backup://progress"; /// ASA update check result (or update-applied notification). diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 05b6592..523334d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -133,13 +133,6 @@ pub fn run() { ); } - // Disable WebKit's DMA-BUF renderer before the WebView is created. - // The DMA-BUF path breaks on modern Linux distributions (Arch, CachyOS, etc.) - // with newer mesa/kernel versions, producing a blank white window. Falling back - // to the SHM renderer has no visible effect for a desktop management UI. - #[cfg(target_os = "linux")] - std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1"); - tauri::Builder::default() // ── Single-instance guard ────────────────────────────────────────── // If a second instance is launched, focus the existing window and exit. @@ -157,7 +150,7 @@ pub fn run() { app.manage(state::AppState::new()); app.manage(state::rcon_pool::RconPool::new()); - app.manage(state::log_watcher::LogWatcherState::new()); + app.manage(state::log_manager::LogManagerState::new()); app.manage(state::scheduler::SchedulerState::new()); app.manage(state::stats_recorder::StatsRecorderState::new()); @@ -409,6 +402,16 @@ pub fn run() { commands::server::scan_running_servers, commands::server::clone_server, commands::server::delete_server, + commands::server::force_server_start_failed, + // Certificates + commands::certs::download_amazon_root_ca, + commands::certs::install_amazon_root_ca, + commands::certs::check_amazon_root_ca_installed, + // Firewall management + commands::firewall::check_firewall_ports, + commands::firewall::add_firewall_rules, + commands::firewall::remove_firewall_rules, + commands::firewall::get_all_firewall_ports, // SteamCMD / installation commands::steamcmd::install_steamcmd, commands::steamcmd::validate_steamcmd, @@ -433,18 +436,39 @@ pub fn run() { commands::rcon::rcon_disable_chat_poll, commands::rcon::rcon_read_ban_list, commands::rcon::rcon_read_whitelist, - // Log watcher + // Log watcher + archive + crash + chat commands::logs::watch_server_log, commands::logs::stop_log_watch, + commands::logs::list_archived_logs, + commands::logs::read_archived_log, + commands::logs::delete_archived_log, + commands::logs::list_crashes, + commands::logs::read_crash_report, + commands::logs::delete_crash_report, + commands::logs::list_other_logs, + commands::logs::read_other_log, + commands::logs::list_chat_logs, + commands::logs::read_chat_log, + commands::logs::cleanup_logs, + commands::logs::get_log_stats, + commands::logs::get_log_storage_root, // Config / INI commands::config::read_server_config, commands::config::write_server_config, commands::config::import_ini_files, - // Backups (Phase 6) - commands::backup::create_backup, - commands::backup::restore_backup, + // Backups + commands::backup::create_server_backup, + commands::backup::create_player_backup, + commands::backup::create_ini_backup, + commands::backup::create_full_backup, + commands::backup::list_ini_backups, + commands::backup::restore_server_backup, + commands::backup::restore_player_backup, + commands::backup::restore_ini_backup, + commands::backup::restore_full_backup, commands::backup::delete_backup, - commands::backup::prune_backups, + commands::backup::cleanup_ark_own_backups, + commands::backup::estimate_dir_size, // Mods (Phase 5) commands::mods::install_mods, commands::mods::open_mod_browser, diff --git a/src-tauri/src/state/log_manager.rs b/src-tauri/src/state/log_manager.rs new file mode 100644 index 0000000..000f17d --- /dev/null +++ b/src-tauri/src/state/log_manager.rs @@ -0,0 +1,403 @@ +use std::collections::HashMap; +use std::io::SeekFrom; +use std::path::PathBuf; +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; +use tauri::{Emitter, Manager}; +use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader}; +use tokio::sync::Mutex; + +use crate::events; + +/// Manages all server log file watchers. +/// Replaces the old LogWatcherState — adds backfill of existing content on start. +pub struct LogManagerState { + pub watchers: Mutex>>, +} + +impl LogManagerState { + pub fn new() -> Self { + Self { + watchers: Mutex::new(HashMap::new()), + } + } + + /// Start tailing `log_path` for `server_id`. + /// + /// 1. Reads all existing content from the beginning, emitting a single + /// `log://backfill/{server_id}` event with Vec. + /// 2. Tails new lines from EOF, emitting `log://line/{server_id}` per line. + /// + /// Calling again for the same `server_id` cancels the previous watcher. + pub async fn start_watcher( + &self, + server_id: &str, + log_path: String, + app: tauri::AppHandle, + ) -> Arc { + let stop_flag = Arc::new(AtomicBool::new(false)); + if let Some(old) = self + .watchers + .lock() + .await + .insert(server_id.to_string(), stop_flag.clone()) + { + old.store(true, Ordering::Relaxed); + } + + let server_id = server_id.to_string(); + let flag = stop_flag.clone(); + tauri::async_runtime::spawn(async move { + tail_log_with_backfill(app, server_id, log_path, flag).await; + }); + + stop_flag + } + + pub async fn stop_watcher(&self, server_id: &str) { + if let Some(flag) = self.watchers.lock().await.remove(server_id) { + flag.store(true, Ordering::Relaxed); + } + } + + /// Resolve the central logs root: `{base_dir}/logs/`. + /// Returns None if bootstrap.json is missing (setup not complete). + pub fn logs_root(app: &tauri::AppHandle) -> Option { + let config_dir = app.path().app_config_dir().ok()?; + let bootstrap_path = config_dir.join("bootstrap.json"); + let text = std::fs::read_to_string(&bootstrap_path).ok()?; + let value: serde_json::Value = serde_json::from_str(&text).ok()?; + let base_dir = value.get("baseDir")?.as_str()?; + Some(PathBuf::from(base_dir).join("logs")) + } + + /// Resolve per-server log directory: `{logs_root}/{server_id}/`. + pub fn server_logs_dir(app: &tauri::AppHandle, server_id: &str) -> Option { + Some(Self::logs_root(app)?.join(server_id)) + } + + /// Archive ALL log and crash data from the server install directory to central + /// storage before each server launch. Handles: + /// - ShooterGame.log → {server_id}/shootergame/ShooterGame_{ts}.log + /// - Other *.log files in Saved/Logs/ → {server_id}/other/{name}_{ts}.log + /// - Crash folders in Saved/Crashes/ → {server_id}/crashes/{folder}/ + /// + /// Returns true if the main log was cleanly handled (or absent). + pub async fn archive_all_server_logs( + app: &tauri::AppHandle, + server_id: &str, + install_path: &str, + ) -> bool { + let timestamp = current_timestamp_str(); + let server_dir = Self::server_logs_dir(app, server_id); + + // ── ShooterGame.log ────────────────────────────────────────────────── + let current_log = format!( + "{}/ShooterGame/Saved/Logs/ShooterGame.log", + install_path + ); + let main_ok = if tokio::fs::metadata(¤t_log).await.is_ok() { + let ok = if let Some(dest_dir) = server_dir.as_ref().map(|d| d.join("shootergame")) { + let _ = tokio::fs::create_dir_all(&dest_dir).await; + let dest = dest_dir.join(format!("ShooterGame_{timestamp}.log")); + move_file(¤t_log, &dest).await + } else { + false + }; + if !ok { + // Fall back to delete so the new session starts at byte 0. + tokio::fs::remove_file(¤t_log).await.is_ok() + } else { + true + } + } else { + true // no prior log — fresh install + }; + + // ── Other *.log files in Saved/Logs/ ──────────────────────────────── + let logs_src_dir = format!("{}/ShooterGame/Saved/Logs", install_path); + if let Ok(mut rd) = tokio::fs::read_dir(&logs_src_dir).await { + if let Some(other_dir) = server_dir.as_ref().map(|d| d.join("other")) { + let _ = tokio::fs::create_dir_all(&other_dir).await; + while let Ok(Some(entry)) = rd.next_entry().await { + let name = entry.file_name().to_string_lossy().to_string(); + // Skip ShooterGame.log (handled above) and our own archives. + if name == "ShooterGame.log" || name.starts_with("ShooterGame_") { + continue; + } + if !name.ends_with(".log") { + continue; + } + let stem = name.trim_end_matches(".log"); + let dest = other_dir.join(format!("{stem}_{timestamp}.log")); + let src = entry.path().to_string_lossy().to_string(); + let _ = move_file(&src, &dest).await; + } + } + } + + // ── Crash folders in Saved/Crashes/ ───────────────────────────────── + let crashes_src = format!("{}/ShooterGame/Saved/Crashes", install_path); + if let Ok(mut rd) = tokio::fs::read_dir(&crashes_src).await { + if let Some(crashes_dir) = server_dir.as_ref().map(|d| d.join("crashes")) { + let _ = tokio::fs::create_dir_all(&crashes_dir).await; + while let Ok(Some(entry)) = rd.next_entry().await { + let meta = match entry.metadata().await { + Ok(m) => m, + Err(_) => continue, + }; + if !meta.is_dir() { + continue; + } + let folder_name = entry.file_name().to_string_lossy().to_string(); + let dest = crashes_dir.join(&folder_name); + // If destination already exists (same crash already moved), skip. + if dest.exists() { + continue; + } + let src = entry.path().to_string_lossy().to_string(); + // Try rename first, then recursive copy+delete. + if tokio::fs::rename(&src, &dest).await.is_err() { + copy_dir_and_remove(&src, &dest).await; + } + } + } + } + + main_ok + } + + /// Append a chat line to today's chat log file. + /// Called by the RCON manager when a GetChat line is received. + pub async fn append_chat_line(app: &tauri::AppHandle, server_id: &str, line: &str) { + let Some(dir) = Self::server_logs_dir(app, server_id) + .map(|d| d.join("chat")) else { return }; + + if tokio::fs::create_dir_all(&dir).await.is_err() { + return; + } + + let date = current_date_str(); + let path = dir.join(format!("chat_{date}.log")); + let ts = current_time_str(); + let entry = format!("[{ts}] {line}\n"); + use tokio::io::AsyncWriteExt; + if let Ok(mut f) = tokio::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .await + { + let _ = f.write_all(entry.as_bytes()).await; + } + } +} + +// --------------------------------------------------------------------------- +// File/directory helpers +// --------------------------------------------------------------------------- + +/// Move a file: try rename first (fast, same filesystem); fall back to copy+delete. +async fn move_file(src: &str, dest: &std::path::Path) -> bool { + if tokio::fs::rename(src, dest).await.is_ok() { + return true; + } + if tokio::fs::copy(src, dest).await.is_ok() { + let _ = tokio::fs::remove_file(src).await; + true + } else { + false + } +} + +/// Recursively copy a directory then remove the source. +async fn copy_dir_and_remove(src: &str, dest: &std::path::Path) { + let src_path = std::path::Path::new(src); + if let Err(_) = tokio::fs::create_dir_all(dest).await { + return; + } + let mut rd = match tokio::fs::read_dir(src_path).await { + Ok(r) => r, + Err(_) => return, + }; + while let Ok(Some(entry)) = rd.next_entry().await { + let dest_file = dest.join(entry.file_name()); + let _ = tokio::fs::copy(entry.path(), &dest_file).await; + } + let _ = tokio::fs::remove_dir_all(src_path).await; +} + +// --------------------------------------------------------------------------- +// Tail task +// --------------------------------------------------------------------------- + +#[derive(Clone, serde::Serialize)] +pub struct LogLine { + pub line: String, + pub level: String, +} + +fn classify_level(line: &str) -> &'static str { + let lower = line.to_ascii_lowercase(); + if lower.contains("error") || lower.contains("fatal") || lower.contains("critical") { + "error" + } else if lower.contains("warning") || lower.contains("warn") { + "warning" + } else { + "info" + } +} + +async fn tail_log_with_backfill( + app: tauri::AppHandle, + server_id: String, + log_path: String, + stop_flag: Arc, +) { + use tokio::fs::File; + + // Wait up to 60 s for the log file to appear (server may still be starting). + let mut file = { + let mut attempts = 0u32; + loop { + if stop_flag.load(Ordering::Relaxed) { + return; + } + match File::open(&log_path).await { + Ok(f) => break f, + Err(_) => { + attempts += 1; + if attempts >= 60 { + return; + } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + } + } + } + }; + + // ── Backfill: read all existing content from start ─────────────────────── + let backfill_event = format!("{}/{server_id}", events::LOG_BACKFILL); + let mut backfill: Vec = Vec::new(); + let mut buf = String::new(); + let mut reader = BufReader::new(&mut file); + loop { + buf.clear(); + match reader.read_line(&mut buf).await { + Ok(0) => break, + Ok(_) => { + let trimmed = buf.trim_end_matches(['\n', '\r']).to_string(); + if !trimmed.is_empty() { + let level = classify_level(&trimmed).to_string(); + backfill.push(LogLine { line: trimmed, level }); + } + } + Err(_) => break, + } + } + if !backfill.is_empty() { + let _ = app.emit(&backfill_event, &backfill); + } + + // Seek to current EOF so we only tail truly new content. + let _ = file.seek(SeekFrom::End(0)).await; + + // ── Tail: stream new lines as they arrive ──────────────────────────────── + let line_event = format!("{}/{server_id}", events::LOG_LINE); + let mut reader = BufReader::new(file); + let mut line_buf = String::new(); + + loop { + if stop_flag.load(Ordering::Relaxed) { + break; + } + match reader.read_line(&mut line_buf).await { + Ok(0) => { + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + Ok(_) => { + 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 }); + } + line_buf.clear(); + } + Err(_) => break, + } + } +} + +// --------------------------------------------------------------------------- +// Time helpers (no external crate, manual calculation) +// --------------------------------------------------------------------------- + +fn current_timestamp_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (y, mo, d, h, min, s) = epoch_to_ymdhms(secs); + format!("{y:04}-{mo:02}-{d:02}_{h:02}-{min:02}-{s:02}") +} + +pub fn current_date_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (y, mo, d, _, _, _) = epoch_to_ymdhms(secs); + format!("{y:04}-{mo:02}-{d:02}") +} + +fn current_time_str() -> String { + use std::time::{SystemTime, UNIX_EPOCH}; + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let (_, _, _, h, min, s) = epoch_to_ymdhms(secs); + format!("{h:02}:{min:02}:{s:02}") +} + +pub fn epoch_to_ymdhms(now_secs: u64) -> (u64, u64, u64, u64, u64, u64) { + let secs_per_day = 86_400u64; + let days = now_secs / secs_per_day; + let day_secs = now_secs % secs_per_day; + + let mut d = days; + let mut y = 1970u64; + loop { + let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); + let days_in_year = if leap { 366 } else { 365 }; + if d < days_in_year { + break; + } + d -= days_in_year; + y += 1; + } + let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0); + let days_in_month = [ + 31u64, + if leap { 29 } else { 28 }, + 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, + ]; + let mut mo = 0usize; + while mo < 12 && d >= days_in_month[mo] { + d -= days_in_month[mo]; + mo += 1; + } + + ( + y, + (mo + 1) as u64, + d + 1, + day_secs / 3600, + (day_secs % 3600) / 60, + day_secs % 60, + ) +} diff --git a/src-tauri/src/state/log_watcher.rs b/src-tauri/src/state/log_watcher.rs deleted file mode 100644 index c193f33..0000000 --- a/src-tauri/src/state/log_watcher.rs +++ /dev/null @@ -1,43 +0,0 @@ -use std::collections::HashMap; -use std::sync::{ - atomic::{AtomicBool, Ordering}, - Arc, -}; -use tokio::sync::Mutex; - -/// Tracks active log-tail tasks keyed by server UUID. -/// Each value is a shared flag; setting it to `true` signals the background -/// task to stop polling the file. -pub struct LogWatcherState { - pub tokens: Mutex>>, -} - -impl LogWatcherState { - pub fn new() -> Self { - Self { - tokens: Mutex::new(HashMap::new()), - } - } - - /// Create a fresh stop-flag for `server_id`, cancelling the previous one - /// if it existed. Returns the new flag for the spawned task to poll. - pub async fn start(&self, server_id: &str) -> Arc { - let flag = Arc::new(AtomicBool::new(false)); - if let Some(old) = self - .tokens - .lock() - .await - .insert(server_id.to_string(), flag.clone()) - { - old.store(true, Ordering::Relaxed); - } - flag - } - - /// Signal the watcher for `server_id` to stop and remove it from the map. - pub async fn stop(&self, server_id: &str) { - if let Some(flag) = self.tokens.lock().await.remove(server_id) { - flag.store(true, Ordering::Relaxed); - } - } -} diff --git a/src-tauri/src/state/mod.rs b/src-tauri/src/state/mod.rs index 854d1f4..40b5398 100644 --- a/src-tauri/src/state/mod.rs +++ b/src-tauri/src/state/mod.rs @@ -1,4 +1,4 @@ -pub mod log_watcher; +pub mod log_manager; pub mod rcon_pool; pub mod scheduler; pub mod stats_recorder; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f4e6874..1194aab 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.11.0", + "version": "0.12.0", "identifier": "xyz.lokisoft.lokiasam", "build": { "frontendDist": "../out", diff --git a/src/app/backups/page.tsx b/src/app/backups/page.tsx new file mode 100644 index 0000000..aa4975d --- /dev/null +++ b/src/app/backups/page.tsx @@ -0,0 +1,124 @@ +"use client"; + +import { useState, useEffect, useCallback } from "react"; +import { useSearchParams, useRouter } from "next/navigation"; +import { Archive, ChevronDown } from "lucide-react"; +import { useServers } from "@/hooks/useServers"; +import { BackupsTab } from "@/components/server/tabs/BackupsTab"; +import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import type { ServerRow } from "@/lib/db"; + +export default function BackupsPage() { + const searchParams = useSearchParams(); + const router = useRouter(); + const { data: servers = [], isLoading } = useServers(); + + const [selectedId, setSelectedId] = useState( + searchParams.get("server") ?? "" + ); + + useEffect(() => { + if (!selectedId && servers.length > 0) { + setSelectedId(servers[0].id); + } + }, [servers, selectedId]); + + const selectedServer: ServerRow | undefined = servers.find( + (s) => s.id === selectedId + ); + + const handleSelect = (id: string) => { + setSelectedId(id); + const url = new URL(window.location.href); + url.searchParams.set("server", id); + router.replace(url.pathname + url.search); + }; + + return ( +
+ {/* Page header */} +
+ +

+ Backups +

+
+ + {/* Server selector */} +
+ + Server: + + + {isLoading ? ( +
+ ) : servers.length === 0 ? ( + + No servers configured + + ) : ( +
+ + +
+ )} + + {selectedServer && ( +
+ + + Port {selectedServer.port} + +
+ )} +
+ + {/* Backup content */} + {selectedServer ? ( +
+ +
+ ) : !isLoading && servers.length === 0 ? ( +
+ +

+ No servers yet +

+

+ Add a server from the Dashboard to start using backups. +

+
+ ) : null} +
+ ); +} diff --git a/src/app/clusters/detail/page.tsx b/src/app/clusters/detail/page.tsx index 09b312f..71a624a 100644 --- a/src/app/clusters/detail/page.tsx +++ b/src/app/clusters/detail/page.tsx @@ -296,8 +296,8 @@ function ClusterDetailContent() {
@@ -333,7 +333,7 @@ function ClusterDetailContent() { style={{ background: "rgba(0,0,0,0.3)", color: "var(--neon-cyan)", - border: "1px solid rgba(0,255,255,0.15)", + border: "1px solid rgba(var(--neon-purple-rgb),0.15)", }} > {cluster.id} diff --git a/src/app/clusters/page.tsx b/src/app/clusters/page.tsx index f4b5903..ffc81f9 100644 --- a/src/app/clusters/page.tsx +++ b/src/app/clusters/page.tsx @@ -237,8 +237,8 @@ function ClusterCard({ cluster, onDelete }: ClusterCardProps) {
@@ -317,12 +317,15 @@ export default function ClustersPage() { {/* Header */}
-

- Clusters -

+
+ +

+ Clusters +

+

Group servers for cross-ARK travel and shared data.

diff --git a/src/app/globals.css b/src/app/globals.css index 409bbf6..93fd26f 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -35,11 +35,11 @@ /* Primary — drives shadcn Switch checked state, focus rings, etc. Overridden at runtime by applyThemeAccent() to match the chosen accent. */ - --color-primary: #bf00ff; + --color-primary: var(--neon-purple); --color-primary-foreground: #050510; --color-input: rgba(var(--neon-purple-rgb), 0.2); - --color-ring: #bf00ff; - --color-muted: rgba(10, 10, 30, 0.75); + --color-ring: var(--neon-purple); + --color-muted: rgba(20, 20, 52, 0.85); --color-muted-foreground: #5858a0; /* Fonts */ @@ -55,49 +55,49 @@ CSS Custom Properties (design tokens) --------------------------------------------------------------------------- */ :root { - /* Backgrounds */ - --background: #050510; - --surface: rgba(10, 10, 30, 0.75); - --surface-elevated: rgba(15, 15, 40, 0.9); + /* Backgrounds — defaults match storm preset */ + --background: #0e1018; + --surface: rgba(18, 22, 35, 0.8); + --surface-elevated: rgba(24, 28, 44, 0.9); --terminal-bg: #000008; - /* Accent RGB components — updated by applyThemeAccent() so all rgba() uses track the active color */ - --neon-purple-rgb: 191, 0, 255; + /* Accent RGB components — defaults match blue accent; updated by applyThemeAccent() */ + --neon-purple-rgb: 64, 128, 255; - /* Borders — purple is the primary accent */ - --border: rgba(191, 0, 255, 0.15); - --border-hover: rgba(191, 0, 255, 0.4); + /* Borders */ + --border: rgba(64, 128, 255, 0.15); + --border-hover: rgba(64, 128, 255, 0.4); - /* Neon colors */ + /* Neon colors — --neon-purple tracks the active accent */ --neon-cyan: #00ffff; - --neon-purple: #bf00ff; + --neon-purple: #4080ff; --neon-green: #00ff88; --neon-red: #ff0055; --neon-orange: #ff8800; - /* Text */ + /* Text — defaults match storm preset */ --foreground: #e0e0ff; --text-primary: #e0e0ff; - --text-muted: #5858a0; - --text-subtle: #3a3a70; + --text-muted: #606880; + --text-subtle: #464e64; /* Glow shadows (used in box-shadow) */ --glow-cyan: 0 0 8px rgba(0,255,255,0.6), 0 0 24px rgba(0,255,255,0.2); - --glow-purple: 0 0 8px rgba(191,0,255,0.6), 0 0 24px rgba(191,0,255,0.2); + --glow-purple: 0 0 8px rgba(64,128,255,0.6), 0 0 24px rgba(64,128,255,0.2); --glow-green: 0 0 8px rgba(0,255,136,0.6), 0 0 24px rgba(0,255,136,0.2); --glow-red: 0 0 8px rgba(255,0,85,0.6), 0 0 24px rgba(255,0,85,0.2); - /* Card glass — purple-tinted borders */ - --glass-bg: rgba(10, 10, 35, 0.6); - --glass-border: rgba(191, 0, 255, 0.12); + /* Card glass */ + --glass-bg: rgba(18, 22, 38, 0.65); + --glass-border: rgba(64, 128, 255, 0.12); --glass-blur: 12px; /* Popover / dropdown surface */ - --popover: #0c0c20; + --popover: #12161e; --popover-foreground: #e0e0ff; - /* Accent — subtle purple highlight for menu item hover/focus */ - --accent: rgba(191, 0, 255, 0.15); + /* Accent — subtle highlight for menu item hover/focus */ + --accent: rgba(64, 128, 255, 0.15); --accent-foreground: #e0e0ff; } diff --git a/src/app/logs/page.tsx b/src/app/logs/page.tsx new file mode 100644 index 0000000..4aea937 --- /dev/null +++ b/src/app/logs/page.tsx @@ -0,0 +1,124 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { useSearchParams, useRouter } from "next/navigation"; +import { ScrollText, ChevronDown } from "lucide-react"; +import { useServers } from "@/hooks/useServers"; +import { LogsTab } from "@/components/server/tabs/LogsTab"; +import { ServerStatusBadge } from "@/components/server/ServerStatusBadge"; +import type { ServerRow } from "@/lib/db"; + +export default function LogsPage() { + const searchParams = useSearchParams(); + const router = useRouter(); + const { data: servers = [], isLoading } = useServers(); + + const [selectedId, setSelectedId] = useState( + searchParams.get("server") ?? "" + ); + + useEffect(() => { + if (!selectedId && servers.length > 0) { + setSelectedId(servers[0].id); + } + }, [servers, selectedId]); + + const selectedServer: ServerRow | undefined = servers.find( + (s) => s.id === selectedId + ); + + const handleSelect = (id: string) => { + setSelectedId(id); + const url = new URL(window.location.href); + url.searchParams.set("server", id); + router.replace(url.pathname + url.search); + }; + + return ( +
+ {/* ── Page header ── */} +
+ +

+ Logs +

+
+ + {/* ── Server selector ── */} +
+ + Server: + + + {isLoading ? ( +
+ ) : servers.length === 0 ? ( + + No servers configured + + ) : ( +
+ + +
+ )} + + {selectedServer && ( +
+ + + Port {selectedServer.port} + +
+ )} +
+ + {/* ── Log viewer — fills remaining height ── */} + {selectedServer ? ( +
+ +
+ ) : !isLoading && servers.length === 0 ? ( +
+ +

+ No servers yet +

+

+ Add a server from the Dashboard to start viewing logs. +

+
+ ) : null} +
+ ); +} diff --git a/src/app/notifications/page.tsx b/src/app/notifications/page.tsx index a61f6bf..b17fe8a 100644 --- a/src/app/notifications/page.tsx +++ b/src/app/notifications/page.tsx @@ -89,9 +89,9 @@ function NotificationRow({ style={{ borderColor: "var(--border)", background: highlighted - ? "rgba(191,0,255,0.12)" + ? "rgba(var(--neon-purple-rgb),0.12)" : "transparent", - outline: highlighted ? "1px solid rgba(191,0,255,0.4)" : "none", + outline: highlighted ? "1px solid rgba(var(--neon-purple-rgb),0.4)" : "none", }} > @@ -224,12 +224,15 @@ function NotificationsContent() { {/* Header */}
-

- Notifications -

+
+ +

+ Notifications +

+

Event log for all managed servers.

diff --git a/src/app/page.tsx b/src/app/page.tsx index 4087af6..eafc485 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,16 +1,26 @@ "use client"; -import { useEffect, useState, useCallback } from "react"; -import { Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, ArrowUp, CheckCircle2, Loader2 } from "lucide-react"; +import { useEffect, useState, useCallback, useRef } from "react"; +import { + Plus, Server, Activity, PowerOff, Power, RefreshCw, Upload, + ArrowUp, Loader2, CheckCircle2, AlertTriangle, LayoutDashboard, +} from "lucide-react"; import { Button } from "@/components/ui/button"; import { Skeleton } from "@/components/ui/skeleton"; +import { Switch } from "@/components/ui/switch"; +import { Label } from "@/components/ui/label"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; import { StatCard } from "@/components/shared/StatCard"; import { ServerCard } from "@/components/server/ServerCard"; import { ImportServerWizard } from "@/components/server/ImportServerWizard"; import { useServers } from "@/hooks/useServers"; -import { getAppSetting, setAppSetting } from "@/lib/db"; +import { getAppSetting, setAppSetting, updateServerStatus } from "@/lib/db"; import { tauriCmd, type UpdateCheckResult } from "@/lib/tauri-commands"; -import { runPerServerUpdateCheck } from "@/lib/update-utils"; +import { runPerServerUpdateCheck, applyUpdateToServer, type ServerUpdateInfo } from "@/lib/update-utils"; +import { buildStartParams } from "@/lib/server-utils"; import { dispatchNotification } from "@/lib/notifications"; import { NOTIFICATION_EVENTS } from "@/data/game-data"; import { useQueryClient } from "@tanstack/react-query"; @@ -19,32 +29,33 @@ import { useTauriEvent } from "@/hooks/useTauriEvent"; import { toast } from "sonner"; // --------------------------------------------------------------------------- -// Update status chip +// UpdateStatusChip — Check for Updates button + post-check dialogs // --------------------------------------------------------------------------- -function UpdateStatusChip() { - const [checking, setChecking] = useState(false); - const [updateAvailable, setUpdateAvailable] = useState(false); - const [cachedBuild, setCachedBuild] = useState(""); +interface UpdateStatusChipProps { + servers: ReturnType["data"]; + onUpdateAllClick: () => void; + onUpdatesFound: (updates: ServerUpdateInfo[]) => void; +} + +function UpdateStatusChip({ servers = [], onUpdateAllClick, onUpdatesFound }: UpdateStatusChipProps) { + const queryClient = useQueryClient(); + const [checking, setChecking] = useState(false); const [latestBuild, setLatestBuild] = useState(""); - const [lastChecked, setLastChecked] = useState(""); + const [cachedBuild, setCachedBuild] = useState(""); const load = useCallback(async () => { - const [avail, cached, latest, checked] = await Promise.all([ - getAppSetting("asa_update_available"), + const [cached, latest] = await Promise.all([ getAppSetting("asa_cached_build_id"), getAppSetting("asa_latest_build_id"), - getAppSetting("asa_last_checked"), ]); - setUpdateAvailable(avail === "true"); setCachedBuild(cached ?? ""); setLatestBuild(latest ?? ""); - setLastChecked(checked ?? ""); }, []); useEffect(() => { load(); }, [load]); - // Listen for background check results fired from the Rust scheduler. + // Background check result — refresh state + run per-server check (with toasts). useTauriEvent("asa://update-check", async (payload) => { if ("updateApplied" in payload && payload.updateApplied) { await setAppSetting("asa_update_available", "false"); @@ -60,9 +71,9 @@ function UpdateStatusChip() { await setAppSetting("asa_latest_build_id", r.latestBuildId); await setAppSetting("asa_last_checked", now); load(); - // Always run per-server check — a server may be behind the cache even - // if the cache itself is current (e.g. server was never updated). - await runPerServerUpdateCheck(); + // Background check: toasts fire per-server, no dialog. + await runPerServerUpdateCheck(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); } }); @@ -77,134 +88,454 @@ function UpdateStatusChip() { toast.error("Base directory or SteamCMD not configured."); return; } - const sep = baseDir.includes("\\") ? "\\" : "/"; + const sep = baseDir.includes("\\") ? "\\" : "/"; const cacheDir = `${baseDir.replace(/[/\\]$/, "")}${sep}lokiasam${sep}cache${sep}asa-server`; const oldBuild = await getAppSetting("asa_cached_build_id") ?? ""; const newBuild = await tauriCmd.updateCache("check", cacheDir, steamcmdPath); - const now = new Date().toISOString(); - const cacheUpdated = !!newBuild && newBuild !== oldBuild; + const now = new Date().toISOString(); await Promise.all([ setAppSetting("asa_cached_build_id", newBuild), setAppSetting("asa_latest_build_id", newBuild), setAppSetting("asa_last_checked", now), ]); - await runPerServerUpdateCheck(); + // Manual check: silent mode suppresses per-server toasts; we show dialog. + const summary = await runPerServerUpdateCheck(true); + queryClient.invalidateQueries({ queryKey: ["servers"] }); load(); - if (cacheUpdated) { + + if (summary.allWithUpdates.length > 0) { + // Show the updates-found dialog to the user. + onUpdatesFound(summary.allWithUpdates); + } else { + toast.success("All servers are up to date."); + } + + // Only notify Discord/email if the cache actually changed. + if (newBuild && newBuild !== oldBuild) { await dispatchNotification({ eventType: NOTIFICATION_EVENTS.UPDATE_AVAILABLE, serverId: null, serverName: "ASA Cache", title: "Cache Updated", - body: `Cache updated to build ${newBuild}. Outdated servers have been flagged.`, + body: `Cache updated to build ${newBuild}. Check for server updates.`, severity: "info", }); - } else { - toast.success(`Cache is up to date (build ${newBuild}).`); } } catch (e) { - await dispatchNotification({ - eventType: NOTIFICATION_EVENTS.UPDATE_FAILED, - serverId: null, - serverName: "ASA Cache", - title: "Cache Update Failed", - body: `Failed to update cache: ${e}`, - severity: "error", - }); + toast.error("Update check failed", { description: String(e) }); } finally { setChecking(false); } }; - const busy = checking; - const neverChecked = !lastChecked; + const serversWithUpdates = (servers ?? []).filter((s) => s.update_available === 1); + const anyStarting = (servers ?? []).some( + (s) => s.update_available === 1 && s.status === "starting" + ); return (
- {updateAvailable ? ( -
0 && ( +
- ) : !neverChecked ? ( -
- - Up to date -
- ) : null} + Update All ({serversWithUpdates.length}) + + )}
); } -export default function DashboardPage() { +// --------------------------------------------------------------------------- +// UpdatesFoundDialog — shown after manual "Check for Updates" finds results +// --------------------------------------------------------------------------- +interface UpdatesFoundDialogProps { + open: boolean; + onOpenChange: (v: boolean) => void; + updates: ServerUpdateInfo[]; + onUpdateAll: (restartAfterUpdate: boolean) => void; +} + +function UpdatesFoundDialog({ open, onOpenChange, updates, onUpdateAll }: UpdatesFoundDialogProps) { + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const anyRunning = updates.some((s) => s.status === "running"); + const anyStarting = updates.some((s) => s.status === "starting"); + + return ( + + + + + + {updates.length === 1 ? "Update Available" : `${updates.length} Updates Available`} + + + The following servers have updates ready to apply from the shared cache. + + + + {/* Server list */} +
+ {updates.map((s) => ( +
+
+ {s.name} + {s.installedBuild !== "unknown" && ( + + {s.installedBuild} → {s.cachedBuild} + + )} +
+ + {s.status} + +
+ ))} +
+ + {/* Warnings */} + {anyRunning && ( +
+ + Running servers will be stopped to apply the update. +
+ )} + {anyStarting && ( +
+ + One or more servers are currently starting. Their startup will be cancelled to apply the update. +
+ )} + + {/* Restart toggle */} + {(anyRunning || anyStarting) && ( +
+ + +
+ )} + + + + + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// UpdateAllDialog — confirmation before applying updates from the header button +// --------------------------------------------------------------------------- + +interface UpdateAllDialogProps { + open: boolean; + onOpenChange: (v: boolean) => void; + updates: ServerUpdateInfo[]; + anyStarting: boolean; + onConfirm: (restartAfterUpdate: boolean) => void; +} + +function UpdateAllDialog({ open, onOpenChange, updates, anyStarting, onConfirm }: UpdateAllDialogProps) { + const [restartAfterUpdate, setRestartAfterUpdate] = useState(true); + const anyRunning = updates.some((s) => s.status === "running"); + + return ( + + + + + + Update All Servers + + + Updates will be applied sequentially from the shared cache. + + + +
+ {updates.map((s) => ( +
+
+ {s.name} + {s.installedBuild !== "unknown" && ( + + {s.installedBuild} → {s.cachedBuild} + + )} +
+ + {s.status} + +
+ ))} +
+ + {anyRunning && ( +
+ + Running servers will be stopped to apply the update. +
+ )} + {anyStarting && ( +
+ + One or more servers are currently starting. Their startup will be cancelled to apply the update. +
+ )} + + {(anyRunning || anyStarting) && ( +
+ + +
+ )} + + + + + +
+
+ ); +} + +// --------------------------------------------------------------------------- +// DashboardPage +// --------------------------------------------------------------------------- + +export default function DashboardPage() { const { data: servers = [], isLoading } = useServers(); - const { setShowNewServerWizard } = useAppStore(); - const [showImport, setShowImport] = useState(false); + const { setShowNewServerWizard, enqueueStartup } = useAppStore(); + const [showImport, setShowImport] = useState(false); + const [showUpdateAllDialog, setShowUpdateAllDialog] = useState(false); + const [showUpdatesFoundDialog, setShowUpdatesFoundDialog] = useState(false); + const [pendingUpdates, setPendingUpdates] = useState([]); + const [updatingAll, setUpdatingAll] = useState(false); const queryClient = useQueryClient(); const total = servers.length; const running = servers.filter((s) => s.status === "running").length; const stopped = total - running; + // Build the ServerUpdateInfo list from the live servers data. + const serversWithUpdates: ServerUpdateInfo[] = servers + .filter((s) => s.update_available === 1) + .map((s) => ({ + id: s.id, + name: s.name, + status: s.status, + installedBuild: "—", + cachedBuild: "—", + })); + + const anyUpdatesStarting = serversWithUpdates.some((s) => s.status === "starting"); + + // ── Update All handler ──────────────────────────────────────────────────── + + const runUpdateAll = useCallback(async (restartAfterUpdate: boolean) => { + if (updatingAll) return; + setUpdatingAll(true); + + const targets = servers.filter((s) => s.update_available === 1); + if (targets.length === 0) { setUpdatingAll(false); return; } + + try { + // First: mark all targets with their initial status. + // Active server = first in list → "updating" + // Rest → "update_queued" + const [first, ...rest] = targets; + + if (rest.length > 0) { + await Promise.all( + rest.map((s) => updateServerStatus(s.id, "update_queued", null)) + ); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + // Process sequentially + for (const server of targets) { + await updateServerStatus(server.id, "updating", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + const wasRunning = server.status === "running" || server.status === "starting"; + + try { + await applyUpdateToServer( + server.id, + server.name, + server.install_path, + wasRunning, + restartAfterUpdate, + (msg) => toast.info(msg, { id: `update-${server.id}` }), + ); + } catch (err) { + if (err && typeof err === "object" && "restartNeeded" in err) { + // Queue this server for startup after update + await updateServerStatus(server.id, "startup_queued", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + const serverData = servers.find((s) => s.id === server.id); + if (serverData) enqueueStartup([serverData.id]); + continue; + } + toast.error(`Failed to update ${server.name}`, { description: String(err) }); + await updateServerStatus(server.id, "stopped", null).catch(() => {}); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + await updateServerStatus(server.id, "stopped", null).catch(() => {}); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + toast.success(`Updated ${targets.length} server${targets.length === 1 ? "" : "s"} successfully.`); + } finally { + setUpdatingAll(false); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + }, [servers, updatingAll, queryClient, enqueueStartup]); + return (
{/* ── Page header ── */}
-

- Server Dashboard -

+
+ +

+ Server Dashboard +

+

Manage your Ark Survival Ascended dedicated servers.

- + setShowUpdateAllDialog(true)} + onUpdatesFound={(updates) => { + setPendingUpdates(updates); + setShowUpdatesFoundDialog(true); + }} + />
)} @@ -313,6 +625,23 @@ export default function DashboardPage() { }} /> )} + + {/* ── Update All confirmation dialog (from header button) ── */} + + + {/* ── Updates found dialog (after manual Check for Updates) ── */} +
); } diff --git a/src/app/servers/detail/page.tsx b/src/app/servers/detail/page.tsx index 4ca5642..c8885d3 100644 --- a/src/app/servers/detail/page.tsx +++ b/src/app/servers/detail/page.tsx @@ -128,7 +128,7 @@ export default function ServerDetailPage() { // When the RCON tab is active the root div fills main's content area exactly // so the log scrolls internally without creating a page-level scrollbar. // Other tabs keep normal flow (gap-6, no height constraint). -
+
{/* ── Header ── */}
{/* ── Tab content ── */} - {activeTab === "rcon" ? ( - // flex-1 min-h-0: fills the remaining height in the h-full flex container - // without overflowing. The RconConsole scrolls the log internally. + {(activeTab === "rcon" || activeTab === "logs" || activeTab === "mods") ? (
- + {activeTab === "rcon" && } + {activeTab === "logs" && } + {activeTab === "mods" && }
) : (
- {activeTab === "overview" && } - {activeTab === "config" && } - {activeTab === "logs" && } - {activeTab === "mods" && } - {activeTab === "backups" && } + {activeTab === "overview" && } + {activeTab === "config" && } + {activeTab === "backups" && } {activeTab === "automation" && }
)} diff --git a/src/app/settings/page.tsx b/src/app/settings/page.tsx index fe28e11..9fb93c8 100644 --- a/src/app/settings/page.tsx +++ b/src/app/settings/page.tsx @@ -2,16 +2,19 @@ import { useState, useEffect, useCallback } from "react"; import { - Folder, Terminal, Info, + Folder, Terminal, Info, Archive, FolderOpen, CheckCircle2, AlertCircle, Loader2, Save, RefreshCw, ArrowUp, Bell, MessageSquare, Mail, Monitor, Send, Download, - Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, + Server, Palette, Link, StopCircle, ToggleLeft, ToggleRight, Layers, Power, ShieldCheck, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Separator } from "@/components/ui/separator"; +import { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from "@/components/ui/select"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, @@ -27,7 +30,9 @@ import { import { runPerServerUpdateCheck, applyUpdateToServer } from "@/lib/update-utils"; import { check } from "@tauri-apps/plugin-updater"; import { getVersion } from "@tauri-apps/api/app"; -import { tauriCmd, type DirCheckResult, type ProtonUpdateInfo, type MigrateProgress } from "@/lib/tauri-commands"; +import { tempDir } from "@tauri-apps/api/path"; +import { tauriCmd, type DirCheckResult, type ProtonUpdateInfo, type MigrateProgress, type PortDef, type FirewallStatus } from "@/lib/tauri-commands"; +import { getServerFirewallPorts } from "@/lib/firewall-utils"; import { listen } from "@tauri-apps/api/event"; import { applyTheme, applyThemeAccent, applyThemePreset, @@ -81,6 +86,52 @@ function Section({ ); } +function BackupSettingsSection() { + const [dismissed, setDismissed] = useState(null); + + useEffect(() => { + getAppSetting("full_backup_warning_dismissed").then( + (v) => setDismissed(v === "true") + ).catch(() => setDismissed(false)); + }, []); + + const toggle = async () => { + const next = !dismissed; + setDismissed(next); + try { + await setAppSetting("full_backup_warning_dismissed", String(next)); + } catch (e) { + toast.error(`Failed to save backup setting: ${e}`); + setDismissed(!next); + } + }; + + return ( +
+
+
+

+ Hide full backup warning +

+

+ When enabled, the size warning dialog is skipped when triggering a full backup. +

+
+ {dismissed === null ? ( +
+ ) : ( + + )} +
+
+ ); +} + // --------------------------------------------------------------------------- // Icon-based toggle (matches the wizard's ToggleRow style) // --------------------------------------------------------------------------- @@ -266,7 +317,7 @@ function BaseDirMigrationSection() { )} @@ -343,7 +394,7 @@ function PathField({ @@ -804,7 +855,7 @@ function ServerUpdatesSection() { {AUTO_CHECK_OPTIONS.map((opt) => (
@@ -969,8 +1020,8 @@ function SteamcmdReinstallRow() { )} +
+ {phase === "error" && ( +

+ {error} +

+ )} +
+ ); +} + +// --------------------------------------------------------------------------- +// Firewall check/repair row +// --------------------------------------------------------------------------- + +function FirewallRepairRow() { + const [phase, setPhase] = useState<"idle" | "checking" | "ready" | "error">("idle"); + const [isFixing, setIsFixing] = useState(false); + const [fwStatus, setFwStatus] = useState(null); + const [error, setError] = useState(""); + + const runCheck = async () => { + setError(""); + setPhase("checking"); + try { + const servers = await getServers(); + const seen = new Map(); + for (const srv of servers) { + for (const p of getServerFirewallPorts(srv)) { + seen.set(`${p.port}/${p.protocol}`, p); + } + } + const allPorts = [...seen.values()]; + if (allPorts.length === 0) { + setFwStatus({ firewallType: "none", active: false, ports: [] }); + setPhase("ready"); + return; + } + const result = await tauriCmd.checkFirewallPorts(allPorts); + setFwStatus(result); + setPhase("ready"); + } catch (e) { + setError(String(e)); + setPhase("error"); + } + }; + + const handleFix = async () => { + if (!fwStatus) return; + const missingPorts: PortDef[] = fwStatus.ports + .filter((p) => !p.covered) + .map((p) => ({ port: p.port, protocol: p.protocol as "tcp" | "udp" })); + setIsFixing(true); + try { + const protonPath = IS_LINUX ? (await getAppSetting("proton_path")) ?? undefined : undefined; + await tauriCmd.addFirewallRules(missingPorts, protonPath); + toast.success("Firewall rules added."); + await runCheck(); + } catch (e) { + setError(String(e)); + setPhase("error"); + toast.error(`Failed to add firewall rules: ${e}`); + } finally { + setIsFixing(false); + } + }; + + const missing = fwStatus?.ports.filter((p) => !p.covered) ?? []; + const allGood = fwStatus !== null && (!fwStatus.active || missing.length === 0); + const busy = phase === "checking" || isFixing; + + return ( +
+
+
+

Firewall Rules

+

+ Check and repair port rules for all configured servers. +

+
+ +
+ + {phase === "ready" && fwStatus && ( +
+ {!fwStatus.active ? ( +

+ + No active firewall detected — nothing to do. +

+ ) : fwStatus.ports.length === 0 ? ( +

No servers configured.

+ ) : ( + <> + {fwStatus.ports.map((p) => ( +

+ {p.covered + ? + : } + {p.port}/{p.protocol.toUpperCase()} — {p.covered ? "allowed" : "missing"} +

+ ))} + {missing.length > 0 && ( + + )} + + )} +
+ )} + + {phase === "error" && ( +

{error}

+ )} +
+ ); +} + // --------------------------------------------------------------------------- // Proton-GE Update section (Linux only) // --------------------------------------------------------------------------- @@ -1090,8 +1363,8 @@ function ProtonGeUpdateSection() { {updateInfo && !downloadDone && (
{updateInfo.currentVersion ? (
@@ -1116,7 +1389,7 @@ function ProtonGeUpdateSection() { {/* Action buttons */}
@@ -1124,8 +1397,8 @@ function ProtonGeUpdateSection() { {(updateInfo?.updateAvailable || (!protonPath && updateInfo)) && (isManaged || !looksExternal) && ( - - {runningCount > 0 ? `${runningCount} server${runningCount !== 1 ? "s" : ""} running` : "No servers running"} - + Quick Start Guide
+ + {/* Bottom nav items (Notifications + Settings pinned to bottom) */} +
+ {BOTTOM_NAV.map((item) => ( + + ))} +
+ + + {tourOpen && createPortal( + setTourOpen(false)} />, + document.body + )} + ); } diff --git a/src/components/layout/StartupQueueManager.tsx b/src/components/layout/StartupQueueManager.tsx new file mode 100644 index 0000000..4aac505 --- /dev/null +++ b/src/components/layout/StartupQueueManager.tsx @@ -0,0 +1,103 @@ +"use client"; + +/** + * StartupQueueManager — processes the startup queue sequentially. + * + * Watches the server list and the Zustand startupQueue. When no server is + * currently in the "starting" state and the queue is non-empty, it pops the + * next server and starts it. This ensures servers are started one at a time + * to avoid overloading the host machine. + * + * Queue entries have status = "startup_queued" in the DB so the badge shows. + * When a server is manually started by the user it bypasses this queue entirely. + */ + +import { useEffect, useRef } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useServers } from "@/hooks/useServers"; +import { useAppStore } from "@/store/useAppStore"; +import { getServer, updateServerStatus } from "@/lib/db"; +import { tauriCmd } from "@/lib/tauri-commands"; +import { buildStartParams } from "@/lib/server-utils"; +import { warnIfFirewallMissing } from "@/lib/firewall-utils"; +import { dispatchNotification } from "@/lib/notifications"; +import { NOTIFICATION_EVENTS } from "@/data/game-data"; +import { toast } from "sonner"; + +export function StartupQueueManager() { + const queryClient = useQueryClient(); + const { data: servers = [] } = useServers(); + const startupQueue = useAppStore((s) => s.startupQueue); + const dequeueNextStartup = useAppStore((s) => s.dequeueNextStartup); + const setNoRetryServer = useAppStore((s) => s.setNoRetryServer); + const startingRef = useRef(false); + + useEffect(() => { + // Guard: don't start another server while one is already starting, + // or if the queue is empty. + const anyStarting = servers.some((s) => s.status === "starting"); + if (anyStarting || startupQueue.length === 0 || startingRef.current) return; + + const nextId = startupQueue[0]; + + // Quick cache check: if the server has been fully deleted, skip immediately. + if (servers.length > 0 && !servers.find((s) => s.id === nextId)) { + dequeueNextStartup(); + return; + } + + startingRef.current = true; + dequeueNextStartup(); + + (async () => { + try { + // Read authoritative status from DB — the TanStack cache may still be + // stale when enqueueStartup fires immediately after a DB write, causing + // the cache-based status check to see "stopped" and silently skip the server. + const server = await getServer(nextId); + + if (!server || server.status !== "startup_queued") { + // Server was cancelled or doesn't exist — skip without error. + return; + } + + await updateServerStatus(server.id, "starting", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + await warnIfFirewallMissing(server); + const params = await buildStartParams(server); + const pid = await tauriCmd.startServer(params); + + await updateServerStatus(server.id, "starting", pid); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } catch (err) { + const raw = typeof err === "string" ? err : String(err); + const isExeMissing = raw.startsWith("exe_missing:"); + const userMsg = isExeMissing ? raw.slice("exe_missing: ".length) : raw; + + // Re-read name for the error notification since we may not have `server` in scope. + const serverName = servers.find((s) => s.id === nextId)?.name ?? nextId; + + if (isExeMissing) setNoRetryServer(nextId); + + await updateServerStatus(nextId, "start-failed", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + + toast.error(`${serverName} failed to start`, { description: userMsg }); + dispatchNotification({ + eventType: NOTIFICATION_EVENTS.SERVER_START_FAILED, + serverId: nextId, + serverName, + title: `${serverName} failed to start`, + body: userMsg, + severity: "error", + }); + } finally { + startingRef.current = false; + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + })(); + }, [servers, startupQueue, dequeueNextStartup, queryClient, setNoRetryServer]); + + return null; +} diff --git a/src/components/layout/StartupReconciliationManager.tsx b/src/components/layout/StartupReconciliationManager.tsx index 9f49e7e..78a9e0e 100644 --- a/src/components/layout/StartupReconciliationManager.tsx +++ b/src/components/layout/StartupReconciliationManager.tsx @@ -8,14 +8,23 @@ import { tauriCmd } from "@/lib/tauri-commands"; export function StartupReconciliationManager() { const queryClient = useQueryClient(); - const { setIsServerScanPending } = useAppStore(); + const { setIsServerScanPending, setPreScanStatuses } = useAppStore(); useEffect(() => { - setIsServerScanPending(true); (async () => { + // Always capture pre-scan statuses and mark the scan complete, even on error. + // StartupRecoveryManager waits for preScanStatuses to be set before it runs. + let servers: Awaited> = []; try { - const servers = await getServers(); + servers = await getServers(); + } catch { + // DB unavailable — proceed with empty snapshot + } + + setPreScanStatuses(Object.fromEntries(servers.map((s) => [s.id, s.status]))); + setIsServerScanPending(true); + try { if (!servers.length) return; const entries = servers.map((s) => ({ serverId: s.id, installPath: s.install_path })); @@ -27,6 +36,10 @@ export function StartupReconciliationManager() { return; } + // States that StartupRecoveryManager handles after the scan — skip them here + // so they aren't wiped by the reconciliation. + const QUEUE_STATES = new Set(["startup_queued", "update_queued"]); + await Promise.all( results.map(async (r) => { const current = servers.find((s) => s.id === r.serverId); @@ -37,7 +50,7 @@ export function StartupReconciliationManager() { await updateServerStatus(r.serverId, "running", r.pid); } } else { - if (current.status !== "stopped") { + if (current.status !== "stopped" && !QUEUE_STATES.has(current.status)) { await updateServerStatus(r.serverId, "stopped", null); } } diff --git a/src/components/layout/StartupRecoveryManager.tsx b/src/components/layout/StartupRecoveryManager.tsx new file mode 100644 index 0000000..f4d257b --- /dev/null +++ b/src/components/layout/StartupRecoveryManager.tsx @@ -0,0 +1,183 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; +import { ToggleLeft, ToggleRight } from "lucide-react"; +import { useAppStore } from "@/store/useAppStore"; +import { + getServers, getAppSetting, setAppSetting, updateServerStatus, + type ServerRow, +} from "@/lib/db"; +import { applyUpdateToServer } from "@/lib/update-utils"; +import { + Dialog, DialogContent, DialogDescription, + DialogFooter, DialogHeader, DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; + +export function StartupRecoveryManager() { + const queryClient = useQueryClient(); + const isServerScanPending = useAppStore((s) => s.isServerScanPending); + const preScanStatuses = useAppStore((s) => s.preScanStatuses); + const { enqueueStartup } = useAppStore(); + + const hasRunRef = useRef(false); + const [downedServers, setDownedServers] = useState([]); + const [showDownedDialog, setShowDownedDialog] = useState(false); + const [rememberChoice, setRememberChoice] = useState(false); + + useEffect(() => { + // Wait until reconciliation finishes and pre-scan data is available + if (isServerScanPending || hasRunRef.current || !preScanStatuses) return; + hasRunRef.current = true; + + (async () => { + const servers = await getServers(); + + // --- 1. Re-queue startup_queued servers -------------------------------- + const startupQueued = servers.filter((s) => s.status === "startup_queued"); + if (startupQueued.length > 0) { + enqueueStartup(startupQueued.map((s) => s.id)); + } + + // --- 2. Resume update_queued servers sequentially ---------------------- + const updateQueued = servers.filter((s) => s.status === "update_queued"); + if (updateQueued.length > 0) { + const count = updateQueued.length; + toast.info( + count === 1 + ? `Resuming update for ${updateQueued[0].name}…` + : `Resuming update queue for ${count} servers…`, + ); + (async () => { + for (const server of updateQueued) { + try { + await updateServerStatus(server.id, "updating", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + await applyUpdateToServer(server.id, server.name, server.install_path, false, false); + } catch { + // applyUpdateToServer already dispatches a failure notification + } + await updateServerStatus(server.id, "stopped", null); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + })(); + } + + // --- 3. Queue auto_start servers that are stopped ---------------------- + const autoStartStopped = servers.filter( + (s) => s.auto_start === 1 && s.status === "stopped", + ); + if (autoStartStopped.length > 0) { + for (const s of autoStartStopped) { + await updateServerStatus(s.id, "startup_queued", null); + } + enqueueStartup(autoStartStopped.map((s) => s.id)); + queryClient.invalidateQueries({ queryKey: ["servers"] }); + } + + // --- 4. Detect downed servers (were running/starting, now stopped, no auto_start) --- + const RUNNING_STATES = new Set(["running", "starting"]); + const downed = servers.filter( + (s) => + RUNNING_STATES.has(preScanStatuses[s.id] ?? "") && + s.status === "stopped" && + s.auto_start === 0, + ); + + if (downed.length === 0) return; + + const pref = (await getAppSetting("auto_restart_downed")) ?? "ask"; + + if (pref === "auto") { + await enqueueDownedServers(downed, enqueueStartup, queryClient); + } else if (pref === "ask") { + setDownedServers(downed); + setShowDownedDialog(true); + } + // pref === "never" → do nothing + })(); + }, [isServerScanPending, preScanStatuses]); // eslint-disable-line react-hooks/exhaustive-deps + + const handleLeaveOffline = async () => { + setShowDownedDialog(false); + if (rememberChoice) await setAppSetting("auto_restart_downed", "never"); + }; + + const handleRestartNow = async () => { + setShowDownedDialog(false); + if (rememberChoice) await setAppSetting("auto_restart_downed", "auto"); + await enqueueDownedServers(downedServers, enqueueStartup, queryClient); + }; + + return ( + + + + Servers Went Offline + + The following server{downedServers.length > 1 ? "s were" : " was"} running in your last + session but went offline while the app was closed. + + + +
    + {downedServers.map((s) => ( +
  • + {s.name} +
  • + ))} +
+ +
+

Remember my choice

+ +
+ + + + + +
+
+ ); +} + +async function enqueueDownedServers( + servers: ServerRow[], + enqueueStartup: (ids: string[]) => void, + queryClient: ReturnType, +) { + for (const s of servers) { + await updateServerStatus(s.id, "startup_queued", null); + } + enqueueStartup(servers.map((s) => s.id)); + queryClient.invalidateQueries({ queryKey: ["servers"] }); +} diff --git a/src/components/layout/TopBar.tsx b/src/components/layout/TopBar.tsx index c99b18e..93f56eb 100644 --- a/src/components/layout/TopBar.tsx +++ b/src/components/layout/TopBar.tsx @@ -18,9 +18,11 @@ export function TopBar() { return (
diff --git a/src/components/server/ImportServerWizard.tsx b/src/components/server/ImportServerWizard.tsx index 08d2dbb..c247af8 100644 --- a/src/components/server/ImportServerWizard.tsx +++ b/src/components/server/ImportServerWizard.tsx @@ -103,7 +103,7 @@ function Step1({ onDetected }: Step1Props) { onClick={handleScan} disabled={!path.trim() || scanning} className="gap-2" - style={{ background: "rgba(191,0,255,0.15)", border: "1px solid rgba(191,0,255,0.4)", color: "var(--neon-purple)" }} + style={{ background: "rgba(var(--neon-purple-rgb),0.15)", border: "1px solid rgba(var(--neon-purple-rgb),0.4)", color: "var(--neon-purple)" }} > {scanning ? : } Scan Folder @@ -205,7 +205,7 @@ function Step2({ installPath, detected, onBack, onImported }: Step2Props) { onClick={() => setMapId(m.id)} className="text-xs px-3 py-1.5 rounded-lg transition-all" style={{ - background: mapId === m.id ? "rgba(191,0,255,0.15)" : "transparent", + background: mapId === m.id ? "rgba(var(--neon-purple-rgb),0.15)" : "transparent", border: `1px solid ${mapId === m.id ? "var(--neon-purple)" : "var(--border)"}`, color: mapId === m.id ? "var(--neon-purple)" : "var(--text-muted)", }} @@ -252,7 +252,7 @@ function Step2({ installPath, detected, onBack, onImported }: Step2Props) {
A new RCON password will be generated. Save data, configs, and mods are left untouched — only a database record is created. @@ -296,12 +296,12 @@ export function ImportServerWizard({ onClose, onImported }: Props) {
{/* Header */}
@@ -326,7 +326,7 @@ export function ImportServerWizard({ onClose, onImported }: Props) {
= n ? "rgba(191,0,255,0.2)" : "rgba(255,255,255,0.04)", + background: step >= n ? "rgba(var(--neon-purple-rgb),0.2)" : "rgba(255,255,255,0.04)", border: `1px solid ${step >= n ? "var(--neon-purple)" : "var(--border)"}`, color: step >= n ? "var(--neon-purple)" : "var(--text-muted)", }} diff --git a/src/components/server/ServerActionMenu.tsx b/src/components/server/ServerActionMenu.tsx index 90f7df4..fa60dd8 100644 --- a/src/components/server/ServerActionMenu.tsx +++ b/src/components/server/ServerActionMenu.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import { MoreVertical, Trash2, Copy, FolderOpen, HardDrive, Loader2 } from "lucide-react"; import { DropdownMenu, @@ -22,6 +22,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { toast } from "sonner"; import { tauriCmd } from "@/lib/tauri-commands"; +import { ARK_MAPS } from "@/data/game-data"; import { deleteServerRecord, createServer, @@ -35,10 +36,13 @@ import { getAppSetting, isServerNameTaken, insertBackup, + getServers, } from "@/lib/db"; import { useQueryClient } from "@tanstack/react-query"; import type { ServerRow } from "@/lib/db"; import type { BackupRecord } from "@/lib/tauri-commands"; +import { getExclusivePorts as computeExclusivePorts } from "@/lib/firewall-utils"; +import type { PortDef } from "@/lib/tauri-commands"; const uuidv4 = () => crypto.randomUUID(); interface Props { @@ -60,11 +64,25 @@ function DeleteDialog({ }) { const queryClient = useQueryClient(); const [deleteFiles, setDeleteFiles] = useState(false); + const [removeRules, setRemoveRules] = useState(false); const [deleting, setDeleting] = useState(false); + const [exclusivePorts, setExclusivePorts] = useState([]); + + // Compute exclusive ports when the dialog opens + useEffect(() => { + if (!open) return; + getServers().then((all) => { + setExclusivePorts(computeExclusivePorts(server, all)); + }).catch(() => {}); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]); const handleDelete = async () => { setDeleting(true); try { + if (removeRules && exclusivePorts.length > 0) { + await tauriCmd.removeFirewallRules(exclusivePorts).catch(() => {}); + } await tauriCmd.deleteServer(server.id, server.install_path, deleteFiles); await deleteServerRecord(server.id); queryClient.invalidateQueries({ queryKey: ["servers"] }); @@ -76,6 +94,10 @@ function DeleteDialog({ } }; + const exclusivePortList = exclusivePorts + .map((p) => `${p.port}/${p.protocol.toUpperCase()}`) + .join(", "); + return ( !v && onClose()}> @@ -88,20 +110,39 @@ function DeleteDialog({ -