Compare commits

..
3 Commits
Author SHA1 Message Date
Lncvrt 792d1add47 Yes. 2026-03-10 21:44:53 -07:00
Lncvrt ab2dcdedf7 Fixes to that last commit 2026-03-09 14:27:02 -07:00
Lncvrt 39b462c73f Port to win 7/8 2026-03-09 14:07:26 -07:00
83 changed files with 2837 additions and 5744 deletions

No files matched your search

+249 -309
View File
File diff suppressed because it is too large. Load diff
+25 -37
View File
@@ -1,7 +1,7 @@
{ {
"name": "lncvrt-games-launcher", "name": "lncvrt-games-launcher",
"private": true, "private": true,
"version": "1.10.0", "version": "1.6.5",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
@@ -11,45 +11,33 @@
"tauri": "tauri" "tauri": "tauri"
}, },
"dependencies": { "dependencies": {
"@fortawesome/fontawesome-svg-core": "7.3.1", "@fortawesome/fontawesome-svg-core": "7.2.0",
"@fortawesome/free-brands-svg-icons": "7.3.1", "@fortawesome/free-brands-svg-icons": "7.2.0",
"@fortawesome/free-solid-svg-icons": "7.3.1", "@fortawesome/free-solid-svg-icons": "7.2.0",
"@fortawesome/react-fontawesome": "3.5.0", "@fortawesome/react-fontawesome": "3.2.0",
"@tauri-apps/api": "2.12.0", "@tauri-apps/api": "2.10.1",
"@tauri-apps/plugin-cli": "2.5.0", "@tauri-apps/plugin-dialog": "2.6.0",
"@tauri-apps/plugin-clipboard-manager": "2.4.0", "@tauri-apps/plugin-fs": "2.4.5",
"@tauri-apps/plugin-dialog": "2.8.0", "@tauri-apps/plugin-http": "2.5.7",
"@tauri-apps/plugin-fs": "2.6.0", "@tauri-apps/plugin-opener": "2.5.3",
"@tauri-apps/plugin-http": "2.7.0", "@tauri-apps/plugin-os": "2.3.2",
"@tauri-apps/plugin-notification": "2.5.0", "next": "16.1.6",
"@tauri-apps/plugin-opener": "2.6.0", "pretty-bytes": "7.1.0",
"@tauri-apps/plugin-os": "2.4.0", "react": "19.2.4",
"@tauri-apps/plugin-process": "2.4.0", "react-dom": "19.2.4"
"@tauri-apps/plugin-store": "2.5.0",
"@tauri-apps/plugin-updater": "2.13.0",
"@tauri-apps/plugin-window-state": "2.5.0",
"date-fns": "4.4.0",
"dompurify": "3.4.16",
"next": "16.3.6",
"pretty-bytes": "7.2.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"semver": "7.8.5",
"swiper": "14.2.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "3.3.7", "@eslint/eslintrc": "3.3.5",
"@tailwindcss/postcss": "4.3.3", "@tailwindcss/postcss": "4.2.1",
"@tauri-apps/cli": "2.12.0", "@tauri-apps/cli": "2.10.1",
"@types/crypto-js": "4.2.2", "@types/crypto-js": "4.2.2",
"@types/node": "26.6.3", "@types/node": "25.3.5",
"@types/react": "19.3.0", "@types/react": "19.2.14",
"@types/react-dom": "19.3.0", "@types/react-dom": "19.2.3",
"@types/semver": "7.8.0",
"crypto-js": "4.2.0", "crypto-js": "4.2.0",
"eslint": "9.39.5", "eslint": "9.39.4",
"eslint-config-next": "16.3.6", "eslint-config-next": "16.1.6",
"tailwindcss": "4.3.3", "tailwindcss": "4.2.1",
"typescript": "6.0.3" "typescript": "5.9.3"
} }
} }
+8
View File
@@ -0,0 +1,8 @@
[build]
target = "x86_64-win7-windows-msvc"
[unstable]
build-std = ["std", "panic_abort"]
[toolchain]
channel = "nightly"
+18 -42
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "lncvrt-games-launcher" name = "lncvrt-games-launcher"
version = "1.10.0" version = "1.6.5"
authors = ["Lncvrt"] authors = ["Lncvrt"]
edition = "2024" edition = "2024"
@@ -9,51 +9,27 @@ name = "lncvrt_games_launcher_lib"
crate-type = ["staticlib", "cdylib", "rlib"] crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies] [build-dependencies]
tauri-build = { version = "2.7.0", features = [] } tauri-build = { version = "2.5.6", features = [] }
[dependencies] [dependencies]
tauri = { version = "2.12.0", features = [] } tauri = { version = "2.10.3", features = [] }
tauri-plugin-opener = "2.6.0" tauri-plugin-opener = "2.5.3"
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.151" serde_json = "1.0.149"
tauri-plugin-os = "2.4.0" tauri-plugin-os = "2.3.2"
reqwest = { version = "0.13.5", default-features = false, features = [ reqwest = { version = "0.13.2", default-features = false, features = ["stream", "rustls"] }
"stream", tokio = "1.50.0"
"rustls", futures-util = { version = "0.3.32", features = ["io"] }
] } tauri-plugin-fs = "2.4.5"
tokio = "1.53.1" zip = "8.2.0"
futures-util = { version = "0.3.34", features = ["io"] } libc = "0.2.183"
tauri-plugin-fs = "2.6.0" tauri-plugin-dialog = "2.6.0"
zip = "8.6.0" tauri-plugin-http = "2.5.7"
tauri-plugin-dialog = "2.8.0"
tauri-plugin-notification = "2.5.0"
sha2 = "0.11.0"
tauri-plugin-clipboard-manager = "2.4.0"
tauri-plugin-prevent-default = "6.0.0"
base64 = "0.23.1"
tauri-plugin-http = "2.8.0"
dashmap = "6.2.1"
tauri-plugin-store = "2.5.0"
hex = "0.4.3"
ed25519-dalek = { version = "3.0.0", features = ["pkcs8"] }
pem = "4.0.0"
[target.'cfg(any(target_os = "windows", target_os = "linux"))'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
sysinfo = "0.39.6" shlex = "1.3.0"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies] [target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-single-instance = "2.5.0" tauri-plugin-single-instance = "2.4.0"
tauri-plugin-updater = "2.13.0"
tauri-plugin-window-state = "2.5.0"
tauri-plugin-process = "2.4.0"
tauri-plugin-cli = "2.5.0"
[target.'cfg(target_os = "windows")'.dependencies]
tauri-plugin-decorum = "1.1.1"
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
strip = true
panic = "abort"
+16 -29
View File
@@ -2,54 +2,41 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Capability for the main window", "description": "Capability for the main window",
"windows": ["main"], "windows": [
"main"
],
"permissions": [ "permissions": [
"core:default", "core:default",
"opener:default", "opener:default",
"os:default", "os:default",
"core:window:default",
"core:window:allow-close",
"core:window:allow-center",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-set-size",
"core:window:allow-set-focus",
"core:window:allow-is-maximized",
"core:window:allow-start-dragging",
"core:window:allow-toggle-maximize",
"core:window:allow-request-user-attention",
"core:window:allow-show",
"core:window:allow-hide",
"core:webview:allow-create-webview-window",
"fs:default", "fs:default",
"fs:allow-remove",
"dialog:default", "dialog:default",
"dialog:allow-open",
"notification:default",
"clipboard-manager:default",
"clipboard-manager:allow-write-text",
"store:default",
"store:allow-load",
"store:allow-save",
"fs:allow-applocaldata-read", "fs:allow-applocaldata-read",
"fs:allow-applocaldata-write", "fs:allow-applocaldata-write",
{ {
"identifier": "fs:scope", "identifier": "fs:scope",
"allow": [{ "path": "**" }] "allow": [
{ "path": "$APPLOCALDATA/game/**" }
]
}, },
{ {
"identifier": "opener:allow-open-path", "identifier": "opener:allow-open-path",
"allow": [{ "path": "**" }] "allow": [
{ "path": "$APPLOCALDATA/game/**" }
]
}, },
{ {
"identifier": "http:default", "identifier": "http:default",
"allow": [ "allow": [
{ "url": "https://games.lncvrt.xyz/api/launcher/latest" },
{ "url": "https://games.lncvrt.xyz/api/launcher/versions" }, { "url": "https://games.lncvrt.xyz/api/launcher/versions" },
{ "url": "https://games.lncvrt.xyz/api/launcher/download" }, { "url": "https://games.lncvrt.xyz/api/launcher/download" },
{ "url": "https://games.lncvrt.xyz/api/launcher/mods" }, { "url": "https://games.lncvrt.xyz/api/berrydash/account" },
{ "url": "https://games.lncvrt.xyz/api/account/login" }, { "url": "https://games.lncvrt.xyz/api/berrydash/leaderboard/score" },
{ "url": "https://games.lncvrt.xyz/api/account/change-username" }, { "url": "https://games.lncvrt.xyz/api/berrydash/leaderboard/berry" },
{ "url": "https://games.lncvrt.xyz/api/account/change-password" } { "url": "https://games.lncvrt.xyz/api/berrydash/leaderboard/coin" },
{ "url": "https://games.lncvrt.xyz/api/berrydash/leaderboard/legacy" },
{ "url": "https://games.lncvrt.xyz/api/berrydash/leaderboard/total" }
] ]
} }
] ]
-6
View File
@@ -1,6 +0,0 @@
{
"identifier": "desktop-capability",
"platforms": ["macOS", "windows", "linux"],
"windows": ["main"],
"permissions": ["window-state:default", "updater:default", "process:default"]
}
-6
View File
@@ -1,6 +0,0 @@
{
"identifier": "windows-capability",
"platforms": ["windows"],
"windows": ["main"],
"permissions": ["decorum:allow-show-snap-overlay"]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 105 KiB

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 250 KiB

After

Width:  |  Height:  |  Size: 248 KiB

+63 -742
View File
@@ -1,14 +1,4 @@
use base64::Engine;
use dashmap::DashMap;
use ed25519_dalek::pkcs8::DecodePublicKey;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use futures_util::stream::StreamExt; use futures_util::stream::StreamExt;
use pem::parse;
use sha2::{Digest, Sha512};
use std::fs;
use std::path::Path;
use std::sync::{OnceLock, RwLock};
use std::time::Instant;
use std::{ use std::{
fs::{File, create_dir_all}, fs::{File, create_dir_all},
io::{BufReader, copy}, io::{BufReader, copy},
@@ -16,60 +6,9 @@ use std::{
process::Command, process::Command,
time::Duration, time::Duration,
}; };
use tauri::window::{ProgressBarState, ProgressBarStatus};
use tauri::{AppHandle, Emitter, Manager}; use tauri::{AppHandle, Emitter, Manager};
use tauri_plugin_os::platform;
use tauri_plugin_window_state::StateFlags;
use tokio::io::AsyncReadExt;
use tokio::{io::AsyncWriteExt, time::timeout}; use tokio::{io::AsyncWriteExt, time::timeout};
use zip::ZipArchive; use zip::ZipArchive;
use zip::result::ZipError;
#[cfg(any(target_os = "windows", target_os = "linux"))]
use sysinfo::System;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
#[cfg(not(debug_assertions))]
use tauri_plugin_updater::UpdaterExt;
struct AppState {
custom_data_dir: RwLock<Option<PathBuf>>,
}
fn data_dir(app: &AppHandle) -> Result<PathBuf, String> {
let state = app.state::<AppState>();
let guard = state.custom_data_dir.read().unwrap();
match &*guard {
Some(p) => Ok(p.clone()),
None => app.path().app_local_data_dir().map_err(|e| e.to_string()),
}
}
static CANCEL_MAP: OnceLock<DashMap<String, bool>> = OnceLock::new();
fn cancel_map() -> &'static DashMap<String, bool> {
CANCEL_MAP.get_or_init(DashMap::new)
}
fn is_cancelled(name: &str) -> bool {
cancel_map().get(name).map(|v| *v).unwrap_or(false)
}
#[cfg(any(target_os = "windows", target_os = "linux"))]
fn is_running_by_path(path: &Path) -> bool {
let sys = System::new_all();
let target = match path.canonicalize() {
Ok(t) => t,
Err(_) => return false,
};
sys.processes().values().any(|proc| {
proc.exe()
.and_then(|exe| exe.canonicalize().ok())
.map_or(false, |exe| exe == target)
})
}
fn should_skip(name: &str) -> bool { fn should_skip(name: &str) -> bool {
name.starts_with("__MACOSX/") name.starts_with("__MACOSX/")
@@ -78,33 +17,23 @@ fn should_skip(name: &str) -> bool {
|| name.ends_with(".DS_Store") || name.ends_with(".DS_Store")
} }
async fn unzip_to_dir(app: AppHandle, zip_path: PathBuf, out_dir: PathBuf, name: String) -> String { async fn unzip_to_dir(zip_path: PathBuf, out_dir: PathBuf) -> String {
let _ = app.emit("unzip-start", format!("{}", name));
let res = tauri::async_runtime::spawn_blocking(move || { let res = tauri::async_runtime::spawn_blocking(move || {
let file = File::open(zip_path)?; let file = File::open(zip_path)?;
let mut archive = ZipArchive::new(BufReader::new(file))?; let mut archive = ZipArchive::new(BufReader::new(file))?;
let total = archive.len();
for i in 0..total { for i in 0..archive.len() {
let mut entry = archive.by_index(i)?; let mut entry = archive.by_index(i)?;
let entry_name = entry.name(); let name = entry.name();
if should_skip(entry_name) { if should_skip(name) {
continue; continue;
} }
let outpath = out_dir.join(entry_name); let outpath = out_dir.join(name);
if !outpath.starts_with(&out_dir) {
return Err(ZipError::InvalidArchive("Path traversal detected".into()));
}
if entry.is_dir() { if entry.is_dir() {
create_dir_all(&outpath)?; create_dir_all(&outpath)?;
#[cfg(unix)]
if let Some(mode) = entry.unix_mode() {
std::fs::set_permissions(&outpath, std::fs::Permissions::from_mode(mode))?;
}
} else { } else {
if let Some(parent) = outpath.parent() { if let Some(parent) = outpath.parent() {
create_dir_all(parent)?; create_dir_all(parent)?;
@@ -112,14 +41,7 @@ async fn unzip_to_dir(app: AppHandle, zip_path: PathBuf, out_dir: PathBuf, name:
let mut outfile = File::create(&outpath)?; let mut outfile = File::create(&outpath)?;
copy(&mut entry, &mut outfile)?; copy(&mut entry, &mut outfile)?;
#[cfg(unix)]
if let Some(mode) = entry.unix_mode() {
std::fs::set_permissions(&outpath, std::fs::Permissions::from_mode(mode))?;
}
} }
let _ = app.emit("unzip-progress", format!("{}:{}:{}", name, i + 1, total));
} }
Ok::<(), zip::result::ZipError>(()) Ok::<(), zip::result::ZipError>(())
@@ -133,301 +55,79 @@ async fn unzip_to_dir(app: AppHandle, zip_path: PathBuf, out_dir: PathBuf, name:
} }
#[tauri::command] #[tauri::command]
fn folder_size(app: AppHandle, version: String) -> String { async fn download(app: AppHandle, url: String, name: String) -> String {
let path = match data_dir(&app) { let client = reqwest::Client::new();
Ok(p) => p.join("game").join(&version), let resp = match client.get(&url).send().await {
Ok(r) => r,
Err(_) => return "-1".to_string(), Err(_) => return "-1".to_string(),
}; };
fn inner(path: &Path) -> u64 {
let mut size = 0;
if let Ok(entries) = fs::read_dir(path) {
for entry in entries.flatten() {
if let Ok(metadata) = entry.metadata() {
if metadata.is_file() {
size += metadata.len();
} else if metadata.is_dir() {
size += inner(&entry.path());
}
}
}
}
size
}
let p = Path::new(&path); let total_size = resp.content_length().unwrap_or(0);
if p.exists() && p.is_dir() {
inner(p).to_string()
} else {
"-1".to_string()
}
}
#[tauri::command] let mut downloaded: u64 = 0;
async fn download( let mut stream = resp.bytes_stream();
app: AppHandle,
url: String,
name: String,
hash: String,
download_type: i8,
mod_id: String,
) -> String {
let _ = app.emit("download-start", format!("{}", name));
let window = app.get_webview_window("main").expect("main window missing");
let base_dir = match data_dir(&app) { let downloads_path = match app.path().app_local_data_dir() {
Ok(p) => p, Ok(p) => p.join("downloads"),
Err(_) => { Err(_) => return "-1".to_string(),
let _ = &app.emit("download-stop", format!("{}", name)); };
return "-1".to_string(); let game_path = match app.path().app_local_data_dir() {
} Ok(p) => p.join("game"),
Err(_) => return "-1".to_string(),
}; };
let downloads_path = base_dir.join("downloads");
let game_path = base_dir.join("game");
let download_part_path = downloads_path.join(format!("{}.part", name)); let download_part_path = downloads_path.join(format!("{}.part", name));
let download_zip_path = downloads_path.join(format!("{}.zip", name)); let download_zip_path = downloads_path.join(format!("{}.zip", name));
if tokio::fs::try_exists(game_path.join(&name)) if download_part_path.exists() {
.await let _ = tokio::fs::remove_file(&download_part_path).await;
.is_ok_and(|v| v)
&& !tokio::fs::try_exists(&download_part_path)
.await
.is_ok_and(|v| v)
&& !tokio::fs::try_exists(&download_zip_path)
.await
.is_ok_and(|v| v)
{
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::None),
progress: Some(0),
});
return "1".to_string();
} }
let _ = tokio::fs::create_dir_all(&downloads_path).await; let _ = tokio::fs::create_dir_all(&downloads_path).await;
let resume_from: u64 = match tokio::fs::metadata(&download_part_path).await { if let Ok(true) = tokio::fs::try_exists(&game_path.join(name.clone())).await {
Ok(meta) => { let _ = tokio::fs::remove_dir_all(&game_path.join(name.clone())).await;
let size = meta.len();
size
}
Err(_) => 0,
};
let client = reqwest::Client::new();
let mut request = client.get(&url);
if resume_from > 0 {
request = request.header("Range", format!("bytes={}-", resume_from));
}
let resp = match request.send().await {
Ok(r) => r,
Err(_) => {
let _ = &app.emit("download-stop", format!("{}", name));
return "-1".to_string();
}
};
let status = resp.status();
let actual_resume_from = if resume_from > 0 && status == reqwest::StatusCode::OK {
let _ = tokio::fs::remove_file(&download_part_path).await;
0
} else if resume_from > 0 && status == reqwest::StatusCode::PARTIAL_CONTENT {
resume_from
} else if resume_from > 0 {
let _ = tokio::fs::remove_file(&download_part_path).await;
0
} else {
0
};
let remaining_size = resp.content_length().unwrap_or(0);
let total_size = actual_resume_from + remaining_size;
let _ = app.emit("download-size", format!("{}:{}", &name, &total_size));
let mut file = if actual_resume_from > 0 {
match tokio::fs::OpenOptions::new()
.append(true)
.open(&download_part_path)
.await
{
Ok(f) => f,
Err(_) => {
let _ = &app.emit("download-stop", format!("{}", name));
return "-1".to_string();
}
}
} else {
if download_type == 0 {
if let Ok(true) = tokio::fs::try_exists(&game_path.join(&name)).await {
let _ = tokio::fs::remove_dir_all(&game_path.join(&name)).await;
}
let _ = tokio::fs::create_dir_all(&game_path.join(&name)).await;
}
match tokio::fs::File::create(&download_part_path).await {
Ok(f) => f,
Err(_) => {
let _ = &app.emit("download-stop", format!("{}", name));
return "-1".to_string();
}
}
};
let mut downloaded: u64 = actual_resume_from;
let mut stream = resp.bytes_stream();
let start = Instant::now();
let mut chunk_count: u64 = 0;
while let Ok(Some(chunk_result)) = timeout(Duration::from_secs(5), stream.next()).await {
if is_cancelled(&name) {
cancel_map().remove(&name);
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::None),
progress: Some(0),
});
return "0".to_string();
}
let chunk = match chunk_result {
Ok(c) => c,
Err(_) => {
let _ = &app.emit("download-stop", format!("{}", name));
return "-1".to_string();
}
};
chunk_count += 1;
if let Err(_) = file.write_all(&chunk).await {
let _ = &app.emit("download-stop", format!("{}", name));
return "-1".to_string();
}
downloaded += chunk.len() as u64;
let progress = if total_size > 0 {
((downloaded as f64) / (total_size as f64)) * 100.0
} else {
0.0
};
let session_bytes = downloaded - actual_resume_from;
let elapsed_secs = start.elapsed().as_secs_f64();
let speed = if elapsed_secs > 0.0 {
session_bytes as f64 / elapsed_secs
} else {
0.0
};
let eta_secs = if total_size > downloaded && speed > 0.0 {
(total_size - downloaded) as f64 / speed
} else {
0.0
};
if chunk_count % 50 == 0 || downloaded == total_size {
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::Normal),
progress: Some(progress as u64),
});
}
let _ = app.emit(
"download-progress",
format!(
"{}:{:.8}:{}:{}:{:.2}",
&name, progress, downloaded, speed, eta_secs
),
);
}
if total_size > 0 && downloaded < total_size {
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::None),
progress: Some(0),
});
return "-1".to_string();
}
let _ = app.emit("download-hash-checking", format!("{}", &name));
let download_hash = {
let mut file = match tokio::fs::File::open(&download_part_path).await {
Ok(f) => f,
Err(_) => {
return "-1".to_string();
}
};
let mut hasher = Sha512::new();
let mut buffer = [0u8; 8192];
loop {
let bytes_read = match file.read(&mut buffer).await {
Ok(n) => n,
Err(_) => {
return "-1".to_string();
}
};
if bytes_read == 0 {
break;
}
hasher.update(&buffer[..bytes_read]);
}
drop(file);
hex::encode(hasher.finalize())
};
if hash != download_hash {
let _ = tokio::fs::remove_file(&download_part_path).await;
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::None),
progress: Some(0),
});
return "-1".to_string();
}
if let Err(_) = tokio::fs::rename(&download_part_path, &download_zip_path).await {
let _ = window.set_progress_bar(ProgressBarState {
status: Some(ProgressBarStatus::None),
progress: Some(0),
});
return "-1".to_string();
} }
let _ = tokio::fs::create_dir_all(&game_path.join(&name)).await; let _ = tokio::fs::create_dir_all(&game_path.join(&name)).await;
let unzip_res = unzip_to_dir( let mut file = match tokio::fs::File::create(download_part_path.clone()).await {
app.clone(), Ok(f) => f,
download_zip_path.clone(), Err(_) => return "-1".to_string(),
if download_type == 2 { };
game_path
.join(&name)
.join("BepInEx")
.join("plugins")
.join(&mod_id)
} else {
game_path.join(&name)
},
name.clone(),
)
.await;
let _ = tokio::fs::remove_file(&download_zip_path).await; while let Ok(Some(chunk_result)) = timeout(Duration::from_secs(5), stream.next()).await {
let chunk = match chunk_result {
Ok(c) => c,
Err(_) => return "-1".to_string(),
};
if unzip_res == "-1" { if let Err(_) = file.write_all(&chunk).await {
let _ = window.set_progress_bar(ProgressBarState { return "-1".to_string();
status: Some(ProgressBarStatus::None), }
progress: Some(0),
}); downloaded += chunk.len() as u64;
}
if total_size > 0 && downloaded < total_size {
return "-1".to_string(); return "-1".to_string();
} }
let _ = window.set_progress_bar(ProgressBarState { let _ = app.emit("download-finishing", format!("{}", &name));
status: Some(ProgressBarStatus::None),
progress: Some(0), if let Err(_) = tokio::fs::rename(download_part_path.clone(), download_zip_path.clone()).await {
}); return "-1".to_string();
"1".to_string() }
let unzip_res = unzip_to_dir(download_zip_path.clone(), game_path.join(&name)).await;
let _ = tokio::fs::remove_file(download_zip_path.clone()).await;
if unzip_res == "-1" {
return "-1".to_string();
}
return "1".to_string();
} }
#[allow(unused_variables)] #[allow(unused_variables)]
@@ -440,7 +140,7 @@ fn launch_game(
use_wine: bool, use_wine: bool,
wine_command: String, wine_command: String,
) { ) {
let game_folder = match data_dir(&app) { let game_folder = match app.path().app_local_data_dir() {
Ok(p) => p.join("game").join(&name), Ok(p) => p.join("game").join(&name),
Err(_) => return, Err(_) => return,
}; };
@@ -448,255 +148,19 @@ fn launch_game(
return; return;
} }
let exe_path = game_folder.join(&executable); if let Err(_) = Command::new(game_folder.join(&executable))
.current_dir(&game_folder)
//if already running on macos, it'll auto take the user to that proccess .spawn()
#[cfg(any(target_os = "windows", target_os = "linux"))]
{ {
use tauri_plugin_dialog::{DialogExt, MessageDialogKind}; eprintln!("Failed to launch game");
if !use_wine && is_running_by_path(&exe_path) {
app.dialog()
.message(format!(
"{} is already running, if this doesn't seem true, try to kill the proccess.",
display_name
))
.kind(MessageDialogKind::Error)
.title("Game already running")
.show(|_| {});
return;
}
}
#[cfg(target_os = "linux")]
{
if use_wine {
let quoted_path = format!("\"{}\"", exe_path.to_string_lossy());
let cmd = wine_command.replace("%path%", &quoted_path);
if let Err(e) =
Command::new(&std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()))
.arg("-c")
.arg(cmd)
.current_dir(&game_folder)
.spawn()
{
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
eprintln!("Failed to launch game with Wine: {}", e);
app.dialog()
.message(format!(
"{} failed to launch with Wine\n\n{}",
display_name, e
))
.kind(MessageDialogKind::Error)
.title("Game already running")
.show(|_| {});
}
return;
}
}
let bepinex_folder = game_folder.join("BepInEx");
if platform() == "macos" && !bepinex_folder.exists() && executable.ends_with(".app") {
if let Err(_) = Command::new("open")
.arg(&executable)
.current_dir(&game_folder)
.spawn()
{
eprintln!("Failed to launch game on macOS");
}
} else {
if (platform() == "macos" || platform() == "linux") && bepinex_folder.exists() {
if let Err(_) = Command::new("./run_bepinex.sh")
.arg(&executable)
.current_dir(&game_folder)
.spawn()
{
eprintln!("Failed to launch game");
}
} else {
if let Err(_) = Command::new(&exe_path).current_dir(&game_folder).spawn() {
eprintln!("Failed to launch game");
}
}
}
}
#[tauri::command]
fn verify_signature(body: String, signature: String, public_key: String) -> bool {
let Ok(pubkey_pem_bytes) = base64::engine::general_purpose::STANDARD.decode(public_key) else {
return false;
};
let Ok(sig_bytes) = base64::engine::general_purpose::STANDARD.decode(signature) else {
return false;
};
let Ok(pubkey_pem) = String::from_utf8(pubkey_pem_bytes) else {
return false;
};
let Ok(parsed) = parse(pubkey_pem) else {
return false;
};
let Ok(pubkey) = VerifyingKey::from_public_key_der(&parsed.contents()) else {
return false;
};
let Ok(sig) = Signature::from_slice(&sig_bytes) else {
return false;
};
pubkey.verify(body.as_bytes(), &sig).is_ok()
}
#[tauri::command]
async fn cancel_download(name: String) {
cancel_map().insert(name.clone(), true);
}
fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
fs::create_dir_all(dst)?;
for entry in fs::read_dir(src)? {
let entry = entry?;
let src_path = entry.path();
let dst_path = dst.join(entry.file_name());
if src_path.is_dir() {
copy_dir_recursive(&src_path, &dst_path)?;
} else {
fs::copy(&src_path, &dst_path)?;
}
}
Ok(())
}
fn move_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
if !src.exists() {
return Ok(());
}
if let Some(parent) = dst.parent() {
fs::create_dir_all(parent)?;
}
if dst.exists() {
fs::remove_dir_all(dst)?;
}
match fs::rename(src, dst) {
Ok(()) => Ok(()),
Err(_) => {
copy_dir_recursive(src, dst)?;
fs::remove_dir_all(src)?;
Ok(())
}
}
}
#[tauri::command]
async fn move_game_data(app: AppHandle, destination: String) -> Result<(), String> {
let default_dir = app.path().app_local_data_dir().map_err(|e| e.to_string())?;
let current_dir = data_dir(&app)?;
let new_dir = if destination.is_empty() {
default_dir.clone()
} else {
PathBuf::from(&destination)
};
if current_dir == new_dir {
return Ok(());
}
let src_game = current_dir.join("game");
let dst_game = new_dir.join("game");
let src_downloads = current_dir.join("downloads");
let dst_downloads = new_dir.join("downloads");
tauri::async_runtime::spawn_blocking(move || {
fs::create_dir_all(&new_dir).map_err(|e| e.to_string())?;
move_dir(&src_game, &dst_game).map_err(|e| e.to_string())?;
move_dir(&src_downloads, &dst_downloads).map_err(|e| e.to_string())?;
Ok::<(), String>(())
})
.await
.map_err(|e| e.to_string())??;
let state = app.state::<AppState>();
let mut guard = state.custom_data_dir.write().unwrap();
if destination.is_empty() {
*guard = None;
} else {
*guard = Some(PathBuf::from(&destination));
}
Ok(())
}
#[tauri::command]
fn open_game_folder(app: AppHandle, version: String) -> Result<(), String> {
let dir = data_dir(&app)?;
let path = dir.join("game").join(&version);
if !path.exists() || !path.is_dir() {
return Err(format!("Game folder \"{}\" not found.", path.display()));
}
#[cfg(target_os = "macos")]
Command::new("open")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
#[cfg(target_os = "windows")]
Command::new("explorer")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
#[cfg(target_os = "linux")]
Command::new("xdg-open")
.arg(&path)
.spawn()
.map_err(|e| e.to_string())?;
Ok(())
}
#[tauri::command]
fn remove_stale_executable(app: AppHandle, version: String, executable: String) -> bool {
let dir = match data_dir(&app) {
Ok(d) => d,
Err(_) => return false,
};
let path = dir.join("game").join(&version).join(&executable);
if path.exists() {
fs::remove_file(&path).is_ok()
} else {
false
} }
} }
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
#[allow(unused)] #[allow(unused_variables)]
let mut builder = tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_cli::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(
tauri_plugin_store::Builder::new()
.default_serialize_fn(|cache| Ok(serde_json::to_vec(cache)?))
.build(),
)
.plugin(tauri_plugin_http::init()) .plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_prevent_default::init())
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(
StateFlags::all() & !StateFlags::VISIBLE & !StateFlags::DECORATIONS,
)
.build(),
)
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| { .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
if let Some(window) = app.get_webview_window("main") { if let Some(window) = app.get_webview_window("main") {
let _ = window.set_focus(); let _ = window.set_focus();
@@ -706,150 +170,7 @@ pub fn run() {
.plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_os::init()) .plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![download, launch_game])
download,
launch_game,
folder_size,
verify_signature,
cancel_download,
move_game_data,
open_game_folder,
remove_stale_executable
])
.setup(|app| {
let custom_dir = app
.path()
.app_config_dir()
.ok()
.map(|d| d.join("settings.json"))
.filter(|p| p.exists())
.and_then(|p| fs::read_to_string(p).ok())
.and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
.and_then(|v| {
v.get("customDataLocation")
.and_then(|s| s.as_str())
.filter(|s| !s.is_empty())
.map(PathBuf::from)
});
app.manage(AppState {
custom_data_dir: RwLock::new(custom_dir),
});
let window = app.get_webview_window("main").unwrap();
let app_handle = app.handle().clone();
window.on_window_event(move |event| {
if let tauri::WindowEvent::CloseRequested { .. } = event {
app_handle.exit(0);
}
});
#[cfg(target_os = "windows")]
{
use tauri_plugin_decorum::WebviewWindowExt;
if let Err(e) = window.create_overlay_titlebar() {
eprintln!("Failed to create overlay titlebar: {:?}", e);
}
}
#[cfg(not(debug_assertions))]
{
use tauri_plugin_cli::CliExt;
match app.cli().matches() {
Ok(matches) => match matches.args.get("no-check-updates") {
Some(arg) => {
if arg.value == false {
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
update(handle, window.clone()).await.unwrap();
});
} else {
let mut new_url = window.url().unwrap();
new_url.set_path("/main");
let _ = window.navigate(new_url);
}
}
None => {}
},
Err(_) => {}
}
}
Ok(())
});
#[cfg(target_os = "windows")]
{
builder = builder.plugin(tauri_plugin_decorum::init());
}
builder
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }
#[cfg(not(debug_assertions))]
async fn update(
app: tauri::AppHandle,
window: tauri::WebviewWindow,
) -> tauri_plugin_updater::Result<()> {
use tauri_plugin_os::arch;
let plat = {
#[cfg(target_os = "linux")]
{
if std::path::Path::new("/etc/debian_version").exists() {
"linux-debian"
} else if std::path::Path::new("/etc/redhat-release").exists() {
"linux-redhat"
} else {
let mut new_url = window.url().unwrap();
new_url.set_path("/update/outdated");
window.navigate(new_url).unwrap();
return Ok(());
}
}
#[cfg(not(target_os = "linux"))]
{
platform()
}
};
if let Some(update) = app
.updater_builder()
.target(format!("{}-{}", plat, arch()))
.build()?
.check()
.await?
{
let mut new_url = window.url().unwrap();
new_url.set_path("/update/updating");
window.navigate(new_url).unwrap();
let _ = window.show();
let _ = window.set_focus();
let mut downloaded = 0;
update
.download_and_install(
|chunk_length, content_length| {
downloaded += chunk_length;
println!("downloaded {downloaded} from {content_length:?}");
},
|| {
println!("download finished");
},
)
.await?;
println!("update installed");
app.restart();
}
let mut new_url = window.url().unwrap();
new_url.set_path("/main");
window.navigate(new_url).unwrap();
Ok(())
}
+21 -5
View File
@@ -1,21 +1,37 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Lncvrt Games Launcher", "productName": "Lncvrt Games Launcher",
"version": "1.10.0", "version": "1.6.5",
"identifier": "xyz.lncvrt.games-launcher", "identifier": "xyz.lncvrt.games-launcher",
"build": { "build": {
"beforeDevCommand": "next dev --webpack", "beforeDevCommand": "bun next dev --webpack",
"devUrl": "http://localhost:3000", "devUrl": "http://localhost:3000",
"beforeBuildCommand": "next build", "beforeBuildCommand": "bun next build",
"frontendDist": "../out" "frontendDist": "../out"
}, },
"app": { "app": {
"windows": [], "withGlobalTauri": true,
"windows": [
{
"title": "Lncvrt Games Launcher",
"width": 1000,
"height": 600,
"minWidth": 875,
"minHeight": 500
}
],
"security": { "security": {
"csp": null "csp": null
} }
}, },
"bundle": { "bundle": {
"active": false "active": true,
"icon": ["icons/icon.ico"],
"targets": "nsis",
"windows": {
"webviewInstallMode": {
"type": "embedBootstrapper"
}
}
} }
} }
-54
View File
@@ -1,54 +0,0 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Lncvrt Games Launcher",
"version": "1.10.0",
"identifier": "xyz.lncvrt.games-launcher",
"build": {
"beforeDevCommand": "next dev --webpack",
"devUrl": "http://localhost:3000",
"beforeBuildCommand": "next build",
"frontendDist": "../out"
},
"app": {
"windows": [
{
"title": "Lncvrt Games Launcher",
"url": "/update/checking",
"width": 1000,
"height": 500,
"minWidth": 1000,
"minHeight": 500
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"category": "Game",
"shortDescription": "A launcher for downloading, managing, and launching games with built-in mod support.",
"longDescription": "Lncvrt Games Launcher lets you download and manage multiple versions of games, install mods, and launch them directly. Linux users can run Windows exclusive games via Wine (or proton via a custom command).",
"targets": ["deb", "rpm"],
"icon": ["icons/icon.png"],
"createUpdaterArtifacts": true
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFODI3MTAwQkNBMjE4REEKUldUYUdLSzhBSEdDM3J0N1NvbENsdDQ3c3BOdWlFajErVnlLZitSc2l5WVI0VjQ1ZHNMWjYzaUwK",
"endpoints": [
"https://games.lncvrt.xyz/api/launcher/update?target={{target}}&currentVersion={{current_version}}"
]
},
"cli": {
"description": "Lncvrt Games Launcher CLI",
"args": [
{
"short": "n",
"name": "no-check-updates",
"description": "Bypasses th eupdate checker"
}
]
}
}
}
-60
View File
@@ -1,60 +0,0 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Lncvrt Games Launcher",
"version": "1.10.0",
"identifier": "xyz.lncvrt.games-launcher",
"build": {
"beforeDevCommand": "next dev --webpack",
"devUrl": "http://localhost:3000",
"beforeBuildCommand": "next build",
"frontendDist": "../out"
},
"app": {
"macOSPrivateApi": true,
"windows": [
{
"title": "Lncvrt Games Launcher",
"url": "/update/checking",
"width": 1000,
"height": 500,
"minWidth": 1000,
"minHeight": 500,
"titleBarStyle": "Overlay",
"hiddenTitle": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"category": "Game",
"shortDescription": "A launcher for downloading, managing, and launching games with built-in mod support.",
"longDescription": "Lncvrt Games Launcher lets you download and manage multiple versions of games, install mods, and launch them directly. Linux users can run Windows exclusive games via Wine (or proton via a custom command).",
"targets": ["dmg", "app"],
"icon": ["icons/icon.icns"],
"createUpdaterArtifacts": true,
"macOS": {
"minimumSystemVersion": "14.0"
}
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFODI3MTAwQkNBMjE4REEKUldUYUdLSzhBSEdDM3J0N1NvbENsdDQ3c3BOdWlFajErVnlLZitSc2l5WVI0VjQ1ZHNMWjYzaUwK",
"endpoints": [
"https://games.lncvrt.xyz/api/launcher/update?target={{target}}&currentVersion={{current_version}}"
]
},
"cli": {
"description": "Lncvrt Games Launcher CLI",
"args": [
{
"short": "n",
"name": "no-check-updates",
"description": "Bypasses th eupdate checker"
}
]
}
}
}
-57
View File
@@ -1,57 +0,0 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Lncvrt Games Launcher",
"version": "1.10.0",
"identifier": "xyz.lncvrt.games-launcher",
"build": {
"beforeDevCommand": "next dev --webpack",
"devUrl": "http://localhost:3000",
"beforeBuildCommand": "next build",
"frontendDist": "../out"
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "Lncvrt Games Launcher",
"url": "/update/checking",
"width": 1000,
"height": 532,
"minWidth": 1000,
"minHeight": 532,
"decorations": false,
"shadow": true
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"category": "Game",
"shortDescription": "A launcher for downloading, managing, and launching games with built-in mod support.",
"longDescription": "Lncvrt Games Launcher lets you download and manage multiple versions of games, install mods, and launch them directly. Linux users can run Windows exclusive games via Wine (or proton via a custom command).",
"targets": ["msi"],
"icon": ["icons/icon.ico"],
"createUpdaterArtifacts": true
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFODI3MTAwQkNBMjE4REEKUldUYUdLSzhBSEdDM3J0N1NvbENsdDQ3c3BOdWlFajErVnlLZitSc2l5WVI0VjQ1ZHNMWjYzaUwK",
"endpoints": [
"https://games.lncvrt.xyz/api/launcher/update?target={{target}}&currentVersion={{current_version}}"
]
},
"cli": {
"description": "Lncvrt Games Launcher CLI",
"args": [
{
"short": "n",
"name": "no-check-updates",
"description": "Bypasses th eupdate checker"
}
]
}
}
}
@@ -8,14 +8,14 @@ import {
SetStateAction SetStateAction
} from 'react' } from 'react'
import { DownloadProgress } from '@/types/DownloadProgress' import { DownloadProgress } from '@/types/DownloadProgress'
import { VersionsConfig } from '@/types/VersionsConfig'
import { NormalConfig } from '@/types/NormalConfig'
import { ServerVersionsResponse } from '@/types/ServerVersionsResponse' import { ServerVersionsResponse } from '@/types/ServerVersionsResponse'
import { Mod } from '@/types/Mod'
import { Store } from '@tauri-apps/plugin-store'
import { GameVersion } from '@/types/GameVersion' import { GameVersion } from '@/types/GameVersion'
import { Game } from '@/types/Game'
type GlobalCtxType = { type GlobalCtxType = {
serverVersionList: ServerVersionsResponse | null serverVersionList: ServerVersionsResponse | null
setServerVersionList: Dispatch<SetStateAction<ServerVersionsResponse | null>>
selectedVersionList: string[] selectedVersionList: string[]
setSelectedVersionList: (value: SetStateAction<string[]>) => void setSelectedVersionList: (value: SetStateAction<string[]>) => void
downloadProgress: DownloadProgress[] downloadProgress: DownloadProgress[]
@@ -26,55 +26,31 @@ type GlobalCtxType = {
setPopupMode: Dispatch<SetStateAction<number | null>> setPopupMode: Dispatch<SetStateAction<number | null>>
fadeOut: boolean fadeOut: boolean
setFadeOut: Dispatch<SetStateAction<boolean>> setFadeOut: Dispatch<SetStateAction<boolean>>
downloadedVersionsConfig: VersionsConfig | null
setDownloadedVersionsConfig: Dispatch<SetStateAction<VersionsConfig | null>>
normalConfig: NormalConfig | null
setNormalConfig: Dispatch<SetStateAction<NormalConfig | null>>
managingVersion: string | null managingVersion: string | null
setManagingVersion: Dispatch<SetStateAction<string | null>> setManagingVersion: Dispatch<SetStateAction<string | null>>
setSelectedGame: Dispatch<SetStateAction<number | null>> setSelectedGame: Dispatch<SetStateAction<number | null>>
getVersionInfo: (id: string | undefined) => GameVersion | undefined
getGameInfo: (game: number | undefined) => Game | undefined
getListOfGames(): Game[]
getVersionsAmountData: (gameId: number) => {
installed: number
total: number
} | null
viewingInfoFromDownloads: boolean viewingInfoFromDownloads: boolean
version: string | null version: string | null
downloadVersions: ( downloadVersions: (list: string[]) => Promise<void>
list: Array<{
id: string
type: 0 | 1 | 2
modDownload?: number
gameId?: number
modId?: number
modVersion?: string
}>
) => Promise<void>
category: number category: number
setCategory: Dispatch<SetStateAction<number>> setCategory: Dispatch<SetStateAction<number>>
downloadQueue: string[] downloadQueue: string[]
setDownloadQueue: Dispatch<SetStateAction<string[]>> setDownloadQueue: Dispatch<SetStateAction<string[]>>
closePopup: () => void closePopup: () => void
getSpecialVersionsList(game?: number | undefined): GameVersion[]
selectedGame: number | null selectedGame: number | null
setViewingInfoFromDownloads: Dispatch<SetStateAction<boolean>> setViewingInfoFromDownloads: Dispatch<SetStateAction<boolean>>
showModInfo: Mod | null
setShowModInfo: Dispatch<SetStateAction<Mod | null>>
getSpecialVersionsList: (game?: number) => GameVersion[]
settings: Store | null
versions: Store | null
account: Store | null
sidebarShowGames: boolean
linuxUseWine: boolean
linuxWineCommand: string
theme: string
customDataLocation: string
developerMode: boolean
versionsList: Record<string, number>
modsList: Record<string, Record<string, number>>
launchesList: Record<string, Record<string, number>>
accountSession: string | null
accountId: string | null
accountName: string | null
accountAdmin: boolean
managingGame: number | null
setManagingGame: Dispatch<SetStateAction<number | null>>
needsRevisionUpdate: (
lastRevision: number | undefined,
version: string
) => boolean
uninstallVersion: (version: string, updateList?: boolean) => Promise<void>
launchGame: (versionInfo: GameVersion) => Promise<void>
} }
const GlobalCtx = createContext<GlobalCtxType | null>(null) const GlobalCtx = createContext<GlobalCtxType | null>(null)
+15 -44
View File
@@ -1,9 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
html {
overscroll-behavior: none;
}
body { body {
@apply bg-(--col0) text-white select-none; @apply bg-(--col0) text-white select-none;
} }
@@ -18,7 +14,6 @@ body {
--col6: rgb(96, 96, 96); --col6: rgb(96, 96, 96);
--col7: rgb(112, 112, 112); --col7: rgb(112, 112, 112);
--col8: rgb(128, 128, 128); --col8: rgb(128, 128, 128);
--col9: rgb(144, 144, 144);
} }
.red-theme { .red-theme {
@@ -31,7 +26,6 @@ body {
--col6: rgb(120, 96, 96); --col6: rgb(120, 96, 96);
--col7: rgb(136, 112, 112); --col7: rgb(136, 112, 112);
--col8: rgb(152, 128, 128); --col8: rgb(152, 128, 128);
--col9: rgb(168, 144, 144);
} }
.blue-theme { .blue-theme {
@@ -44,7 +38,6 @@ body {
--col6: rgb(96, 96, 120); --col6: rgb(96, 96, 120);
--col7: rgb(112, 112, 136); --col7: rgb(112, 112, 136);
--col8: rgb(128, 128, 152); --col8: rgb(128, 128, 152);
--col9: rgb(144, 144, 168);
} }
.purple-theme { .purple-theme {
@@ -57,11 +50,9 @@ body {
--col6: rgb(108, 96, 120); --col6: rgb(108, 96, 120);
--col7: rgb(124, 112, 136); --col7: rgb(124, 112, 136);
--col8: rgb(140, 128, 152); --col8: rgb(140, 128, 152);
--col9: rgb(156, 144, 168);
} }
.button, .button {
.input-field {
@apply rounded-md cursor-pointer text-[16px] py-1 px-2 transition-colors border; @apply rounded-md cursor-pointer text-[16px] py-1 px-2 transition-colors border;
} }
@@ -70,29 +61,17 @@ body {
} }
.btntheme2, .btntheme2,
.main-container .main-entry .entry-info-item, .downloads-entry .entry-info-item,
.main-container .main-entry .button { .downloads-entry .button {
@apply bg-(--col3) border-(--col5) hover:bg-(--col5) hover:border-(--col7) disabled:text-gray-300 disabled:bg-(--col2) disabled:border-(--col6) disabled:hover:text-gray-100 disabled:hover:bg-(--col3) disabled:hover:border-(--col7); @apply bg-(--col3) border-(--col5) hover:bg-(--col5) hover:border-(--col7) disabled:text-gray-300 disabled:bg-(--col2) disabled:border-(--col6) disabled:hover:text-gray-100 disabled:hover:bg-(--col3) disabled:hover:border-(--col7);
} }
.btntheme3, .btntheme3,
.main-container .main-entry:hover .entry-info-item, .downloads-entry:hover .entry-info-item,
.main-container .main-entry:hover .button { .downloads-entry:hover .button {
@apply bg-(--col4) border-(--col6) hover:bg-(--col6) hover:border-(--col8) disabled:text-gray-300 disabled:bg-(--col2) disabled:border-(--col7) disabled:hover:text-gray-100 disabled:hover:bg-(--col4) disabled:hover:border-(--col8); @apply bg-(--col4) border-(--col6) hover:bg-(--col6) hover:border-(--col8) disabled:text-gray-300 disabled:bg-(--col2) disabled:border-(--col7) disabled:hover:text-gray-100 disabled:hover:bg-(--col4) disabled:hover:border-(--col8);
} }
.input-field.btntheme1 {
@apply focus:bg-(--col4) focus:border-(--col6);
}
.input-field.btntheme2 {
@apply focus:bg-(--col5) focus:border-(--col7);
}
.input-field.btntheme3 {
@apply focus:bg-(--col6) focus:border-(--col8);
}
::-webkit-scrollbar { ::-webkit-scrollbar {
@apply w-2; @apply w-2;
} }
@@ -123,18 +102,6 @@ body {
} }
} }
.main-container {
@apply bg-(--col1) border border-(--col3) rounded-lg overflow-y-auto w-full;
}
.main-container.main-flex {
@apply flex flex-col gap-2 p-2;
}
.main-container .main-entry {
@apply flex justify-between items-center p-2 rounded-lg text-gray-200 text-lg transition-colors bg-(--col2) hover:bg-(--col3) border border-(--col4) hover:border-(--col5) cursor-pointer;
}
.popup-overlay { .popup-overlay {
@apply fixed w-screen h-screen z-99999 flex justify-center items-center animate-[fadeIn_0.2s_ease-out_forwards] left-0 top-0 bg-[rgba(0,0,0,0.5)]; @apply fixed w-screen h-screen z-99999 flex justify-center items-center animate-[fadeIn_0.2s_ease-out_forwards] left-0 top-0 bg-[rgba(0,0,0,0.5)];
} }
@@ -155,18 +122,22 @@ body {
@apply relative h-fit bg-(--col3) m-2 p-2 rounded-lg border border-(--col5); @apply relative h-fit bg-(--col3) m-2 p-2 rounded-lg border border-(--col5);
} }
.popup-top-button { .popup-entry button {
@apply flex justify-center items-center absolute text-2xl text-gray-200 hover:text-white cursor-pointer h-12 w-12 p-3 rounded-lg top-2 transition-colors border; @apply absolute;
}
.close-button {
@apply flex justify-center items-center absolute text-2xl text-gray-200 hover:text-white cursor-pointer h-12 w-12 p-3 rounded-lg left-2 top-2 transition-colors border;
} }
*:focus { *:focus {
@apply outline-none; @apply outline-none;
} }
.input-field {
@apply border-2 border-(--col4) rounded-md bg-(--col2) py-1 px-2 focus:bg-(--col3) focus:border-(--col6) transition-colors w-full;
}
.entry-info-item { .entry-info-item {
@apply flex flex-row items-center gap-1 border text-gray-300 py-1 px-2 rounded-md w-fit text-[16px] transition-colors cursor-pointer; @apply flex flex-row items-center gap-1 border text-gray-300 py-1 px-2 rounded-md w-fit text-[16px] transition-colors cursor-pointer;
} }
code {
@apply bg-(--col4) border border-(--col6) rounded-lg px-1 py-0.5 text-sm;
}
+13
View File
@@ -0,0 +1,13 @@
@import "tailwindcss";
.downloads-container {
@apply flex justify-center;
}
.downloads-scroll {
@apply bg-(--col1) border border-(--col3) rounded-lg overflow-y-auto w-full;
}
.downloads-entry {
@apply flex justify-between items-center m-2 p-2 rounded-lg text-gray-200 text-lg transition-colors bg-(--col2) hover:bg-(--col3) border border-(--col4) hover:border-(--col5) cursor-pointer;
}
@@ -0,0 +1,315 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { BirdColor } from '@/types/BerryDash/BirdColor'
import { GetIconForUser } from '@/lib/BerryDash'
import Image from 'next/image'
import './styles.css'
import { useRouter } from 'next/navigation'
import { fetch } from '@tauri-apps/plugin-http'
interface BaseEntry {
id: number
username: string
value: number
icon: number
overlay: number
birdColor: BirdColor
overlayColor: BirdColor
customIcon: string | null
}
interface Stats {
highScore: string
totalNormalBerries: string
totalPoisonBerries: string
totalSlowBerries: string
totalUltraBerries: string
totalSpeedyBerries: string
totalCoinBerries: string
totalRandomBerries: string
totalAntiBerries: string
totalGoldenBerries: string
coins: string
}
interface LeaderboardEntry extends BaseEntry {
type: 'leaderboard'
value: number
}
interface Account extends BaseEntry {
type: 'account'
stats: Stats
xp: bigint
}
export function calculateXP (
normalBerries: bigint,
poisonBerries: bigint,
slowBerries: bigint,
ultraBerries: bigint,
speedyBerries: bigint,
coinBerries: bigint,
randomBerries: bigint,
antiBerries: bigint,
goldenBerries: bigint
): bigint {
let totalXp = 0n
totalXp += normalBerries
totalXp -= poisonBerries
totalXp -= slowBerries
totalXp += ultraBerries * 5n
totalXp += speedyBerries * 10n
totalXp += coinBerries * 10n
totalXp += randomBerries
totalXp -= antiBerries
totalXp += goldenBerries * 4n
if (totalXp < 0n) totalXp = 0n
return totalXp
}
export function calculateLevel (xp: bigint): number {
const levelDivisor = 50.0
const xpNumber = Number(xp)
const discriminant = 95 * 95 + levelDivisor * 2 * xpNumber
const level = (-95 + Math.sqrt(discriminant)) / levelDivisor
return Math.floor(level) + 1
}
export default function BerryDashLeaderboards () {
const [selected, setSelected] = useState<number>(-1)
const [selectedBerryOption, setSelectedBerryOption] = useState<number>(0)
const [entries, setEntries] = useState<(LeaderboardEntry | Account)[]>([])
const router = useRouter()
const Refresh = useCallback(async () => {
try {
if (selected == 3 || selected == 4) {
const response = await fetch(
'https://games.lncvrt.xyz/api/berrydash/account?username='
)
const data = await response.json()
if (data.success) {
let accounts = data.data as Account[]
accounts = accounts.map(acc => {
const xp = calculateXP(
BigInt(acc.stats.totalNormalBerries),
BigInt(acc.stats.totalPoisonBerries),
BigInt(acc.stats.totalSlowBerries),
BigInt(acc.stats.totalUltraBerries),
BigInt(acc.stats.totalSpeedyBerries),
BigInt(acc.stats.totalCoinBerries),
BigInt(acc.stats.totalRandomBerries),
BigInt(acc.stats.totalAntiBerries),
BigInt(acc.stats.totalGoldenBerries)
)
return { ...acc, xp }
})
accounts.sort((a, b) => (b.xp > a.xp ? 1 : b.xp < a.xp ? -1 : 0))
setEntries(accounts)
} else console.log('Failed')
} else {
const response = await fetch(
'https://games.lncvrt.xyz/api/berrydash/leaderboard/' +
(selected == 0
? 'score'
: selected == 1
? 'berry?berry=' + selectedBerryOption
: selected == 2
? 'coin'
: selected == 5
? 'legacy'
: 'total')
)
const data = await response.json()
if (data.success) setEntries(data.data as LeaderboardEntry[])
}
} catch {
setEntries([])
}
}, [selected, selectedBerryOption])
useEffect(() => {
document.title = 'Lncvrt Games - Berry Dash Leaderboards'
}, [])
useEffect(() => {
if (selected != -1) setTimeout(() => Refresh(), 0)
}, [selected, Refresh])
return (
<div className='mx-4 mt-4'>
<div className='flex justify-between items-center mb-4'>
<p className='text-3xl'>Berry Dash Leaderboards</p>
<div className='flex gap-2'>
<button
className='button btntheme1'
onClick={() => {
setEntries([])
Refresh()
}}
title='Click to refresh the leaderboards.'
hidden={selected == -1}
>
Refresh
</button>
<button
className='button btntheme1'
onClick={() => {
if (selected == -1) router.push('/game?id=1')
else {
setSelected(-1)
setEntries([])
}
}}
title='Click to go up a level.'
>
Back
</button>
</div>
</div>
<div className='box h-[calc(100vh-84px)]'>
{selected == -1 ? (
<>
<p className='text-center mt-2 text-xl'>Select a Leaderboard</p>
<div className='flex flex-col gap-2 mt-2 items-center justify-center'>
<button
className='leaderboard-button'
onClick={() => setSelected(0)}
>
Score Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(1)}
>
Berry Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(2)}
>
Coins Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(3)}
>
Level Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(4)}
>
Total XP Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(5)}
>
Legacy Leaderboard
</button>
<button
className='leaderboard-button'
onClick={() => setSelected(6)}
>
Total Berries Leaderboard
</button>
</div>
</>
) : (
<>
<div
className={`flex flex-col gap-2 overflow-y-auto ${
selected == 1 ? 'h-[calc(100vh-136px)]' : 'h-[calc(100vh-96px)]'
} px-1`}
>
{entries.map((item, index) => {
const isAccount = 'stats' in item
const isLeaderboard = 'value' in item && !isAccount
return (
<div
key={item.id}
className='leaderboard-entry flex justify-between items-center'
>
<div className='flex items-center gap-1'>
<Image
src={
!item.customIcon
? `https://games.lncvrt.xyz/api/berrydash/render-icon?icon=${
item.icon == 1
? GetIconForUser(item.id)
: item.icon
}&overlay=${item.overlay}&birdR=${
item.birdColor[0]
}&birdG=${item.birdColor[1]}&birdB=${
item.birdColor[2]
}&overlayR=${item.overlayColor[0]}&overlayG=${
item.overlayColor[1]
}&overlayB=${item.overlayColor[2]}`
: `https://games.lncvrt.xyz/api/berrydash/icon-marketplace/icon?id=${item.customIcon}&raw=true`
}
width={48}
height={48}
alt=''
className='pointer-events-none scale-x-[-1]'
/>
<p>
{item.username} (#{index + 1})
</p>
</div>
{isLeaderboard ? (
<p>
{selected === 1 || selected === 6
? 'Berries'
: selected === 2
? 'Coins'
: 'Score'}
: {item.value.toLocaleString('en-US')}
</p>
) : isAccount ? (
<p>
{selected === 3 ? 'Level' : 'XP'}:{' '}
{selected === 3
? calculateLevel(item.xp).toLocaleString('en-US')
: item.xp.toLocaleString('en-US')}
</p>
) : null}
</div>
)
})}
</div>
{selected == 1 && (
<div className='flex justify-center'>
<select
value={selectedBerryOption}
onChange={e => setSelectedBerryOption(Number(e.target.value))}
className='leaderboard-select mt-0.75'
>
<option value='0'>Normal Berry</option>
<option value='1'>Poison Berry</option>
<option value='2'>Slow Berry</option>
<option value='3'>Ultra Berry</option>
<option value='4'>Speedy Berry</option>
<option value='5'>Coin Berry</option>
<option value='6'>Random Berry</option>
<option value='7'>Anti Berry</option>
<option value='8'>Golden Berry</option>
</select>
</div>
)}
</>
)}
</div>
</div>
)
}
@@ -0,0 +1,14 @@
@import "tailwindcss";
.box {
@apply bg-(--col1) border border-(--col3) rounded-lg w-auto p-1;
}
.leaderboard-button,
.leaderboard-select {
@apply bg-(--col2) hover:bg-(--col4) border border-(--col4) hover:border-(--col6) rounded-lg px-4 py-2 inline-block transition-all duration-200 cursor-pointer;
}
.leaderboard-entry {
@apply rounded-lg text-gray-200 text-lg px-1 py-0.5 transition-colors bg-(--col2) hover:bg-(--col3) border border-(--col4) hover:border-(--col5) cursor-pointer;
}
+364
View File
@@ -0,0 +1,364 @@
'use client'
import { useEffect } from 'react'
import '@/app/Installs.css'
import { invoke } from '@tauri-apps/api/core'
import { useGlobal } from '@/app/GlobalProvider'
import { useRouter, useSearchParams } from 'next/navigation'
import { platform } from '@tauri-apps/plugin-os'
import { faWarning } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { ask } from '@tauri-apps/plugin-dialog'
import { BaseDirectory, exists, remove } from '@tauri-apps/plugin-fs'
import { writeVersionsConfig } from '@/lib/BazookaManager'
import { openFolder } from '@/lib/Util'
export default function Installs () {
const {
showPopup,
setShowPopup,
setPopupMode,
setFadeOut,
setSelectedVersionList,
downloadedVersionsConfig,
normalConfig,
setManagingVersion,
getVersionInfo,
getGameInfo,
setSelectedGame,
serverVersionList,
category,
setCategory,
setDownloadedVersionsConfig,
downloadVersions
} = useGlobal()
const params = useSearchParams()
const router = useRouter()
const id = Number(params.get('id') || 0)
const game = serverVersionList?.games.find(g => g.id === id)
useEffect(() => {
if (!showPopup) return
setSelectedVersionList([])
}, [normalConfig, setSelectedVersionList, showPopup])
if (!id || !game) return <p>Invalid game</p>
const needsRevisionUpdate = (
lastRevision: number | undefined,
version: string
) => {
if (!lastRevision) return false
return (
lastRevision > 0 &&
(downloadedVersionsConfig == undefined
? 0
: downloadedVersionsConfig?.list[version]) /
1000 <=
lastRevision
)
}
return (
<div className='mx-4 mt-4'>
<div className='flex justify-between items-center mb-4'>
<p
className={`text-3xl truncate ${
category != -1
? 'w-[calc(100vw-495px)]'
: game.id == 1
? 'w-[calc(100vw-560px)]'
: 'w-[calc(100vw-440px)]'
}`}
>
{game.name} Installs
</p>
<div className='flex gap-2'>
<button
className='button btntheme1'
onClick={() => {
router.push('/game/berrydash/leaderboards')
}}
title='View the leaderboards for this game.'
hidden={game.id != 1}
>
Leaderboards
</button>
<button
className='button btntheme1'
onClick={() => {
setCategory(-1)
}}
title='Click to go up a level.'
hidden={category == -1}
>
Back
</button>
<button
className='button btntheme1'
onClick={() => {
setSelectedGame(id)
setPopupMode(0)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to download more versions of this game.'
>
Download versions
</button>
</div>
</div>
<div className='downloads-container'>
<div className='downloads-scroll h-[calc(100vh-84px)]'>
{category == -1 &&
Object.entries(game.categoryNames)
.sort(([a], [b]) => Number(b) - Number(a))
.filter(([key]) => {
const count = Object.keys(
downloadedVersionsConfig?.list ?? {}
).filter(v => {
const info = getVersionInfo(v)
if (!info) return false
if (
platform() == 'linux' &&
info.wine &&
!normalConfig?.settings.useWineOnUnixWhenNeeded
)
return false
return info.game === id && info.category === Number(key)
}).length
return count >= 1
})
.map(([key, value]) => {
return (
<div
key={key}
className={'downloads-entry'}
title={'Click to view category'}
onClick={() => setCategory(Number(key))}
>
<div className='h-18 w-screen relative'>
<p className='text-2xl'>{value}</p>
<div
className='entry-info-item flex absolute left-0 bottom-0'
title='The amount of versions installed of this game in installed/installable format.'
onClick={e => e.stopPropagation()}
>
<p>
{(() => {
const count =
Object.keys(
downloadedVersionsConfig?.list ?? []
).filter(v => {
const info = getVersionInfo(v)
if (!info) return false
if (
platform() == 'linux' &&
info.wine &&
!normalConfig?.settings
.useWineOnUnixWhenNeeded
)
return false
return (
info.game === id &&
info.category == Number(key)
)
}).length ?? 0
return `${count} install${count === 1 ? '' : 's'}`
})()}
</p>
</div>
</div>
</div>
)
})}
{Object.keys(downloadedVersionsConfig?.list ?? []).filter(v => {
const info = getVersionInfo(v)
if (!info) return false
return info.game === id
}).length != 0 ? (
Object.keys(downloadedVersionsConfig?.list ?? [])
.sort((a, b) => {
const infoA = getVersionInfo(a)
const infoB = getVersionInfo(b)
if (!infoA || !infoB) return -1
return infoB.place - infoA.place
})
.filter(v => {
const info = getVersionInfo(v)
if (!info) return false
if (
platform() == 'linux' &&
info.wine &&
!normalConfig?.settings.useWineOnUnixWhenNeeded
)
return false
return (
info.game === id &&
(category == -1
? info.category == -1
: info.category == category)
)
})
.map(entry => (
<div
key={entry}
className={'downloads-entry'}
title={
'Click to launch game. Right-click to manage this version install'
}
onClick={async () => {
if (
needsRevisionUpdate(
getVersionInfo(entry)?.lastRevision,
entry
)
) {
const answer = await ask(
'Before proceeding, if you do not want your installation directory wiped just yet, please backup the files to another directory. When you click "Yes", it will be wiped. Click "No" if you want to open the installation folder instead.',
{
title: 'Revision Update',
kind: 'warning'
}
)
if (answer) {
const answer2 = await ask(
'Are you sure you want to update? If you did not read the last popup, please go back and read it.',
{
title: 'Revision Update',
kind: 'warning'
}
)
if (!answer2) return
//open downloads popup
setPopupMode(1)
setShowPopup(true)
setFadeOut(false)
//uninstall
setDownloadedVersionsConfig(prev => {
if (!prev) return prev
const updatedList = Object.fromEntries(
Object.entries(prev.list).filter(
([k]) => k !== entry
)
)
const updatedConfig = {
...prev,
list: updatedList
}
writeVersionsConfig(updatedConfig)
return updatedConfig
})
if (
await exists('game/' + entry, {
baseDir: BaseDirectory.AppLocalData
})
)
await remove('game/' + entry, {
baseDir: BaseDirectory.AppLocalData,
recursive: true
})
//reinstall
setSelectedVersionList([entry])
downloadVersions([entry])
} else {
openFolder(entry)
}
return
}
const verInfo = getVersionInfo(entry)
if (verInfo == undefined) return
const gameInfo = getGameInfo(verInfo.game)
if (gameInfo == undefined) return
invoke('launch_game', {
name: verInfo.id,
executable: verInfo.executable,
displayName: verInfo.displayName,
useWine: !!(
platform() == 'linux' &&
verInfo.wine &&
normalConfig?.settings.useWineOnUnixWhenNeeded
),
wineCommand: normalConfig?.settings.wineOnUnixCommand
})
}}
onContextMenu={e => {
e.preventDefault()
setManagingVersion(entry)
setPopupMode(2)
setShowPopup(true)
setFadeOut(false)
}}
>
<div className='h-18 w-screen relative'>
<p className='text-2xl'>
{getVersionInfo(entry)?.displayName}{' '}
</p>
<div className='flex gap-2 absolute left-0 bottom-0'>
<div
className='entry-info-item'
title='The date the game was installed.'
onClick={e => e.stopPropagation()}
>
<p>
Installed{' '}
{new Intl.DateTimeFormat(undefined).format(
downloadedVersionsConfig?.list[entry]
)}
</p>
</div>
<div
className='entry-info-item'
title='This version is using wine. It cannot be guarenteed to work fully and might not work at all.'
hidden={
!(
platform() == 'linux' && getVersionInfo(entry)?.wine
) ||
needsRevisionUpdate(
getVersionInfo(entry)?.lastRevision,
entry
)
}
onClick={e => e.stopPropagation()}
>
<FontAwesomeIcon icon={faWarning} color='#ffc800' />
<p>Uses wine</p>
</div>
<div
className='entry-info-item'
onClick={e => e.stopPropagation()}
hidden={
!needsRevisionUpdate(
getVersionInfo(entry)?.lastRevision,
entry
)
}
>
<FontAwesomeIcon icon={faWarning} color='#ffc800' />
<p>Needs revision update!</p>
</div>
</div>
</div>
</div>
))
) : (
<div className='flex justify-center items-center h-full'>
<p className='text-3xl'>No versions installed</p>
</div>
)}
</div>
</div>
</div>
)
}
+510
View File
@@ -0,0 +1,510 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import Sidebar from '@/componets/Sidebar'
import './Globals.css'
import { DownloadProgress } from '@/types/DownloadProgress'
import { invoke } from '@tauri-apps/api/core'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronLeft, faXmark } from '@fortawesome/free-solid-svg-icons'
import {
readNormalConfig,
readVersionsConfig,
writeVersionsConfig
} from '@/lib/BazookaManager'
import { VersionsConfig } from '@/types/VersionsConfig'
import { NormalConfig } from '@/types/NormalConfig'
import { app } from '@tauri-apps/api'
import { openUrl } from '@tauri-apps/plugin-opener'
import { GlobalProvider } from './GlobalProvider'
import { Roboto } from 'next/font/google'
import { ServerVersionsResponse } from '@/types/ServerVersionsResponse'
import { GameVersion } from '@/types/GameVersion'
import { Game } from '@/types/Game'
import { listen } from '@tauri-apps/api/event'
import { usePathname } from 'next/navigation'
import { arch, platform } from '@tauri-apps/plugin-os'
import { BaseDirectory, exists, remove } from '@tauri-apps/plugin-fs'
import VersionsDownloadPopup from '@/componets/popups/VersionsDownload'
import GamesDownloadPopup from '@/componets/popups/GamesDownload'
import DownloadsPopup from '@/componets/popups/Downloads'
import VersionVersionPopup from '@/componets/popups/VersionVersion'
import { fetch } from '@tauri-apps/plugin-http'
const roboto = Roboto({
subsets: ['latin']
})
export default function RootLayout ({
children
}: {
children: React.ReactNode
}) {
const [loading, setLoading] = useState(true)
const [loadingText, setLoadingText] = useState('Loading...')
const [outdated, setOutdated] = useState(false)
const [version, setVersion] = useState<string | null>(null)
const [platformName, setPlatformName] = useState<string | null>(null)
const [serverVersionList, setServerVersionList] =
useState<null | ServerVersionsResponse>(null)
const [selectedVersionList, setSelectedVersionList] = useState<string[]>([])
const [downloadedVersionsConfig, setDownloadedVersionsConfig] =
useState<VersionsConfig | null>(null)
const [normalConfig, setNormalConfig] = useState<NormalConfig | null>(null)
const [showPopup, setShowPopup] = useState(false)
const [popupMode, setPopupMode] = useState<null | number>(null)
const [fadeOut, setFadeOut] = useState(false)
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress[]>(
[]
)
const [downloadQueue, setDownloadQueue] = useState<string[]>([])
const [isProcessingQueue, setIsProcessingQueue] = useState<boolean>(false)
const [managingVersion, setManagingVersion] = useState<string | null>(null)
const [viewingInfoFromDownloads, setViewingInfoFromDownloads] =
useState<boolean>(false)
const [selectedGame, setSelectedGame] = useState<number | null>(null)
const [category, setCategory] = useState<number>(-1)
const pathname = usePathname()
const revisionCheck = useRef(false)
function getSpecialVersionsList (game?: number): GameVersion[] {
if (!normalConfig || !serverVersionList) return []
return serverVersionList.versions
.filter(
v => !Object.keys(downloadedVersionsConfig?.list ?? []).includes(v.id)
)
.filter(v => {
if (
platformName == 'linux' &&
v.wine &&
!normalConfig.settings.useWineOnUnixWhenNeeded
)
return false
if (game && v.game != game) return false
if (category != -1 && v.category != category) return false
if (downloadProgress.length != 0) {
return !downloadProgress.some(d => d.version === v.id)
}
return true
})
.sort((a, b) => {
if (b.game !== a.game) return a.game - b.game
return 0
})
}
const getVersionInfo = useCallback(
(id: string | undefined): GameVersion | undefined => {
if (!id) return undefined
return serverVersionList?.versions.find(v => v.id === id)
},
[serverVersionList]
)
const getGameInfo = useCallback(
(game: number | undefined): Game | undefined => {
if (!game) return undefined
return serverVersionList?.games.find(g => g.id === game)
},
[serverVersionList]
)
function getListOfGames (): Game[] {
if (!downloadedVersionsConfig?.list) return []
const gamesMap = new Map<number, Game>()
Object.keys(downloadedVersionsConfig.list).forEach(i => {
const version = getVersionInfo(i)
if (!version) return
const game = getGameInfo(version.game)
if (!game) return
gamesMap.set(game.id, game)
})
return Array.from(gamesMap.values())
}
function getVersionsAmountData (gameId: number): {
installed: number
total: number
} | null {
if (!downloadedVersionsConfig || !serverVersionList) return null
const allowWine =
platformName !== 'linux' || normalConfig?.settings.useWineOnUnixWhenNeeded
const installed = Object.keys(downloadedVersionsConfig.list).filter(v => {
const info = getVersionInfo(v)
if (!info) return false
if (info.wine && !allowWine) return false
return getGameInfo(info.game)?.id === gameId
}).length
const total = serverVersionList.versions.filter(v => {
if (!v) return false
if (v.wine && !allowWine) return false
return getGameInfo(v.game)?.id === gameId
}).length
return { installed, total }
}
const closePopup = useCallback(() => {
if (popupMode == 0 && selectedGame && pathname === '/') {
setSelectedGame(null)
setSelectedVersionList([])
} else if (viewingInfoFromDownloads) {
setViewingInfoFromDownloads(false)
setPopupMode(0)
} else {
setFadeOut(true)
setTimeout(() => setShowPopup(false), 200)
}
}, [popupMode, selectedGame, pathname, viewingInfoFromDownloads])
useEffect(() => {
let unlistenProgress: (() => void) | null = null
listen<string>('download-finishing', event => {
const displayName = event.payload
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = { ...copy[i], finishing: true }
return copy
})
}).then(f => (unlistenProgress = f))
return () => {
unlistenProgress?.()
}
}, [downloadProgress])
useEffect(() => {
;(async () => {
setPlatformName(platform())
const client = await app.getVersion()
setVersion(client)
if (process.env.NODE_ENV === 'production') {
try {
const response = await fetch(
'https://games.lncvrt.xyz/api/launcher/latest'
)
const data = await response.text()
if (data !== client) {
setOutdated(true)
return
}
} catch {
setLoadingText('Failed to check latest version.')
return
}
}
try {
const response = await fetch(
`https://games.lncvrt.xyz/api/launcher/versions?platform=${platform()}&arch=${arch()}`
)
const data = await response.json()
setServerVersionList(data)
} catch {
setLoadingText('Failed to download versions list.')
return
}
const normalConfig = await readNormalConfig()
const versionsConfig = await readVersionsConfig()
setDownloadedVersionsConfig(versionsConfig)
setNormalConfig(normalConfig)
setLoading(false)
})()
}, [])
const downloadVersions = useCallback(
async (list: string[]): Promise<void> => {
if (list.length === 0) return
setSelectedVersionList([])
const newVersions = list.filter(
version =>
!downloadQueue.includes(version) &&
!downloadProgress.some(d => d.version === version)
)
if (newVersions.length === 0) return
const newDownloads = newVersions.map(
version => new DownloadProgress(version, false, true, false)
)
setDownloadProgress(prev => [...prev, ...newDownloads])
setDownloadQueue(prev => [...prev, ...newVersions])
},
[downloadQueue, downloadProgress]
)
useEffect(() => {
if (isProcessingQueue || downloadQueue.length === 0) return
const processNextDownload = async () => {
setIsProcessingQueue(true)
const versionId = downloadQueue[0]
const info = getVersionInfo(versionId)
if (!info) {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
return
}
const gameInfo = getGameInfo(info.game)
if (!gameInfo) {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
return
}
setDownloadProgress(prev =>
prev.map(d => (d.version === versionId ? { ...d, queued: false } : d))
)
const downloadInfoRequest = await fetch(
'https://games.lncvrt.xyz/api/launcher/download?gameId=' +
info.id +
'&downloadId=' +
info.download
)
const data = await downloadInfoRequest.json()
if (!data.success) {
setDownloadProgress(prev =>
prev.map(d =>
d.version === versionId
? { ...d, queued: false, failed: true, progress: 0 }
: d
)
)
return
}
const res = await invoke<string>('download', {
url: data.data.url,
name: info.id
})
if (res === '1') {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadedVersionsConfig(prev => {
if (!prev) return prev
const updated = {
...prev,
list: {
...prev.list,
[versionId]: Date.now()
}
}
writeVersionsConfig(updated)
return updated
})
} else {
setDownloadProgress(prev =>
prev.map(d =>
d.version === versionId
? { ...d, queued: false, failed: true, progress: 0 }
: d
)
)
}
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
}
processNextDownload()
}, [
downloadQueue,
isProcessingQueue,
getVersionInfo,
getGameInfo,
normalConfig
])
useEffect(() => {
if (revisionCheck.current) return
if (!serverVersionList || !downloadedVersionsConfig) return
revisionCheck.current = true
;(async () => {
for (const [key, value] of Object.entries(
downloadedVersionsConfig.list
)) {
const verInfo = serverVersionList.versions.find(item => item.id === key)
if (
!verInfo ||
(verInfo.lastRevision > 0 && value / 1000 <= verInfo.lastRevision)
) {
if (
await exists('game/' + key + '/' + verInfo?.executable, {
baseDir: BaseDirectory.AppLocalData
})
)
await remove('game/' + key + '/' + verInfo?.executable, {
baseDir: BaseDirectory.AppLocalData,
recursive: true
})
}
}
})()
}, [serverVersionList, downloadedVersionsConfig, downloadVersions])
return (
<>
<html lang='en' className={roboto.className}>
<body
className={
normalConfig?.settings.theme === 1
? 'red-theme'
: normalConfig?.settings.theme === 2
? 'blue-theme'
: normalConfig?.settings.theme === 3
? 'purple-theme'
: 'dark-theme'
}
>
{loading ? (
<>
<div className='w-screen h-screen flex items-center justify-center'>
{outdated ? (
<div className='text-center'>
<p className='text-8xl mb-4'>Outdated Launcher!</p>
<p className='text-4xl mb-4'>
Please update to the latest version to continue.
</p>
<button
className='button'
onClick={() =>
openUrl('https://games.lncvrt.xyz/berrydash/download')
}
>
Download latest version
</button>
</div>
) : (
<p className='text-7xl text-center'>{loadingText}</p>
)}
</div>
</>
) : (
<GlobalProvider
value={{
serverVersionList,
selectedVersionList,
setSelectedVersionList,
downloadProgress,
setDownloadProgress,
showPopup,
setShowPopup,
popupMode,
setPopupMode,
fadeOut,
setFadeOut,
downloadedVersionsConfig,
setDownloadedVersionsConfig,
normalConfig,
setNormalConfig,
managingVersion,
setManagingVersion,
getVersionInfo,
getGameInfo,
getListOfGames,
setSelectedGame,
getVersionsAmountData,
viewingInfoFromDownloads,
version,
downloadVersions,
category,
setCategory,
downloadQueue,
setDownloadQueue,
closePopup,
getSpecialVersionsList,
selectedGame,
setViewingInfoFromDownloads
}}
>
<div
tabIndex={0}
onKeyDown={e => {
if (showPopup && e.key === 'Escape') closePopup()
}}
>
<Sidebar />
<div className='relative z-0'>
<main className='ml-60'>{children}</main>
</div>
{showPopup && (
<div
className={`popup-overlay ${fadeOut ? 'fade-out' : ''}`}
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) {
if (viewingInfoFromDownloads) {
setPopupMode(0)
setViewingInfoFromDownloads(false)
setManagingVersion(null)
setSelectedGame(null)
}
setFadeOut(true)
setTimeout(() => setShowPopup(false), 200)
}
}}
>
<div className='popup-box'>
<button
className='close-button btntheme1'
onClick={() => closePopup()}
>
<FontAwesomeIcon
icon={
(popupMode == 0 &&
selectedGame &&
pathname === '/') ||
viewingInfoFromDownloads ||
popupMode == 4
? faChevronLeft
: faXmark
}
/>
</button>
{popupMode === 0 && selectedGame ? (
<VersionsDownloadPopup />
) : popupMode === 0 && !selectedGame ? (
<GamesDownloadPopup />
) : popupMode === 1 ? (
<DownloadsPopup />
) : popupMode === 2 ? (
<VersionVersionPopup />
) : null}
</div>
</div>
)}
</div>
</GlobalProvider>
)}
</body>
</html>
</>
)
}
-416
View File
@@ -1,416 +0,0 @@
'use client'
import { verifySignature } from '@/lib/util'
import { useGlobal } from '@/providers/GlobalProvider'
import { app } from '@tauri-apps/api'
import { message } from '@tauri-apps/plugin-dialog'
import { fetch } from '@tauri-apps/plugin-http'
import { openUrl } from '@tauri-apps/plugin-opener'
import { arch, platform } from '@tauri-apps/plugin-os'
import { Dispatch, SetStateAction, useState } from 'react'
function AccountLoggedOut () {
const { account, setServerVersionList } = useGlobal()
const [username, setUsername] = useState<string>('')
const [password, setPassword] = useState<string>('')
return (
<>
<p className='text-3xl ml-4 mt-4'>Account Login</p>
<div className='ml-4 mt-4 bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<form
className='flex flex-col gap-2'
onSubmit={async e => {
e.preventDefault()
const response = await fetch(
'https://games.lncvrt.xyz/api/account/login',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username,
password
})
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status != 200 ||
!(await verifySignature(JSON.stringify(data), signature))
) {
await message(
"Failed to login, there was an issue validating the data wasn't tampered with.",
{ title: 'Request tampered', kind: 'error' }
)
return
}
if (data.success) {
const response2 = await fetch(
'https://games.lncvrt.xyz/api/launcher/versions',
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch(),
Authorization: data.data.session
}
}
)
const signature2 = response2.headers.get('x-signature') ?? ''
const data2 = await response2.json()
if (
response2.status == 200 &&
(await verifySignature(JSON.stringify(data2), signature2))
) {
setServerVersionList(data2)
}
await account?.set('session', data.data.session)
await account?.set('name', data.data.username)
await account?.set('id', data.data.id)
await account?.set('admin', data.data.admin)
} else {
await message(data.message || 'n/a', {
title: 'Failed to login',
kind: 'error'
})
}
}}
>
<input
id='username'
name='username'
placeholder='Username'
type='username'
value={username}
onChange={e => setUsername(e.target.value)}
required
className='input-field btntheme1'
/>
<input
id='password'
name='password'
placeholder='Password'
type='password'
value={password}
onChange={e => setPassword(e.target.value)}
required
className='input-field btntheme1'
/>
<button type='submit' className='button btntheme1'>
Login
</button>
<div className='flex justify-center flex-col gap-2 mt-6 text-center'>
<button
type='button'
onClick={async () =>
await openUrl(
'https://games.lncvrt.xyz/account/forgot-username'
)
}
className='button btntheme1'
>
Forgot username?
</button>
<button
type='button'
onClick={async () =>
await openUrl(
'https://games.lncvrt.xyz/account/forgot-password'
)
}
className='button btntheme1'
>
Forgot password?
</button>
<button
type='button'
onClick={async () =>
await openUrl('https://games.lncvrt.xyz/account/register')
}
className='button btntheme1'
>
Don&apos;t have an account?
</button>
</div>
</form>
</div>
</>
)
}
function AccountChangeUsername ({
setChangingUsername
}: {
setChangingUsername: Dispatch<SetStateAction<boolean>>
}) {
const { account, accountSession } = useGlobal()
const [newUsername, setNewUsername] = useState<string>('')
return (
<>
<p className='text-3xl ml-4 mt-4'>Change Account Username</p>
<div className='ml-4 mt-4 bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<form
className='flex flex-col gap-2'
onSubmit={async e => {
e.preventDefault()
const response = await fetch(
'https://games.lncvrt.xyz/api/account/change-username',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
authorization: accountSession ?? ''
},
body: JSON.stringify({
newUsername
})
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status != 200 ||
!(await verifySignature(JSON.stringify(data), signature))
) {
await message(
"Failed to change username, there was an issue validating the data wasn't tampered with.",
{ title: 'Request tampered', kind: 'error' }
)
return
}
if (data.success) {
await account?.set('session', data.data)
await account?.set('name', newUsername)
setChangingUsername(false)
} else {
await message(data.message || 'n/a', {
title: 'Failed to change username',
kind: 'error'
})
}
}}
>
<input
id='new-username'
name='new-username'
placeholder='New username'
type='username'
value={newUsername}
onChange={e => setNewUsername(e.target.value)}
required
className='input-field btntheme1'
/>
<button type='submit' className='button btntheme1'>
Change Username
</button>
<button
type='button'
className='button btntheme1'
onClick={() => setChangingUsername(false)}
>
Back
</button>
</form>
</div>
</>
)
}
function AccountChangePassword ({
setChangingPassword
}: {
setChangingPassword: Dispatch<SetStateAction<boolean>>
}) {
const { account, accountSession, setServerVersionList } = useGlobal()
const [newPassword, setNewPassword] = useState<string>('')
const [retypeNewPassword, setRetypeNewPassword] = useState<string>('')
return (
<>
<p className='text-3xl ml-4 mt-4'>Change Account Password</p>
<div className='ml-4 mt-4 bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<form
className='flex flex-col gap-2'
onSubmit={async e => {
e.preventDefault()
if (newPassword !== retypeNewPassword) {
await message('Passwords must match', {
title: "Passwords don't match!",
kind: 'error'
})
return
}
const response = await fetch(
'https://games.lncvrt.xyz/api/account/change-password',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
authorization: accountSession ?? ''
},
body: JSON.stringify({
newPassword
})
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status != 200 ||
!(await verifySignature(JSON.stringify(data), signature))
) {
await message(
"Failed to change password, there was an issue validating the data wasn't tampered with.",
{ title: 'Request tampered', kind: 'error' }
)
return
}
if (data.success) {
const response2 = await fetch(
'https://games.lncvrt.xyz/api/launcher/versions',
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch(),
Authorization: data.data
}
}
)
const signature2 = response2.headers.get('x-signature') ?? ''
const data2 = await response2.json()
if (
response2.status == 200 &&
(await verifySignature(JSON.stringify(data2), signature2))
) {
setServerVersionList(data2)
}
await account?.set('session', data.data)
setChangingPassword(false)
} else {
await message(data.message || 'n/a', {
title: 'Failed to change password',
kind: 'error'
})
}
}}
>
<input
id='new-password'
name='new-password'
placeholder='New password'
type='password'
autoComplete='new-password'
value={newPassword}
onChange={e => setNewPassword(e.target.value)}
required
className='input-field btntheme1'
/>
<input
id='retype-new-password'
name='retype-new-password'
placeholder='Re-type password'
type='password'
autoComplete='new-password'
value={retypeNewPassword}
onChange={e => setRetypeNewPassword(e.target.value)}
required
className='input-field btntheme1'
/>
<button type='submit' className='button btntheme1'>
Change Password
</button>
<button
type='button'
className='button btntheme1'
onClick={() => setChangingPassword(false)}
>
Back
</button>
</form>
</div>
</>
)
}
function AccountLoggedIn () {
const { account, accountName, setServerVersionList } = useGlobal()
const [changingUsername, setChangingUsername] = useState<boolean>(false)
const [changingPassword, setChangingPassword] = useState<boolean>(false)
if (changingUsername)
return <AccountChangeUsername setChangingUsername={setChangingUsername} />
if (changingPassword)
return <AccountChangePassword setChangingPassword={setChangingPassword} />
return (
<>
<p className='text-3xl ml-4 mt-4'>Account</p>
<div className='ml-4 mt-4 bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<p>Logged in as: {accountName}</p>
<div className='flex justify-center flex-col gap-2 mt-4 text-center'>
<button
onClick={() => setChangingUsername(true)}
className='button btntheme1'
>
Change username
</button>
<button
onClick={() => setChangingPassword(true)}
className='button btntheme1'
>
Change password
</button>
<button
onClick={async () => {
const response = await fetch(
'https://games.lncvrt.xyz/api/launcher/versions',
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch(),
Authorization: ''
}
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status == 200 &&
(await verifySignature(JSON.stringify(data), signature))
) {
setServerVersionList(data)
}
await account?.clear()
}}
className='button btntheme1'
>
Logout
</button>
</div>
</div>
</>
)
}
export default function AccountsPage () {
const { accountSession, accountId, accountName } = useGlobal()
if (!accountSession || !accountId || !accountName) return <AccountLoggedOut />
else return <AccountLoggedIn />
}
-389
View File
@@ -1,389 +0,0 @@
'use client'
import { useEffect } from 'react'
import { useGlobal } from '@/providers/GlobalProvider'
import { useSearchParams } from 'next/navigation'
import { platform } from '@tauri-apps/plugin-os'
import { faWarning } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { ask } from '@tauri-apps/plugin-dialog'
import { BaseDirectory, exists } from '@tauri-apps/plugin-fs'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
export default function GamePage () {
const {
versionsList,
serverVersionList,
showPopup,
setShowPopup,
setPopupMode,
setFadeOut,
setSelectedVersionList,
setManagingVersion,
setSelectedGame,
category,
setCategory,
downloadVersions,
downloadProgress,
linuxUseWine,
customDataLocation,
needsRevisionUpdate,
launchGame,
developerMode,
theme,
accountSession,
accountId,
accountName,
version
} = useGlobal()
const params = useSearchParams()
const id = Number(params.get('id') || 0)
const game = serverVersionList?.games.find(g => g.id === id)
useEffect(() => {
if (!showPopup) return
setSelectedVersionList([])
}, [setSelectedVersionList, showPopup])
if (!id || !game) return null
const filteredVersions = Object.keys(versionsList).filter(v => {
const info = serverVersionList?.versions.find(vf => vf.id == v)
if (!info) return false
if (platform() == 'linux' && info.wine && !linuxUseWine) return false
return (
info.game === id &&
(category == -1 ? info.category == -1 : info.category == category)
)
})
return (
<div className='mx-4 mt-4'>
<div className='flex justify-between items-center mb-4'>
<p className='text-3xl truncate min-w-0 flex-1'>{game.name} Installs</p>
<div className='flex gap-2'>
{game.id == 1 && (
<>
<button
className='button btntheme1'
onClick={async () => {
const window = await WebviewWindow.getByLabel(
'berrydashchatroom'
)
if (window) {
await window.setFocus()
return
}
new WebviewWindow('berrydashchatroom', {
title: 'Berry Dash Chatroom',
url: `https://games.lncvrt.xyz/game/berry-dash/chatroom?launcher=${version}&theme=${theme}&accountToken=${accountSession}&accountId=${accountId}&accountName=${accountName}`,
width: 800,
height: 600,
minWidth: 800,
minHeight: 600
})
}}
title='View the chatroom for this game.'
>
Chatroom
</button>
<button
className='button btntheme1'
onClick={async () => {
const window = await WebviewWindow.getByLabel(
'berrydashleaderboards'
)
if (window) {
await window.setFocus()
return
}
new WebviewWindow('berrydashleaderboards', {
title: 'Berry Dash Leaderboards',
url: `https://games.lncvrt.xyz/game/berry-dash/leaderboards?launcher=${version}&theme=${theme}`,
width: 800,
height: 600,
minWidth: 800,
minHeight: 600
})
}}
title='View the leaderboards for this game.'
>
Leaderboards
</button>
</>
)}
{game.id == 9 && category == -1 && (
<button
className='button btntheme1'
onClick={async () => {
const window = await WebviewWindow.getByLabel('xpsdashboard')
if (window) {
await window.setFocus()
return
}
new WebviewWindow('xpsdashboard', {
title: 'XPS Dashboard',
url: 'https://xps.lncvrt.xyz/dashboard/',
width: 1280,
height: 720,
minWidth: 1280,
minHeight: 720
})
}}
title='Open the GDPS Dashboard!'
>
Dashboard
</button>
)}
{game.id == 11 && category == -1 && (
<button
className='button btntheme1'
onClick={async () => {
const window = await WebviewWindow.getByLabel('georayschatroom')
if (window) {
await window.setFocus()
return
}
new WebviewWindow('georayschatroom', {
title: 'Geometry Rays Chatroom',
url: `https://games.lncvrt.xyz/game/geometry-rays/chatroom?launcher=${version}&theme=${theme}`,
width: 800,
height: 600,
minWidth: 800,
minHeight: 600
})
}}
title='View the chatroom for this game.'
>
Chatroom
</button>
)}
{category != -1 && (
<button
className='button btntheme1'
onClick={() => {
setCategory(-1)
}}
title='Click to go up a level.'
>
Back
</button>
)}
<button
className='button btntheme1'
onClick={() => {
setSelectedGame(id)
setPopupMode(0)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to download more versions of this game.'
>
Download versions
</button>
</div>
</div>
<div
className={`main-container main-flex ${
platform() == 'windows'
? 'h-[calc(100vh-116px)]'
: 'h-[calc(100vh-84px)]'
}`}
>
{category == -1 &&
Object.entries(game.categoryNames)
.filter(([key]) => {
const count = Object.keys(versionsList).filter(v => {
const info = serverVersionList?.versions.find(vf => vf.id == v)
if (!info) return false
if (platform() == 'linux' && info.wine && !linuxUseWine)
return false
return info.game === id && info.category === Number(key)
}).length
return count >= 1
})
.sort(([a], [b]) => Number(b) - Number(a))
.map(([key, value]) => {
return (
<div
key={key}
className='main-entry'
title='Click to view category.'
onClick={() => setCategory(Number(key))}
>
<div className='h-18 w-screen relative'>
{developerMode && (
<p className='absolute bottom-0 right-0 text-sm'>{key}</p>
)}
<p className='text-2xl'>{value}</p>
<div
className='entry-info-item flex absolute left-0 bottom-0'
title='The amount of versions installed of this game in installed/installable format.'
onClick={e => e.stopPropagation()}
>
<p>
{(() => {
const count =
Object.keys(versionsList).filter(v => {
const info = serverVersionList?.versions.find(
vf => vf.id == v
)
if (!info) return false
if (
platform() == 'linux' &&
info.wine &&
!linuxUseWine
)
return false
return (
info.game === id && info.category == Number(key)
)
}).length ?? 0
return `${count} install${count === 1 ? '' : 's'}`
})()}
</p>
</div>
</div>
</div>
)
})}
{filteredVersions.length === 0 &&
(category !== -1 ||
Object.keys(versionsList).filter(v => {
const info = serverVersionList?.versions.find(vf => vf.id == v)
if (!info) return false
if (platform() == 'linux' && info.wine && !linuxUseWine)
return false
return info.game === id
}).length === 0) && (
<div className='flex justify-center items-center h-full'>
<p className='text-3xl'>No versions installed</p>
</div>
)}
{filteredVersions
.sort((a, b) => {
const infoA = serverVersionList?.versions.find(vf => vf.id == a)
const infoB = serverVersionList?.versions.find(vf => vf.id == b)
if (!infoA || !infoB) return 0
return infoB.place - infoA.place
})
.map(v => {
const versionInfo = serverVersionList?.versions.find(
vf => vf.id == v
)
if (!versionInfo) return
return (
<div
key={v}
className='main-entry'
title='Click to launch game. Right-click to manage this version install.'
onClick={async () => await launchGame(versionInfo)}
onContextMenu={e => {
e.preventDefault()
setManagingVersion(v)
setPopupMode(2)
setShowPopup(true)
setFadeOut(false)
}}
>
<div className='h-18 w-screen relative'>
{developerMode && (
<p className='absolute bottom-0 right-0 text-sm'>
{versionInfo.id}
</p>
)}
<p className='text-2xl'>{versionInfo.displayName}</p>
<div className='flex gap-2 absolute left-0 bottom-0'>
<div
className='entry-info-item'
title='The date the game was installed.'
>
<p>
Installed{' '}
{new Intl.DateTimeFormat(undefined).format(
versionsList[v]
)}
</p>
</div>
{platform() == 'linux' &&
versionInfo.wine &&
!needsRevisionUpdate(versionInfo.lastRevision, v) && (
<div
className='entry-info-item'
title='This version is using wine. It cannot be guarenteed to work fully and might not work at all.'
>
<FontAwesomeIcon icon={faWarning} color='#ffc800' />
<p>Uses wine</p>
</div>
)}
{needsRevisionUpdate(versionInfo.lastRevision, v) && (
<div className='entry-info-item'>
<FontAwesomeIcon icon={faWarning} color='#ffc800' />
<p>Needs revision update!</p>
</div>
)}
</div>
{versionInfo.modSupportDownload && (
<button
className='absolute right-0 bottom-0 button'
title='Click to manage mods for this game!'
onClick={async e => {
e.stopPropagation()
if (
!(await exists(
customDataLocation
? customDataLocation + '/'
: '' + 'game/' + v + '/BepInEx',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
))
) {
if (
(await ask(
"You don't have BepInEx (the mod loader for Unity Games), would you like to install it now? It is about 1MB in size. If you choose yes, it will download the recommended BepInEx version for " +
versionInfo.displayName +
'.',
{ title: 'BepInEx not found!', kind: 'error' }
)) &&
!downloadProgress.find(d => d.version == v)
) {
await downloadVersions([
{
id: v,
type: 1
}
])
}
return
}
setManagingVersion(v)
setPopupMode(3)
setShowPopup(true)
setFadeOut(false)
}}
>
Mod Manager
</button>
)}
</div>
</div>
)
})}
</div>
</div>
)
}
-992
View File
@@ -1,992 +0,0 @@
'use client'
import '@/styles/globals.css'
import { useCallback, useEffect, useRef, useState } from 'react'
import Sidebar from '@/components/Sidebar'
import { DownloadProgress } from '@/types/DownloadProgress'
import { app } from '@tauri-apps/api'
import { GlobalProvider } from '@/providers/GlobalProvider'
import { Roboto } from 'next/font/google'
import { ServerVersionsResponse } from '@/types/ServerVersionsResponse'
import { listen } from '@tauri-apps/api/event'
import { usePathname } from 'next/navigation'
import { arch, platform } from '@tauri-apps/plugin-os'
import {
isPermissionGranted,
requestPermission
} from '@tauri-apps/plugin-notification'
import {
BaseDirectory,
copyFile,
exists,
readTextFile,
remove
} from '@tauri-apps/plugin-fs'
import { fetch } from '@tauri-apps/plugin-http'
import { openFolder, verifySignature } from '@/lib/util'
import { getCurrentWindow, UserAttentionType } from '@tauri-apps/api/window'
import { Mod } from '@/types/Mod'
import { load, Store } from '@tauri-apps/plugin-store'
import { notifyUser } from '@/lib/notifications'
import { GameVersion } from '@/types/GameVersion'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronLeft, faXmark } from '@fortawesome/free-solid-svg-icons'
import { invoke } from '@tauri-apps/api/core'
import semver from 'semver'
import { exit } from '@tauri-apps/plugin-process'
import { ask, message } from '@tauri-apps/plugin-dialog'
import VersionsDownloadPopup from '@/popups/VersionsDownload'
import GamesDownloadPopup from '@/popups/GamesDownload'
import DownloadsPopup from '@/popups/Downloads'
import ManageVersionPopup from '@/popups/ManageVersion'
import ModDownloadsPopup from '@/popups/ModDownloads'
import VersionChangelogPopup from '@/popups/VersionChangelog'
import ManageGamePopup from '@/popups/ManageGame'
const roboto = Roboto({
subsets: ['latin']
})
export default function RootLayout ({
children
}: {
children: React.ReactNode
}) {
const [loading, setLoading] = useState(true)
const [version, setVersion] = useState<string | null>(null)
const [platformName, setPlatformName] = useState<string | null>(null)
const [serverVersionList, setServerVersionList] =
useState<null | ServerVersionsResponse>(null)
const [selectedVersionList, setSelectedVersionList] = useState<string[]>([])
const [showPopup, setShowPopup] = useState(false)
const [popupMode, setPopupMode] = useState<null | number>(null)
const [fadeOut, setFadeOut] = useState(false)
const [downloadProgress, setDownloadProgress] = useState<DownloadProgress[]>(
[]
)
const [downloadQueue, setDownloadQueue] = useState<string[]>([])
const [isProcessingQueue, setIsProcessingQueue] = useState<boolean>(false)
const [managingVersion, setManagingVersion] = useState<string | null>(null)
const [managingGame, setManagingGame] = useState<number | null>(null)
const [viewingInfoFromDownloads, setViewingInfoFromDownloads] =
useState<boolean>(false)
const [selectedGame, setSelectedGame] = useState<number | null>(null)
const [category, setCategory] = useState<number>(-1)
const [showModInfo, setShowModInfo] = useState<Mod | null>(null)
const pathname = usePathname()
const revisionCheck = useRef(false)
const [settings, setSettings] = useState<Store | null>(null)
const [versions, setVersions] = useState<Store | null>(null)
const [account, setAccount] = useState<Store | null>(null)
const [sidebarShowGames, setSidebarShowGames] = useState<boolean>(false)
const [linuxUseWine, setLinuxUseWine] = useState<boolean>(false)
const [linuxWineCommand, setLinuxWineCommand] =
useState<string>('wine %path%')
const [theme, setTheme] = useState<string>('dark')
const [customDataLocation, setCustomDataLocation] = useState<string>('')
const [developerMode, setDeveloperMode] = useState<boolean>(false)
const [versionsList, setVersionsList] = useState<Record<string, number>>({})
const [modsList, setModsList] = useState<
Record<string, Record<string, number>>
>({})
const [launchesList, setLaunchesList] = useState<
Record<string, Record<string, number>>
>({})
const [accountSession, setAccountSession] = useState<string | null>(null)
const [accountId, setAccountId] = useState<string | null>(null)
const [accountName, setAccountName] = useState<string | null>(null)
const [accountAdmin, setAccountAdmin] = useState<boolean>(false)
const downloadVersions = useCallback(
async (
list: Array<{
id: string
type: 0 | 1 | 2
modDownload?: number
gameId?: number
modId?: number
modVersion?: string
}>
): Promise<void> => {
if (list.length === 0) return
setSelectedVersionList([])
const newVersions = list.filter(
item =>
!downloadQueue.includes(item.id) &&
!downloadProgress.some(d => d.version === item.id)
)
if (newVersions.length === 0) return
const newDownloads = newVersions.map(
item =>
new DownloadProgress(
item.id,
0,
0,
false,
false,
false,
false,
true,
false,
0,
0,
0,
false,
0,
0,
null,
null,
null,
item.type,
item.modDownload ?? null,
item.gameId ?? null,
item.modId ?? null,
item.modVersion ?? null
)
)
setDownloadProgress(prev => [...prev, ...newDownloads])
setDownloadQueue(prev => [...prev, ...newVersions.map(v => v.id)])
},
[downloadQueue, downloadProgress]
)
useEffect(() => {
if (isProcessingQueue || downloadQueue.length === 0) return
const processNextDownload = async () => {
setIsProcessingQueue(true)
const versionId = downloadQueue[0]
const downloadInfo = downloadProgress.find(d => d.version == versionId)
if (!downloadInfo) {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
return
}
const info = serverVersionList?.versions.find(vf => vf.id == versionId)
if (!info) {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
return
}
const gameInfo = serverVersionList?.games.find(vf => vf.id == info.game)
if (!gameInfo) {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
return
}
setDownloadProgress(prev =>
prev.map(d => (d.version === versionId ? { ...d, queued: false } : d))
)
const downloadInfoRequest = await fetch(
'https://games.lncvrt.xyz/api/launcher/download' +
(downloadInfo.type == 0
? '?versionId=' + info.id + '&downloadId=' + info.download
: '?downloadId=' +
(downloadInfo.type == 1
? info.modSupportDownload
: downloadInfo.modDownload)) +
(downloadInfo.type == 2 ? '&modId=' + downloadInfo.modId : ''),
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch()
}
}
)
const signature = downloadInfoRequest.headers.get('x-signature') ?? ''
const data = await downloadInfoRequest.json()
if (
downloadInfoRequest.status != 200 ||
!(await verifySignature(JSON.stringify(data), signature)) ||
!data.success
) {
setDownloadProgress(prev =>
prev.map(d =>
d.version === versionId
? { ...d, queued: false, failed: true, progress: 0 }
: d
)
)
await notifyUser(
'Download Failed',
`The download for version ${info.displayName} has failed.`
)
await getCurrentWindow().requestUserAttention(
UserAttentionType.Critical
)
return
}
setDownloadProgress(prev =>
prev.map(d =>
d.version === versionId
? {
...d,
url: data.data.url,
executable: downloadInfo.type == 0 ? info.executable : null,
hash: data.data.hash
}
: d
)
)
const res = await invoke<string>('download', {
url: data.data.url,
name: info.id,
hash: data.data.hash,
downloadType: downloadInfo.type,
modId: String(downloadInfo.modId ?? '')
})
if (res === '1') {
setDownloadProgress(prev => prev.filter(d => d.version !== versionId))
if (downloadInfo.type != 1) {
if (downloadInfo.type == 2) {
const currentMods =
(await versions?.get<Record<string, Record<string, number>>>(
'mods'
)) ?? {}
await versions?.set('mods', {
...currentMods,
[downloadInfo.modGame! + '-' + downloadInfo.modId!]: {
[downloadInfo.modVersion!]: Date.now()
}
})
} else {
const currentList =
(await versions?.get<Record<string, number>>('list')) ?? {}
await versions?.set('list', {
...currentList,
[versionId]: Date.now()
})
}
}
} else if (res == '0') {
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === info.id)
if (i === -1) return prev
if (prev[i].canceled) {
return prev.filter((_, idx) => idx !== i)
}
const copy = [...prev]
copy[i] = {
...copy[i],
downloading: false,
paused: true,
failed: false
}
return copy
})
} else if (res == '-1') {
setDownloadProgress(prev =>
prev.map(d =>
d.version === versionId
? { ...d, queued: false, failed: true, progress: 0 }
: d
)
)
await notifyUser(
'Download Failed',
`The download for version ${info.displayName} has failed.`
)
await getCurrentWindow().requestUserAttention(
UserAttentionType.Critical
)
}
setDownloadQueue(prev => prev.slice(1))
setIsProcessingQueue(false)
}
processNextDownload()
}, [
downloadQueue,
isProcessingQueue,
downloadProgress,
serverVersionList,
settings,
versions,
versionsList,
modsList
])
function getSpecialVersionsList (game?: number): GameVersion[] {
if (!serverVersionList) return []
return serverVersionList.versions
.filter(v => !Object.keys(versionsList).includes(v.id))
.filter(v => {
if (platformName == 'linux' && v.wine && !linuxUseWine) return false
if (game && v.game != game) return false
if (category != -1 && v.category != category) return false
if (downloadProgress.length != 0) {
return !downloadProgress.some(d => d.version === v.id)
}
return true
})
.sort((a, b) => {
if (b.game !== a.game) return a.game - b.game
return 0
})
}
const closePopup = useCallback(() => {
if (popupMode == 0 && selectedGame && pathname === '/main/library') {
setSelectedGame(null)
setSelectedVersionList([])
} else if (viewingInfoFromDownloads) {
setViewingInfoFromDownloads(false)
setPopupMode(0)
} else if (popupMode == 3 && showModInfo) {
setShowModInfo(null)
} else if (popupMode == 4) {
setPopupMode(2)
} else {
setFadeOut(true)
setTimeout(() => setShowPopup(false), 200)
}
}, [popupMode, selectedGame, pathname, viewingInfoFromDownloads, showModInfo])
const needsRevisionUpdate = (
lastRevision: number | undefined,
version: string
) => {
if (!lastRevision) return false
return (
lastRevision > 0 &&
(versionsList == undefined ? 0 : versionsList[version]) / 1000 <=
lastRevision
)
}
const uninstallVersion = async (
version: string,
updateList: boolean = true
) => {
if (updateList)
await versions?.set(
'list',
Object.fromEntries(
Object.entries(versionsList).filter(([k]) => k !== version)
)
)
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') +
'game/' +
version,
{
baseDir: customDataLocation ? undefined : BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
'game/' +
version,
{
baseDir: customDataLocation ? undefined : BaseDirectory.AppLocalData,
recursive: true
}
)
}
const launchGame = async (versionInfo: GameVersion) => {
if (needsRevisionUpdate(versionInfo.lastRevision, versionInfo.id)) {
const answer = await ask(
'Before proceeding, if you do not want your installation directory wiped just yet, please backup the files to another directory. When you click "Yes", it will be wiped. Click "No" if you want to open the installation folder instead.',
{
title: 'Revision Update',
kind: 'warning'
}
)
if (answer) {
const answer2 = await ask(
'Are you sure you want to update? If you did not read the last popup, please go back and read it.',
{
title: 'Revision Update',
kind: 'warning'
}
)
if (!answer2) return
//open downloads popup
setPopupMode(1)
setShowPopup(true)
setFadeOut(false)
//uninstall
await uninstallVersion(versionInfo.id)
//reinstall
setSelectedVersionList([versionInfo.id])
await downloadVersions([
{
id: versionInfo.id,
type: 0
}
])
} else {
await openFolder(versionInfo.id)
}
return
}
await invoke('launch_game', {
name: versionInfo.id,
executable: versionInfo.executable,
displayName: versionInfo.displayName,
useWine: !!(platform() == 'linux' && versionInfo.wine && linuxUseWine),
wineCommand: linuxWineCommand
})
await versions?.set('launches', {
...launchesList,
[versionInfo.game]: {
...launchesList[versionInfo.game],
[versionInfo.id]: Date.now()
}
})
}
useEffect(() => {
const unlisteners: (() => void)[] = []
const setupListeners = async () => {
unlisteners.push(
await listen<string>('download-size', event => {
const [displayName, sizeStr] = event.payload.split(':')
const size = Number(sizeStr)
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = { ...copy[i], size }
return copy
})
})
)
unlisteners.push(
await listen<string>('download-progress', async event => {
const [displayName, progStr, totalSizeStr, speedStr, etaSecsStr] =
event.payload.split(':')
const prog = Number(progStr)
const progBytes = Number(totalSizeStr)
const speed = Number(speedStr)
const etaSecs = Number(etaSecsStr)
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = {
...copy[i],
progress: prog,
progressBytes: progBytes,
speed,
etaSecs
}
return copy
})
})
)
unlisteners.push(
await listen<string>('download-hash-checking', event => {
const displayName = event.payload
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = { ...copy[i], hash_checking: true, downloading: false }
return copy
})
})
)
unlisteners.push(
await listen<string>('unzip-start', event => {
const displayName = event.payload
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = { ...copy[i], hash_checking: false, unzipping: true }
return copy
})
})
)
unlisteners.push(
await listen<string>('unzip-progress', async event => {
const [displayName, unzippedStr, unzipTotalStr] =
event.payload.split(':')
const unzipped = Number(unzippedStr)
const unzipTotal = Number(unzipTotalStr)
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = {
...copy[i],
unzipped,
unzipTotal
}
return copy
})
})
)
unlisteners.push(
await listen<string>('download-start', event => {
const displayName = event.payload
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = {
...copy[i],
downloading: true,
paused: false,
failed: false
}
return copy
})
})
)
unlisteners.push(
await listen<string>('download-stop', event => {
const displayName = event.payload
setDownloadProgress(prev => {
const i = prev.findIndex(d => d.version === displayName)
if (i === -1) return prev
const copy = [...prev]
copy[i] = { ...copy[i], downloading: false }
return copy
})
})
)
}
setupListeners()
return () => {
unlisteners.forEach(unlisten => unlisten())
}
}, [])
useEffect(() => {
;(async () => {
setPlatformName(platform())
const client = await app.getVersion()
setVersion(client)
const legacyOptions = {
baseDir: BaseDirectory.AppLocalData
}
if (
platform() == 'windows' &&
(await exists('versions.json', legacyOptions))
) {
if (
await exists('versions.json', {
baseDir: BaseDirectory.AppConfig
})
)
await remove('versions.json', {
baseDir: BaseDirectory.AppConfig
})
await copyFile('versions.json', 'versions.json', {
fromPathBaseDir: BaseDirectory.AppLocalData,
toPathBaseDir: BaseDirectory.AppConfig
})
await remove('versions.json', legacyOptions)
}
const settingsLocal = await load('settings.json', {
autoSave: true,
defaults: {
version: client,
sidebarAlwaysShowGames: true,
linuxUseWine: false,
linuxWineCommand: 'wine %path%',
theme: 'dark',
customDataLocation: '',
developerMode: false
}
})
const versionsLocal = await load('versions.json', {
autoSave: true,
defaults: {
version: client,
list: {},
mods: {},
launches: {}
}
})
const accountLocal = await load('account.json', {
autoSave: true,
defaults: {
version: client,
session: null,
id: null,
name: null,
admin: false
}
})
const cfgVer = (await settingsLocal.get<string>('version')) ?? client
const versVer = (await versionsLocal.get<string>('version')) ?? client
if (semver.gt(cfgVer, client) || semver.gt(versVer, client)) {
exit(1)
return
}
await settingsLocal.set('version', client)
await versionsLocal.set('version', client)
await accountLocal.set('version', client)
if (await exists('config.json', legacyOptions)) {
const config = await readTextFile('config.json', legacyOptions)
const raw = JSON.parse(config)
if (
raw.settings &&
raw.settings.theme &&
semver.satisfies(raw.version, '>=1.0.0 <=1.5.4')
) {
const parsed = Number(raw.settings.theme)
if (parsed == 3) raw.settings.theme = 2
if (parsed == 4) raw.settings.theme = 3
else if (parsed != 0 && parsed != 1) raw.settings.theme = 0
}
if (raw.settings.allowNotifications)
await settingsLocal?.set(
'notificationsAllowed',
Boolean(raw.settings.allowNotifications)
)
if (raw.settings.alwaysShowGamesInSidebar)
await settingsLocal?.set(
'sidebarAlwaysShowGames',
Boolean(raw.settings.alwaysShowGamesInSidebar)
)
if (raw.settings.useWineOnUnixWhenNeeded)
await settingsLocal?.set(
'linuxUseWine',
Boolean(raw.settings.useWineOnUnixWhenNeeded)
)
if (raw.settings.wineOnUnixCommand)
await settingsLocal?.set(
'linuxWineCommand',
String(raw.settings.wineOnUnixCommand)
)
if (raw.settings.theme) {
const tempTheme = (() => {
switch (Number(raw.settings.theme)) {
case 1:
return 'red'
case 2:
return 'blue'
case 3:
return 'purple'
default:
return 'dark'
}
})()
await settingsLocal?.set('theme', tempTheme)
}
await remove('config.json', legacyOptions)
}
setSettings(settingsLocal)
setVersions(versionsLocal)
setAccount(accountLocal)
try {
const response = await fetch(
'https://games.lncvrt.xyz/api/launcher/versions',
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch(),
Authorization: (await accountLocal.get('session')) ?? ''
}
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status == 200 &&
(await verifySignature(JSON.stringify(data), signature))
) {
setServerVersionList(data)
} else {
await message(
'Failed to get version manifest, please try again later.',
{ title: 'Error fetching launcher manifest', kind: 'error' }
)
await exit(1)
return
}
} catch {
await message(
'Failed to get version manifest, please try again later.',
{ title: 'Error fetching launcher manifest', kind: 'error' }
)
await exit(1)
return
}
if (!(await isPermissionGranted())) {
await requestPermission()
}
setLoading(false)
})()
}, [])
useEffect(() => {
if (revisionCheck.current) return
if (!serverVersionList) return
revisionCheck.current = true
;(async () => {
for (const [key, value] of Object.entries(versionsList)) {
const verInfo = serverVersionList.versions.find(item => item.id === key)
if (
verInfo &&
verInfo.lastRevision > 0 &&
value / 1000 <= verInfo.lastRevision
) {
await invoke('remove_stale_executable', {
version: key,
executable: verInfo.executable
})
}
}
})()
}, [serverVersionList, versionsList])
useEffect(() => {
if (
downloadProgress.length === 0 &&
downloadQueue.length === 0 &&
showPopup &&
popupMode === 1
) {
setTimeout(async () => {
await notifyUser('Downloads Complete', 'All downloads finished!')
await getCurrentWindow().requestUserAttention(
UserAttentionType.Informational
)
closePopup()
}, 0)
}
}, [downloadProgress, downloadQueue, showPopup, popupMode, closePopup])
useEffect(() => {
if (!settings || !versions) return
const unlisteners: Promise<() => void>[] = []
function watchSettings<T> (key: string, fn: (v: T | undefined) => void) {
settings!.get<T>(key).then(fn)
unlisteners.push(settings!.onKeyChange<T>(key, fn))
}
function watchVersions<T> (key: string, fn: (v: T | undefined) => void) {
versions!.get<T>(key).then(fn)
unlisteners.push(versions!.onKeyChange<T>(key, fn))
}
function watchAccount<T> (key: string, fn: (v: T | undefined) => void) {
account!.get<T>(key).then(fn)
unlisteners.push(account!.onKeyChange<T>(key, fn))
}
watchSettings<string>('theme', v => setTheme(v ?? 'dark'))
watchSettings<boolean>('sidebarShowGames', v =>
setSidebarShowGames(v ?? true)
)
watchSettings<boolean>('linuxUseWine', v => setLinuxUseWine(v ?? false))
watchSettings<string>('linuxWineCommand', v =>
setLinuxWineCommand(v ?? 'wine %path%')
)
watchSettings<string>('customDataLocation', v =>
setCustomDataLocation(v ?? '')
)
watchSettings<boolean>('developerMode', v => setDeveloperMode(v ?? false))
watchVersions<Record<string, number>>('list', v => setVersionsList(v ?? {}))
watchVersions<Record<string, Record<string, number>>>('mods', v =>
setModsList(v ?? {})
)
watchVersions<Record<string, Record<string, number>>>('launches', v =>
setLaunchesList(v ?? {})
)
watchAccount<string | null>('session', v => setAccountSession(v ?? null))
watchAccount<string | null>('id', v => setAccountId(v ?? null))
watchAccount<string | null>('name', v => setAccountName(v ?? null))
watchAccount<boolean>('admin', v => setAccountAdmin(v ?? false))
return () => {
unlisteners.forEach(u => u.then(fn => fn()))
}
}, [settings, versions, account])
return (
<>
<html lang='en' className={roboto.className}>
<body className={theme + '-theme'}>
{!loading && (
<GlobalProvider
value={{
serverVersionList,
setServerVersionList,
selectedVersionList,
setSelectedVersionList,
downloadProgress,
setDownloadProgress,
showPopup,
setShowPopup,
popupMode,
setPopupMode,
fadeOut,
setFadeOut,
managingVersion,
setManagingVersion,
setSelectedGame,
viewingInfoFromDownloads,
version,
downloadVersions,
category,
setCategory,
downloadQueue,
setDownloadQueue,
closePopup,
selectedGame,
setViewingInfoFromDownloads,
showModInfo,
setShowModInfo,
getSpecialVersionsList,
settings,
versions,
account,
sidebarShowGames,
linuxUseWine,
linuxWineCommand,
theme,
customDataLocation,
developerMode,
versionsList,
modsList,
launchesList,
accountSession,
accountId,
accountName,
accountAdmin,
managingGame,
setManagingGame,
needsRevisionUpdate,
uninstallVersion,
launchGame
}}
>
<div
tabIndex={0}
onKeyDown={e => {
if (showPopup && e.key === 'Escape') closePopup()
}}
>
<Sidebar />
{platformName == 'windows' && (
<div className='relative z-2 ml-59.75 w-[calc(100vw-239px)] border-b border-b-(--col3) h-8.25 bg-(--col1)' />
)}
<div className='relative z-0'>
<main className='ml-60'>{children}</main>
</div>
{showPopup && (
<div
className={`popup-overlay ${fadeOut ? 'fade-out' : ''}`}
onClick={(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) {
if (showModInfo) setShowModInfo(null)
if (viewingInfoFromDownloads) {
setPopupMode(0)
setViewingInfoFromDownloads(false)
setManagingVersion(null)
setSelectedGame(null)
}
setFadeOut(true)
setTimeout(() => setShowPopup(false), 200)
}
}}
>
<div className='popup-box'>
<button
className='popup-top-button left-2 btntheme1'
onClick={() => closePopup()}
>
<FontAwesomeIcon
icon={
(popupMode == 0 &&
selectedGame &&
pathname === '/main/library') ||
viewingInfoFromDownloads ||
(popupMode == 3 && showModInfo) ||
popupMode == 4
? faChevronLeft
: faXmark
}
/>
</button>
{popupMode === 0 && selectedGame ? (
<VersionsDownloadPopup />
) : popupMode === 0 && !selectedGame ? (
<GamesDownloadPopup />
) : popupMode === 1 ? (
<DownloadsPopup />
) : popupMode === 2 ? (
<ManageVersionPopup />
) : popupMode === 3 ? (
<ModDownloadsPopup />
) : popupMode === 4 ? (
<VersionChangelogPopup />
) : popupMode === 5 ? (
<ManageGamePopup />
) : null}
</div>
</div>
)}
</div>
</GlobalProvider>
)}
</body>
</html>
</>
)
}
-147
View File
@@ -1,147 +0,0 @@
'use client'
import { useEffect } from 'react'
import { useGlobal } from '@/providers/GlobalProvider'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCheck,
faShieldHalved,
faWarning
} from '@fortawesome/free-solid-svg-icons'
import { platform } from '@tauri-apps/plugin-os'
import { useRouter } from 'next/navigation'
export default function LibraryPage () {
const {
versionsList,
serverVersionList,
showPopup,
setShowPopup,
setPopupMode,
setFadeOut,
setSelectedVersionList,
setSelectedGame,
setCategory,
setManagingGame,
developerMode
} = useGlobal()
const router = useRouter()
useEffect(() => {
if (!showPopup) return
setSelectedVersionList([])
}, [setSelectedVersionList, showPopup])
const filteredGames =
serverVersionList?.games.filter(g =>
serverVersionList.versions
.filter(v => v.game === g.id)
.some(v => Object.keys(versionsList).includes(v.id))
) ?? []
return (
<div className='mx-4 mt-4'>
<div className='flex justify-between items-center mb-4'>
<p className='text-3xl'>Games</p>
<button
className='button btntheme1'
onClick={() => {
setSelectedGame(null)
setPopupMode(0)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to download more games.'
>
Download game
</button>
</div>
<div
className={`main-container main-flex ${
platform() == 'windows'
? 'h-[calc(100vh-116px)]'
: 'h-[calc(100vh-84px)]'
}`}
>
{filteredGames.length == 0 ? (
<div className='flex justify-center items-center h-full'>
<p className='text-3xl'>No games installed</p>
</div>
) : (
filteredGames.map(i => (
<div
key={i.id}
className='main-entry'
title='Click to view game installs.'
onClick={() => {
setCategory(-1)
router.push('/main/game?id=' + i.id)
}}
onContextMenu={e => {
e.preventDefault()
setManagingGame(i.id)
setPopupMode(5)
setShowPopup(true)
setFadeOut(false)
}}
>
<div className='h-18 w-screen relative'>
{developerMode && (
<p className='absolute bottom-0 right-0 text-sm'>{i.id}</p>
)}
<p className='text-2xl'>{i.name}</p>
<div className='flex gap-2 absolute left-0 bottom-0'>
<div
className='entry-info-item'
title='The amount of versions installed of this game in installed/installable format.'
>
<p>
{(() => {
const gameVersions = (
serverVersionList?.versions ?? []
).filter(v => v.game === i.id)
const installed = gameVersions.filter(v =>
Object.keys(versionsList).includes(v.id)
).length
return gameVersions.length
? `${installed}/${gameVersions.length}`
: 'N/A'
})()}{' '}
versions installed
</p>
</div>
{i.official ? (
<div
className='entry-info-item'
title='This game is official.'
>
<FontAwesomeIcon icon={faCheck} color='#19c84b' />
<p>Official</p>
</div>
) : (
<div
className='entry-info-item'
title={
i.verified
? 'This game is verified to be safe'
: 'This game is not verified to be save. Proceed with caution.'
}
>
<FontAwesomeIcon
icon={i.verified ? faShieldHalved : faWarning}
color={i.verified ? '#19c84b' : '#ffc800'}
/>
<p>{i.verified ? 'Verified' : 'Unverified'}</p>
</div>
)}
</div>
</div>
</div>
))
)}
</div>
</div>
)
}
-180
View File
@@ -1,180 +0,0 @@
'use client'
import { useGlobal } from '@/providers/GlobalProvider'
import { Swiper, SwiperSlide } from 'swiper/react'
import type { Swiper as SwiperType } from 'swiper'
import { Navigation } from 'swiper/modules'
import 'swiper/css'
import { formatDistanceToNow } from 'date-fns'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faChevronLeft,
faChevronRight,
faEllipsis,
faPlay
} from '@fortawesome/free-solid-svg-icons'
import { useEffect, useRef, useState } from 'react'
export default function HomePage () {
const {
launchesList,
serverVersionList,
versionsList,
accountName,
launchGame,
setManagingVersion,
setPopupMode,
setShowPopup,
setFadeOut
} = useGlobal()
const filteredLaunchesList = Object.fromEntries(
Object.entries(launchesList)
.flatMap(([gameId, launches]) => {
const entries = Object.entries(launches).filter(([version]) => {
return (
serverVersionList?.versions.find(v => version == v.id) &&
Object.entries(versionsList).find(([v]) => v == version)
)
})
if (entries.length === 0) return []
const [version, timestamp] = entries.reduce((latest, current) =>
current[1] > latest[1] ? current : latest
)
return [[`${gameId}-${version}`, timestamp] as const]
})
.sort((a, b) => b[1] - a[1])
)
const swiperRef = useRef<SwiperType | null>(null)
const prevRef = useRef<HTMLButtonElement>(null)
const nextRef = useRef<HTMLButtonElement>(null)
const [isLocked, setIsLocked] = useState(false)
const [recentSlidesPerView, setRecentSlidesPerView] = useState(1)
useEffect(() => {
const update = () => {
setRecentSlidesPerView(Math.floor(window.innerWidth / 400))
}
update()
window.addEventListener('resize', update)
return () => window.removeEventListener('resize', update)
}, [])
return (
<div className='mx-4 mt-4'>
<div className='flex flex-col gap-1 mb-4'>
<p className='text-3xl'>Home</p>
<p className='text-gray-300'>Welcome back, {accountName ?? 'User'}!</p>
</div>
<div>
<p className='text-2xl'>Jump back in</p>
{Object.entries(filteredLaunchesList).length == 0 ? (
<p className='text-gray-300'>You have no recently launched games</p>
) : (
<div className='flex flex-col items-center gap-2'>
<Swiper
modules={[Navigation]}
spaceBetween={16}
slidesPerView={Math.min(
recentSlidesPerView,
Object.entries(filteredLaunchesList).length
)}
autoHeight={false}
className='w-full'
onSwiper={swiper => {
swiperRef.current = swiper
setIsLocked(swiper.isLocked)
}}
onResize={swiper => {
setIsLocked(swiper.isLocked)
}}
onUpdate={swiper => {
setIsLocked(swiper.isLocked)
}}
onBeforeInit={swiper => {
if (
swiper.params.navigation &&
typeof swiper.params.navigation !== 'boolean'
) {
swiper.params.navigation.prevEl = prevRef.current
swiper.params.navigation.nextEl = nextRef.current
}
}}
>
{Object.entries(filteredLaunchesList).map(([key, timestamp]) => {
const versionInfo = serverVersionList?.versions.find(
v => v.id == key.split('-').slice(1).join('-')
)
if (!versionInfo) return
return (
<SwiperSlide
key={key}
className='flex flex-col gap-2 bg-(--col1) border border-(--col3) rounded-lg px-3 py-2'
>
<p
className='truncate text-2xl'
title={versionInfo?.displayName}
>
{versionInfo?.displayName}
</p>
<p className='truncate text-gray-300'>
Last played{' '}
<span title={new Date(timestamp).toString()}>
{formatDistanceToNow(new Date(timestamp), {
addSuffix: true
})}
</span>
</p>
<div className='flex flex-row gap-2 my-1'>
<FontAwesomeIcon
icon={faPlay}
className='button btntheme1'
onClick={async () => await launchGame(versionInfo)}
/>
<FontAwesomeIcon
icon={faEllipsis}
className='button btntheme1'
onClick={() => {
setManagingVersion(versionInfo.id)
setPopupMode(2)
setShowPopup(true)
setFadeOut(false)
}}
/>
</div>
</SwiperSlide>
)
})}
</Swiper>
{!isLocked && (
<div className='flex flex-row gap-2'>
<button
ref={prevRef}
onClick={() => swiperRef.current?.slidePrev()}
className='button btntheme1 w-8 h-8 flex justify-center items-center'
>
<FontAwesomeIcon icon={faChevronLeft} />
</button>
<button
ref={nextRef}
onClick={() => swiperRef.current?.slideNext()}
className='button btntheme1 w-8 h-8 flex justify-center items-center'
>
<FontAwesomeIcon icon={faChevronRight} />
</button>
</div>
)}
</div>
)}
</div>
</div>
)
}
-310
View File
@@ -1,310 +0,0 @@
'use client'
import { Setting } from '@/components/Setting'
import { useGlobal } from '@/providers/GlobalProvider'
import { copyToClipboard } from '@/lib/clipboard'
import { platform } from '@tauri-apps/plugin-os'
import { confirm, message, open } from '@tauri-apps/plugin-dialog'
import { invoke } from '@tauri-apps/api/core'
import Dropdown from '@/components/Dropdown'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { exit, relaunch } from '@tauri-apps/plugin-process'
import { BaseDirectory, exists, readDir, remove } from '@tauri-apps/plugin-fs'
import { openPath } from '@tauri-apps/plugin-opener'
import { appLocalDataDir } from '@tauri-apps/api/path'
import { getCurrentWindow } from '@tauri-apps/api/window'
export default function SettingsPage () {
const {
settings,
versions,
account,
version,
versionsList,
linuxUseWine,
linuxWineCommand,
theme,
customDataLocation,
downloadProgress
} = useGlobal()
return (
<>
<p className='text-3xl ml-4 mt-4'>Settings</p>
<div className='flex flex-row p-4 gap-4'>
<div className='bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<Setting
label='Use wine if needed'
value={linuxUseWine}
onChange={async () => {
await settings?.set('linuxUseWine', !linuxUseWine)
}}
className={platform() == 'linux' ? '' : 'hidden'}
/>
{platform() == 'linux' && linuxUseWine && (
<>
<p>Wine Command:</p>
<input
type='text'
value={linuxWineCommand}
onChange={async e =>
await settings?.set('linuxWineCommand', e.target.value)
}
className='input-field my-1'
></input>
</>
)}
<Setting
label='Use custom data location'
value={!!customDataLocation}
disabled={downloadProgress.length > 0}
onChange={async () => {
if (customDataLocation) {
try {
const confirmation = await confirm(
'Data will be moved back to the original location. The launcher will restart when completed and will not be visible until the restart.',
{ title: 'Moving data', kind: 'warning' }
)
if (!confirmation) return
const window = getCurrentWindow()
await window.hide()
await invoke('move_game_data', { destination: '' })
await settings?.set('customDataLocation', '')
await relaunch()
} catch {
await exit(1)
}
} else {
const selected = await open({
directory: true,
title: 'Select data location'
})
if (!selected || typeof selected !== 'string') return
try {
const confirmation = await confirm(
`Data will be moved to the directory "${selected}". The launcher will restart when completed and will not be visible until the restart.`,
{ title: 'Moving data', kind: 'warning' }
)
if (!confirmation) return
const window = getCurrentWindow()
await window.hide()
await invoke('move_game_data', { destination: selected })
await settings?.set('customDataLocation', selected)
await relaunch()
} catch {
await exit(1)
await exit(1)
}
}
}}
title='Move game data to a custom storage location, like a different disk.'
/>
{customDataLocation && (
<p className='text-sm opacity-50 ml-6 -mt-1 mb-2'>
{customDataLocation}
</p>
)}
<div className='flex flex-row gap-2 items-center'>
<p
title='The theme you want the launcher to use.'
className='text-lg'
>
Theme:
</p>
<Dropdown
value={theme}
options={[
{ label: 'Dark', value: 'dark' },
{ label: 'Red', value: 'red' },
{ label: 'Blue', value: 'blue' },
{ label: 'Purple', value: 'purple' }
]}
onChange={async val => {
await settings?.set('theme', val)
const window = await WebviewWindow.getByLabel(
'berrydashleaderboards'
)
if (window) {
await window.close()
new WebviewWindow('berrydashleaderboards', {
title: 'Berry Dash Leaderboards',
url:
'https://games.lncvrt.xyz/game/berry-dash/leaderboards?launcher=1&theme=' +
val,
width: 800,
height: 600,
resizable: false,
maximizable: false
})
}
}}
/>
</div>
</div>
<div className='bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit flex flex-col gap-2'>
<button
className='button btntheme1'
title='Restarts the launcher. This may help if the launcher is having issues.'
onClick={async () => await relaunch()}
>
Restart launcher
</button>
<button
className='button btntheme1'
title='Completely reset the launcher, delete games, logout of account & reset settings.'
onClick={async () => {
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') + 'game',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') + 'game',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') +
'downloads',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
'downloads',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
await settings?.clear()
await versions?.clear()
await account?.clear()
await relaunch()
}}
>
Reset launcher
</button>
<button
className='button btntheme1'
title='If you pause or cancel a download, it will be removed here.'
onClick={async () => {
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') +
'downloads',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
'downloads',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
}}
>
Delete download cache
</button>
<button
className='button btntheme1'
title='If you had a game that was downloaded before it was taken down after you downloaded it, it will get removed here.'
onClick={async () => {
const items = await readDir(
(customDataLocation ? customDataLocation + '/' : '') + 'game',
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
const removed: string[] = []
for (const item of items) {
if (item.isFile || item.isSymlink) continue
if (
!Object.entries(versionsList).find(v => v[0] == item.name)
) {
removed.push(item.name)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
'game/' +
item.name,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
}
}
await message(
'Removed the following game items: ' +
(removed.length == 0 ? '(none)' : removed.join(', ')),
{ title: 'Sucessfully cleaned games folder', kind: 'info' }
)
}}
>
Delete invalid/unavailable games
</button>
<button
className='button btntheme1'
title='This will open the directory with the app data.'
onClick={async () => await openPath(await appLocalDataDir())}
>
Open app data folder
</button>
{customDataLocation && (
<button
className='button btntheme1'
title='This will open the directory with the custom app data.'
onClick={async () => await openPath(customDataLocation)}
>
Open custom app data folder
</button>
)}
<p className='text-center'>Hover buttons for descriptions</p>
</div>
</div>
<p
className='fixed bottom-1.5 right-1.5 rounded-md cursor-pointer px-1 border z-100 transition-colors btntheme1'
onClick={async () => await copyToClipboard(`v${version}`)}
title='The current launcher version.'
>
v{version}
</p>
</>
)
}
+127
View File
@@ -0,0 +1,127 @@
'use client'
import { useEffect } from 'react'
import './Installs.css'
import { useGlobal } from './GlobalProvider'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCheck,
faShieldHalved,
faWarning
} from '@fortawesome/free-solid-svg-icons'
import { useRouter } from 'next/navigation'
export default function Installs () {
const {
showPopup,
setShowPopup,
setPopupMode,
setFadeOut,
setSelectedVersionList,
downloadedVersionsConfig,
normalConfig,
setSelectedGame,
getListOfGames,
getVersionsAmountData,
setCategory
} = useGlobal()
const router = useRouter()
useEffect(() => {
if (!showPopup) return
setSelectedVersionList([])
}, [normalConfig, setSelectedVersionList, showPopup])
return (
<div className='mx-4 mt-4'>
<div className='flex justify-between items-center mb-4'>
<p className='text-3xl'>Games</p>
<button
className='button btntheme1'
onClick={() => {
setSelectedGame(null)
setPopupMode(0)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to download more games.'
>
Download game
</button>
</div>
<div className='downloads-container'>
<div className='downloads-scroll h-[calc(100vh-84px)]'>
{downloadedVersionsConfig &&
Object.keys(downloadedVersionsConfig.list).length ? (
getListOfGames()
.sort((a, b) => {
return a.id - b.id
})
.map(i => (
<div
key={i.id}
className={'downloads-entry'}
title={'Click to view game installs'}
onClick={() => {
setCategory(-1)
router.push('/game?id=' + i.id)
}}
>
<div className='h-18 w-screen relative'>
<p className='text-2xl'>{i.name}</p>
<div className='flex gap-2 absolute left-0 bottom-0'>
<div
className='entry-info-item'
title='The amount of versions installed of this game in installed/installable format.'
onClick={e => e.stopPropagation()}
>
<p>
{(() => {
const data = getVersionsAmountData(i.id)
if (!data) return 'N/A'
return `${data.installed}/${data.total}`
})()}{' '}
versions installed
</p>
</div>
<div
className='entry-info-item'
hidden={!i.official}
title='This game is official.'
onClick={e => e.stopPropagation()}
>
<FontAwesomeIcon icon={faCheck} color='#19c84b' />
<p>Official</p>
</div>
<div
className='entry-info-item'
hidden={i.official}
title={
i.verified
? 'This game is verified to be safe'
: 'This game is not verified to be save. Proceed with caution.'
}
onClick={e => e.stopPropagation()}
>
<FontAwesomeIcon
icon={i.verified ? faShieldHalved : faWarning}
color={i.verified ? '#19c84b' : '#ffc800'}
/>
<p>{i.verified ? 'Verified' : 'Unverified'}</p>
</div>
</div>
</div>
</div>
))
) : (
<div className='flex justify-center items-center h-full'>
<p className='text-3xl'>No games installed</p>
</div>
)}
</div>
</div>
</div>
)
}
+156
View File
@@ -0,0 +1,156 @@
'use client'
import { useEffect, useState } from 'react'
import { Setting } from '@/componets/Setting'
import { writeNormalConfig } from '@/lib/BazookaManager'
import { useGlobal } from '@/app/GlobalProvider'
import { platform } from '@tauri-apps/plugin-os'
export default function Settings () {
const [alwaysShowGamesInSidebar, setAlwaysShowGamesInSidebar] =
useState(false)
const [useWineOnUnixWhenNeeded, setUseWineOnUnixWhenNeeded] = useState(false)
const [wineOnUnixCommand, setWineOnUnixCommand] = useState('wine %path%')
const [theme, setTheme] = useState(0)
const [loaded, setLoaded] = useState(false)
const { normalConfig, setNormalConfig, version } = useGlobal()
useEffect(() => {
;(async () => {
while (normalConfig != null) {
setAlwaysShowGamesInSidebar(
normalConfig.settings.alwaysShowGamesInSidebar
)
setUseWineOnUnixWhenNeeded(
normalConfig.settings.useWineOnUnixWhenNeeded
)
setWineOnUnixCommand(normalConfig.settings.wineOnUnixCommand)
setTheme(normalConfig.settings.theme)
setLoaded(true)
break
}
})()
}, [normalConfig])
return (
<>
<p className='text-3xl ml-4 mt-4'>Settings</p>
{loaded && (
<div className='ml-4 mt-4 bg-(--col1) border border-(--col3) rounded-lg p-4 w-fit h-fit'>
<Setting
label='Always show games in sidebar'
value={alwaysShowGamesInSidebar}
onChange={async () => {
if (!normalConfig) return
setAlwaysShowGamesInSidebar(!alwaysShowGamesInSidebar)
setNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
alwaysShowGamesInSidebar: !alwaysShowGamesInSidebar
}
})
await writeNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
alwaysShowGamesInSidebar: !alwaysShowGamesInSidebar
}
})
}}
title="This setting will make it so when you are on a page like this, the games won't disappear."
/>
<Setting
label='Use wine when needed to launch games'
value={useWineOnUnixWhenNeeded}
onChange={async () => {
if (!normalConfig) return
setUseWineOnUnixWhenNeeded(!useWineOnUnixWhenNeeded)
setNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
useWineOnUnixWhenNeeded: !useWineOnUnixWhenNeeded
}
})
await writeNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
useWineOnUnixWhenNeeded: !useWineOnUnixWhenNeeded
}
})
}}
className={platform() == 'linux' ? '' : 'hidden'}
/>
<p hidden={!(platform() == 'linux' && useWineOnUnixWhenNeeded)}>
Wine Command:
</p>
<input
type='text'
value={wineOnUnixCommand}
onChange={async e => {
if (!normalConfig) return
setWineOnUnixCommand(e.target.value)
setNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
wineOnUnixCommand: e.target.value
}
})
await writeNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
wineOnUnixCommand: e.target.value
}
})
}}
className={`input-field my-1 ${
platform() == 'linux' && useWineOnUnixWhenNeeded ? '' : 'hidden'
}`}
></input>
<div title='The theme you want the launcher to use.'>
<label className='text-lg'>Theme:</label>
<select
className='ml-2 bg-(--col2) border border-(--col4) rounded-md'
value={theme}
onChange={async e => {
if (!normalConfig) return
const newTheme = parseInt(e.target.value)
setTheme(newTheme)
setNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
theme: newTheme
}
})
await writeNormalConfig({
...normalConfig,
settings: {
...normalConfig.settings,
theme: newTheme
}
})
}}
>
<option value={0}>Dark (default)</option>
<option value={1}>Red</option>
<option value={2}>Blue</option>
<option value={3}>Purple</option>
</select>
</div>
</div>
)}
<p
className='fixed bottom-1.5 right-1.5 rounded-md cursor-pointer px-1 border z-100 transition-colors btntheme1'
title='The current launcher version.'
>
v{version}
</p>
</>
)
}
-16
View File
@@ -1,16 +0,0 @@
'use client'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
export default function UpdateCheckingPage () {
const router = useRouter()
useEffect(() => {
if (process.env.NODE_ENV !== 'production') {
router.push('/main')
}
}, [])
return <p className='text-5xl text-center'>Checking for updates</p>
}
-41
View File
@@ -1,41 +0,0 @@
'use client'
import '@/styles/globals.css'
import { platform } from '@tauri-apps/plugin-os'
import { Roboto } from 'next/font/google'
import { useEffect, useState } from 'react'
const roboto = Roboto({
subsets: ['latin']
})
export default function RootLayout ({
children
}: {
children: React.ReactNode
}) {
const [platformName, setPlatformName] = useState<string | null>(null)
useEffect(() => {
setTimeout(() => setPlatformName(platform()), 0)
}, [])
return (
<>
<html lang='en' className={roboto.className}>
<body className='dark-theme'>
{platformName == 'windows' && (
<div className='relative z-2 w-screen border-b border-b-(--col3) h-8.25 bg-(--col1)' />
)}
<div
className={`w-screen ${
platformName == 'windows' ? 'h-[calc(100vh-64px)]' : 'h-screen'
} flex items-center justify-center`}
>
{children}
</div>
</body>
</html>
</>
)
}
-20
View File
@@ -1,20 +0,0 @@
'use client'
import { openUrl } from '@tauri-apps/plugin-opener'
export default function UpdateCheckingPage () {
return (
<div className='text-center'>
<p className='text-6xl mb-4'>Outdated Launcher!</p>
<p className='text-2xl mb-4'>
Please update to the latest version to continue.
</p>
<button
className='button btntheme1'
onClick={() => openUrl('https://games.lncvrt.xyz/download')}
>
Download latest version!
</button>
</div>
)
}
-5
View File
@@ -1,5 +0,0 @@
'use client'
export default function UpdateCheckingPage () {
return <p className='text-5xl text-center'>Updating launcher</p>
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.2 MiB

-61
View File
@@ -1,61 +0,0 @@
import { useState, useRef, useEffect } from 'react'
import '@/styles/dropdown.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronDown } from '@fortawesome/free-solid-svg-icons'
type Option = {
label: string
value: string | number
}
type Props = {
value: string | number
options: Option[]
onChange: (value: string | number) => void | Promise<void>
}
export default function Dropdown ({ value, options, onChange }: Props) {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
const selected = options.find(o => o.value === value)
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) {
setOpen(false)
}
}
window.addEventListener('mousedown', handleClick)
return () => window.removeEventListener('mousedown', handleClick)
}, [])
return (
<div ref={ref} className='dropdown'>
<button className='dropdown-btn' onClick={() => setOpen(o => !o)}>
<span>{selected?.label ?? 'Select...'}</span>
<FontAwesomeIcon
icon={faChevronDown}
className={`dropdown-arrow ${open ? 'open' : ''}`}
/>
</button>
<div className={`dropdown-menu ${open ? 'open' : ''}`}>
{options.map((option, i) => (
<div
key={option.value}
className={`dropdown-item ${
option.value === value ? 'active' : ''
}`}
style={{ ['--i']: i } as React.CSSProperties}
onClick={async () => {
await onChange(option.value)
setOpen(false)
}}
>
{option.label}
</div>
))}
</div>
</div>
)
}
-12
View File
@@ -1,12 +0,0 @@
import '@/styles/dropdown.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faChevronDown } from '@fortawesome/free-solid-svg-icons'
export default function ExpandArrow ({ open }: { open: boolean }) {
return (
<FontAwesomeIcon
icon={faChevronDown}
className={`dropdown-arrow ${!open ? 'open' : ''}`}
/>
)
}
-17
View File
@@ -1,17 +0,0 @@
type ProgressBarProps = {
progress: number
className?: string
}
export default function ProgressBar ({ progress, className }: ProgressBarProps) {
return (
<div
className={`w-full bg-(--col1) border border-(--col5) rounded-full h-4 overflow-hidden ${className}`}
>
<div
className='bg-(--col8) border-r border-r-(--col5) h-full'
style={{ width: `${progress}%` }}
/>
</div>
)
}
-282
View File
@@ -1,282 +0,0 @@
'use client'
import '@/styles/sidebar.css'
import Icon from '@/assets/Icon.png'
import { openUrl } from '@tauri-apps/plugin-opener'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCog,
faDownload,
faGamepad,
faHexagonNodes,
faHome,
faLayerGroup,
faUser,
faUserShield
} from '@fortawesome/free-solid-svg-icons'
import { faDiscord } from '@fortawesome/free-brands-svg-icons'
import { platform } from '@tauri-apps/plugin-os'
import { useGlobal } from '@/providers/GlobalProvider'
import Image from 'next/image'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { Lexend } from 'next/font/google'
import React, { useState } from 'react'
import { message } from '@tauri-apps/plugin-dialog'
import ExpandArrow from './ExpandArrow'
const lexend = Lexend({
subsets: ['latin']
})
export default function Sidebar () {
const {
serverVersionList,
versionsList,
setShowPopup,
setPopupMode,
setFadeOut,
downloadProgress,
category,
setCategory,
linuxUseWine,
setManagingGame,
settings,
developerMode,
accountName,
accountAdmin,
sidebarShowGames
} = useGlobal()
const pathname = usePathname()
const params = useSearchParams()
const router = useRouter()
const [devModeClicks, setDevModeClicks] = useState<number>(0)
return (
<aside className='sidebar'>
{platform() == 'macos' && (
<div
className='macos-drag'
onMouseDown={async e => {
if (e.buttons === 1) {
if (e.detail === 2) {
await getCurrentWindow().toggleMaximize()
} else {
await getCurrentWindow().startDragging()
}
}
}}
/>
)}
<div
className={
'flex items-center h-10 w-60 ' +
(platform() == 'windows' ? 'pl-1 pt-1' : 'pl-2 pt-2') +
(platform() == 'macos'
? // ? Number(version().split('.')[0]) >= 26
// ? ' mt-6'
' mt-5'
: '')
}
onMouseDown={async e => {
if (platform() != 'macos') return
if (e.buttons === 1) {
if (e.detail === 2) {
await getCurrentWindow().toggleMaximize()
} else {
await getCurrentWindow().startDragging()
}
}
}}
>
<Image draggable={false} src={Icon} width={36} height={36} alt='' />
<p className={`ml-1 text-[16px] whitespace-nowrap ${lexend.className}`}>
Lncvrt Games Launcher
</p>
</div>
<nav className='nav-links overflow-auto'>
<Link
draggable={false}
href='/main'
className={`link relative flex items-center ${
pathname === '/main' ? 'active' : ''
}`}
>
<FontAwesomeIcon icon={faHome} className='mr-2' /> Home
</Link>
<Link
draggable={false}
href='/main/library'
className={`link relative flex items-center ${
pathname === '/main/library' || pathname.startsWith('/main/game')
? 'active'
: ''
}`}
onContextMenu={async e => {
e.preventDefault()
if (developerMode) {
await settings?.set('developerMode', false)
await message(
'Developer mode disabled! You can enable it again by right clicking the games button 3 times again.',
{ title: 'Developer mode off', kind: 'info' }
)
return
}
if (devModeClicks == 2) {
await settings?.set('developerMode', true)
setDevModeClicks(0)
await message(
'Developer mode sucessfully enabled! You can disable it by right clicking the games button again.',
{ title: 'Developer mode on', kind: 'info' }
)
} else {
setDevModeClicks(devModeClicks + 1)
}
}}
>
<FontAwesomeIcon icon={faHexagonNodes} className='mr-2' /> Library
{(pathname === '/main/library' ||
pathname.startsWith('/main/game')) && (
<div
className='ml-auto w-6 h-6 flex justify-center items-center'
onClick={async e => {
e.preventDefault()
await settings?.set('sidebarShowGames', !sidebarShowGames)
}}
>
<ExpandArrow open={sidebarShowGames} />
</div>
)}
</Link>
{(pathname === '/main/library' || pathname.startsWith('/main/game')) &&
sidebarShowGames &&
serverVersionList?.games
.filter(g =>
serverVersionList.versions
.filter(v => v.game === g.id)
.some(v => Object.keys(versionsList).includes(v.id))
)
.map(i => (
<React.Fragment key={i.id}>
<div
draggable={false}
className={`link ${
pathname === '/main/game' &&
Number(params.get('id') || 0) == i.id
? 'active'
: ''
} ml-auto w-50`}
onClick={() => {
setCategory(-1)
router.push('/main/game?id=' + i.id)
}}
onContextMenu={e => {
e.preventDefault()
setManagingGame(i.id)
setPopupMode(5)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to view game installs.'
>
<div className='flex items-center'>
<FontAwesomeIcon
icon={
Object.entries(i.categoryNames).length > 0
? faLayerGroup
: faGamepad
}
className='mr-2'
/>
<span className='truncate max-w-full'>{i.name}</span>
</div>
</div>
{Object.entries(i.categoryNames)
.sort(([a], [b]) => Number(b) - Number(a))
.filter(([key]) => {
const count = Object.keys(versionsList).filter(v => {
const info = serverVersionList.versions.find(
vf => vf.id == v
)
if (!info) return false
if (platform() == 'linux' && info.wine && !linuxUseWine)
return false
return info.game === i.id && info.category === Number(key)
}).length
return count >= 1
})
.map(([key, value]) => (
<div
key={`${i.id}-${key}`}
draggable={false}
className={`link ${
pathname === '/main/game' &&
Number(params.get('id') || 0) == i.id &&
category == Number(key)
? 'active'
: ''
} ml-auto w-47.5`}
onClick={() => {
setCategory(Number(key))
router.push('/main/game?id=' + i.id)
}}
title="Click to view this game's category."
>
<div className='flex items-center'>
<FontAwesomeIcon icon={faGamepad} className='mr-1' />
<span className='truncate max-w-full'>{value}</span>
</div>
</div>
))}
</React.Fragment>
))}
<Link
draggable={false}
href='/main/settings'
className={`link ${pathname === '/main/settings' ? 'active' : ''}`}
>
<FontAwesomeIcon icon={faCog} className='mr-1' /> Settings
</Link>
<Link
draggable={false}
href='/main/account'
className={`link ${pathname === '/main/account' ? 'active' : ''}`}
>
<FontAwesomeIcon
icon={accountAdmin ? faUserShield : faUser}
className='mr-1'
/>{' '}
{accountName ?? 'Account'}
</Link>
<button
onClick={() => openUrl('https://games.lncvrt.xyz/discord')}
className='link mr-auto'
>
<FontAwesomeIcon icon={faDiscord} className='mr-1' /> Community
</button>
</nav>
{downloadProgress.length != 0 && (
<div
className='sidebar-downloads'
onClick={() => {
setPopupMode(1)
setShowPopup(true)
setFadeOut(false)
}}
>
<p>
<FontAwesomeIcon icon={faDownload} /> Downloads
</p>
</div>
)}
</aside>
)
}
@@ -5,13 +5,13 @@
} }
.setting-checkbox { .setting-checkbox {
@apply appearance-none w-full h-full border border-(--col4) rounded-sm bg-(--col2) transition-colors cursor-pointer; @apply appearance-none w-full h-full border-2 border-(--col4) rounded-md bg-(--col2) transition-colors cursor-pointer;
} }
.setting-checkbox:checked { .setting-checkbox:checked {
@apply bg-(--col4) border-(--col6); @apply bg-(--col4) border-(--col6);
} }
.setting-checkbox-wrapper svg { .fa-check-icon {
@apply absolute top-1/2 left-1/2 text-white text-[12px] pointer-events-none -translate-x-2/4 -translate-y-2/4; @apply absolute top-1/2 left-1/2 text-white text-[11px] pointer-events-none -translate-x-2/4 -translate-y-2/4;
} }
@@ -1,4 +1,4 @@
import '@/styles/setting.css' import './Setting.css'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/free-solid-svg-icons' import { faCheck } from '@fortawesome/free-solid-svg-icons'
import { SettingProps } from '@/types/SettingProps' import { SettingProps } from '@/types/SettingProps'
@@ -8,8 +8,7 @@ export function Setting ({
value, value,
onChange, onChange,
className, className,
title, title
disabled
}: SettingProps) { }: SettingProps) {
return ( return (
<div className={`flex items-center gap-2 mb-2 ${className}`} title={title}> <div className={`flex items-center gap-2 mb-2 ${className}`} title={title}>
@@ -19,10 +18,9 @@ export function Setting ({
type='checkbox' type='checkbox'
className='setting-checkbox' className='setting-checkbox'
checked={value} checked={value}
disabled={disabled}
onChange={() => onChange(!value)} onChange={() => onChange(!value)}
/> />
{value && <FontAwesomeIcon icon={faCheck} />} {value && <FontAwesomeIcon icon={faCheck} className='fa-check-icon' />}
</div> </div>
</div> </div>
) )
@@ -5,7 +5,7 @@
} }
.sidebar-downloads { .sidebar-downloads {
@apply text-[#bdbdbd] fixed bottom-2 left-2 bg-(--col2) rounded-lg border border-(--col3) px-4 py-3 text-xl cursor-pointer transition-colors opacity-75; @apply text-[#bdbdbd] fixed bottom-2 left-2 bg-(--col2) rounded-lg border border-(--col3) px-4 py-3 text-xl cursor-pointer transition-colors duration-[0.25s] opacity-75;
} }
.sidebar-downloads:hover { .sidebar-downloads:hover {
@@ -14,11 +14,11 @@
} }
.nav-links { .nav-links {
@apply flex flex-col px-4 space-y-1 pt-3; @apply flex flex-col px-4 space-y-1;
} }
.link { .link {
@apply text-[#bdbdbd] p-2 rounded-md no-underline cursor-pointer transition-colors border border-transparent; @apply text-[#bdbdbd] p-2 rounded-md no-underline cursor-pointer transition-colors duration-[0.25s] border border-transparent;
} }
.link.active { .link.active {
+183
View File
@@ -0,0 +1,183 @@
'use client'
import './Sidebar.css'
import Icon from '@/assets/Icon.png'
import { openUrl } from '@tauri-apps/plugin-opener'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCog,
faDownload,
faGamepad,
faHexagonNodes,
faLayerGroup
} from '@fortawesome/free-solid-svg-icons'
import { faDiscord } from '@fortawesome/free-brands-svg-icons'
import { platform } from '@tauri-apps/plugin-os'
import { useGlobal } from '@/app/GlobalProvider'
import Image from 'next/image'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { Lexend } from 'next/font/google'
import React from 'react'
const lexend = Lexend({
subsets: ['latin']
})
export default function Sidebar () {
const {
normalConfig,
getListOfGames,
setShowPopup,
setPopupMode,
setFadeOut,
downloadProgress,
downloadedVersionsConfig,
getVersionInfo,
category,
setCategory
} = useGlobal()
const pathname = usePathname()
const params = useSearchParams()
const router = useRouter()
return (
<aside className='sidebar'>
<div className='flex items-center h-10 w-60'>
<Image draggable={false} src={Icon} width={36} height={36} alt='' />
<p className={`ml-1 text-[16px] whitespace-nowrap ${lexend.className}`}>
Lncvrt Games Launcher
</p>
</div>
<nav className='nav-links overflow-auto pt-2'>
<Link
draggable={false}
href='/'
className={`link relative flex items-center ${
pathname === '/' || pathname.startsWith('/game') ? 'active' : ''
}`}
>
<FontAwesomeIcon icon={faHexagonNodes} className='mr-2' /> Games
</Link>
{getListOfGames()
.sort((a, b) => {
return a.id - b.id
})
.map(i => (
<React.Fragment key={i.id}>
<div
draggable={false}
className={`link ${
(pathname === '/game' &&
Number(params.get('id') || 0) == i.id) ||
(i.id == 1 && pathname === '/game/berrydash/leaderboards')
? 'active'
: ''
} ml-auto w-50 ${
normalConfig?.settings.alwaysShowGamesInSidebar ||
pathname === '/' ||
pathname.startsWith('/game')
? ''
: 'hidden'
}`}
onClick={() => {
setCategory(-1)
router.push('/game?id=' + i.id)
}}
>
<div className='flex items-center'>
<FontAwesomeIcon
icon={
Object.entries(i.categoryNames).length > 0
? faLayerGroup
: faGamepad
}
className='mr-1'
/>
<span className='truncate max-w-full'>{i.name}</span>
</div>
</div>
{Object.entries(i.categoryNames)
.sort(([a], [b]) => Number(b) - Number(a))
.filter(([key]) => {
const count = Object.keys(
downloadedVersionsConfig?.list ?? {}
).filter(v => {
const info = getVersionInfo(v)
if (!info) return false
if (
platform() == 'linux' &&
info.wine &&
!normalConfig?.settings.useWineOnUnixWhenNeeded
)
return false
return info.game === i.id && info.category === Number(key)
}).length
return count >= 1
})
.map(([key, value]) => (
<div
key={`${i.id}-${key}`}
draggable={false}
className={`link ${
(pathname === '/game' &&
Number(params.get('id') || 0) == i.id) ||
(i.id == 1 &&
pathname === '/game/berrydash/leaderboards' &&
category == Number(key))
? 'active'
: ''
} ml-auto w-47.5 ${
normalConfig?.settings.alwaysShowGamesInSidebar ||
pathname === '/' ||
pathname.startsWith('/game')
? ''
: 'hidden'
}`}
onClick={() => {
setCategory(Number(key))
router.push('/game?id=' + i.id)
}}
>
<div className='flex items-center'>
<FontAwesomeIcon icon={faGamepad} className='mr-1' />
<span className='truncate max-w-full'>{value}</span>
</div>
</div>
))}
</React.Fragment>
))}
<Link
draggable={false}
href='/settings'
className={`link ${pathname === '/settings' ? 'active' : ''}`}
>
<FontAwesomeIcon icon={faCog} className='mr-1' /> Settings
</Link>
<button
onClick={() => openUrl('https://games.lncvrt.xyz/discord')}
className='link mr-auto'
>
<FontAwesomeIcon icon={faDiscord} className='mr-1' /> Community
</button>
</nav>
<div
className='sidebar-downloads'
hidden={downloadProgress.length == 0}
onClick={() => {
setPopupMode(1)
setShowPopup(true)
setFadeOut(false)
}}
>
<p>
<FontAwesomeIcon icon={faDownload} /> Downloads
</p>
</div>
</aside>
)
}
+68
View File
@@ -0,0 +1,68 @@
import { useGlobal } from '@/app/GlobalProvider'
export default function DownloadsPopup () {
const {
downloadProgress,
getVersionInfo,
setDownloadProgress,
downloadQueue,
setDownloadQueue
} = useGlobal()
return (
<>
<p className='text-xl text-center'>Downloads</p>
<div className='popup-content'>
{downloadProgress.map((v, i) => {
const queuePosition = downloadQueue.indexOf(v.version)
return (
<div key={i} className='popup-entry flex flex-col justify-between'>
<p className='text-2xl text-center'>
{getVersionInfo(v.version)?.displayName}
</p>
<div className='mt-6.25 flex items-center justify-between'>
{v.failed || v.queued ? (
<div className='flex items-center justify-between w-full'>
<span
className={`${
v.failed ? 'text-red-500' : 'text-yellow-300'
} inline-block text-center flex-1`}
>
{v.failed
? 'Download failed'
: queuePosition === 0
? 'Starting soon...'
: `Queued (Position ${queuePosition + 1})`}
</span>
<button
className='button btntheme3 -ml-1.25'
onClick={() => {
setDownloadQueue(prev =>
prev.filter(id => id !== v.version)
)
setDownloadProgress(prev =>
prev.filter(d => d.version !== v.version)
)
}}
title='Click to remove this version from the download queue.'
>
Remove
</button>
</div>
) : v.finishing ? (
<span className='text-green-300 inline-block w-full text-center'>
Finishing...
</span>
) : (
<div className='flex flex-col gap-1 w-full'>
<span className='text-center'>Downloading...</span>
</div>
)}
</div>
</div>
)
})}
</div>
</>
)
}
+92
View File
@@ -0,0 +1,92 @@
import { useGlobal } from '@/app/GlobalProvider'
import {
faCheck,
faCode,
faDownload,
faShieldHalved,
faWarning
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
export default function GamesDownloadPopup () {
const { serverVersionList, getVersionsAmountData, setSelectedGame } =
useGlobal()
return (
<>
<p className='text-xl text-center'>Select a game to download</p>
<div className='popup-content'>
{serverVersionList?.games
.filter(v => {
const data = getVersionsAmountData(v.id)
if (!data) return false
if (data.total > 0) return true
})
.map((v, i) => (
<div key={i} className='popup-entry'>
<p className='text-2xl'>{v.name}</p>
<div className='flex gap-2'>
<div
className='entry-info-item btntheme3'
title='The amount of versions installed of this game in installed/installable format.'
>
<p>
{(() => {
const data = getVersionsAmountData(v.id)
if (!data) return 'N/A'
return `${data.installed}/${data.total}`
})()}{' '}
versions installed
</p>
</div>
<div
className='entry-info-item btntheme3'
hidden={!v.official}
title='This game is official.'
>
<FontAwesomeIcon icon={faCheck} color='#19c84b' />
<p>Official</p>
</div>
<div
className='entry-info-item btntheme3'
hidden={v.official}
title={
v.verified
? 'This game is verified to be safe'
: 'This game is NOT verified to be save. Proceed with caution.'
}
>
<FontAwesomeIcon
icon={v.verified ? faShieldHalved : faWarning}
color={v.verified ? '#19c84b' : '#ffc800'}
/>
<p>{v.verified ? 'Verified' : 'Unverified'}</p>
</div>
</div>
<div
className='entry-info-item btntheme3 mt-2'
hidden={v.developer == null}
title={`The developer of ${v.name} is ${v.developer}.`}
>
<FontAwesomeIcon icon={faCode} color='lightgray' />
<p>Developer: {v.developer}</p>
</div>
<button
className='button btntheme3 right-2 bottom-2'
onClick={() => setSelectedGame(v.id)}
title={`Click to download specific versions of the game. You have ${(() => {
const data = getVersionsAmountData(v.id)
if (!data) return 'N/A'
return `${data.installed} of ${data.total}`
})()} versions downloaded.`}
>
<>
<FontAwesomeIcon icon={faDownload} /> Download
</>
</button>
</div>
))}
</div>
</>
)
}
+180
View File
@@ -0,0 +1,180 @@
'use client'
import {
faArrowUpRightFromSquare,
faCheck,
faCode,
faShieldHalved,
faWarning
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { useGlobal } from '@/app/GlobalProvider'
import { message } from '@tauri-apps/plugin-dialog'
import { BaseDirectory, exists, remove } from '@tauri-apps/plugin-fs'
import { writeVersionsConfig } from '@/lib/BazookaManager'
import { openFolder } from '@/lib/Util'
export default function VersionVersionPopup () {
const {
getGameInfo,
getVersionInfo,
managingVersion,
downloadedVersionsConfig,
viewingInfoFromDownloads,
setManagingVersion,
closePopup,
setDownloadedVersionsConfig,
setPopupMode,
setSelectedVersionList,
downloadVersions
} = useGlobal()
if (!managingVersion || !downloadedVersionsConfig) return <></>
const versionInfo = getVersionInfo(managingVersion)
const gameInfo = getGameInfo(versionInfo?.game)
return (
<>
<p className='text-xl text-center'>Viewing {versionInfo?.displayName}</p>
<div className='popup-content flex flex-col items-center justify-center gap-2 h-full'>
<div
className='entry-info-item btntheme2'
hidden={viewingInfoFromDownloads}
>
<p>
Installed{' '}
{new Intl.DateTimeFormat(undefined).format(
downloadedVersionsConfig.list[managingVersion] ?? 0
)}
</p>
</div>
<div
className='entry-info-item btntheme2'
hidden={!versionInfo || versionInfo.releaseDate == 0}
>
<p>
Released{' '}
{new Intl.DateTimeFormat(undefined).format(
versionInfo?.releaseDate ? versionInfo.releaseDate * 1000 : 0
)}
</p>
</div>
<div className='entry-info-item btntheme2' hidden={!gameInfo?.official}>
<FontAwesomeIcon icon={faCheck} color='#19c84b' />
<p>Official</p>
</div>
<div className='entry-info-item btntheme2' hidden={gameInfo?.official}>
<FontAwesomeIcon
icon={gameInfo?.verified ? faShieldHalved : faWarning}
color={gameInfo?.verified ? '#19c84b' : '#ffc800'}
/>
<p>{gameInfo?.verified ? 'Verified' : 'Unverified'}</p>
</div>
<div
className='entry-info-item btntheme2'
hidden={gameInfo?.developer == null}
>
<FontAwesomeIcon icon={faCode} color='lightgray' />
<p>Developer: {gameInfo?.developer}</p>
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
if (!versionInfo) return
await message(atob(versionInfo.changelog), {
title: 'Changelog for ' + versionInfo.displayName,
kind: 'info'
})
}}
hidden={!versionInfo?.changelog}
>
<p>View Changelog</p>
<FontAwesomeIcon icon={faArrowUpRightFromSquare} color='lightgray' />
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => openFolder(managingVersion)}
title="Click to browse the game's files."
hidden={viewingInfoFromDownloads}
>
Open Folder
<FontAwesomeIcon icon={faArrowUpRightFromSquare} color='lightgray' />
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
closePopup()
setDownloadedVersionsConfig(prev => {
if (!prev) return prev
const updatedList = Object.fromEntries(
Object.entries(prev.list).filter(([k]) => k !== managingVersion)
)
const updatedConfig = {
...prev,
list: updatedList
}
writeVersionsConfig(updatedConfig)
return updatedConfig
})
if (
await exists('game/' + managingVersion, {
baseDir: BaseDirectory.AppLocalData
})
)
await remove('game/' + managingVersion, {
baseDir: BaseDirectory.AppLocalData,
recursive: true
})
}}
title='Click to uninstall this game. This will NOT remove any progress or any save files.'
hidden={viewingInfoFromDownloads}
>
Uninstall
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
//change popup to downloads
setManagingVersion(null)
setPopupMode(1)
//uninstall
setDownloadedVersionsConfig(prev => {
if (!prev) return prev
const updatedList = Object.fromEntries(
Object.entries(prev.list).filter(([k]) => k !== managingVersion)
)
const updatedConfig = {
...prev,
list: updatedList
}
writeVersionsConfig(updatedConfig)
return updatedConfig
})
if (
await exists('game/' + managingVersion, {
baseDir: BaseDirectory.AppLocalData
})
)
await remove('game/' + managingVersion, {
baseDir: BaseDirectory.AppLocalData,
recursive: true
})
//reinstall
setSelectedVersionList([managingVersion])
downloadVersions([managingVersion])
}}
title="Click to reinstall this game. This will NOT remove any progress or any save files. This WILL uninstall any modifications to the game's executable files."
hidden={viewingInfoFromDownloads}
>
Reinstall
</div>
</div>
</>
)
}
+120
View File
@@ -0,0 +1,120 @@
import { useGlobal } from '@/app/GlobalProvider'
import { faAdd, faInfo, faRemove } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
export default function VersionsDownloadPopup () {
const {
selectedVersionList,
setSelectedVersionList,
setManagingVersion,
setPopupMode,
getSpecialVersionsList,
selectedGame,
setViewingInfoFromDownloads,
downloadedVersionsConfig,
downloadVersions,
getGameInfo
} = useGlobal()
if (!selectedGame) return <></>
return (
<>
<p className='text-xl text-center'>Select versions to download</p>
<div className='popup-content'>
{getSpecialVersionsList(selectedGame).map((v, i) => (
<div key={i} className='popup-entry'>
<div className='flex items-center'>
<p
className={`text-2xl truncate ${
selectedVersionList.includes(v.id)
? 'max-w-84.5'
: 'max-w-91.5'
}`}
>
{v.displayName}
</p>
</div>
<button
className='button btntheme3 right-20.75 bottom-1.75'
onClick={() => {
setSelectedVersionList(prev =>
prev.includes(v.id)
? prev.filter(i => i !== v.id)
: [...prev, v.id]
)
}}
title={
selectedVersionList.includes(v.id)
? 'This version will be downloaded. Click to remove from the list of versions that will be downloaded.'
: 'This version will NOT be downloaded. Click to add from the list of versions that will be downloaded.'
}
>
{selectedVersionList.includes(v.id) ? (
<>
<FontAwesomeIcon icon={faRemove} /> Remove
</>
) : (
<>
<FontAwesomeIcon icon={faAdd} /> Add
</>
)}
</button>
<button
className='button btntheme3 right-1.5 bottom-1.75'
onClick={() => {
setManagingVersion(v.id)
setViewingInfoFromDownloads(true)
setPopupMode(2)
}}
title='Click to view version info'
>
<FontAwesomeIcon icon={faInfo} /> Info
</button>
</div>
))}
</div>
<div className='flex justify-center'>
<button
className='button btntheme1 w-fit mt-2 -mb-4'
onClick={() => {
if (downloadedVersionsConfig) {
downloadVersions(selectedVersionList)
setPopupMode(1)
}
}}
disabled={selectedVersionList.length == 0}
title={
selectedVersionList.length == 0
? 'Select at least one version to download'
: `Download ${selectedVersionList.length} version${
selectedVersionList.length == 1 ? '' : 's'
} of ${getGameInfo(selectedGame)?.name}`
}
>
Download {selectedVersionList.length} version
{selectedVersionList.length == 1 ? '' : 's'}
</button>
<button
className='button btntheme1 w-fit mt-2 ml-2 -mb-4'
onClick={() => {
const allIds = getSpecialVersionsList(selectedGame).map(v => v.id)
setSelectedVersionList(prev =>
prev.length === allIds.length ? [] : allIds
)
}}
title={
selectedVersionList.length ===
getSpecialVersionsList(selectedGame).length
? 'Click to remove all selected versions for download.'
: 'Click to add all selected versions for download.'
}
>
{selectedVersionList.length ===
getSpecialVersionsList(selectedGame).length
? 'Deselect All'
: 'Select All'}
</button>
</div>
</>
)
}
+148
View File
@@ -0,0 +1,148 @@
import { app } from '@tauri-apps/api'
import { NormalConfig } from '@/types/NormalConfig'
import {
BaseDirectory,
create,
exists,
mkdir,
readTextFile,
writeFile
} from '@tauri-apps/plugin-fs'
import { VersionsConfig } from '@/types/VersionsConfig'
export async function readNormalConfig (): Promise<NormalConfig> {
const version = await app.getVersion()
try {
const options = {
baseDir: BaseDirectory.AppLocalData
}
const doesFolderExist = await exists('', options)
const doesConfigExist = await exists('config.json', options)
if (!doesFolderExist || !doesConfigExist) {
if (!doesFolderExist) {
await mkdir('', options)
}
const file = await create('config.json', options)
await file.write(
new TextEncoder().encode(
JSON.stringify(new NormalConfig(version), null, 2)
)
)
await file.close()
return new NormalConfig(version)
}
const config = await readTextFile('config.json', options)
const raw = JSON.parse(config)
if (
raw.settings &&
raw.settings.theme &&
(raw.version == '1.0.0' ||
raw.version == '1.1.0' ||
raw.version == '1.1.1' ||
raw.version == '1.2.0' ||
raw.version == '1.3.0' ||
raw.version == '1.3.1' ||
raw.version == '1.4.0' ||
raw.version == '1.5.0' ||
raw.version == '1.5.1' ||
raw.version == '1.5.2' ||
raw.version == '1.5.3' ||
raw.version == '1.5.4')
) {
const parsed = Number(raw.settings.theme)
if (parsed == 3) raw.settings.theme = 2
if (parsed == 4) raw.settings.theme = 3
else if (parsed != 0 && parsed != 1) raw.settings.theme = 0
}
raw.version = version
writeNormalConfig(raw)
return NormalConfig.import(raw)
} catch {
return new NormalConfig(version)
}
}
export async function writeNormalConfig (data: NormalConfig) {
const options = {
baseDir: BaseDirectory.AppLocalData
}
const doesFolderExist = await exists('', options)
const doesConfigExist = await exists('config.json', options)
if (!doesFolderExist || !doesConfigExist) {
if (!doesFolderExist) {
await mkdir('', options)
}
const file = await create('config.json', options)
await file.write(new TextEncoder().encode(JSON.stringify(data, null, 2)))
await file.close()
} else {
await writeFile(
'config.json',
new TextEncoder().encode(JSON.stringify(data, null, 2)),
options
)
}
}
export async function readVersionsConfig (): Promise<VersionsConfig> {
const version = await app.getVersion()
try {
const options = {
baseDir: BaseDirectory.AppLocalData
}
const doesFolderExist = await exists('', options)
const doesConfigExist = await exists('versions.json', options)
if (!doesFolderExist || !doesConfigExist) {
if (!doesFolderExist) {
await mkdir('', options)
}
const file = await create('versions.json', options)
await file.write(
new TextEncoder().encode(
JSON.stringify(new VersionsConfig(version), null, 2)
)
)
await file.close()
return new VersionsConfig(version)
}
const config = await readTextFile('versions.json', options)
const raw = JSON.parse(config)
if (raw.list && raw.timestamps) {
raw.list = raw.timestamps
delete raw.timestamps
await writeFile(
'versions.json',
new TextEncoder().encode(JSON.stringify(raw, null, 2)),
options
)
}
raw.version = version
writeVersionsConfig(raw)
return VersionsConfig.import(raw)
} catch {
return new VersionsConfig(version)
}
}
export async function writeVersionsConfig (data: VersionsConfig) {
const options = {
baseDir: BaseDirectory.AppLocalData
}
const doesFolderExist = await exists('', options)
const doesConfigExist = await exists('versions.json', options)
if (!doesFolderExist || !doesConfigExist) {
if (!doesFolderExist) {
await mkdir('', options)
}
const file = await create('versions.json', options)
await file.write(new TextEncoder().encode(JSON.stringify(data, null, 2)))
await file.close()
} else {
await writeFile(
'versions.json',
new TextEncoder().encode(JSON.stringify(data, null, 2)),
options
)
}
}
+7
View File
@@ -0,0 +1,7 @@
export const GetIconForUser = (user: number) => {
if (user == 1) return -1
else if (user == 2) return -2
else if (user == 4) return -3
else if (user == 3) return -4
else return 1
}
+50
View File
@@ -0,0 +1,50 @@
import { message } from '@tauri-apps/plugin-dialog'
import { BaseDirectory, exists, stat } from '@tauri-apps/plugin-fs'
import { openPath } from '@tauri-apps/plugin-opener'
import { join, appLocalDataDir } from '@tauri-apps/api/path'
export const openFolder = async (name: string) => {
const relativePath = await join('game', name)
const basePath = await appLocalDataDir()
const absolutePath = await join(basePath, relativePath)
const folderExists = await exists(relativePath, {
baseDir: BaseDirectory.AppLocalData
})
if (!folderExists) {
await message(`Game folder "${absolutePath}" not found.`, {
title: 'Folder not found',
kind: 'error'
})
return
}
const folderStat = await stat(relativePath, {
baseDir: BaseDirectory.AppLocalData
})
if (folderStat.isFile) {
await message(`Game folder "${absolutePath}" not found.`, {
title: 'Folder not found',
kind: 'error'
})
return
}
await openPath(absolutePath)
}
export const formatEtaSmart = (seconds: number) => {
if (seconds < 60) return `${Math.floor(seconds)}s`
if (seconds < 3600)
return `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`
if (seconds < 86400) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
return `${h}h ${m}m`
}
const d = Math.floor(seconds / 86400)
const h = Math.floor((seconds % 86400) / 3600)
return `${d}d ${h}h`
}
-7
View File
@@ -1,7 +0,0 @@
import { writeText } from '@tauri-apps/plugin-clipboard-manager'
import { notifyUser } from './notifications'
export async function copyToClipboard (text: string) {
await writeText(text)
await notifyUser('Copied', 'Text "' + text + '" copied to clipboard')
}
-17
View File
@@ -1,17 +0,0 @@
import {
isPermissionGranted,
requestPermission,
sendNotification
} from '@tauri-apps/plugin-notification'
export async function notifyUser (title: string, body: string) {
let permissionGranted = await isPermissionGranted()
if (!permissionGranted) {
const permission = await requestPermission()
permissionGranted = permission === 'granted'
}
if (permissionGranted) {
sendNotification({ title, body })
}
}
-40
View File
@@ -1,40 +0,0 @@
import { message } from '@tauri-apps/plugin-dialog'
import { invoke } from '@tauri-apps/api/core'
export const openFolder = async (name: string) => {
try {
await invoke('open_game_folder', { version: name })
} catch (e) {
await message(String(e), {
title: 'Folder not found',
kind: 'error'
})
}
}
export const formatEtaSmart = (seconds: number) => {
if (seconds < 60) return `${Math.floor(seconds)}s`
if (seconds < 3600)
return `${Math.floor(seconds / 60)}m ${Math.floor(seconds % 60)}s`
if (seconds < 86400) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
return `${h}h ${m}m`
}
const d = Math.floor(seconds / 86400)
const h = Math.floor((seconds % 86400) / 3600)
return `${d}d ${h}h`
}
export const verifySignature = async (body: string, signature: string) => {
try {
const result = await invoke<boolean>('verify_signature', {
body: body ?? '',
signature: signature ?? '',
publicKey: process.env.NEXT_PUBLIC_PUBLIC_SIGNING_KEY ?? ''
})
return Boolean(result)
} catch {
return false
}
}
-257
View File
@@ -1,257 +0,0 @@
import { useGlobal } from '@/providers/GlobalProvider'
import prettyBytes from 'pretty-bytes'
import ProgressBar from '@/components/ProgressBar'
import { formatEtaSmart } from '@/lib/util'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCancel,
faPause,
faPlay,
faTrash
} from '@fortawesome/free-solid-svg-icons'
import { invoke } from '@tauri-apps/api/core'
import { notifyUser } from '@/lib/notifications'
import { getCurrentWindow, UserAttentionType } from '@tauri-apps/api/window'
export default function DownloadsPopup () {
const {
downloadProgress,
setDownloadProgress,
downloadQueue,
setDownloadQueue,
versionsList,
modsList,
versions,
serverVersionList
} = useGlobal()
return (
<>
<p className='text-xl text-center'>Downloads</p>
<div className='popup-content'>
{downloadProgress.map((v, i) => {
const queuePosition = downloadQueue.indexOf(v.version)
return (
<div
key={i}
className='popup-entry flex flex-col justify-between relative'
>
<div className='absolute right-2 top-2 flex flex-row gap-2'>
{(v.downloading || v.paused) && (
<>
<div
className='cursor-pointer bg-(--col5) hover:bg-(--col7) border border-(--col7) hover:border-(--col9) transition-colors w-8 h-8 flex items-center justify-center rounded-full'
onClick={async () => {
if (v.downloading) {
await invoke('cancel_download', { name: v.version })
} else {
setDownloadProgress(prev => {
const i = prev.findIndex(
d => d.version === v.version
)
if (i === -1) return prev
const copy = [...prev]
copy[i] = {
...copy[i],
paused: false,
downloading: true
}
return copy
})
const res = await invoke<string>('download', {
url: v.url,
name: v.version,
hash: v.hash,
downloadType: v.type,
modId: String(v.modId ?? '')
})
if (res === '1') {
setDownloadProgress(prev =>
prev.filter(d => d.version !== v.version)
)
if (v.type != 1) {
if (v.type == 2) {
await versions?.set('mods', {
...modsList,
[v.modGame! + '-' + v.modId!]: {
[v.modVersion!]: Date.now()
}
})
} else {
await versions?.set('list', {
...versionsList,
[v.version]: Date.now()
})
}
}
} else if (res == '0') {
setDownloadProgress(prev => {
const i = prev.findIndex(
d => d.version === v.version
)
if (i === -1) return prev
if (prev[i].canceled) {
return prev.filter((_, idx) => idx !== i)
}
const copy = [...prev]
copy[i] = {
...copy[i],
downloading: false,
paused: true,
failed: false
}
return copy
})
} else if (res == '-1') {
setDownloadProgress(prev =>
prev.map(d =>
d.version === v.version
? {
...d,
queued: false,
failed: true,
progress: 0
}
: d
)
)
await notifyUser(
'Download Failed',
`The download for version ${
serverVersionList?.versions.find(
vf => vf.id == v.version
)?.displayName
} has failed.`
)
await getCurrentWindow().requestUserAttention(
UserAttentionType.Critical
)
}
}
}}
>
<FontAwesomeIcon
icon={v.downloading ? faPause : faPlay}
className='w-6 h-6'
/>
</div>
<div
className='cursor-pointer bg-(--col5) hover:bg-(--col7) border border-(--col7) hover:border-(--col9) transition-colors w-8 h-8 flex items-center justify-center rounded-full'
onClick={async () => {
if (!v.paused) {
await invoke('cancel_download', { name: v.version })
setDownloadProgress(prev => {
const i = prev.findIndex(
d => d.version === v.version
)
if (i === -1) return prev
const copy = [...prev]
copy[i] = {
...copy[i],
canceled: true
}
return copy
})
} else {
setDownloadProgress(prev => {
const i = prev.findIndex(
d => d.version === v.version
)
if (i === -1) return prev
return prev.filter((_, idx) => idx !== i)
})
}
}}
>
<FontAwesomeIcon icon={faCancel} className='w-6 h-6' />
</div>
</>
)}
{(v.failed || v.queued) && (
<div
className='cursor-pointer bg-(--col5) hover:bg-(--col7) border border-(--col7) hover:border-(--col9) transition-colors w-8 h-8 flex items-center justify-center rounded-full'
onClick={() => {
setDownloadQueue(prev =>
prev.filter(id => id !== v.version)
)
setDownloadProgress(prev =>
prev.filter(d => d.version !== v.version)
)
}}
>
<FontAwesomeIcon icon={faTrash} className='w-6 h-6' />
</div>
)}
</div>
<p className='text-2xl text-center'>
{v.type == 1
? 'Mod loader for '
: v.type == 2
? 'Mod for '
: null}{' '}
{
serverVersionList?.versions.find(vf => vf.id == v.version)
?.displayName
}
</p>
<div className='mt-6.25 flex items-center justify-between'>
{v.failed || v.queued ? (
<div className='flex items-center justify-between w-full'>
<span
className={`${
v.failed ? 'text-red-500' : 'text-yellow-300'
} inline-block text-center flex-1`}
>
{v.failed
? 'Download failed'
: queuePosition === 0
? 'Starting soon...'
: `Queued (Position ${queuePosition + 1})`}
</span>
</div>
) : v.hash_checking ? (
<span className='text-blue-300 inline-block w-full text-center'>
Verifying file integrity...
</span>
) : v.unzipping ? (
<div className='flex flex-col gap-1 w-full'>
<span className='text-center'>
Unzipped {v.unzipped} / {v.unzipTotal} files
</span>
<ProgressBar
progress={(v.unzipped / v.unzipTotal) * 100}
className='w-full'
/>
</div>
) : (
<div className='flex flex-col gap-1 w-full'>
<span className='text-center'>
Downloaded{' '}
{prettyBytes(v.progressBytes, {
minimumFractionDigits: 1,
maximumFractionDigits: 1
})}{' '}
of{' '}
{prettyBytes(v.size, {
minimumFractionDigits: 1,
maximumFractionDigits: 1
})}{' '}
(ETA: {formatEtaSmart(v.etaSecs)} &bull; Speed:{' '}
{prettyBytes(v.speed, {
minimumFractionDigits: 1,
maximumFractionDigits: 1
})}
/s)
</span>
<ProgressBar progress={v.progress} className='w-full' />
</div>
)}
</div>
</div>
)
})}
</div>
</>
)
}
-66
View File
@@ -1,66 +0,0 @@
import { useGlobal } from '@/providers/GlobalProvider'
import {
faArrowUpRightFromSquare,
faInfo
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
export default function GamesDownloadPopup () {
const {
serverVersionList,
setSelectedGame,
setManagingGame,
setPopupMode,
setShowPopup,
setFadeOut,
setViewingInfoFromDownloads,
developerMode
} = useGlobal()
return (
<>
<p className='text-xl text-center'>Select a game to download</p>
<div className='popup-content'>
{serverVersionList?.games
.filter(g => {
const gameVersions = serverVersionList.versions.filter(
gv => gv.game === g.id
)
if (gameVersions.length > 0) return true
})
.map((g, i) => (
<div
key={i}
className='popup-entry grid items-center gap-3'
style={{ gridTemplateColumns: 'auto minmax(0, 1fr) auto' }}
>
<button
className='button btntheme3'
onClick={() => {
setViewingInfoFromDownloads(true)
setManagingGame(g.id)
setPopupMode(5)
setShowPopup(true)
setFadeOut(false)
}}
title='Click to view game info.'
>
<FontAwesomeIcon icon={faInfo} /> Info
</button>
<p className='text-2xl text-center truncate' title={g.name}>
{developerMode ? <span className='text-sm'>{g.id} </span> : ''}
{g.name}
</p>
<button
className='button btntheme3'
onClick={() => setSelectedGame(g.id)}
title='Click to view versions of the game.'
>
<FontAwesomeIcon icon={faArrowUpRightFromSquare} /> View
</button>
</div>
))}
</div>
</>
)
}
-173
View File
@@ -1,173 +0,0 @@
'use client'
import {
faCheck,
faCode,
faDownload,
faHardDrive,
faShieldHalved,
faWarning
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { useGlobal } from '@/providers/GlobalProvider'
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useMemo, useState } from 'react'
import prettyBytes from 'pretty-bytes'
import { BaseDirectory, exists, remove } from '@tauri-apps/plugin-fs'
export default function ManageGamePopup () {
const {
versionsList,
serverVersionList,
closePopup,
versions,
customDataLocation,
managingGame
} = useGlobal()
const [gameSize, setGameSize] = useState<number>(0)
const versionsInstalled = useMemo(() => {
return serverVersionList?.versions.filter(
vf => vf.game == managingGame && Object.keys(versionsList).includes(vf.id)
)
}, [serverVersionList, managingGame, versionsList])
const gameInfo = serverVersionList?.games.find(vf => vf.id == managingGame)
useEffect(() => {
if (!versionsInstalled || versionsInstalled.length == 0) return
let cancelled = false
const run = async () => {
let total = 0
setGameSize(0)
for (const version of versionsInstalled) {
if (cancelled) return
const size = await invoke<string>('folder_size', {
version: version.id
}).catch(() => '0')
total += Number(size)
setGameSize(total)
}
}
run()
return () => {
cancelled = true
}
}, [versionsInstalled])
return (
<>
<p className='text-xl text-center'>Viewing {gameInfo?.name}</p>
<div className='popup-content h-full w-full flex justify-center items-center flex-col gap-2'>
<div className='flex flex-row gap-2 justify-center'>
{gameInfo?.official ? (
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon icon={faCheck} color='#19c84b' />
<p>Official</p>
</div>
) : (
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon
icon={gameInfo?.verified ? faShieldHalved : faWarning}
color={gameInfo?.verified ? '#19c84b' : '#ffc800'}
/>
<p>{gameInfo?.verified ? 'Verified' : 'Unverified'}</p>
</div>
)}
{gameInfo?.developer != null && (
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon icon={faCode} color='lightgray' />
<p>Developer: {gameInfo?.developer}</p>
</div>
)}
</div>
<div className='flex flex-row gap-2 justify-center'>
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon icon={faDownload} color='lightgray' />
<p>
{(() => {
if (!serverVersionList) return 'N/A'
const gameVersions = serverVersionList.versions.filter(
vf => vf.game === managingGame
)
const installed = gameVersions.filter(v =>
Object.keys(versionsList).includes(v.id)
).length
return gameVersions.length
? `${installed}/${gameVersions.length}`
: 'N/A'
})()}{' '}
versions installed
</p>
</div>
{versionsInstalled?.length != 0 && (
<>
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon icon={faHardDrive} color='lightgray' />
<p>
Size on disk:{' '}
{prettyBytes(gameSize, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})}
</p>
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
closePopup()
if (!versionsInstalled) return
const updatedList = { ...versionsList }
for (const version of versionsInstalled)
delete updatedList[version.id]
await versions?.set('list', updatedList)
for (const version of versionsInstalled) {
const managingVersion = version.id
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') +
'game/' +
managingVersion,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
'game/' +
managingVersion,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
}
}}
title='Click to uninstall this game. This will NOT remove any progress or any save files.'
>
Uninstall
</div>
</>
)}
</div>
</div>
</>
)
}
-149
View File
@@ -1,149 +0,0 @@
'use client'
import {
faArrowUpRightFromSquare,
faHardDrive
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { useGlobal } from '@/providers/GlobalProvider'
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useState } from 'react'
import prettyBytes from 'pretty-bytes'
import { openFolder } from '@/lib/util'
export default function ManageVersionPopup () {
const {
versionsList,
serverVersionList,
managingVersion,
viewingInfoFromDownloads,
setManagingVersion,
closePopup,
setPopupMode,
setSelectedVersionList,
downloadVersions,
uninstallVersion
} = useGlobal()
const [versionSize, setVersionSize] = useState<number>(0)
useEffect(() => {
if (viewingInfoFromDownloads) return
invoke<string>('folder_size', {
version: managingVersion
}).then(size => {
setVersionSize(Number(size))
})
}, [managingVersion, setVersionSize, viewingInfoFromDownloads])
if (!managingVersion) return null
const versionInfo = serverVersionList?.versions.find(
vf => vf.id == managingVersion
)
return (
<>
<p className='text-xl text-center'>Viewing {versionInfo?.displayName}</p>
<div className='popup-content h-full w-full flex justify-center items-center flex-col gap-2'>
<div className='flex flex-row gap-2 justify-center'>
{!viewingInfoFromDownloads && (
<div className='entry-info-item btntheme2'>
<p>
Installed{' '}
{new Intl.DateTimeFormat(undefined).format(
versionsList[managingVersion] ?? 0
)}
</p>
</div>
)}
{versionInfo && (
<>
{versionInfo.releaseDate != 0 && (
<div className='entry-info-item btntheme2'>
<p>
Released{' '}
{new Intl.DateTimeFormat(undefined).format(
versionInfo?.releaseDate
? versionInfo.releaseDate * 1000
: 0
)}
</p>
</div>
)}
{versionInfo.changelog && (
<div
className='entry-info-item btntheme2'
onClick={() => setPopupMode(4)}
>
<p>View Changelog</p>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
color='lightgray'
/>
</div>
)}
</>
)}
</div>
{!viewingInfoFromDownloads && (
<div className='flex flex-row gap-2 justify-center'>
<div className='entry-info-item btntheme2'>
<FontAwesomeIcon icon={faHardDrive} color='lightgray' />
<p>
Size on disk:{' '}
{prettyBytes(versionSize, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})}
</p>
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => openFolder(managingVersion)}
title="Click to browse the game's files."
>
Open Folder
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
color='lightgray'
/>
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
closePopup()
uninstallVersion(managingVersion)
}}
title='Click to uninstall this game. This will NOT remove any progress or any save files.'
>
Uninstall
</div>
<div
className='entry-info-item btntheme2'
onClick={async () => {
//change popup to downloads
setManagingVersion(null)
setPopupMode(1)
//uninstall
uninstallVersion(managingVersion)
//reinstall
setSelectedVersionList([managingVersion])
await downloadVersions([
{
id: managingVersion,
type: 0
}
])
}}
title="Click to reinstall this game. This will NOT remove any progress or any save files. This WILL uninstall any modifications to the game's executable files."
>
Reinstall
</div>
</div>
)}
</div>
</>
)
}
-421
View File
@@ -1,421 +0,0 @@
'use client'
import { useGlobal } from '@/providers/GlobalProvider'
import { verifySignature } from '@/lib/util'
import { Mod } from '@/types/Mod'
import {
faArrowUpRightFromSquare,
faClock,
faCodeBranch,
faDownload,
faGlobe,
faPeopleGroup,
faRefresh,
faTrash
} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { message } from '@tauri-apps/plugin-dialog'
import { BaseDirectory, exists, remove } from '@tauri-apps/plugin-fs'
import { fetch } from '@tauri-apps/plugin-http'
import { arch, platform } from '@tauri-apps/plugin-os'
import { useEffect, useState } from 'react'
import { app } from '@tauri-apps/api'
export default function ModDownloadsPopup () {
const {
modsList,
serverVersionList,
managingVersion,
showModInfo,
setShowModInfo,
downloadVersions,
downloadProgress,
versions,
customDataLocation
} = useGlobal()
const [mods, setMods] = useState<Mod[] | 0 | 1>(0)
const [tab, setTab] = useState<number>(0)
useEffect(() => {
if (!managingVersion) return
;(async () => {
const response = await fetch(
'https://games.lncvrt.xyz/api/launcher/mods?version=' + managingVersion,
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch()
}
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status == 200 &&
(await verifySignature(JSON.stringify(data), signature))
) {
setMods(data as Mod[])
} else {
setMods(1)
}
})()
}, [managingVersion])
if (!managingVersion || !serverVersionList) return null
const versionInfo = serverVersionList.versions.find(
v => v.id == managingVersion
)
return (
<>
{typeof mods != 'number' && showModInfo == null && (
<button
className='popup-top-button btntheme1 right-2'
onClick={async () => {
setMods(0)
const response = await fetch(
'https://games.lncvrt.xyz/api/launcher/mods?version=' +
managingVersion,
{
headers: {
Requester: 'LncvrtGamesLauncherClient',
ClientVersion: await app.getVersion(),
ClientPlatform: platform() + '-' + arch()
}
}
)
const signature = response.headers.get('x-signature') ?? ''
const data = await response.json()
if (
response.status == 200 &&
(await verifySignature(JSON.stringify(data), signature))
) {
setMods(data as Mod[])
} else {
setMods(1)
}
}}
>
<FontAwesomeIcon icon={faRefresh} />
</button>
)}
<p className='text-xl text-center'>
{!showModInfo
? versionInfo?.displayName + ' Mod Manager'
: showModInfo.name +
' by ' +
showModInfo.creators[0] +
(showModInfo.creators.length > 1
? ' + ' + (showModInfo.creators.length - 1) + ' more'
: '')}
</p>
{typeof mods != 'number' && !showModInfo ? (
<div className='flex flex-row justify-center items-center -mb-2 mt-0.5 gap-1.5'>
<button
className={`button ${tab == 0 ? 'btntheme3' : 'btntheme2'}`}
onClick={() => setTab(0)}
>
<FontAwesomeIcon icon={faDownload} />
Installed
</button>
<button
className={`button ${tab == 1 ? 'btntheme3' : 'btntheme2'}`}
onClick={() => setTab(1)}
>
<FontAwesomeIcon icon={faGlobe} />
Download
</button>
</div>
) : null}
<div className='popup-content h-full'>
{typeof mods == 'number' ||
(!showModInfo &&
mods.filter(v =>
tab == 0
? Object.keys(modsList).includes(
String(versionInfo?.game + '-' + v.id)
)
: !Object.keys(modsList).includes(
String(versionInfo?.game + '-' + v.id)
)
).length == 0) ? (
<p className='text-2xl flex justify-center items-center h-full'>
{typeof mods == 'number'
? mods == 0
? 'Loading'
: 'Failed to load mods'
: tab == 0
? 'No mods installed'
: 'No mods available to download'}
</p>
) : !showModInfo ? (
<div className='flex flex-col items-center justify-center gap-2 p-2'>
{mods
.filter(v =>
tab == 0
? Object.keys(modsList).includes(
String(versionInfo?.game + '-' + v.id)
)
: !Object.keys(modsList).includes(
String(versionInfo?.game + '-' + v.id)
)
)
.map(v => {
const localVersion =
tab == 0
? Object.keys(
modsList[versionInfo?.game + '-' + v.id] ?? {}
)[0]
: null
return (
<div
key={v.id}
className='bg-(--col3) border border-(--col5) rounded-lg w-full h-16 flex flex-row'
>
<div className='flex flex-col justify-center h-full px-3 w-fit'>
<p>
<span className='text-lg'>{v.name}</span>{' '}
<span
className={
tab != 0 || v.latestVersion == localVersion
? 'text-green-300'
: 'text-red-300'
}
>
v{tab == 0 ? localVersion : v.latestVersion}
</span>
{tab == 0 && v.latestVersion != localVersion && (
<span className='text-green-300'>
{' '}
(available: v{v.latestVersion})
</span>
)}
</p>
<p className='text-yellow-200'>
Made by {v.creators[0]}
{v.creators.length > 1
? ' + ' + (v.creators.length - 1) + ' more'
: null}
</p>
</div>
<div className='flex flex-row items-center h-full gap-2 px-3 ml-auto'>
{tab != 0 && (
<p className='text-green-400'>
<FontAwesomeIcon icon={faDownload} />{' '}
{v.downloads.toLocaleString()}
</p>
)}
{tab == 0 && v.latestVersion != localVersion && (
<button
className='button btntheme3'
onClick={async () => {
const path =
'game/' +
versionInfo?.id +
'/BepInEx/plugins/' +
v.id
if (
await exists(
(customDataLocation
? customDataLocation + '/'
: null) + path,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation
? customDataLocation + '/'
: null) + path,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
await versions?.set(
'mods',
Object.fromEntries(
Object.entries(modsList).filter(
([k]) => k !== versionInfo?.game + '-' + v.id
)
)
)
await downloadVersions([
{
id: managingVersion,
type: 2,
modDownload: v.latestDownload,
gameId: versionInfo?.game,
modId: v.id,
modVersion: v.latestVersion
}
])
}}
disabled={downloadProgress.length != 0}
>
Update
</button>
)}
<button
className='button btntheme3'
onClick={() => setShowModInfo(v)}
>
{tab == 0 ? 'View' : 'Get'}
</button>
</div>
</div>
)
})}
</div>
) : (
<div className='flex flex-col h-full w-full items-center'>
<div className='flex flex-col p-2 h-fit w-fit bg-(--col3) border border-(--col5) rounded-lg m-2 items-center'>
<p>
<FontAwesomeIcon icon={faDownload} className='text-green-400' />{' '}
Downloads {showModInfo.downloads.toLocaleString()}
</p>
<p>
<FontAwesomeIcon icon={faClock} /> Released{' '}
{new Intl.DateTimeFormat(undefined).format(
showModInfo.released * 1000
)}
</p>
<p>
<FontAwesomeIcon icon={faClock} /> Updated{' '}
{new Intl.DateTimeFormat(undefined).format(
showModInfo.updated * 1000
)}
</p>
<p>
<FontAwesomeIcon icon={faCodeBranch} /> Version{' '}
{showModInfo.latestVersion}
</p>
</div>
<div className='flex flex-col p-2 bg-(--col3) border border-(--col5) rounded-lg h-full w-[calc(100%-16px)]'>
{showModInfo.description
? atob(showModInfo.description)
: '(No description added)'}
</div>
<div className='flex flex-row h-fit w-full gap-2 justify-center my-2'>
{Object.keys(modsList).includes(
String(versionInfo?.game + '-' + showModInfo.id)
) ? (
<button
className='button btntheme2 w-fit'
disabled={downloadProgress.length != 0}
onClick={async () => {
const path =
'game/' +
versionInfo?.id +
'/BepInEx/plugins/' +
showModInfo.id
if (
await exists(
(customDataLocation ? customDataLocation + '/' : '') +
path,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData
}
)
)
await remove(
(customDataLocation ? customDataLocation + '/' : '') +
path,
{
baseDir: customDataLocation
? undefined
: BaseDirectory.AppLocalData,
recursive: true
}
)
await versions?.set(
'mods',
Object.fromEntries(
Object.entries(modsList).filter(
([k]) =>
k !== versionInfo?.game + '-' + showModInfo.id
)
)
)
}}
>
<FontAwesomeIcon icon={faTrash} className='text-red-400' />{' '}
Uninstall
</button>
) : (
<button
className='button btntheme2 w-fit'
onClick={async () =>
await downloadVersions([
{
id: managingVersion,
type: 2,
modDownload: showModInfo.latestDownload,
gameId: versionInfo?.game,
modId: showModInfo.id,
modVersion: showModInfo.latestVersion
}
])
}
disabled={downloadProgress.length != 0}
>
<FontAwesomeIcon
icon={faDownload}
className='text-green-400'
/>{' '}
Install
</button>
)}
<button
className='button btntheme2 w-fit'
onClick={async () => {
await message(
!showModInfo.changelog
? '(No changelog provided)'
: atob(showModInfo?.changelog ?? ''),
{
title: 'Changelog for ' + showModInfo.name,
kind: 'info'
}
)
}}
>
<FontAwesomeIcon
icon={faArrowUpRightFromSquare}
color='lightgray'
/>{' '}
View changelog
</button>
{showModInfo.creators.length > 2 && (
<button
className='button btntheme2 w-fit'
onClick={async () => {
if (!versionInfo) return
await message(showModInfo.creators.join(', '), {
title: 'Creators for ' + showModInfo.name,
kind: 'info'
})
}}
>
<FontAwesomeIcon icon={faPeopleGroup} color='lightgray' />{' '}
View all creators
</button>
)}
</div>
</div>
)}
</div>
</>
)
}
-60
View File
@@ -1,60 +0,0 @@
'use client'
import { useGlobal } from '@/providers/GlobalProvider'
import { faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import DOMPurify from 'dompurify'
import { useState } from 'react'
export default function VersionChangelogPopup () {
const { serverVersionList, managingVersion, developerMode } = useGlobal()
const [raw, setRaw] = useState<boolean>(false)
if (!managingVersion) return null
const versionInfo = serverVersionList?.versions.find(
vf => vf.id == managingVersion
)
return (
<>
{developerMode && (
<button
className='popup-top-button btntheme1 right-2'
onClick={() => setRaw(!raw)}
>
<FontAwesomeIcon icon={raw ? faEyeSlash : faEye} />
</button>
)}
<p className='text-xl text-center'>
Viewing changelog {versionInfo?.displayName}
</p>
<div className='popup-content h-full w-full p-2 select-text'>
{raw ? (
<>
<p>Raw: {versionInfo?.changelog}</p>
<p
className='whitespace-pre-line'
dangerouslySetInnerHTML={{
__html:
'Decoded: \n' +
DOMPurify.sanitize(atob(versionInfo?.changelog ?? ''))
}}
></p>
</>
) : (
<p
className='whitespace-pre-line'
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(
atob(versionInfo?.changelog ?? '')
.replace(/^- /gm, '&bull; ')
.replaceAll(/`([^`]+)`/g, '<code>$1</code>')
)
}}
></p>
)}
</div>
</>
)
}
-129
View File
@@ -1,129 +0,0 @@
import { useGlobal } from '@/providers/GlobalProvider'
import { faAdd, faInfo, faRemove } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
export default function VersionsDownloadPopup () {
const {
serverVersionList,
getSpecialVersionsList,
selectedVersionList,
setSelectedVersionList,
setManagingVersion,
setPopupMode,
selectedGame,
setViewingInfoFromDownloads,
downloadVersions,
developerMode
} = useGlobal()
const game = serverVersionList?.games.find(g => g.id === selectedGame)
if (!selectedGame || !game) return null
const list = getSpecialVersionsList(selectedGame)
return (
<>
<p className='text-xl text-center'>Select versions to download</p>
<div className='popup-content'>
{list.length != 0 ? (
list.map((v, i) => (
<div
key={i}
className='popup-entry grid items-center gap-3'
style={{ gridTemplateColumns: 'auto minmax(0, 1fr) auto' }}
>
<button
className='button btntheme3'
onClick={() => {
setManagingVersion(v.id)
setViewingInfoFromDownloads(true)
setPopupMode(2)
}}
title='Click to view version info.'
>
<FontAwesomeIcon icon={faInfo} /> Info
</button>
<p
className='text-2xl text-center truncate'
title={v.displayName}
>
{developerMode ? <span className='text-sm'>{v.id} </span> : ''}
{v.displayName}
</p>
<button
className='button btntheme3'
onClick={() => {
setSelectedVersionList(prev =>
prev.includes(v.id)
? prev.filter(i => i !== v.id)
: [...prev, v.id]
)
}}
title={
selectedVersionList.includes(v.id)
? 'This version will be downloaded. Click to remove from the list of versions that will be downloaded.'
: 'This version will NOT be downloaded. Click to add from the list of versions that will be downloaded.'
}
>
{selectedVersionList.includes(v.id) ? (
<>
<FontAwesomeIcon icon={faRemove} /> Remove
</>
) : (
<>
<FontAwesomeIcon icon={faAdd} /> Add
</>
)}
</button>
</div>
))
) : (
<div className='flex flex-col gap-2 justify-center text-center w-full h-full'>
<p className='text-2xl'>No versions available to download</p>
<p>You may already have all versions installed for this game</p>
</div>
)}
</div>
<div className='flex justify-center'>
<button
className='button btntheme1 w-fit mt-2 -mb-4'
onClick={async () => {
await downloadVersions(
selectedVersionList.map(versionId => ({
id: versionId,
type: 0
}))
)
setPopupMode(1)
}}
disabled={selectedVersionList.length == 0}
title={`Download ${selectedVersionList.length} version${
selectedVersionList.length == 1 ? '' : 's'
} of ${game.name}.`}
>
Download {selectedVersionList.length} version
{selectedVersionList.length == 1 ? '' : 's'}
</button>
<button
className='button btntheme1 w-fit mt-2 ml-2 -mb-4'
onClick={() => {
const allIds = list.map(v => v.id)
setSelectedVersionList(prev =>
prev.length === allIds.length ? [] : allIds
)
}}
title={
selectedVersionList.length === list.length
? 'Click to remove all selected versions for download.'
: 'Click to add all selected versions for download.'
}
>
{selectedVersionList.length === list.length
? 'Deselect All'
: 'Select All'}
</button>
</div>
</>
)
}
-60
View File
@@ -1,60 +0,0 @@
@import "tailwindcss";
.dropdown {
@apply relative w-40;
}
.dropdown-btn {
@apply w-full flex items-center justify-between px-2 py-1 rounded-md cursor-pointer
bg-(--col2) hover:bg-(--col3)
border border-(--col4) hover:border-(--col5)
text-white;
}
.dropdown-arrow {
@apply w-3 h-3 transition-transform stroke-current stroke-2 fill-none;
}
.dropdown-arrow.open {
@apply rotate-180;
}
.dropdown-menu {
@apply absolute z-50 mt-1 w-full rounded-md shadow-2xl overflow-hidden
bg-(--col2) border border-(--col4)
origin-top
opacity-0 scale-95 -translate-y-1 pointer-events-none
transition-[opacity,transform] duration-150 ease-out;
}
.dropdown-menu.open {
@apply opacity-100 scale-100 translate-y-0 pointer-events-auto;
}
.dropdown-item {
@apply px-2 py-1 cursor-pointer text-white transition-colors border-b border-(--col4) last:border-b-0;
opacity: 0;
transform: translateY(-10px);
}
.dropdown-item:hover,
.dropdown-item.active {
@apply bg-(--col3);
}
.dropdown-menu.open .dropdown-item {
animation: dropIn 220ms ease-out forwards;
animation-delay: calc(var(--i) * 40ms);
}
@keyframes dropIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
+1
View File
@@ -0,0 +1 @@
export type BirdColor = [number, number, number]
+1 -20
View File
@@ -1,27 +1,8 @@
export class DownloadProgress { export class DownloadProgress {
constructor ( constructor (
public version: string, public version: string,
public progress: number,
public progressBytes: number,
public failed: boolean, public failed: boolean,
public downloading: boolean,
public paused: boolean,
public canceled: boolean,
public queued: boolean, public queued: boolean,
public hash_checking: boolean, public finishing: boolean
public speed: number,
public size: number,
public etaSecs: number,
public unzipping: boolean,
public unzipTotal: number,
public unzipped: number,
public url: string | null,
public executable: string | null,
public hash: string | null,
public type: 0 | 1 | 2,
public modDownload: number | null,
public modGame: number | null,
public modId: number | null,
public modVersion: string | null
) {} ) {}
} }
+1 -2
View File
@@ -8,7 +8,6 @@ export interface GameVersion {
wine: number | undefined wine: number | undefined
category: number category: number
lastRevision: number lastRevision: number
download: number | undefined download: number
executable: string executable: string
modSupportDownload: number | undefined
} }
-12
View File
@@ -1,12 +0,0 @@
export interface Mod {
id: number
name: string
description: string | null
creators: string[]
downloads: number
released: number
updated: number
latestVersion: string
latestDownload: number
changelog: string | null
}
+21
View File
@@ -0,0 +1,21 @@
import { SettingsType } from './SettingsType'
type NormalConfigData = {
version: string
settings?: Partial<SettingsType>
}
export class NormalConfig {
constructor (
public version: string,
public settings: SettingsType = new SettingsType()
) {}
static import (data: NormalConfigData) {
const cfg = new NormalConfig(data.version)
if (data.settings) {
cfg.settings = { ...cfg.settings, ...data.settings }
}
return cfg
}
}
-1
View File
@@ -4,5 +4,4 @@ export type SettingProps = {
onChange: (val: boolean) => void onChange: (val: boolean) => void
className?: string className?: string
title?: string title?: string
disabled?: boolean
} }
+9
View File
@@ -0,0 +1,9 @@
export class SettingsType {
constructor (
public allowNotifications: boolean = true,
public alwaysShowGamesInSidebar: boolean = true,
public useWineOnUnixWhenNeeded: boolean = false,
public wineOnUnixCommand: string = 'wine %path%',
public theme: number = 0
) {}
}
+17
View File
@@ -0,0 +1,17 @@
export type VersionsConfigData = {
version: string
list: Record<string, number>
}
export class VersionsConfig {
constructor (
public version: string,
public list: Record<string, number> = {}
) {}
static import (data: VersionsConfigData) {
const cfg = new VersionsConfig(data.version)
cfg.list = { ...data.list }
return cfg
}
}