offline mode, expanded logging

This commit is contained in:
2024-12-09 04:14:53 +01:00
parent 5244fa9549
commit 2d84c514a7
8 changed files with 296 additions and 88 deletions

View File

@@ -3,11 +3,17 @@ use crate::structs::Config;
use std::{fs, path::PathBuf};
pub fn load(config_path: PathBuf) -> Config {
debug!("Loading config from: {}", config_path.display());
if config_path.exists() {
let cfg = fs::read_to_string(&config_path).unwrap();
let cfg: Config = serde_json::from_str(&cfg).unwrap_or(Config::default());
let cfg: Config = serde_json::from_str(&cfg).unwrap_or_else(|e| {
warn!("Failed to parse config file: {}", e);
Config::default()
});
debug!("Loaded config: {:?}", cfg);
return cfg;
}
info!("No config file found, creating default config");
save(config_path.clone(), Config::default());
Config::default()
}

View File

@@ -1,4 +1,5 @@
use crate::structs::PrintPrefix;
use crate::misc;
use crate::structs::{PrintPrefix, StoredGameData};
use colored::Colorize;
use once_cell::sync::Lazy;
use std::collections::HashMap;
@@ -12,6 +13,8 @@ pub const GH_IW4X_REPO: &str = "iw4x-client";
pub static MASTER: Lazy<Mutex<String>> =
Lazy::new(|| Mutex::new("https://cdn.alterware.ovh".to_owned()));
pub static IS_OFFLINE: Lazy<Mutex<bool>> = Lazy::new(|| Mutex::new(false));
pub static PREFIXES: Lazy<HashMap<&'static str, PrintPrefix>> = Lazy::new(|| {
HashMap::from([
(
@@ -51,3 +54,29 @@ pub static PREFIXES: Lazy<HashMap<&'static str, PrintPrefix>> = Lazy::new(|| {
),
])
});
pub async fn check_connectivity() -> bool {
let master_url = MASTER.lock().unwrap().clone();
match crate::http_async::get_body_string(&master_url).await {
Ok(_) => true,
Err(_) => {
*IS_OFFLINE.lock().unwrap() = true;
false
}
}
}
pub fn get_stored_data() -> Option<StoredGameData> {
let dir = std::env::current_dir().ok()?;
let cache = misc::get_cache(&dir);
cache.stored_data
}
pub fn store_game_data(data: &StoredGameData) -> Result<(), Box<dyn std::error::Error>> {
let dir = std::env::current_dir()?;
let mut cache = misc::get_cache(&dir);
cache.stored_data = Some((*data).clone());
misc::save_cache(&dir, cache);
Ok(())
}

View File

@@ -17,6 +17,8 @@ pub async fn download_file_progress(
path: &PathBuf,
size: u64,
) -> Result<(), String> {
debug!("Starting download: {} -> {}", url, path.display());
let res = client
.get(url)
.header(
@@ -29,9 +31,13 @@ pub async fn download_file_progress(
)
.send()
.await
.map_err(|_| format!("Failed to GET from '{url}'"))?;
.map_err(|e| {
error!("Failed to GET from '{}': {}", url, e);
format!("Failed to GET from '{url}'")
})?;
let total_size = res.content_length().unwrap_or(size);
debug!("Download size: {}", misc::human_readable_bytes(total_size));
pb.set_length(total_size);
let msg = format!(

View File

@@ -337,6 +337,10 @@ async fn update(
skip_iw4x_sp: Option<bool>,
ignore_required_files: Option<bool>,
) {
info!("Starting update for game engine: {}", game.engine);
info!("Update path: {}", dir.display());
debug!("Bonus content: {}, Force update: {}", bonus_content, force);
let skip_iw4x_sp = skip_iw4x_sp.unwrap_or(false);
let ignore_required_files = ignore_required_files.unwrap_or(false);
@@ -344,9 +348,11 @@ async fn update(
http_async::get_body_string(format!("{}/files.json", MASTER.lock().unwrap()).as_str())
.await
.unwrap();
debug!("Retrieved files.json from server");
let cdn_info: Vec<CdnFile> = serde_json::from_str(&res).unwrap();
if !ignore_required_files && !game.required_files_exist(dir) {
error!("Critical game files missing. Required files check failed.");
println!(
"{}\nVerify game file integrity on Steam or reinstall the game.",
"Critical game files missing.".bright_red()
@@ -477,10 +483,33 @@ async fn update(
}
misc::save_cache(dir, cache);
// Store game data for offline mode
let mut stored_data = global::get_stored_data().unwrap_or_default();
stored_data.game_path = dir.to_string_lossy().into_owned();
// Store available clients for this engine
stored_data.clients.insert(
game.engine.to_string(),
game.client.iter().map(|s| s.to_string()).collect(),
);
if let Err(e) = global::store_game_data(&stored_data) {
println!(
"{} Failed to store game data: {}",
PREFIXES.get("error").unwrap().formatted(),
e
);
}
}
#[cfg(windows)]
fn launch(file_path: &PathBuf, args: &str) {
info!(
"Launching game on Windows: {} {}",
file_path.display(),
args
);
println!("\n\nJoin the AlterWare Discord server:\nhttps://discord.gg/2ETE8engZM\n\n");
crate::println_info!("Launching {} {args}", file_path.display());
let exit_status = std::process::Command::new(file_path)
@@ -491,6 +520,12 @@ fn launch(file_path: &PathBuf, args: &str) {
.wait()
.expect("Failed to wait for the game process to finish");
if exit_status.success() {
info!("Game exited successfully with status: {}", exit_status);
} else {
error!("Game exited with error status: {}", exit_status);
}
crate::println_error!("Game exited with {exit_status}");
if !exit_status.success() {
misc::stdin();
@@ -641,6 +676,90 @@ async fn main() {
return;
}
let offline_mode = !global::check_connectivity().await;
if offline_mode {
// Check if this is a first-time run (no stored data)
let stored_data = global::get_stored_data();
if stored_data.is_none() {
println!(
"{} Internet connection is required for first-time installation.",
PREFIXES.get("error").unwrap().formatted()
);
error!("Internet connection required for first-time installation");
println!("Please connect to the internet and try again.");
println!("Press enter to exit...");
misc::stdin();
std::process::exit(1);
}
println!(
"{} No internet connection or MASTER server is unreachable. Running in offline mode...",
PREFIXES.get("error").unwrap().formatted()
);
warn!("No internet connection or MASTER server is unreachable. Running in offline mode...");
// Handle path the same way as online mode
let install_path: PathBuf;
if let Some(path) = arg_value(&args, "--path") {
install_path = PathBuf::from(path);
arg_remove_value(&mut args, "--path");
} else if let Some(path) = arg_value(&args, "-p") {
install_path = PathBuf::from(path);
arg_remove_value(&mut args, "-p");
} else {
install_path = env::current_dir().unwrap();
}
let cfg = config::load(install_path.join("alterware-launcher.json"));
// Try to get stored game data
let stored_data = global::get_stored_data();
if let Some(ref data) = stored_data {
info!("Found stored game data for path: {}", data.game_path);
} else {
warn!("No stored game data found");
}
// Get client from args, config, or prompt user
let client = if args.len() > 1 {
args[1].clone()
} else if let Some(engine) = stored_data
.as_ref()
.and_then(|d| d.clients.get(&cfg.engine))
{
if engine.len() > 1 {
println!("Multiple clients available, select one to launch:");
for (i, c) in engine.iter().enumerate() {
println!("{i}: {c}");
}
info!("Multiple clients available, prompting user for selection");
engine[misc::stdin().parse::<usize>().unwrap()].clone()
} else if !engine.is_empty() {
info!("Using single available client: {}", engine[0]);
engine[0].clone()
} else {
println!(
"{} No client specified and no stored clients available.",
PREFIXES.get("error").unwrap().formatted()
);
error!("No client specified and no stored clients available");
std::process::exit(1);
}
} else {
println!(
"{} No client specified and no stored data available.",
PREFIXES.get("error").unwrap().formatted()
);
error!("No client specified and no stored data available");
std::process::exit(1);
};
info!("Launching game in offline mode with client: {}", client);
// Launch game without updates
launch(&install_path.join(format!("{}.exe", client)), &cfg.args);
return;
}
let install_path: PathBuf;
if let Some(path) = arg_value(&args, "--path") {
install_path = PathBuf::from(path);
@@ -812,6 +931,25 @@ async fn main() {
if !cfg.update_only {
launch(&install_path.join(format!("{c}.exe")), &cfg.args);
}
// Store game data for offline mode
let mut stored_data = global::get_stored_data().unwrap_or_default();
stored_data.game_path = install_path.to_string_lossy().into_owned();
// Store available clients for this engine
stored_data.clients.insert(
g.engine.to_string(),
g.client.iter().map(|s| s.to_string()).collect(),
);
if let Err(e) = global::store_game_data(&stored_data) {
println!(
"{} Failed to store game data: {}",
PREFIXES.get("error").unwrap().formatted(),
e
);
}
return;
}
}

View File

@@ -75,8 +75,17 @@ impl PrintPrefix {
}
}
#[derive(serde::Deserialize, serde::Serialize, Default, PartialEq, Debug, Clone)]
#[derive(serde::Deserialize, serde::Serialize, Default, Debug, Clone, PartialEq)]
pub struct Cache {
pub iw4x_revision: String,
pub hashes: HashMap<String, String>,
#[serde(default)]
pub stored_data: Option<StoredGameData>,
}
#[derive(serde::Deserialize, serde::Serialize, Default, Debug, Clone, PartialEq)]
pub struct StoredGameData {
pub game_path: String,
#[serde(default)]
pub clients: HashMap<String, Vec<String>>,
}

View File

@@ -104,6 +104,7 @@ mod misc {
hashes: [("test".to_string(), "hash".to_string())]
.into_iter()
.collect(),
stored_data: None,
};
misc::save_cache(path, test_cache.clone());
let loaded_cache = misc::get_cache(path);
@@ -112,3 +113,33 @@ mod misc {
fs::remove_file(&cache_file).unwrap();
}
}
mod stored_data {
use crate::{fs, global, structs::StoredGameData};
use serial_test::serial;
use std::{collections::HashMap, path::Path};
#[test]
#[serial]
fn stored_game_data() {
let test_path = "test/path";
let mut test_clients = HashMap::new();
test_clients.insert("iw4".to_string(), vec!["iw4x".to_string()]);
let data = StoredGameData {
game_path: test_path.to_string(),
clients: test_clients,
};
let path = Path::new("tests_tmp");
fs::create_dir_all(path).unwrap();
global::store_game_data(&data).unwrap();
let loaded = global::get_stored_data().unwrap();
assert_eq!(data.game_path, loaded.game_path);
assert_eq!(data.clients, loaded.clients);
fs::remove_dir_all(path).unwrap();
}
}