Compare commits

...

3 Commits

Author SHA1 Message Date
0f48f3fb44 chore: Run cargo clippy && cargo fmt
Signed-off-by: quexeky <git@quexeky.dev>
2025-10-12 20:13:26 +11:00
974666efe2 refactor: Finish refactor
Signed-off-by: quexeky <git@quexeky.dev>
2025-10-12 19:17:40 +11:00
9e1bf9852f refactor: Builds, but some logic still left to move back
Signed-off-by: quexeky <git@quexeky.dev>
2025-10-12 18:33:43 +11:00
66 changed files with 886 additions and 539 deletions

6
Cargo.lock generated
View File

@ -381,9 +381,9 @@ dependencies = [
[[package]]
name = "atomic-instant-full"
version = "0.1.0"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db6541700e074cda41b1c6f98c2cae6cde819967bf142078f069cad85387cdbe"
checksum = "83148e838612d8d701ce16b9f64b8674c097e1b4a14037b294baec03d9072228"
[[package]]
name = "atomic-waker"
@ -1375,6 +1375,7 @@ dependencies = [
"database",
"deranged 0.4.0",
"dirs 6.0.0",
"download_manager",
"droplet-rs",
"dynfmt",
"filetime",
@ -4287,6 +4288,7 @@ dependencies = [
"serde",
"serde_with",
"shared_child",
"tauri",
"tauri-plugin-opener",
"utils",
]

View File

@ -9,4 +9,4 @@ pub enum AppStatus {
SignedIn,
SignedInNeedsReauth,
ServerUnavailable,
}
}

View File

@ -1,4 +1,9 @@
use std::{ffi::OsStr, path::PathBuf, process::{Command, Stdio}, sync::LazyLock};
use std::{
ffi::OsStr,
path::PathBuf,
process::{Command, Stdio},
sync::LazyLock,
};
use log::info;

View File

@ -1,4 +1,4 @@
pub mod autostart;
pub mod user;
pub mod app_status;
pub mod compat;
pub mod autostart;
pub mod compat;
pub mod user;

View File

@ -10,4 +10,3 @@ pub struct User {
display_name: String,
profile_picture_object_id: String,
}

View File

@ -2,7 +2,7 @@ use std::{collections::HashMap, path::PathBuf, str::FromStr};
#[cfg(target_os = "linux")]
use database::platform::Platform;
use database::{db::DATA_ROOT_DIR, GameVersion};
use database::{GameVersion, db::DATA_ROOT_DIR};
use log::warn;
use crate::error::BackupError;
@ -14,6 +14,12 @@ pub struct BackupManager<'a> {
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
}
impl Default for BackupManager<'_> {
fn default() -> Self {
Self::new()
}
}
impl BackupManager<'_> {
pub fn new() -> Self {
BackupManager {
@ -40,66 +46,189 @@ impl BackupManager<'_> {
(Platform::MacOs, Platform::MacOs),
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
),
]),
}
}
}
pub trait BackupHandler: Send + Sync {
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.join("games")) }
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) }
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(self.root_translate(path, game)?.join(self.game_translate(path, game)?)) }
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c }
fn store_user_id_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError) }
fn os_user_name_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&whoami::username()).unwrap()) }
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winAppData>"); Err(BackupError::InvalidSystem) }
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) }
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>"); Err(BackupError::InvalidSystem) }
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDocuments>"); Err(BackupError::InvalidSystem) }
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winPublic>"); Err(BackupError::InvalidSystem) }
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winProgramData>"); Err(BackupError::InvalidSystem) }
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) }
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) }
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgConfig>"); Err(BackupError::InvalidSystem) }
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::new()) }
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(DATA_ROOT_DIR.join("games"))
}
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str(&game.game_id).unwrap())
}
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(self
.root_translate(path, game)?
.join(self.game_translate(path, game)?))
}
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
let c = CommonPath::Home.get().ok_or(BackupError::NotFound);
println!("{:?}", c);
c
}
fn store_user_id_translate(
&self,
_path: &PathBuf,
game: &GameVersion,
) -> Result<PathBuf, BackupError> {
PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError)
}
fn os_user_name_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str(&whoami::username()).unwrap())
}
fn win_app_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winAppData>");
Err(BackupError::InvalidSystem)
}
fn win_local_app_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winLocalAppData>");
Err(BackupError::InvalidSystem)
}
fn win_local_app_data_low_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>");
Err(BackupError::InvalidSystem)
}
fn win_documents_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winDocuments>");
Err(BackupError::InvalidSystem)
}
fn win_public_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winPublic>");
Err(BackupError::InvalidSystem)
}
fn win_program_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winProgramData>");
Err(BackupError::InvalidSystem)
}
fn win_dir_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected Windows Reference in Backup <winDir>");
Err(BackupError::InvalidSystem)
}
fn xdg_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected XDG Reference in Backup <xdgData>");
Err(BackupError::InvalidSystem)
}
fn xdg_config_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
warn!("Unexpected XDG Reference in Backup <xdgConfig>");
Err(BackupError::InvalidSystem)
}
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(PathBuf::new())
}
}
pub struct LinuxBackupManager {}
impl BackupHandler for LinuxBackupManager {
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?)
fn xdg_config_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Data.get().ok_or(BackupError::NotFound)
}
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
fn xdg_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Config.get().ok_or(BackupError::NotFound)
}
}
pub struct WindowsBackupManager {}
impl BackupHandler for WindowsBackupManager {
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
fn win_app_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Config.get().ok_or(BackupError::NotFound)
}
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?)
fn win_local_app_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocal.get().ok_or(BackupError::NotFound)
}
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
fn win_local_app_data_low_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::DataLocalLow
.get()
.ok_or(BackupError::NotFound)
}
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
fn win_dir_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str("C:/Windows").unwrap())
}
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?)
fn win_documents_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Document.get().ok_or(BackupError::NotFound)
}
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
fn win_program_data_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
Ok(PathBuf::from_str("C:/ProgramData").unwrap())
}
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?)
fn win_public_translate(
&self,
_path: &PathBuf,
_game: &GameVersion,
) -> Result<PathBuf, BackupError> {
CommonPath::Public.get().ok_or(BackupError::NotFound)
}
}
pub struct MacBackupManager {}
impl BackupHandler for MacBackupManager {}
impl BackupHandler for MacBackupManager {}

View File

@ -2,5 +2,6 @@ use database::platform::Platform;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Condition {
Os(Platform)
Os(Platform),
Other
}

View File

@ -1,8 +1,8 @@
pub mod backup_manager;
pub mod conditions;
pub mod error;
pub mod metadata;
pub mod resolver;
pub mod placeholder;
pub mod normalise;
pub mod path;
pub mod backup_manager;
pub mod error;
pub mod placeholder;
pub mod resolver;

View File

@ -1,7 +1,6 @@
use database::GameVersion;
use super::conditions::{Condition};
use super::conditions::Condition;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CloudSaveMetadata {
@ -16,15 +15,17 @@ pub struct GameFile {
pub id: Option<String>,
pub data_type: DataType,
pub tags: Vec<Tag>,
pub conditions: Vec<Condition>
pub conditions: Vec<Condition>,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub enum DataType {
Registry,
File,
Other
Other,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[derive(
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
)]
#[serde(rename_all = "camelCase")]
pub enum Tag {
Config,
@ -32,4 +33,4 @@ pub enum Tag {
#[default]
#[serde(other)]
Other,
}
}

View File

@ -5,7 +5,6 @@ use regex::Regex;
use super::placeholder::*;
pub fn normalize(path: &str, os: Platform) -> String {
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
@ -14,18 +13,25 @@ pub fn normalize(path: &str, os: Platform) -> String {
}
static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap());
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap());
static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap());
static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
static APP_DATA_ROAMING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
static APP_DATA_ROAMING: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
static APP_DATA_LOCAL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
static APP_DATA_LOCAL_2: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
static USER_PROFILE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
static DOCUMENTS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
for (pattern, replacement) in [
(&CONSECUTIVE_SLASHES, "/"),
@ -66,7 +72,9 @@ pub fn normalize(path: &str, os: Platform) -> String {
fn too_broad(path: &str) -> bool {
println!("Path: {}", path);
use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
use {
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
};
let path_lower = path.to_lowercase();
@ -77,7 +85,9 @@ fn too_broad(path: &str) -> bool {
}
for item in AVOID_WILDCARDS {
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
if path.starts_with(&format!("{}/*", item))
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
{
return true;
}
}
@ -124,7 +134,6 @@ fn too_broad(path: &str) -> bool {
return true;
}
}
// Drive letters:
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
@ -159,4 +168,4 @@ pub fn usable(path: &str) -> bool {
&& !path.starts_with("../")
&& !too_broad(path)
&& !unprintable.is_match(path)
}
}

View File

@ -13,12 +13,12 @@ pub enum CommonPath {
impl CommonPath {
pub fn get(&self) -> Option<PathBuf> {
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir);
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir);
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir);
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir);
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir);
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir);
#[cfg(windows)]
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {

View File

@ -48,4 +48,4 @@ pub const XDG_DATA: &str = "<xdgData>"; // %WINDIR% on Windows
pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(|| whoami::username());
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(whoami::username);

View File

@ -1,17 +1,13 @@
use std::{
fs::{self, create_dir_all, File},
io::{self, ErrorKind, Read, Write},
fs::{self, File, create_dir_all},
io::{self, Read, Write},
path::{Path, PathBuf},
thread::sleep,
time::Duration,
};
use crate::error::BackupError;
use super::{
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
};
use database::{platform::Platform, GameVersion};
use super::{backup_manager::BackupHandler, placeholder::*};
use database::GameVersion;
use log::{debug, warn};
use rustix::path::Arg;
use tempfile::tempfile;
@ -30,7 +26,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
.iter()
.find_map(|p| match p {
super::conditions::Condition::Os(os) => Some(os),
_ => None,
_ => None
})
.cloned()
{
@ -63,7 +59,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
let binding = serde_json::to_string(meta).unwrap();
let serialized = binding.as_bytes();
let mut file = tempfile().unwrap();
file.write(serialized).unwrap();
file.write_all(serialized).unwrap();
tarball.append_file("metadata", &mut file).unwrap();
tarball.into_inner().unwrap().finish().unwrap()
}
@ -96,7 +92,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
.iter()
.find_map(|p| match p {
super::conditions::Condition::Os(os) => Some(os),
_ => None,
_ => None
})
.cloned()
{
@ -115,7 +111,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
};
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
create_dir_all(&new_path.parent().unwrap()).unwrap();
create_dir_all(new_path.parent().unwrap()).unwrap();
println!(
"Current path {:?} copying to {:?}",
@ -132,23 +128,22 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
let src_path = src.as_ref();
let dest_path = dest.as_ref();
let metadata = fs::metadata(&src_path)?;
let metadata = fs::metadata(src_path)?;
if metadata.is_file() {
// Ensure the parent directory of the destination exists for a file copy
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(&src_path, &dest_path)?;
fs::copy(src_path, dest_path)?;
} else if metadata.is_dir() {
// For directories, we call the recursive helper function.
// The destination for the recursive copy is the `dest_path` itself.
copy_dir_recursive(&src_path, &dest_path)?;
copy_dir_recursive(src_path, dest_path)?;
} else {
// Handle other file types like symlinks if necessary,
// for now, return an error or skip.
return Err(io::Error::new(
io::ErrorKind::Other,
return Err(io::Error::other(
format!("Source {:?} is neither a file nor a directory", src_path),
));
}
@ -157,7 +152,7 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
}
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
fs::create_dir_all(&dest)?;
fs::create_dir_all(dest)?;
for entry in fs::read_dir(src)? {
let entry = entry?;
@ -219,43 +214,3 @@ pub fn parse_path(
println!("Final line: {:?}", &s);
Ok(s)
}
pub fn test() {
let mut meta = CloudSaveMetadata {
files: vec![
GameFile {
path: String::from("<home>/favicon.png"),
id: None,
data_type: super::metadata::DataType::File,
tags: Vec::new(),
conditions: vec![Condition::Os(Platform::Linux)],
},
GameFile {
path: String::from("<home>/Documents/Pixel Art"),
id: None,
data_type: super::metadata::DataType::File,
tags: Vec::new(),
conditions: vec![Condition::Os(Platform::Linux)],
},
],
game_version: GameVersion {
game_id: String::new(),
version_name: String::new(),
platform: Platform::Linux,
launch_command: String::new(),
launch_args: Vec::new(),
launch_command_template: String::new(),
setup_command: String::new(),
setup_args: Vec::new(),
setup_command_template: String::new(),
only_setup: true,
version_index: 0,
delta: false,
umu_id_override: None,
},
save_id: String::from("aaaaaaa"),
};
//resolve(&mut meta);
extract("save".into()).unwrap();
}

View File

@ -10,7 +10,6 @@ use crate::interface::{DatabaseImpls, DatabaseInterface};
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
#[cfg(not(debug_assertions))]
static DATA_ROOT_PREFIX: &str = "drop";
#[cfg(debug_assertions)]
@ -32,16 +31,15 @@ impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
for DropDatabaseSerializer
{
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
native_model::encode(val)
.map_err(|e| DeSerError::Internal(e.to_string()))
native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string()))
}
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
let mut buf = Vec::new();
s.read_to_end(&mut buf)
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
let (val, _version) = native_model::decode(buf)
.map_err(|e| DeSerError::Internal(e.to_string()))?;
let (val, _version) =
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
Ok(val)
}
}
}

View File

@ -1,11 +1,20 @@
use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}};
use std::{
fs::{self, create_dir_all},
mem::ManuallyDrop,
ops::{Deref, DerefMut},
path::PathBuf,
sync::{RwLockReadGuard, RwLockWriteGuard},
};
use chrono::Utc;
use log::{debug, error, info, warn};
use rustbreak::{PathDatabase, RustbreakError};
use url::Url;
use crate::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database};
use crate::{
db::{DATA_ROOT_DIR, DB, DropDatabaseSerializer},
models::data::Database,
};
pub type DatabaseInterface =
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;

View File

@ -2,20 +2,13 @@
pub mod db;
pub mod debug;
pub mod interface;
pub mod models;
pub mod platform;
pub mod interface;
pub use models::data::{
ApplicationTransientStatus,
Database,
DatabaseApplications,
DatabaseAuth,
DownloadType,
DownloadableMetadata,
GameDownloadStatus,
GameVersion,
Settings
};
pub use db::DB;
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
pub use models::data::{
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
};

View File

@ -4,7 +4,7 @@ pub mod data {
use native_model::native_model;
use serde::{Deserialize, Serialize};
// NOTE: Within each version, you should NEVER use these types.
// NOTE: Within each version, you should NEVER use these types.
// Declare it using the actual version that it is from, i.e. v1::Settings rather than just Settings from here
pub type GameVersion = v1::GameVersion;
@ -191,9 +191,7 @@ pub mod data {
use serde_with::serde_as;
use super::{
Deserialize, Serialize, native_model, v1,
};
use super::{Deserialize, Serialize, native_model, v1};
#[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
#[derive(Serialize, Deserialize, Clone, Default)]
@ -277,12 +275,13 @@ pub mod data {
pub install_dirs: Vec<PathBuf>,
// Guaranteed to exist if the game also exists in the app state map
pub game_statuses: HashMap<String, GameDownloadStatus>,
pub game_versions: HashMap<String, HashMap<String, v1::GameVersion>>,
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
#[serde(skip)]
pub transient_statuses: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
pub transient_statuses:
HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
}
impl From<v1::DatabaseApplications> for DatabaseApplications {
fn from(value: v1::DatabaseApplications) -> Self {
@ -303,10 +302,7 @@ pub mod data {
mod v3 {
use std::path::PathBuf;
use super::{
Deserialize, Serialize,
native_model, v2, v1,
};
use super::{Deserialize, Serialize, native_model, v1, v2};
#[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct Database {
@ -358,6 +354,20 @@ pub mod data {
compat_info: None,
}
}
}
impl DatabaseAuth {
pub fn new(
private: String,
cert: String,
client_id: String,
web_token: Option<String>,
) -> Self {
Self {
private,
cert,
client_id,
web_token,
}
}
}
}

View File

@ -1,6 +1,5 @@
use serde::{Deserialize, Serialize};
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
pub enum Platform {
Windows,
@ -44,4 +43,4 @@ impl From<whoami::Platform> for Platform {
platform => unimplemented!("Playform {} is not supported", platform),
}
}
}
}

View File

@ -9,11 +9,14 @@ use std::{
use database::DownloadableMetadata;
use log::{debug, error, info, warn};
use tauri::{AppHandle, Emitter};
use tauri::AppHandle;
use utils::{app_emit, lock, send};
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
use crate::{
download_manager_frontend::DownloadStatus,
error::ApplicationDownloadError,
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
};
use super::{
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
@ -289,7 +292,10 @@ impl DownloadManagerBuilder {
if validate_result {
download_agent.on_complete(&app_handle);
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
send!(
sender,
DownloadManagerSignal::Completed(download_agent.metadata())
);
send!(sender, DownloadManagerSignal::UpdateUIQueue);
return;
}
@ -370,7 +376,7 @@ impl DownloadManagerBuilder {
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
let event_data = StatsUpdateEvent { speed: kbs, time };
app_emit!(self.app_handle, "update_stats", event_data);
app_emit!(&self.app_handle, "update_stats", event_data);
}
fn push_ui_queue_update(&self) {
let queue = &self.download_queue.read();
@ -389,6 +395,6 @@ impl DownloadManagerBuilder {
.collect();
let event_data = QueueUpdateEvent { queue: queue_objs };
app_emit!(self.app_handle, "update_queue", event_data);
app_emit!(&self.app_handle, "update_queue", event_data);
}
}

View File

@ -14,7 +14,6 @@ use log::{debug, info};
use serde::Serialize;
use utils::{lock, send};
use crate::error::ApplicationDownloadError;
use super::{
@ -80,6 +79,7 @@ pub enum DownloadStatus {
/// The actual download queue may be accessed through the .`edit()` function,
/// which provides raw access to the underlying queue.
/// THIS EDITING IS BLOCKING!!!
#[derive(Debug)]
pub struct DownloadManager {
terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>,
download_queue: Queue,
@ -124,8 +124,11 @@ impl DownloadManager {
}
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
let mut queue = self.edit();
let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue");
let current_index =
get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
let to_move = queue
.remove(current_index)
.expect("Failed to remove meta at index from queue");
queue.insert(new_index, to_move);
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
}

View File

@ -3,7 +3,6 @@ use std::sync::Arc;
use database::DownloadableMetadata;
use tauri::AppHandle;
use crate::error::ApplicationDownloadError;
use super::{

View File

@ -1,5 +1,9 @@
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
use humansize::{format_size, BINARY};
use humansize::{BINARY, format_size};
use std::{
fmt::{Display, Formatter},
io,
sync::{Arc, mpsc::SendError},
};
use remote::error::RemoteAccessError;
use serde_with::SerializeDisplay;
@ -44,7 +48,9 @@ pub enum ApplicationDownloadError {
impl Display for ApplicationDownloadError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ApplicationDownloadError::NotInitialized => write!(f, "Download not initalized, did something go wrong?"),
ApplicationDownloadError::NotInitialized => {
write!(f, "Download not initalized, did something go wrong?")
}
ApplicationDownloadError::DiskFull(required, available) => write!(
f,
"Game requires {}, {} remaining left on disk.",
@ -60,10 +66,9 @@ impl Display for ApplicationDownloadError {
write!(f, "checksum failed to validate for download")
}
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
ApplicationDownloadError::DownloadError(error) => write!(
f,
"Download failed with error {error:?}"
),
ApplicationDownloadError::DownloadError(error) => {
write!(f, "Download failed with error {error:?}")
}
}
}
}
@ -72,4 +77,4 @@ impl From<io::Error> for ApplicationDownloadError {
fn from(value: io::Error) -> Self {
ApplicationDownloadError::IoError(Arc::new(value))
}
}
}

View File

@ -2,15 +2,43 @@
#![feature(nonpoison_mutex)]
#![feature(sync_nonpoison)]
use std::sync::{nonpoison::Mutex, LazyLock};
use std::{ops::Deref, sync::OnceLock};
use crate::{download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager};
use tauri::AppHandle;
use crate::{
download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager,
};
pub mod download_manager_builder;
pub mod download_manager_frontend;
pub mod downloadable;
pub mod util;
pub mod error;
pub mod frontend_updates;
pub mod util;
pub static DOWNLOAD_MANAGER: LazyLock<Mutex<DownloadManager>> = LazyLock::new(|| todo!());
pub static DOWNLOAD_MANAGER: DownloadManagerWrapper = DownloadManagerWrapper::new();
pub struct DownloadManagerWrapper(OnceLock<DownloadManager>);
impl DownloadManagerWrapper {
const fn new() -> Self {
DownloadManagerWrapper(OnceLock::new())
}
pub fn init(app_handle: AppHandle) {
DOWNLOAD_MANAGER
.0
.set(DownloadManagerBuilder::build(app_handle))
.expect("Failed to initialise download manager");
}
}
impl Deref for DownloadManagerWrapper {
type Target = DownloadManager;
fn deref(&self) -> &Self::Target {
match self.0.get() {
Some(download_manager) => download_manager,
None => unreachable!("Download manager should always be initialised"),
}
}
}

View File

@ -1,6 +1,6 @@
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
atomic::{AtomicBool, Ordering},
};
#[derive(PartialEq, Eq, PartialOrd, Ord)]
@ -22,7 +22,11 @@ impl From<DownloadThreadControlFlag> for bool {
/// false => Stop
impl From<bool> for DownloadThreadControlFlag {
fn from(value: bool) -> Self {
if value { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop }
if value {
DownloadThreadControlFlag::Go
} else {
DownloadThreadControlFlag::Stop
}
}
}

View File

@ -15,7 +15,7 @@ use crate::download_manager_frontend::DownloadManagerSignal;
use super::rolling_progress_updates::RollingProgressWindow;
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct ProgressObject {
max: Arc<Mutex<usize>>,
progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>,
@ -117,7 +117,9 @@ pub fn calculate_update(progress: &ProgressObject) {
let last_update_time = progress
.last_update_time
.swap(Instant::now(), Ordering::SeqCst);
let time_since_last_update = Instant::now().duration_since(last_update_time).as_millis_f64();
let time_since_last_update = Instant::now()
.duration_since(last_update_time)
.as_millis_f64();
let current_bytes_downloaded = progress.sum();
let max = progress.get_max();
@ -125,7 +127,8 @@ pub fn calculate_update(progress: &ProgressObject) {
.bytes_last_update
.swap(current_bytes_downloaded, Ordering::Acquire);
let bytes_since_last_update = current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
let bytes_since_last_update =
current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
let kilobytes_per_second = bytes_since_last_update / time_since_last_update;

View File

@ -6,7 +6,7 @@ use std::{
use database::DownloadableMetadata;
use utils::lock;
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct Queue {
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
}

View File

@ -3,11 +3,17 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
};
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct RollingProgressWindow<const S: usize> {
window: Arc<[AtomicUsize; S]>,
current: Arc<AtomicUsize>,
}
impl<const S: usize> Default for RollingProgressWindow<S> {
fn default() -> Self {
Self::new()
}
}
impl<const S: usize> RollingProgressWindow<S> {
pub fn new() -> Self {
Self {
@ -31,7 +37,7 @@ impl<const S: usize> RollingProgressWindow<S> {
.collect::<Vec<usize>>();
let amount = valid.len();
let sum = valid.into_iter().sum::<usize>();
sum / amount
}
pub fn reset(&self) {

View File

@ -1,8 +1,13 @@
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata};
use database::{
ApplicationTransientStatus, DownloadType, DownloadableMetadata, borrow_db_checked,
borrow_db_mut_checked,
};
use download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
use download_manager::downloadable::Downloadable;
use download_manager::error::ApplicationDownloadError;
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
use download_manager::util::download_thread_control_flag::{
DownloadThreadControl, DownloadThreadControlFlag,
};
use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
use log::{debug, error, info, warn};
use rayon::ThreadPoolBuilder;
@ -10,7 +15,6 @@ use remote::auth::generate_authorization_header;
use remote::error::RemoteAccessError;
use remote::requests::generate_url;
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
use utils::{app_emit, lock, send};
use std::collections::{HashMap, HashSet};
use std::fs::{OpenOptions, create_dir_all};
use std::io;
@ -18,12 +22,15 @@ use std::path::{Path, PathBuf};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tauri::{AppHandle, Emitter};
use tauri::AppHandle;
use utils::{app_emit, lock, send};
#[cfg(target_os = "linux")]
use rustix::fs::{FallocateFlags, fallocate};
use crate::downloads::manifest::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody};
use crate::downloads::manifest::{
DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody,
};
use crate::downloads::utils::get_disk_available;
use crate::downloads::validate::validate_game_chunk;
use crate::library::{on_game_complete, push_game_update, set_partially_installed};
@ -97,8 +104,7 @@ impl GameDownloadAgent {
result.ensure_manifest_exists().await?;
let required_space = lock!(result
.manifest)
let required_space = lock!(result.manifest)
.as_ref()
.unwrap()
.values()
@ -447,9 +453,13 @@ impl GameDownloadAgent {
let sender = self.sender.clone();
let download_context = download_contexts
.get(&bucket.version)
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
let download_context =
download_contexts.get(&bucket.version).unwrap_or_else(|| {
panic!(
"Could not get bucket version {}. Corrupted state.",
bucket.version
)
});
scope.spawn(move |_| {
// 3 attempts
@ -687,7 +697,10 @@ impl Downloadable for GameDownloadAgent {
Ok(_) => {}
Err(e) => {
error!("could not mark game as complete: {e}");
send!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e)));
send!(
self.sender,
DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))
);
}
}
}

View File

@ -11,7 +11,9 @@ use std::{
};
use download_manager::error::ApplicationDownloadError;
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
use download_manager::util::download_thread_control_flag::{
DownloadThreadControl, DownloadThreadControlFlag,
};
use download_manager::util::progress_object::ProgressHandle;
use log::{debug, info, warn};
use md5::{Context, Digest};
@ -47,7 +49,7 @@ impl DropWriter<File> {
fn finish(mut self) -> io::Result<Digest> {
self.flush()?;
Ok(self.hasher.compute())
Ok(self.hasher.finalize())
}
}
// Write automatically pushes to file and hasher
@ -116,9 +118,12 @@ impl<'a> DropDownloadPipeline<'a, Response, File> {
let mut last_bump = 0;
loop {
let size = MAX_PACKET_LENGTH.min(remaining);
let size = self.source.read(&mut copy_buffer[0..size]).inspect_err(|_| {
info!("got error from {}", drop.filename);
})?;
let size = self
.source
.read(&mut copy_buffer[0..size])
.inspect_err(|_| {
info!("got error from {}", drop.filename);
})?;
remaining -= size;
last_bump += size;

View File

@ -1,5 +1,8 @@
use std::{
collections::HashMap, fs::File, io::{self, Read, Write}, path::{Path, PathBuf}
collections::HashMap,
fs::File,
io::{self, Read, Write},
path::{Path, PathBuf},
};
use log::error;
@ -77,7 +80,10 @@ impl DropData {
}
}
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
*lock!(self.contexts) = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
*lock!(self.contexts) = completed_contexts
.iter()
.map(|s| (s.0.clone(), s.1))
.collect();
}
pub fn set_context(&self, context: String, state: bool) {
lock!(self.contexts).entry(context).insert_entry(state);

View File

@ -1,4 +1,4 @@
use std::fmt::{Display};
use std::fmt::Display;
use serde_with::SerializeDisplay;
@ -9,13 +9,21 @@ pub enum LibraryError {
}
impl Display for LibraryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", match self {
LibraryError::MetaNotFound(id) => {
format!("Could not locate any installed version of game ID {id} in the database")
write!(
f,
"{}",
match self {
LibraryError::MetaNotFound(id) => {
format!(
"Could not locate any installed version of game ID {id} in the database"
)
}
LibraryError::VersionNotFound(game_id) => {
format!(
"Could not locate any installed version for game id {game_id} in the database"
)
}
}
LibraryError::VersionNotFound(game_id) => {
format!("Could not locate any installed version for game id {game_id} in the database")
}
})
)
}
}

View File

@ -3,5 +3,5 @@ mod download_logic;
pub mod drop_data;
pub mod error;
mod manifest;
pub mod utils;
pub mod validate;
pub mod utils;

View File

@ -19,7 +19,7 @@ pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownlo
return Ok(disk.available_space());
}
}
Err(ApplicationDownloadError::IoError(Arc::new(io::Error::other(
"could not find disk of path",
))))
Err(ApplicationDownloadError::IoError(Arc::new(
io::Error::other("could not find disk of path"),
)))
}

View File

@ -3,7 +3,13 @@ use std::{
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
};
use download_manager::{error::ApplicationDownloadError, util::{download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::ProgressHandle}};
use download_manager::{
error::ApplicationDownloadError,
util::{
download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag},
progress_object::ProgressHandle,
},
};
use log::debug;
use md5::Context;
@ -16,7 +22,10 @@ pub fn validate_game_chunk(
) -> Result<bool, ApplicationDownloadError> {
debug!(
"Starting chunk validation {}, {}, {} #{}",
ctx.path.display(), ctx.index, ctx.offset, ctx.checksum
ctx.path.display(),
ctx.index,
ctx.offset,
ctx.checksum
);
// If we're paused
if control_flag.get() == DownloadThreadControlFlag::Stop {
@ -36,13 +45,12 @@ pub fn validate_game_chunk(
let mut hasher = md5::Context::new();
let completed =
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
let completed = validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
if !completed {
return Ok(false);
}
let res = hex::encode(hasher.compute().0);
let res = hex::encode(hasher.finalize().0);
if res != ctx.checksum {
return Ok(false);
}

View File

@ -3,4 +3,5 @@
pub mod collections;
pub mod downloads;
pub mod library;
pub mod scan;
pub mod state;

View File

@ -1,15 +1,20 @@
use std::fs::remove_dir_all;
use std::sync::Mutex;
use std::thread::spawn;
use bitcode::{Decode, Encode};
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion};
use database::{
ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion,
borrow_db_checked, borrow_db_mut_checked,
};
use log::{debug, error, warn};
use remote::{auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url, utils::DROP_CLIENT_SYNC};
use remote::{
auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url,
utils::DROP_CLIENT_SYNC,
};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter};
use std::fs::remove_dir_all;
use std::thread::spawn;
use tauri::AppHandle;
use utils::app_emit;
use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
use crate::state::{GameStatusManager, GameStatusWithTransient};
#[derive(Serialize, Deserialize, Debug)]
pub struct FetchGameStruct {
@ -20,7 +25,11 @@ pub struct FetchGameStruct {
impl FetchGameStruct {
pub fn new(game: Game, status: GameStatusWithTransient, version: Option<GameVersion>) -> Self {
Self { game, status, version }
Self {
game,
status,
version,
}
}
}
@ -168,7 +177,7 @@ pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle)
);
debug!("uninstalled game id {}", &meta.id);
app_emit!(app_handle, "update_library", ());
app_emit!(&app_handle, "update_library", ());
}
});
} else {
@ -284,41 +293,8 @@ pub struct FrontendGameOptions {
launch_string: String,
}
#[tauri::command]
pub fn update_game_configuration(
game_id: String,
options: FrontendGameOptions,
) -> Result<(), LibraryError> {
let mut handle = borrow_db_mut_checked();
let installed_version = handle
.applications
.installed_game_version
.get(&game_id)
.ok_or(LibraryError::MetaNotFound(game_id))?;
let id = installed_version.id.clone();
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
let mut existing_configuration = handle
.applications
.game_versions
.get(&id)
.unwrap()
.get(&version)
.unwrap()
.clone();
// Add more options in here
existing_configuration.launch_command_template = options.launch_string;
// Add no more options past here
handle
.applications
.game_versions
.get_mut(&id)
.unwrap()
.insert(version.to_string(), existing_configuration);
Ok(())
impl FrontendGameOptions {
pub fn launch_string(&self) -> &String {
&self.launch_string
}
}

View File

@ -1,16 +1,11 @@
use std::fs;
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
use log::warn;
use crate::{
database::{
db::borrow_db_mut_checked,
models::data::{DownloadType, DownloadableMetadata},
},
games::{
downloads::drop_data::{DropData, DROP_DATA_PATH},
library::set_partially_installed_db,
},
downloads::drop_data::{DROP_DATA_PATH, DropData},
library::set_partially_installed_db,
};
pub fn scan_install_dirs() {

View File

@ -19,7 +19,7 @@ impl GameStatusManager {
version: None,
})
.cloned();
let offline_state = database.applications.game_statuses.get(game_id).cloned();
if online_state.is_some() {

View File

@ -14,5 +14,6 @@ page_size = "0.6.0"
serde = "1.0.228"
serde_with = "3.15.0"
shared_child = "1.1.1"
tauri = "2.8.5"
tauri-plugin-opener = "2.5.0"
utils = { version = "0.1.0", path = "../utils" }

View File

@ -8,7 +8,12 @@ pub struct DropFormatArgs {
}
impl DropFormatArgs {
pub fn new(launch_string: String, working_dir: &String, executable_name: &String, absolute_executable_name: String) -> Self {
pub fn new(
launch_string: String,
working_dir: &String,
executable_name: &String,
absolute_executable_name: String,
) -> Self {
let mut positional = Vec::new();
let mut map: HashMap<&'static str, String> = HashMap::new();

View File

@ -1,14 +1,41 @@
#![feature(nonpoison_mutex)]
#![feature(sync_nonpoison)]
use std::sync::{LazyLock, nonpoison::Mutex};
use std::{
ops::Deref,
sync::{OnceLock, nonpoison::Mutex},
};
use tauri::AppHandle;
use crate::process_manager::ProcessManager;
pub static PROCESS_MANAGER: LazyLock<Mutex<ProcessManager>> =
LazyLock::new(|| Mutex::new(ProcessManager::new()));
pub static PROCESS_MANAGER: ProcessManagerWrapper = ProcessManagerWrapper::new();
pub mod error;
pub mod format;
pub mod process_handlers;
pub mod process_manager;
pub struct ProcessManagerWrapper(OnceLock<Mutex<ProcessManager<'static>>>);
impl ProcessManagerWrapper {
const fn new() -> Self {
ProcessManagerWrapper(OnceLock::new())
}
pub fn init(app_handle: AppHandle) {
PROCESS_MANAGER
.0
.set(Mutex::new(ProcessManager::new(app_handle)))
.unwrap_or_else(|_| panic!("Failed to initialise Process Manager")); // Using panic! here because we can't implement Debug
}
}
impl Deref for ProcessManagerWrapper {
type Target = Mutex<ProcessManager<'static>>;
fn deref(&self) -> &Self::Target {
match self.0.get() {
Some(process_manager) => process_manager,
None => unreachable!("Download manager should always be initialised"),
}
}
}

View File

@ -1,8 +1,7 @@
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
use database::{platform::Platform, Database, DownloadableMetadata, GameVersion};
use database::{Database, DownloadableMetadata, GameVersion, platform::Platform};
use log::debug;
use crate::{error::ProcessError, process_manager::ProcessHandler};
pub struct NativeGameLauncher;
@ -46,7 +45,9 @@ impl ProcessHandler for UMULauncher {
};
Ok(format!(
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
umu = UMU_LAUNCHER_EXECUTABLE.as_ref().expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
umu = UMU_LAUNCHER_EXECUTABLE
.as_ref()
.expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
launch = launch_command,
args = args.join(" ")
))
@ -86,7 +87,12 @@ impl ProcessHandler for AsahiMuvmLauncher {
.next()
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
.trim();
let cmd = format!("umu-run{}", args_cmd.next().ok_or(ProcessError::InvalidArguments(umu_string.clone()))?);
let cmd = format!(
"umu-run{}",
args_cmd
.next()
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
);
Ok(format!("{args} muvm -- {cmd}"))
}

View File

@ -6,6 +6,7 @@ use std::{
process::{Command, ExitStatus},
str::FromStr,
sync::Arc,
thread::spawn,
time::{Duration, SystemTime},
};
@ -15,10 +16,10 @@ use database::{
};
use dynfmt::Format;
use dynfmt::SimpleCurlyFormat;
use games::state::GameStatusManager;
use games::{library::push_game_update, state::GameStatusManager};
use log::{debug, info, warn};
use serde::{Deserialize, Serialize};
use shared_child::SharedChild;
use tauri::AppHandle;
use crate::{
PROCESS_MANAGER,
@ -41,10 +42,11 @@ pub struct ProcessManager<'a> {
(Platform, Platform),
&'a (dyn ProcessHandler + Sync + Send + 'static),
)>,
app_handle: AppHandle,
}
impl ProcessManager<'_> {
pub fn new() -> Self {
pub fn new(app_handle: AppHandle) -> Self {
let log_output_dir = DATA_ROOT_DIR.join("logs");
ProcessManager {
@ -82,6 +84,7 @@ impl ProcessManager<'_> {
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
),
],
app_handle,
}
}
@ -172,13 +175,12 @@ impl ProcessManager<'_> {
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
// TODO
// push_game_update(
// &self.app_handle,
// &game_id,
// Some(version_data.clone()),
// status,
// );
push_game_update(
&self.app_handle,
&game_id,
Some(version_data.clone()),
status,
);
Ok(())
}
@ -363,13 +365,12 @@ impl ProcessManager<'_> {
.transient_statuses
.insert(meta.clone(), ApplicationTransientStatus::Running {});
// TODO
// push_game_update(
// &self.app_handle,
// &meta.id,
// None,
// (None, Some(ApplicationTransientStatus::Running {})),
// );
push_game_update(
&self.app_handle,
&meta.id,
None,
(None, Some(ApplicationTransientStatus::Running {})),
);
let wait_thread_handle = launch_process_handle.clone();
let wait_thread_game_id = meta.clone();
@ -382,12 +383,14 @@ impl ProcessManager<'_> {
manually_killed: false,
},
);
spawn(move || {
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
PROCESS_MANAGER
.lock()
.on_process_finish(wait_thread_game_id.id, result)
PROCESS_MANAGER
.lock()
.on_process_finish(wait_thread_game_id.id, result)
});
Ok(())
}
}

View File

@ -2,14 +2,18 @@ use std::{collections::HashMap, env};
use chrono::Utc;
use client::{app_status::AppStatus, user::User};
use database::interface::borrow_db_checked;
use database::{DatabaseAuth, interface::borrow_db_checked};
use droplet_rs::ssl::sign_nonce;
use gethostname::gethostname;
use log::{error, warn};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{error::{DropServerError, RemoteAccessError}, requests::make_authenticated_get, utils::DROP_CLIENT_SYNC};
use crate::{
error::{DropServerError, RemoteAccessError},
requests::make_authenticated_get,
utils::DROP_CLIENT_SYNC,
};
use super::{
cache::{cache_object, get_cached_object},
@ -31,19 +35,31 @@ struct InitiateRequestBody {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct HandshakeRequestBody {
pub struct HandshakeRequestBody {
client_id: String,
token: String,
}
impl HandshakeRequestBody {
pub fn new(client_id: String, token: String) -> Self {
Self { client_id, token }
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct HandshakeResponse {
pub struct HandshakeResponse {
private: String,
certificate: String,
id: String,
}
impl From<HandshakeResponse> for DatabaseAuth {
fn from(value: HandshakeResponse) -> Self {
DatabaseAuth::new(value.private, value.certificate, value.id, None)
}
}
pub fn generate_authorization_header() -> String {
let certs = {
let db = borrow_db_checked();

View File

@ -15,9 +15,9 @@ use crate::error::{CacheError, RemoteAccessError};
macro_rules! offline {
($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => {
async move {
if ::database::borrow_db_checked().settings.force_offline
|| ::utils::lock!($var).status == ::client::app_status::AppStatus::Offline {
async move {
if ::database::borrow_db_checked().settings.force_offline
|| $var.lock().status == ::client::app_status::AppStatus::Offline {
$func2( $( $arg ), *).await
} else {
$func1( $( $arg ), *).await

View File

@ -4,7 +4,7 @@ use std::{
sync::Arc,
};
use http::{header::ToStrError, HeaderName, StatusCode};
use http::{HeaderName, StatusCode, header::ToStrError};
use serde_with::SerializeDisplay;
use url::ParseError;
@ -19,7 +19,6 @@ pub struct DropServerError {
// pub url: String,
}
#[derive(Debug, SerializeDisplay)]
pub enum RemoteAccessError {
FetchError(Arc<reqwest::Error>),
@ -120,17 +119,25 @@ pub enum CacheError {
HeaderNotFound(HeaderName),
ParseError(ToStrError),
Remote(RemoteAccessError),
ConstructionError(http::Error)
ConstructionError(http::Error),
}
impl Display for CacheError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = match self {
CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
CacheError::ParseError(to_str_error) => format!("Could not parse cache with error {to_str_error}"),
CacheError::Remote(remote_access_error) => format!("Cache got remote access error: {remote_access_error}"),
CacheError::ConstructionError(error) => format!("Could not construct cache body with error {error}"),
CacheError::HeaderNotFound(header_name) => {
format!("Could not find header {header_name} in cache")
}
CacheError::ParseError(to_str_error) => {
format!("Could not parse cache with error {to_str_error}")
}
CacheError::Remote(remote_access_error) => {
format!("Cache got remote access error: {remote_access_error}")
}
CacheError::ConstructionError(error) => {
format!("Could not construct cache body with error {error}")
}
};
write!(f, "{s}")
}
}
}

View File

@ -1,5 +1,5 @@
use database::{interface::DatabaseImpls, DB};
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
use database::{DB, interface::DatabaseImpls};
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
use log::{debug, warn};
use tauri::UriSchemeResponder;
@ -15,13 +15,19 @@ pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: Ur
Ok(r) => responder.respond(r),
Err(e) => {
warn!("Cache error: {e}");
responder.respond(Response::builder().status(500).body(Vec::new()).expect("Failed to build error response"));
responder.respond(
Response::builder()
.status(500)
.body(Vec::new())
.expect("Failed to build error response"),
);
}
};
}
pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Vec<u8>>, CacheError>
{
pub async fn fetch_object(
request: http::Request<Vec<u8>>,
) -> Result<Response<Vec<u8>>, CacheError> {
// Drop leading /
let object_id = &request.uri().path()[1..];
@ -48,13 +54,13 @@ pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Ve
let data = match r.bytes().await {
Ok(data) => Vec::from(data),
Err(e) => {
warn!(
"Could not get data from cache object {object_id} with error {e}",
);
warn!("Could not get data from cache object {object_id} with error {e}",);
Vec::new()
}
};
let resp = resp_builder.body(data).expect("Failed to build object cache response body");
let resp = resp_builder
.body(data)
.expect("Failed to build object cache response body");
if cache_result.map_or(true, |x| x.has_expired()) {
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
.expect("Failed to create cached object");

View File

@ -1,10 +1,10 @@
pub mod auth;
#[macro_use]
pub mod cache;
pub mod error;
pub mod fetch_object;
pub mod requests;
pub mod server_proto;
pub mod utils;
pub mod error;
pub use auth::setup;
pub use auth::setup;

View File

@ -1,4 +1,4 @@
use database::{interface::DatabaseImpls, DB};
use database::{DB, interface::DatabaseImpls};
use url::Url;
use crate::{

View File

@ -1,26 +1,30 @@
use std::str::FromStr;
use database::borrow_db_checked;
use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
use http::{Request, Response, StatusCode, Uri, uri::PathAndQuery};
use log::{error, warn};
use tauri::UriSchemeResponder;
use utils::webbrowser_open::webbrowser_open;
use crate::utils::DROP_CLIENT_SYNC;
pub async fn handle_server_proto_offline_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
pub async fn handle_server_proto_offline_wrapper(
request: Request<Vec<u8>>,
responder: UriSchemeResponder,
) {
responder.respond(match handle_server_proto_offline(request).await {
Ok(res) => res,
Err(_) => unreachable!()
Err(_) => unreachable!(),
});
}
pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode>{
pub async fn handle_server_proto_offline(
_request: Request<Vec<u8>>,
) -> Result<Response<Vec<u8>>, StatusCode> {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Vec::new())
.expect("Failed to build error response for proto offline"))
}
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
@ -28,7 +32,12 @@ pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: U
Ok(r) => responder.respond(r),
Err(e) => {
warn!("Cache error: {e}");
responder.respond(Response::builder().status(e).body(Vec::new()).expect("Failed to build error response"));
responder.respond(
Response::builder()
.status(e)
.body(Vec::new())
.expect("Failed to build error response"),
);
}
}
}
@ -39,20 +48,25 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
Some(auth) => auth,
None => {
error!("Could not find auth in database");
return Err(StatusCode::UNAUTHORIZED)
return Err(StatusCode::UNAUTHORIZED);
}
};
let web_token = match &auth.web_token {
Some(token) => token,
None => return Err(StatusCode::UNAUTHORIZED),
};
let remote_uri = db_handle.base_url.parse::<Uri>().expect("Failed to parse base url");
let remote_uri = db_handle
.base_url
.parse::<Uri>()
.expect("Failed to parse base url");
let path = request.uri().path();
let mut new_uri = request.uri().clone().into_parts();
new_uri.path_and_query =
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
new_uri.path_and_query = Some(
PathAndQuery::from_str(&format!("{path}?noWrapper=true"))
.expect("Failed to parse request path in proto"),
);
new_uri.authority = remote_uri.authority().cloned();
new_uri.scheme = remote_uri.scheme().cloned();
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
@ -62,7 +76,7 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
webbrowser_open(new_uri.to_string());
return Ok(Response::new(Vec::new()))
return Ok(Response::new(Vec::new()));
}
let client = DROP_CLIENT_SYNC.clone();
@ -70,13 +84,14 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
.request(request.method().clone(), new_uri.to_string())
.header("Authorization", format!("Bearer {web_token}"))
.headers(request.headers().clone())
.send() {
Ok(response) => response,
Err(e) => {
warn!("Could not send response. Got {e} when sending");
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST))
},
};
.send()
{
Ok(response) => response,
Err(e) => {
warn!("Could not send response. Got {e} when sending");
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST));
}
};
let response_status = response.status();
let response_body = match response.bytes() {

View File

@ -15,7 +15,7 @@ pub struct DropHealthcheck {
app_name: String,
}
impl DropHealthcheck {
pub fn app_name(&self) -> &String{
pub fn app_name(&self) -> &String {
&self.app_name
}
}
@ -46,11 +46,13 @@ fn fetch_certificates() -> Vec<Certificate> {
}
}
.read_to_end(&mut buf)
.unwrap_or_else(|e| panic!(
"Failed to read to end of certificate file {} with error {}",
c.path().display(),
e
));
.unwrap_or_else(|e| {
panic!(
"Failed to read to end of certificate file {} with error {}",
c.path().display(),
e
)
});
match Certificate::from_pem_bundle(&buf) {
Ok(certificates) => {
@ -87,7 +89,10 @@ pub fn get_client_sync() -> reqwest::blocking::Client {
for cert in DROP_CERT_BUNDLE.iter() {
client = client.add_root_certificate(cert.clone());
}
client.use_rustls_tls().build().expect("Failed to build synchronous client")
client
.use_rustls_tls()
.build()
.expect("Failed to build synchronous client")
}
pub fn get_client_async() -> reqwest::Client {
let mut client = reqwest::ClientBuilder::new();
@ -95,7 +100,10 @@ pub fn get_client_async() -> reqwest::Client {
for cert in DROP_CERT_BUNDLE.iter() {
client = client.add_root_certificate(cert.clone());
}
client.use_rustls_tls().build().expect("Failed to build asynchronous client")
client
.use_rustls_tls()
.build()
.expect("Failed to build asynchronous client")
}
pub fn get_client_ws() -> reqwest::Client {
let mut client = reqwest::ClientBuilder::new();
@ -108,4 +116,4 @@ pub fn get_client_ws() -> reqwest::Client {
.http1_only()
.build()
.expect("Failed to build websocket client")
}
}

View File

@ -86,6 +86,7 @@ process = { path = "../process" }
remote = { version = "0.1.0", path = "../remote" }
utils = { path = "../utils" }
games = { version = "0.1.0", path = "../games" }
download_manager = { version = "0.1.0", path = "../download_manager" }
[dependencies.dynfmt]
version = "0.1.5"

View File

@ -1,30 +1,29 @@
use std::sync::nonpoison::Mutex;
use database::{borrow_db_checked, borrow_db_mut_checked};
use download_manager::DOWNLOAD_MANAGER;
use log::{debug, error};
use tauri::AppHandle;
use tauri_plugin_autostart::ManagerExt;
use utils::lock;
use crate::{AppState};
use crate::AppState;
#[tauri::command]
pub fn fetch_state(
state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>,
) -> Result<String, String> {
let guard = lock!(state);
pub fn fetch_state(state: tauri::State<'_, Mutex<AppState>>) -> Result<String, String> {
let guard = state.lock();
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
drop(guard);
Ok(cloned_state)
}
#[tauri::command]
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
cleanup_and_exit(&app, &state);
pub fn quit(app: tauri::AppHandle) {
cleanup_and_exit(&app);
}
pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
pub fn cleanup_and_exit(app: &AppHandle) {
debug!("cleaning up and exiting application");
let download_manager = lock!(state).download_manager.clone();
match download_manager.ensure_terminated() {
match DOWNLOAD_MANAGER.ensure_terminated() {
Ok(res) => match res {
Ok(()) => debug!("download manager terminated correctly"),
Err(()) => error!("download manager failed to terminate correctly"),

View File

@ -1,16 +1,12 @@
use serde_json::json;
use crate::{
error::remote_access_error::RemoteAccessError,
remote::{
auth::generate_authorization_header,
cache::{cache_object, get_cached_object},
requests::{generate_url, make_authenticated_get},
utils::DROP_CLIENT_ASYNC,
},
use games::collections::collection::{Collection, Collections};
use remote::{
auth::generate_authorization_header,
cache::{cache_object, get_cached_object},
error::RemoteAccessError,
requests::{generate_url, make_authenticated_get},
utils::DROP_CLIENT_ASYNC,
};
use super::collection::{Collection, Collections};
use serde_json::json;
#[tauri::command]
pub async fn fetch_collections(

View File

@ -1,27 +1,22 @@
use std::sync::Mutex;
use database::DownloadableMetadata;
use download_manager::DOWNLOAD_MANAGER;
#[tauri::command]
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
lock!(state).download_manager.pause_downloads();
pub fn pause_downloads() {
DOWNLOAD_MANAGER.pause_downloads();
}
#[tauri::command]
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
lock!(state).download_manager.resume_downloads();
pub fn resume_downloads() {
DOWNLOAD_MANAGER.resume_downloads();
}
#[tauri::command]
pub fn move_download_in_queue(
state: tauri::State<'_, Mutex<AppState>>,
old_index: usize,
new_index: usize,
) {
lock!(state)
.download_manager
.rearrange(old_index, new_index);
pub fn move_download_in_queue(old_index: usize, new_index: usize) {
DOWNLOAD_MANAGER.rearrange(old_index, new_index);
}
#[tauri::command]
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
lock!(state).download_manager.cancel(meta);
pub fn cancel_game(meta: DownloadableMetadata) {
DOWNLOAD_MANAGER.cancel(meta);
}

View File

@ -1,34 +1,31 @@
use std::{
path::PathBuf,
sync::{Arc, Mutex},
use std::{path::PathBuf, sync::Arc};
use database::{GameDownloadStatus, borrow_db_checked};
use download_manager::{
DOWNLOAD_MANAGER, downloadable::Downloadable, error::ApplicationDownloadError,
};
use crate::{
database::{
db::borrow_db_checked,
models::data::GameDownloadStatus,
}, download_manager::downloadable::Downloadable, error::application_download_error::ApplicationDownloadError, lock, AppState
};
use super::download_agent::GameDownloadAgent;
use games::downloads::download_agent::GameDownloadAgent;
#[tauri::command]
pub async fn download_game(
game_id: String,
game_version: String,
install_dir: usize,
state: tauri::State<'_, Mutex<AppState<'_>>>,
) -> Result<(), ApplicationDownloadError> {
let sender = { lock!(state).download_manager.get_sender().clone() };
let sender = { DOWNLOAD_MANAGER.get_sender().clone() };
let game_download_agent =
GameDownloadAgent::new_from_index(game_id.clone(), game_version.clone(), install_dir, sender).await?;
let game_download_agent = GameDownloadAgent::new_from_index(
game_id.clone(),
game_version.clone(),
install_dir,
sender,
)
.await?;
let game_download_agent =
Arc::new(Box::new(game_download_agent) as Box<dyn Downloadable + Send + Sync>);
lock!(state)
.download_manager
DOWNLOAD_MANAGER
.queue_download(game_download_agent.clone())
.unwrap();
@ -36,10 +33,7 @@ pub async fn download_game(
}
#[tauri::command]
pub async fn resume_download(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
) -> Result<(), ApplicationDownloadError> {
pub async fn resume_download(game_id: String) -> Result<(), ApplicationDownloadError> {
let s = borrow_db_checked()
.applications
.game_statuses
@ -57,21 +51,25 @@ pub async fn resume_download(
} => (version_name, install_dir),
};
let sender = lock!(state).download_manager.get_sender();
let sender = DOWNLOAD_MANAGER.get_sender();
let parent_dir: PathBuf = install_dir.into();
let game_download_agent = Arc::new(Box::new(
GameDownloadAgent::new(
game_id,
version_name.clone(),
parent_dir.parent().unwrap_or_else(|| panic!("Failed to get parent directry of {}", parent_dir.display())).to_path_buf(),
parent_dir
.parent()
.unwrap_or_else(|| {
panic!("Failed to get parent directry of {}", parent_dir.display())
})
.to_path_buf(),
sender,
)
.await?,
) as Box<dyn Downloadable + Send + Sync>);
lock!(state)
.download_manager
DOWNLOAD_MANAGER
.queue_download(game_download_agent)
.unwrap();
Ok(())

View File

@ -1,19 +1,28 @@
use std::sync::Mutex;
use std::sync::nonpoison::Mutex;
use database::{borrow_db_checked, borrow_db_mut_checked, GameDownloadStatus, GameVersion};
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, Game}, state::{GameStatusManager, GameStatusWithTransient}};
use database::{GameDownloadStatus, GameVersion, borrow_db_checked, borrow_db_mut_checked};
use games::{
downloads::error::LibraryError,
library::{FetchGameStruct, FrontendGameOptions, Game, get_current_meta, uninstall_game_logic},
state::{GameStatusManager, GameStatusWithTransient},
};
use log::warn;
use process::PROCESS_MANAGER;
use remote::{auth::generate_authorization_header, cache::{cache_object, cache_object_db, get_cached_object, get_cached_object_db}, error::{DropServerError, RemoteAccessError}, offline, requests::generate_url, utils::DROP_CLIENT_ASYNC};
use remote::{
auth::generate_authorization_header,
cache::{cache_object, cache_object_db, get_cached_object, get_cached_object_db},
error::{DropServerError, RemoteAccessError},
offline,
requests::generate_url,
utils::DROP_CLIENT_ASYNC,
};
use tauri::AppHandle;
use utils::lock;
use crate::AppState;
#[tauri::command]
pub async fn fetch_library(
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
hard_refresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
offline!(
@ -22,12 +31,12 @@ pub async fn fetch_library(
fetch_library_logic_offline,
state,
hard_refresh
).await
)
.await
}
pub async fn fetch_library_logic(
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
hard_fresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
let do_hard_refresh = hard_fresh.unwrap_or(false);
@ -54,7 +63,7 @@ pub async fn fetch_library_logic(
let mut games: Vec<Game> = response.json().await?;
let mut handle = lock!(state);
let mut handle = state.lock();
let mut db_handle = borrow_db_mut_checked();
@ -95,7 +104,7 @@ pub async fn fetch_library_logic(
Ok(games)
}
pub async fn fetch_library_logic_offline(
_state: tauri::State<'_, Mutex<AppState<'_>>>,
_state: tauri::State<'_, Mutex<AppState>>,
_hard_refresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
let mut games: Vec<Game> = get_cached_object("library")?;
@ -117,10 +126,10 @@ pub async fn fetch_library_logic_offline(
}
pub async fn fetch_game_logic(
id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
let version = {
let state_handle = lock!(state);
let state_handle = state.lock();
let db_lock = borrow_db_checked();
@ -173,7 +182,7 @@ pub async fn fetch_game_logic(
let game: Game = response.json().await?;
let mut state_handle = lock!(state);
let mut state_handle = state.lock();
state_handle.games.insert(id.clone(), game.clone());
let mut db_handle = borrow_db_mut_checked();
@ -197,7 +206,7 @@ pub async fn fetch_game_logic(
pub async fn fetch_game_version_options_logic(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<Vec<GameVersion>, RemoteAccessError> {
let client = DROP_CLIENT_ASYNC.clone();
@ -216,7 +225,7 @@ pub async fn fetch_game_version_options_logic(
let data: Vec<GameVersion> = response.json().await?;
let state_lock = lock!(state);
let state_lock = state.lock();
let process_manager_lock = PROCESS_MANAGER.lock();
let data: Vec<GameVersion> = data
.into_iter()
@ -228,10 +237,9 @@ pub async fn fetch_game_version_options_logic(
Ok(data)
}
pub async fn fetch_game_logic_offline(
id: String,
_state: tauri::State<'_, Mutex<AppState<'_>>>,
_state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
let db_handle = borrow_db_checked();
let metadata_option = db_handle.applications.installed_game_version.get(&id);
@ -256,7 +264,7 @@ pub async fn fetch_game_logic_offline(
#[tauri::command]
pub async fn fetch_game(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
offline!(
state,
@ -264,7 +272,8 @@ pub async fn fetch_game(
fetch_game_logic_offline,
game_id,
state
).await
)
.await
}
#[tauri::command]
@ -287,7 +296,49 @@ pub fn uninstall_game(game_id: String, app_handle: AppHandle) -> Result<(), Libr
#[tauri::command]
pub async fn fetch_game_version_options(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<Vec<GameVersion>, RemoteAccessError> {
fetch_game_version_options_logic(game_id, state).await
}
#[tauri::command]
pub fn update_game_configuration(
game_id: String,
options: FrontendGameOptions,
) -> Result<(), LibraryError> {
let mut handle = borrow_db_mut_checked();
let installed_version = handle
.applications
.installed_game_version
.get(&game_id)
.ok_or(LibraryError::MetaNotFound(game_id))?;
let id = installed_version.id.clone();
let version = installed_version
.version
.clone()
.ok_or(LibraryError::VersionNotFound(id.clone()))?;
let mut existing_configuration = handle
.applications
.game_versions
.get(&id)
.unwrap()
.get(&version)
.unwrap()
.clone();
// Add more options in here
existing_configuration.launch_command_template = options.launch_string().clone();
// Add no more options past here
handle
.applications
.game_versions
.get_mut(&id)
.unwrap()
.insert(version.to_string(), existing_configuration);
Ok(())
}

View File

@ -4,33 +4,78 @@
#![feature(duration_millis_float)]
#![feature(iterator_try_collect)]
#![feature(nonpoison_mutex)]
#![feature(sync_nonpoison)]
#![deny(clippy::all)]
use std::collections::HashMap;
use std::{
collections::HashMap, env, fs::File, io::Write, panic::PanicHookInfo, path::Path, str::FromStr,
sync::nonpoison::Mutex, time::SystemTime,
};
use ::client::{app_status::AppStatus, compat::CompatInfo, user::User};
use database::{borrow_db_checked, GameDownloadStatus};
use ::games::library::Game;
use ::remote::auth;
use ::client::{app_status::AppStatus, autostart::sync_autostart_on_startup, user::User};
use ::download_manager::DownloadManagerWrapper;
use ::games::{library::Game, scan::scan_install_dirs};
use ::process::ProcessManagerWrapper;
use ::remote::{
auth::{self, HandshakeRequestBody, HandshakeResponse, generate_authorization_header},
cache::clear_cached_object,
error::RemoteAccessError,
fetch_object::fetch_object_wrapper,
offline,
server_proto::{handle_server_proto_offline_wrapper, handle_server_proto_wrapper},
utils::DROP_CLIENT_ASYNC,
};
use database::{
DB, GameDownloadStatus, borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR,
interface::DatabaseImpls,
};
use log::{LevelFilter, debug, info, warn};
use log4rs::{
Config,
append::{console::ConsoleAppender, file::FileAppender},
config::{Appender, Root},
encode::pattern::PatternEncoder,
};
use serde::Serialize;
use tauri::AppHandle;
use tauri::{
AppHandle, Manager, RunEvent, WindowEvent,
menu::{Menu, MenuItem, PredefinedMenuItem},
tray::TrayIconBuilder,
};
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_dialog::DialogExt;
use url::Url;
use utils::app_emit;
mod games;
use crate::client::cleanup_and_exit;
mod client;
mod collections;
mod download_manager;
mod downloads;
mod games;
mod process;
mod remote;
mod settings;
use client::*;
use collections::*;
use download_manager::*;
use downloads::*;
use games::*;
use process::*;
use remote::*;
use settings::*;
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppState<'a> {
pub struct AppState {
status: AppStatus,
user: Option<User>,
games: HashMap<String, Game>,
}
async fn setup(handle: AppHandle) -> AppState<'static> {
async fn setup(handle: AppHandle) -> AppState {
let logfile = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{d} | {l} | {f}:{L} - {m}{n}",
@ -62,9 +107,9 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
log4rs::init_config(config).expect("Failed to initialise log4rs");
let games = HashMap::new();
let download_manager = Arc::new(DownloadManagerBuilder::build(handle.clone()));
let process_manager = Arc::new(Mutex::new(ProcessManager::new(handle.clone())));
let compat_info = create_new_compat_info();
ProcessManagerWrapper::init(handle.clone());
DownloadManagerWrapper::init(handle.clone());
debug!("checking if database is set up");
let is_set_up = DB.database_is_set_up();
@ -76,9 +121,6 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
status: AppStatus::NotConfigured,
user: None,
games,
download_manager,
process_manager,
compat_info,
};
}
@ -141,9 +183,6 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
status: app_status,
user,
games,
download_manager,
process_manager,
compat_info,
}
}
@ -165,7 +204,7 @@ pub fn custom_panic_handler(e: &PanicHookInfo) -> Option<()> {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
panic::set_hook(Box::new(|e| {
std::panic::set_hook(Box::new(|e| {
let _ = custom_panic_handler(e);
println!("{e}");
}));
@ -328,7 +367,7 @@ pub fn run() {
.expect("Failed to show window");
}
"quit" => {
cleanup_and_exit(app, &app.state());
cleanup_and_exit(app);
}
_ => {
@ -418,20 +457,20 @@ fn run_on_tray<T: FnOnce()>(f: T) {
// TODO: Refactor
pub async fn recieve_handshake(app: AppHandle, path: String) {
// Tell the app we're processing
app_emit!(app, "auth/processing", ());
app_emit!(&app, "auth/processing", ());
let handshake_result = recieve_handshake_logic(&app, path).await;
if let Err(e) = handshake_result {
warn!("error with authentication: {e}");
app_emit!(app, "auth/failed", e.to_string());
app_emit!(&app, "auth/failed", e.to_string());
return;
}
let app_state = app.state::<Mutex<AppState>>();
let (app_status, user) = remote::setup().await;
let (app_status, user) = auth::setup().await;
let mut state_lock = lock!(app_state);
let mut state_lock = app_state.lock();
state_lock.status = app_status;
state_lock.user = user;
@ -441,7 +480,7 @@ pub async fn recieve_handshake(app: AppHandle, path: String) {
drop(state_lock);
app_emit!(app, "auth/finished", ());
app_emit!(&app, "auth/finished", ());
}
// TODO: Refactor
@ -465,10 +504,7 @@ async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), Re
let token = path_chunks
.get(2)
.expect("Failed to get token from path chunks");
let body = HandshakeRequestBody {
client_id: (client_id).to_string(),
token: (token).to_string(),
};
let body = HandshakeRequestBody::new((client_id).to_string(), (token).to_string());
let endpoint = base_url.join("/api/v1/client/auth/handshake")?;
let client = DROP_CLIENT_ASYNC.clone();
@ -481,12 +517,7 @@ async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), Re
{
let mut handle = borrow_db_mut_checked();
handle.auth = Some(DatabaseAuth {
private: response_struct.private,
cert: response_struct.certificate,
client_id: response_struct.id,
web_token: None,
});
handle.auth = Some(response_struct.into());
}
let web_token = {
@ -504,4 +535,3 @@ async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), Re
Ok(())
}

View File

@ -1,9 +1,8 @@
use std::sync::Mutex;
use std::sync::nonpoison::Mutex;
use process::{error::ProcessError, PROCESS_MANAGER};
use process::{PROCESS_MANAGER, error::ProcessError};
use tauri::AppHandle;
use tauri_plugin_opener::OpenerExt;
use utils::lock;
use crate::AppState;
@ -12,15 +11,15 @@ pub fn launch_game(
id: String,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), ProcessError> {
let state_lock = lock!(state);
let process_manager_lock = PROCESS_MANAGER.lock();
let state_lock = state.lock();
let mut process_manager_lock = PROCESS_MANAGER.lock();
//let meta = DownloadableMetadata {
// id,
// version: Some(version),
// download_type: DownloadType::Game,
//};
match process_manager_lock.launch_process(id, &state_lock) {
match process_manager_lock.launch_process(id) {
Ok(()) => {}
Err(e) => return Err(e),
}
@ -32,9 +31,7 @@ pub fn launch_game(
}
#[tauri::command]
pub fn kill_game(
game_id: String,
) -> Result<(), ProcessError> {
pub fn kill_game(game_id: String) -> Result<(), ProcessError> {
PROCESS_MANAGER
.lock()
.kill_game(game_id)
@ -42,10 +39,7 @@ pub fn kill_game(
}
#[tauri::command]
pub fn open_process_logs(
game_id: String,
app_handle: AppHandle
) -> Result<(), ProcessError> {
pub fn open_process_logs(game_id: String, app_handle: AppHandle) -> Result<(), ProcessError> {
let process_manager_lock = PROCESS_MANAGER.lock();
let dir = process_manager_lock.get_log_dir(game_id);

View File

@ -1,22 +1,29 @@
use std::{sync::Mutex, time::Duration};
use std::{sync::nonpoison::Mutex, time::Duration};
use client::app_status::AppStatus;
use database::{borrow_db_checked, borrow_db_mut_checked};
use futures_lite::StreamExt;
use log::{debug, warn};
use remote::{auth::{auth_initiate_logic, generate_authorization_header}, cache::{cache_object, get_cached_object}, error::RemoteAccessError, requests::generate_url, setup, utils::{DropHealthcheck, DROP_CLIENT_ASYNC, DROP_CLIENT_WS_CLIENT}};
use remote::{
auth::{auth_initiate_logic, generate_authorization_header},
cache::{cache_object, get_cached_object},
error::RemoteAccessError,
requests::generate_url,
setup,
utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_WS_CLIENT, DropHealthcheck},
};
use reqwest_websocket::{Message, RequestBuilderExt};
use serde::Deserialize;
use tauri::{AppHandle, Emitter, Manager};
use tauri::{AppHandle, Manager};
use url::Url;
use utils::{app_emit, lock, webbrowser_open::webbrowser_open};
use utils::{app_emit, webbrowser_open::webbrowser_open};
use crate::{recieve_handshake, AppState};
use crate::{AppState, recieve_handshake};
#[tauri::command]
pub async fn use_remote(
url: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), RemoteAccessError> {
debug!("connecting to url {url}");
let base_url = Url::parse(&url)?;
@ -37,7 +44,7 @@ pub async fn use_remote(
return Err(RemoteAccessError::InvalidEndpoint);
}
let mut app_state = lock!(state);
let mut app_state = state.lock();
app_state.status = AppStatus::SignedOut;
drop(app_state);
@ -91,21 +98,21 @@ pub fn sign_out(app: AppHandle) {
// Update app state
{
let app_state = app.state::<Mutex<AppState>>();
let mut app_state_handle = lock!(app_state);
let state = app.state::<Mutex<AppState>>();
let mut app_state_handle = state.lock();
app_state_handle.status = AppStatus::SignedOut;
app_state_handle.user = None;
}
// Emit event for frontend
app_emit!(app, "auth/signedout", ());
app_emit!(&app, "auth/signedout", ());
}
#[tauri::command]
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState<'_>>>) -> Result<(), ()> {
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState>>) -> Result<(), ()> {
let (app_status, user) = setup().await;
let mut guard = lock!(state);
let mut guard = state.lock();
guard.status = app_status;
guard.user = user;
drop(guard);
@ -181,7 +188,7 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
let result = load().await;
if let Err(err) = result {
warn!("{err}");
app_emit!(app, "auth/failed", err.to_string());
app_emit!(&app, "auth/failed", err.to_string());
}
});

View File

@ -4,20 +4,14 @@ use std::{
path::{Path, PathBuf},
};
use database::{
Settings, borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, debug::SystemData,
};
use download_manager::error::DownloadManagerError;
use games::scan::scan_install_dirs;
use log::error;
use serde_json::Value;
use crate::{
database::{db::borrow_db_mut_checked, scan::scan_install_dirs},
error::download_manager_error::DownloadManagerError,
};
use super::{
db::{DATA_ROOT_DIR, borrow_db_checked},
debug::SystemData,
models::data::Settings,
};
// Will, in future, return disk/remaining size
// Just returns the directories that have been set up
#[tauri::command]

View File

@ -7,7 +7,7 @@
"beforeDevCommand": "yarn --cwd main dev --port 1432",
"devUrl": "http://localhost:1432/",
"beforeBuildCommand": "yarn build",
"frontendDist": "../../.output"
"frontendDist": "../.output"
},
"app": {
"security": {

View File

@ -1,6 +1,7 @@
#[macro_export]
macro_rules! app_emit {
($app:expr, $event:expr, $p:expr) => {
$app.emit($event, $p).expect(&format!("Failed to emit event {}", $event));
::tauri::Emitter::emit($app, $event, $p)
.expect(&format!("Failed to emit event {}", $event));
};
}

View File

@ -1,6 +1,11 @@
#[macro_export]
macro_rules! send {
($download_manager:expr, $signal:expr) => {
$download_manager.send($signal).unwrap_or_else(|_| panic!("Failed to send signal {} to the download manager", stringify!(signal)))
$download_manager.send($signal).unwrap_or_else(|_| {
panic!(
"Failed to send signal {} to the download manager",
stringify!(signal)
)
})
};
}
}

View File

@ -1,6 +1,8 @@
#[macro_export]
macro_rules! lock {
($mutex:expr) => {
$mutex.lock().unwrap_or_else(|_| panic!("Failed to lock onto {}", stringify!($mutex)))
$mutex
.lock()
.unwrap_or_else(|_| panic!("Failed to lock onto {}", stringify!($mutex)))
};
}
}

View File

@ -2,6 +2,10 @@ use log::warn;
pub fn webbrowser_open<T: AsRef<str>>(url: T) {
if let Err(e) = webbrowser::open(url.as_ref()) {
warn!("Could not open web browser to url {} with error {}", url.as_ref(), e);
warn!(
"Could not open web browser to url {} with error {}",
url.as_ref(),
e
);
};
}
}