mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-13 00:02:41 +10:00
Compare commits
3 Commits
5d22b883d5
...
0f48f3fb44
| Author | SHA1 | Date | |
|---|---|---|---|
| 0f48f3fb44 | |||
| 974666efe2 | |||
| 9e1bf9852f |
6
Cargo.lock
generated
6
Cargo.lock
generated
@ -381,9 +381,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "atomic-instant-full"
|
name = "atomic-instant-full"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "db6541700e074cda41b1c6f98c2cae6cde819967bf142078f069cad85387cdbe"
|
checksum = "83148e838612d8d701ce16b9f64b8674c097e1b4a14037b294baec03d9072228"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "atomic-waker"
|
name = "atomic-waker"
|
||||||
@ -1375,6 +1375,7 @@ dependencies = [
|
|||||||
"database",
|
"database",
|
||||||
"deranged 0.4.0",
|
"deranged 0.4.0",
|
||||||
"dirs 6.0.0",
|
"dirs 6.0.0",
|
||||||
|
"download_manager",
|
||||||
"droplet-rs",
|
"droplet-rs",
|
||||||
"dynfmt",
|
"dynfmt",
|
||||||
"filetime",
|
"filetime",
|
||||||
@ -4287,6 +4288,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_with",
|
"serde_with",
|
||||||
"shared_child",
|
"shared_child",
|
||||||
|
"tauri",
|
||||||
"tauri-plugin-opener",
|
"tauri-plugin-opener",
|
||||||
"utils",
|
"utils",
|
||||||
]
|
]
|
||||||
|
|||||||
@ -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;
|
use log::info;
|
||||||
|
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
pub mod autostart;
|
|
||||||
pub mod user;
|
|
||||||
pub mod app_status;
|
pub mod app_status;
|
||||||
|
pub mod autostart;
|
||||||
pub mod compat;
|
pub mod compat;
|
||||||
|
pub mod user;
|
||||||
|
|||||||
@ -10,4 +10,3 @@ pub struct User {
|
|||||||
display_name: String,
|
display_name: String,
|
||||||
profile_picture_object_id: String,
|
profile_picture_object_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,7 +2,7 @@ use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
|||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use database::platform::Platform;
|
use database::platform::Platform;
|
||||||
use database::{db::DATA_ROOT_DIR, GameVersion};
|
use database::{GameVersion, db::DATA_ROOT_DIR};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
|
||||||
use crate::error::BackupError;
|
use crate::error::BackupError;
|
||||||
@ -14,6 +14,12 @@ pub struct BackupManager<'a> {
|
|||||||
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Default for BackupManager<'_> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl BackupManager<'_> {
|
impl BackupManager<'_> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
BackupManager {
|
BackupManager {
|
||||||
@ -40,65 +46,188 @@ impl BackupManager<'_> {
|
|||||||
(Platform::MacOs, Platform::MacOs),
|
(Platform::MacOs, Platform::MacOs),
|
||||||
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
),
|
),
|
||||||
|
|
||||||
]),
|
]),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait BackupHandler: Send + Sync {
|
pub trait BackupHandler: Send + Sync {
|
||||||
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.join("games")) }
|
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) }
|
Ok(DATA_ROOT_DIR.join("games"))
|
||||||
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 game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
fn store_user_id_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError) }
|
Ok(PathBuf::from_str(&game.game_id).unwrap())
|
||||||
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 base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) }
|
Ok(self
|
||||||
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) }
|
.root_translate(path, game)?
|
||||||
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDocuments>"); Err(BackupError::InvalidSystem) }
|
.join(self.game_translate(path, game)?))
|
||||||
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 home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) }
|
let c = CommonPath::Home.get().ok_or(BackupError::NotFound);
|
||||||
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) }
|
println!("{:?}", c);
|
||||||
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgConfig>"); Err(BackupError::InvalidSystem) }
|
c
|
||||||
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::new()) }
|
}
|
||||||
|
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 {}
|
pub struct LinuxBackupManager {}
|
||||||
impl BackupHandler for LinuxBackupManager {
|
impl BackupHandler for LinuxBackupManager {
|
||||||
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
fn xdg_config_translate(
|
||||||
Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?)
|
&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> {
|
fn xdg_data_translate(
|
||||||
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
&self,
|
||||||
|
_path: &PathBuf,
|
||||||
|
_game: &GameVersion,
|
||||||
|
) -> Result<PathBuf, BackupError> {
|
||||||
|
CommonPath::Config.get().ok_or(BackupError::NotFound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub struct WindowsBackupManager {}
|
pub struct WindowsBackupManager {}
|
||||||
impl BackupHandler for WindowsBackupManager {
|
impl BackupHandler for WindowsBackupManager {
|
||||||
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
fn win_app_data_translate(
|
||||||
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
&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> {
|
fn win_local_app_data_translate(
|
||||||
Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?)
|
&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> {
|
fn win_local_app_data_low_translate(
|
||||||
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
|
&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())
|
Ok(PathBuf::from_str("C:/Windows").unwrap())
|
||||||
}
|
}
|
||||||
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
fn win_documents_translate(
|
||||||
Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?)
|
&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())
|
Ok(PathBuf::from_str("C:/ProgramData").unwrap())
|
||||||
}
|
}
|
||||||
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
fn win_public_translate(
|
||||||
Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?)
|
&self,
|
||||||
|
_path: &PathBuf,
|
||||||
|
_game: &GameVersion,
|
||||||
|
) -> Result<PathBuf, BackupError> {
|
||||||
|
CommonPath::Public.get().ok_or(BackupError::NotFound)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub struct MacBackupManager {}
|
pub struct MacBackupManager {}
|
||||||
|
|||||||
@ -2,5 +2,6 @@ use database::platform::Platform;
|
|||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum Condition {
|
pub enum Condition {
|
||||||
Os(Platform)
|
Os(Platform),
|
||||||
|
Other
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
|
pub mod backup_manager;
|
||||||
pub mod conditions;
|
pub mod conditions;
|
||||||
|
pub mod error;
|
||||||
pub mod metadata;
|
pub mod metadata;
|
||||||
pub mod resolver;
|
|
||||||
pub mod placeholder;
|
|
||||||
pub mod normalise;
|
pub mod normalise;
|
||||||
pub mod path;
|
pub mod path;
|
||||||
pub mod backup_manager;
|
pub mod placeholder;
|
||||||
pub mod error;
|
pub mod resolver;
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
use database::GameVersion;
|
use database::GameVersion;
|
||||||
|
|
||||||
use super::conditions::{Condition};
|
use super::conditions::Condition;
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct CloudSaveMetadata {
|
pub struct CloudSaveMetadata {
|
||||||
@ -16,15 +15,17 @@ pub struct GameFile {
|
|||||||
pub id: Option<String>,
|
pub id: Option<String>,
|
||||||
pub data_type: DataType,
|
pub data_type: DataType,
|
||||||
pub tags: Vec<Tag>,
|
pub tags: Vec<Tag>,
|
||||||
pub conditions: Vec<Condition>
|
pub conditions: Vec<Condition>,
|
||||||
}
|
}
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum DataType {
|
pub enum DataType {
|
||||||
Registry,
|
Registry,
|
||||||
File,
|
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")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub enum Tag {
|
pub enum Tag {
|
||||||
Config,
|
Config,
|
||||||
|
|||||||
@ -5,7 +5,6 @@ use regex::Regex;
|
|||||||
|
|
||||||
use super::placeholder::*;
|
use super::placeholder::*;
|
||||||
|
|
||||||
|
|
||||||
pub fn normalize(path: &str, os: Platform) -> String {
|
pub fn normalize(path: &str, os: Platform) -> String {
|
||||||
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
|
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 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_1: LazyLock<Regex> =
|
||||||
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
|
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_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
|
||||||
static ENDING_DOT: 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 INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
|
||||||
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").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: 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_ROAMING: LazyLock<Regex> =
|
||||||
static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
||||||
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
static APP_DATA_LOCAL: LazyLock<Regex> =
|
||||||
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
||||||
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").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 [
|
for (pattern, replacement) in [
|
||||||
(&CONSECUTIVE_SLASHES, "/"),
|
(&CONSECUTIVE_SLASHES, "/"),
|
||||||
@ -66,7 +72,9 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
|||||||
|
|
||||||
fn too_broad(path: &str) -> bool {
|
fn too_broad(path: &str) -> bool {
|
||||||
println!("Path: {}", path);
|
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();
|
let path_lower = path.to_lowercase();
|
||||||
|
|
||||||
@ -77,7 +85,9 @@ fn too_broad(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for item in AVOID_WILDCARDS {
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -125,7 +135,6 @@ fn too_broad(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Drive letters:
|
// Drive letters:
|
||||||
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
||||||
if drives.is_match(path) {
|
if drives.is_match(path) {
|
||||||
|
|||||||
@ -13,12 +13,12 @@ pub enum CommonPath {
|
|||||||
|
|
||||||
impl CommonPath {
|
impl CommonPath {
|
||||||
pub fn get(&self) -> Option<PathBuf> {
|
pub fn get(&self) -> Option<PathBuf> {
|
||||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
|
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir);
|
||||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
|
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir);
|
||||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
|
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir);
|
||||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
|
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir);
|
||||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
|
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir);
|
||||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
|
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir);
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
||||||
|
|||||||
@ -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 XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
|
||||||
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_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);
|
||||||
|
|||||||
@ -1,17 +1,13 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs::{self, create_dir_all, File},
|
fs::{self, File, create_dir_all},
|
||||||
io::{self, ErrorKind, Read, Write},
|
io::{self, Read, Write},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
thread::sleep,
|
|
||||||
time::Duration,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::error::BackupError;
|
use crate::error::BackupError;
|
||||||
|
|
||||||
use super::{
|
use super::{backup_manager::BackupHandler, placeholder::*};
|
||||||
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
use database::GameVersion;
|
||||||
};
|
|
||||||
use database::{platform::Platform, GameVersion};
|
|
||||||
use log::{debug, warn};
|
use log::{debug, warn};
|
||||||
use rustix::path::Arg;
|
use rustix::path::Arg;
|
||||||
use tempfile::tempfile;
|
use tempfile::tempfile;
|
||||||
@ -30,7 +26,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
|||||||
.iter()
|
.iter()
|
||||||
.find_map(|p| match p {
|
.find_map(|p| match p {
|
||||||
super::conditions::Condition::Os(os) => Some(os),
|
super::conditions::Condition::Os(os) => Some(os),
|
||||||
_ => None,
|
_ => None
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
{
|
{
|
||||||
@ -63,7 +59,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
|||||||
let binding = serde_json::to_string(meta).unwrap();
|
let binding = serde_json::to_string(meta).unwrap();
|
||||||
let serialized = binding.as_bytes();
|
let serialized = binding.as_bytes();
|
||||||
let mut file = tempfile().unwrap();
|
let mut file = tempfile().unwrap();
|
||||||
file.write(serialized).unwrap();
|
file.write_all(serialized).unwrap();
|
||||||
tarball.append_file("metadata", &mut file).unwrap();
|
tarball.append_file("metadata", &mut file).unwrap();
|
||||||
tarball.into_inner().unwrap().finish().unwrap()
|
tarball.into_inner().unwrap().finish().unwrap()
|
||||||
}
|
}
|
||||||
@ -96,7 +92,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
|||||||
.iter()
|
.iter()
|
||||||
.find_map(|p| match p {
|
.find_map(|p| match p {
|
||||||
super::conditions::Condition::Os(os) => Some(os),
|
super::conditions::Condition::Os(os) => Some(os),
|
||||||
_ => None,
|
_ => None
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
{
|
{
|
||||||
@ -115,7 +111,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
|
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!(
|
println!(
|
||||||
"Current path {:?} copying to {:?}",
|
"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 src_path = src.as_ref();
|
||||||
let dest_path = dest.as_ref();
|
let dest_path = dest.as_ref();
|
||||||
|
|
||||||
let metadata = fs::metadata(&src_path)?;
|
let metadata = fs::metadata(src_path)?;
|
||||||
|
|
||||||
if metadata.is_file() {
|
if metadata.is_file() {
|
||||||
// Ensure the parent directory of the destination exists for a file copy
|
// Ensure the parent directory of the destination exists for a file copy
|
||||||
if let Some(parent) = dest_path.parent() {
|
if let Some(parent) = dest_path.parent() {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
fs::copy(&src_path, &dest_path)?;
|
fs::copy(src_path, dest_path)?;
|
||||||
} else if metadata.is_dir() {
|
} else if metadata.is_dir() {
|
||||||
// For directories, we call the recursive helper function.
|
// For directories, we call the recursive helper function.
|
||||||
// The destination for the recursive copy is the `dest_path` itself.
|
// 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 {
|
} else {
|
||||||
// Handle other file types like symlinks if necessary,
|
// Handle other file types like symlinks if necessary,
|
||||||
// for now, return an error or skip.
|
// for now, return an error or skip.
|
||||||
return Err(io::Error::new(
|
return Err(io::Error::other(
|
||||||
io::ErrorKind::Other,
|
|
||||||
format!("Source {:?} is neither a file nor a directory", src_path),
|
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<()> {
|
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)? {
|
for entry in fs::read_dir(src)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
@ -219,43 +214,3 @@ pub fn parse_path(
|
|||||||
println!("Final line: {:?}", &s);
|
println!("Final line: {:?}", &s);
|
||||||
Ok(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();
|
|
||||||
}
|
|
||||||
|
|||||||
@ -10,7 +10,6 @@ use crate::interface::{DatabaseImpls, DatabaseInterface};
|
|||||||
|
|
||||||
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
||||||
|
|
||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
#[cfg(not(debug_assertions))]
|
||||||
static DATA_ROOT_PREFIX: &str = "drop";
|
static DATA_ROOT_PREFIX: &str = "drop";
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
@ -32,16 +31,15 @@ impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
|||||||
for DropDatabaseSerializer
|
for DropDatabaseSerializer
|
||||||
{
|
{
|
||||||
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
||||||
native_model::encode(val)
|
native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string()))
|
||||||
.map_err(|e| DeSerError::Internal(e.to_string()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
s.read_to_end(&mut buf)
|
s.read_to_end(&mut buf)
|
||||||
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
||||||
let (val, _version) = native_model::decode(buf)
|
let (val, _version) =
|
||||||
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||||
Ok(val)
|
Ok(val)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -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 chrono::Utc;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use rustbreak::{PathDatabase, RustbreakError};
|
use rustbreak::{PathDatabase, RustbreakError};
|
||||||
use url::Url;
|
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 =
|
pub type DatabaseInterface =
|
||||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||||
|
|||||||
@ -2,20 +2,13 @@
|
|||||||
|
|
||||||
pub mod db;
|
pub mod db;
|
||||||
pub mod debug;
|
pub mod debug;
|
||||||
|
pub mod interface;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod platform;
|
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 db::DB;
|
||||||
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
|
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
|
pub use models::data::{
|
||||||
|
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
|
||||||
|
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
|
||||||
|
};
|
||||||
|
|||||||
@ -191,9 +191,7 @@ pub mod data {
|
|||||||
|
|
||||||
use serde_with::serde_as;
|
use serde_with::serde_as;
|
||||||
|
|
||||||
use super::{
|
use super::{Deserialize, Serialize, native_model, v1};
|
||||||
Deserialize, Serialize, native_model, v1,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
|
#[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
|
||||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||||
@ -282,7 +280,8 @@ pub mod data {
|
|||||||
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
|
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
|
||||||
|
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub transient_statuses: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
pub transient_statuses:
|
||||||
|
HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
||||||
}
|
}
|
||||||
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
||||||
fn from(value: v1::DatabaseApplications) -> Self {
|
fn from(value: v1::DatabaseApplications) -> Self {
|
||||||
@ -303,10 +302,7 @@ pub mod data {
|
|||||||
mod v3 {
|
mod v3 {
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use super::{
|
use super::{Deserialize, Serialize, native_model, v1, v2};
|
||||||
Deserialize, Serialize,
|
|
||||||
native_model, v2, v1,
|
|
||||||
};
|
|
||||||
#[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
|
#[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
|
||||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||||
pub struct Database {
|
pub struct Database {
|
||||||
@ -358,6 +354,20 @@ pub mod data {
|
|||||||
compat_info: None,
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
||||||
pub enum Platform {
|
pub enum Platform {
|
||||||
Windows,
|
Windows,
|
||||||
|
|||||||
@ -9,11 +9,14 @@ use std::{
|
|||||||
|
|
||||||
use database::DownloadableMetadata;
|
use database::DownloadableMetadata;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use tauri::{AppHandle, Emitter};
|
use tauri::AppHandle;
|
||||||
use utils::{app_emit, lock, send};
|
use utils::{app_emit, lock, send};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
|
download_manager_frontend::DownloadStatus,
|
||||||
|
error::ApplicationDownloadError,
|
||||||
|
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
|
||||||
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
||||||
@ -289,7 +292,10 @@ impl DownloadManagerBuilder {
|
|||||||
|
|
||||||
if validate_result {
|
if validate_result {
|
||||||
download_agent.on_complete(&app_handle);
|
download_agent.on_complete(&app_handle);
|
||||||
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
|
send!(
|
||||||
|
sender,
|
||||||
|
DownloadManagerSignal::Completed(download_agent.metadata())
|
||||||
|
);
|
||||||
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -370,7 +376,7 @@ impl DownloadManagerBuilder {
|
|||||||
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
|
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
|
||||||
let event_data = StatsUpdateEvent { speed: kbs, time };
|
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) {
|
fn push_ui_queue_update(&self) {
|
||||||
let queue = &self.download_queue.read();
|
let queue = &self.download_queue.read();
|
||||||
@ -389,6 +395,6 @@ impl DownloadManagerBuilder {
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let event_data = QueueUpdateEvent { queue: queue_objs };
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,7 +14,6 @@ use log::{debug, info};
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use utils::{lock, send};
|
use utils::{lock, send};
|
||||||
|
|
||||||
|
|
||||||
use crate::error::ApplicationDownloadError;
|
use crate::error::ApplicationDownloadError;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
@ -80,6 +79,7 @@ pub enum DownloadStatus {
|
|||||||
/// The actual download queue may be accessed through the .`edit()` function,
|
/// The actual download queue may be accessed through the .`edit()` function,
|
||||||
/// which provides raw access to the underlying queue.
|
/// which provides raw access to the underlying queue.
|
||||||
/// THIS EDITING IS BLOCKING!!!
|
/// THIS EDITING IS BLOCKING!!!
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct DownloadManager {
|
pub struct DownloadManager {
|
||||||
terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>,
|
terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>,
|
||||||
download_queue: Queue,
|
download_queue: Queue,
|
||||||
@ -124,8 +124,11 @@ impl DownloadManager {
|
|||||||
}
|
}
|
||||||
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
|
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
|
||||||
let mut queue = self.edit();
|
let mut queue = self.edit();
|
||||||
let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
|
let current_index =
|
||||||
let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue");
|
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);
|
queue.insert(new_index, to_move);
|
||||||
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
|
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,6 @@ use std::sync::Arc;
|
|||||||
use database::DownloadableMetadata;
|
use database::DownloadableMetadata;
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
|
||||||
use crate::error::ApplicationDownloadError;
|
use crate::error::ApplicationDownloadError;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
|
|||||||
@ -1,5 +1,9 @@
|
|||||||
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
|
use humansize::{BINARY, format_size};
|
||||||
use humansize::{format_size, BINARY};
|
use std::{
|
||||||
|
fmt::{Display, Formatter},
|
||||||
|
io,
|
||||||
|
sync::{Arc, mpsc::SendError},
|
||||||
|
};
|
||||||
|
|
||||||
use remote::error::RemoteAccessError;
|
use remote::error::RemoteAccessError;
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
@ -44,7 +48,9 @@ pub enum ApplicationDownloadError {
|
|||||||
impl Display for ApplicationDownloadError {
|
impl Display for ApplicationDownloadError {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
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!(
|
ApplicationDownloadError::DiskFull(required, available) => write!(
|
||||||
f,
|
f,
|
||||||
"Game requires {}, {} remaining left on disk.",
|
"Game requires {}, {} remaining left on disk.",
|
||||||
@ -60,10 +66,9 @@ impl Display for ApplicationDownloadError {
|
|||||||
write!(f, "checksum failed to validate for download")
|
write!(f, "checksum failed to validate for download")
|
||||||
}
|
}
|
||||||
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
|
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
|
||||||
ApplicationDownloadError::DownloadError(error) => write!(
|
ApplicationDownloadError::DownloadError(error) => {
|
||||||
f,
|
write!(f, "Download failed with error {error:?}")
|
||||||
"Download failed with error {error:?}"
|
}
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -2,15 +2,43 @@
|
|||||||
#![feature(nonpoison_mutex)]
|
#![feature(nonpoison_mutex)]
|
||||||
#![feature(sync_nonpoison)]
|
#![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_builder;
|
||||||
pub mod download_manager_frontend;
|
pub mod download_manager_frontend;
|
||||||
pub mod downloadable;
|
pub mod downloadable;
|
||||||
pub mod util;
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod frontend_updates;
|
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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
use std::sync::{
|
use std::sync::{
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
Arc,
|
Arc,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||||
@ -22,7 +22,11 @@ impl From<DownloadThreadControlFlag> for bool {
|
|||||||
/// false => Stop
|
/// false => Stop
|
||||||
impl From<bool> for DownloadThreadControlFlag {
|
impl From<bool> for DownloadThreadControlFlag {
|
||||||
fn from(value: bool) -> Self {
|
fn from(value: bool) -> Self {
|
||||||
if value { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop }
|
if value {
|
||||||
|
DownloadThreadControlFlag::Go
|
||||||
|
} else {
|
||||||
|
DownloadThreadControlFlag::Stop
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -15,7 +15,7 @@ use crate::download_manager_frontend::DownloadManagerSignal;
|
|||||||
|
|
||||||
use super::rolling_progress_updates::RollingProgressWindow;
|
use super::rolling_progress_updates::RollingProgressWindow;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct ProgressObject {
|
pub struct ProgressObject {
|
||||||
max: Arc<Mutex<usize>>,
|
max: Arc<Mutex<usize>>,
|
||||||
progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>,
|
progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>,
|
||||||
@ -117,7 +117,9 @@ pub fn calculate_update(progress: &ProgressObject) {
|
|||||||
let last_update_time = progress
|
let last_update_time = progress
|
||||||
.last_update_time
|
.last_update_time
|
||||||
.swap(Instant::now(), Ordering::SeqCst);
|
.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 current_bytes_downloaded = progress.sum();
|
||||||
let max = progress.get_max();
|
let max = progress.get_max();
|
||||||
@ -125,7 +127,8 @@ pub fn calculate_update(progress: &ProgressObject) {
|
|||||||
.bytes_last_update
|
.bytes_last_update
|
||||||
.swap(current_bytes_downloaded, Ordering::Acquire);
|
.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;
|
let kilobytes_per_second = bytes_since_last_update / time_since_last_update;
|
||||||
|
|
||||||
|
|||||||
@ -6,7 +6,7 @@ use std::{
|
|||||||
use database::DownloadableMetadata;
|
use database::DownloadableMetadata;
|
||||||
use utils::lock;
|
use utils::lock;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct Queue {
|
pub struct Queue {
|
||||||
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
|
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,11 +3,17 @@ use std::sync::{
|
|||||||
atomic::{AtomicUsize, Ordering},
|
atomic::{AtomicUsize, Ordering},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct RollingProgressWindow<const S: usize> {
|
pub struct RollingProgressWindow<const S: usize> {
|
||||||
window: Arc<[AtomicUsize; S]>,
|
window: Arc<[AtomicUsize; S]>,
|
||||||
current: Arc<AtomicUsize>,
|
current: Arc<AtomicUsize>,
|
||||||
}
|
}
|
||||||
|
impl<const S: usize> Default for RollingProgressWindow<S> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl<const S: usize> RollingProgressWindow<S> {
|
impl<const S: usize> RollingProgressWindow<S> {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
|||||||
@ -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::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
|
||||||
use download_manager::downloadable::Downloadable;
|
use download_manager::downloadable::Downloadable;
|
||||||
use download_manager::error::ApplicationDownloadError;
|
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 download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use rayon::ThreadPoolBuilder;
|
use rayon::ThreadPoolBuilder;
|
||||||
@ -10,7 +15,6 @@ use remote::auth::generate_authorization_header;
|
|||||||
use remote::error::RemoteAccessError;
|
use remote::error::RemoteAccessError;
|
||||||
use remote::requests::generate_url;
|
use remote::requests::generate_url;
|
||||||
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
|
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
|
||||||
use utils::{app_emit, lock, send};
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::fs::{OpenOptions, create_dir_all};
|
use std::fs::{OpenOptions, create_dir_all};
|
||||||
use std::io;
|
use std::io;
|
||||||
@ -18,12 +22,15 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::sync::mpsc::Sender;
|
use std::sync::mpsc::Sender;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use tauri::{AppHandle, Emitter};
|
use tauri::AppHandle;
|
||||||
|
use utils::{app_emit, lock, send};
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use rustix::fs::{FallocateFlags, fallocate};
|
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::utils::get_disk_available;
|
||||||
use crate::downloads::validate::validate_game_chunk;
|
use crate::downloads::validate::validate_game_chunk;
|
||||||
use crate::library::{on_game_complete, push_game_update, set_partially_installed};
|
use crate::library::{on_game_complete, push_game_update, set_partially_installed};
|
||||||
@ -97,8 +104,7 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
result.ensure_manifest_exists().await?;
|
result.ensure_manifest_exists().await?;
|
||||||
|
|
||||||
let required_space = lock!(result
|
let required_space = lock!(result.manifest)
|
||||||
.manifest)
|
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.values()
|
.values()
|
||||||
@ -447,9 +453,13 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
let sender = self.sender.clone();
|
let sender = self.sender.clone();
|
||||||
|
|
||||||
let download_context = download_contexts
|
let download_context =
|
||||||
.get(&bucket.version)
|
download_contexts.get(&bucket.version).unwrap_or_else(|| {
|
||||||
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
|
panic!(
|
||||||
|
"Could not get bucket version {}. Corrupted state.",
|
||||||
|
bucket.version
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
scope.spawn(move |_| {
|
scope.spawn(move |_| {
|
||||||
// 3 attempts
|
// 3 attempts
|
||||||
@ -687,7 +697,10 @@ impl Downloadable for GameDownloadAgent {
|
|||||||
Ok(_) => {}
|
Ok(_) => {}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("could not mark game as complete: {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))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -11,7 +11,9 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use download_manager::error::ApplicationDownloadError;
|
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 download_manager::util::progress_object::ProgressHandle;
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, warn};
|
||||||
use md5::{Context, Digest};
|
use md5::{Context, Digest};
|
||||||
@ -47,7 +49,7 @@ impl DropWriter<File> {
|
|||||||
|
|
||||||
fn finish(mut self) -> io::Result<Digest> {
|
fn finish(mut self) -> io::Result<Digest> {
|
||||||
self.flush()?;
|
self.flush()?;
|
||||||
Ok(self.hasher.compute())
|
Ok(self.hasher.finalize())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Write automatically pushes to file and hasher
|
// Write automatically pushes to file and hasher
|
||||||
@ -116,7 +118,10 @@ impl<'a> DropDownloadPipeline<'a, Response, File> {
|
|||||||
let mut last_bump = 0;
|
let mut last_bump = 0;
|
||||||
loop {
|
loop {
|
||||||
let size = MAX_PACKET_LENGTH.min(remaining);
|
let size = MAX_PACKET_LENGTH.min(remaining);
|
||||||
let size = self.source.read(&mut copy_buffer[0..size]).inspect_err(|_| {
|
let size = self
|
||||||
|
.source
|
||||||
|
.read(&mut copy_buffer[0..size])
|
||||||
|
.inspect_err(|_| {
|
||||||
info!("got error from {}", drop.filename);
|
info!("got error from {}", drop.filename);
|
||||||
})?;
|
})?;
|
||||||
remaining -= size;
|
remaining -= size;
|
||||||
|
|||||||
@ -1,5 +1,8 @@
|
|||||||
use std::{
|
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;
|
use log::error;
|
||||||
@ -77,7 +80,10 @@ impl DropData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
|
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) {
|
pub fn set_context(&self, context: String, state: bool) {
|
||||||
lock!(self.contexts).entry(context).insert_entry(state);
|
lock!(self.contexts).entry(context).insert_entry(state);
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
use std::fmt::{Display};
|
use std::fmt::Display;
|
||||||
|
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
|
|
||||||
@ -9,13 +9,21 @@ pub enum LibraryError {
|
|||||||
}
|
}
|
||||||
impl Display for LibraryError {
|
impl Display for LibraryError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
write!(f, "{}", match self {
|
write!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
match self {
|
||||||
LibraryError::MetaNotFound(id) => {
|
LibraryError::MetaNotFound(id) => {
|
||||||
format!("Could not locate any installed version of game ID {id} in the database")
|
format!(
|
||||||
|
"Could not locate any installed version of game ID {id} in the database"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
LibraryError::VersionNotFound(game_id) => {
|
LibraryError::VersionNotFound(game_id) => {
|
||||||
format!("Could not locate any installed version for game id {game_id} in the database")
|
format!(
|
||||||
|
"Could not locate any installed version for game id {game_id} in the database"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,5 +3,5 @@ mod download_logic;
|
|||||||
pub mod drop_data;
|
pub mod drop_data;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod manifest;
|
mod manifest;
|
||||||
pub mod validate;
|
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
pub mod validate;
|
||||||
|
|||||||
@ -19,7 +19,7 @@ pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownlo
|
|||||||
return Ok(disk.available_space());
|
return Ok(disk.available_space());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(ApplicationDownloadError::IoError(Arc::new(io::Error::other(
|
Err(ApplicationDownloadError::IoError(Arc::new(
|
||||||
"could not find disk of path",
|
io::Error::other("could not find disk of path"),
|
||||||
))))
|
)))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,13 @@ use std::{
|
|||||||
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
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 log::debug;
|
||||||
use md5::Context;
|
use md5::Context;
|
||||||
|
|
||||||
@ -16,7 +22,10 @@ pub fn validate_game_chunk(
|
|||||||
) -> Result<bool, ApplicationDownloadError> {
|
) -> Result<bool, ApplicationDownloadError> {
|
||||||
debug!(
|
debug!(
|
||||||
"Starting chunk validation {}, {}, {} #{}",
|
"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 we're paused
|
||||||
if control_flag.get() == DownloadThreadControlFlag::Stop {
|
if control_flag.get() == DownloadThreadControlFlag::Stop {
|
||||||
@ -36,13 +45,12 @@ pub fn validate_game_chunk(
|
|||||||
|
|
||||||
let mut hasher = md5::Context::new();
|
let mut hasher = md5::Context::new();
|
||||||
|
|
||||||
let completed =
|
let completed = validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
|
||||||
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
|
|
||||||
if !completed {
|
if !completed {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
let res = hex::encode(hasher.compute().0);
|
let res = hex::encode(hasher.finalize().0);
|
||||||
if res != ctx.checksum {
|
if res != ctx.checksum {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,4 +3,5 @@
|
|||||||
pub mod collections;
|
pub mod collections;
|
||||||
pub mod downloads;
|
pub mod downloads;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
|
pub mod scan;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
|||||||
@ -1,15 +1,20 @@
|
|||||||
use std::fs::remove_dir_all;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
use std::thread::spawn;
|
|
||||||
use bitcode::{Decode, Encode};
|
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 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 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 utils::app_emit;
|
||||||
|
|
||||||
use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
|
use crate::state::{GameStatusManager, GameStatusWithTransient};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct FetchGameStruct {
|
pub struct FetchGameStruct {
|
||||||
@ -20,7 +25,11 @@ pub struct FetchGameStruct {
|
|||||||
|
|
||||||
impl FetchGameStruct {
|
impl FetchGameStruct {
|
||||||
pub fn new(game: Game, status: GameStatusWithTransient, version: Option<GameVersion>) -> Self {
|
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);
|
debug!("uninstalled game id {}", &meta.id);
|
||||||
app_emit!(app_handle, "update_library", ());
|
app_emit!(&app_handle, "update_library", ());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@ -284,41 +293,8 @@ pub struct FrontendGameOptions {
|
|||||||
launch_string: String,
|
launch_string: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
impl FrontendGameOptions {
|
||||||
pub fn update_game_configuration(
|
pub fn launch_string(&self) -> &String {
|
||||||
game_id: String,
|
&self.launch_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(())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,16 +1,11 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
|
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{
|
downloads::drop_data::{DROP_DATA_PATH, DropData},
|
||||||
db::borrow_db_mut_checked,
|
|
||||||
models::data::{DownloadType, DownloadableMetadata},
|
|
||||||
},
|
|
||||||
games::{
|
|
||||||
downloads::drop_data::{DropData, DROP_DATA_PATH},
|
|
||||||
library::set_partially_installed_db,
|
library::set_partially_installed_db,
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn scan_install_dirs() {
|
pub fn scan_install_dirs() {
|
||||||
|
|||||||
@ -14,5 +14,6 @@ page_size = "0.6.0"
|
|||||||
serde = "1.0.228"
|
serde = "1.0.228"
|
||||||
serde_with = "3.15.0"
|
serde_with = "3.15.0"
|
||||||
shared_child = "1.1.1"
|
shared_child = "1.1.1"
|
||||||
|
tauri = "2.8.5"
|
||||||
tauri-plugin-opener = "2.5.0"
|
tauri-plugin-opener = "2.5.0"
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
utils = { version = "0.1.0", path = "../utils" }
|
||||||
|
|||||||
@ -8,7 +8,12 @@ pub struct DropFormatArgs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 positional = Vec::new();
|
||||||
let mut map: HashMap<&'static str, String> = HashMap::new();
|
let mut map: HashMap<&'static str, String> = HashMap::new();
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,41 @@
|
|||||||
#![feature(nonpoison_mutex)]
|
#![feature(nonpoison_mutex)]
|
||||||
#![feature(sync_nonpoison)]
|
#![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;
|
use crate::process_manager::ProcessManager;
|
||||||
|
|
||||||
pub static PROCESS_MANAGER: LazyLock<Mutex<ProcessManager>> =
|
pub static PROCESS_MANAGER: ProcessManagerWrapper = ProcessManagerWrapper::new();
|
||||||
LazyLock::new(|| Mutex::new(ProcessManager::new()));
|
|
||||||
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod format;
|
pub mod format;
|
||||||
pub mod process_handlers;
|
pub mod process_handlers;
|
||||||
pub mod process_manager;
|
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"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,8 +1,7 @@
|
|||||||
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
|
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 log::debug;
|
||||||
|
|
||||||
|
|
||||||
use crate::{error::ProcessError, process_manager::ProcessHandler};
|
use crate::{error::ProcessError, process_manager::ProcessHandler};
|
||||||
|
|
||||||
pub struct NativeGameLauncher;
|
pub struct NativeGameLauncher;
|
||||||
@ -46,7 +45,9 @@ impl ProcessHandler for UMULauncher {
|
|||||||
};
|
};
|
||||||
Ok(format!(
|
Ok(format!(
|
||||||
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
"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,
|
launch = launch_command,
|
||||||
args = args.join(" ")
|
args = args.join(" ")
|
||||||
))
|
))
|
||||||
@ -86,7 +87,12 @@ impl ProcessHandler for AsahiMuvmLauncher {
|
|||||||
.next()
|
.next()
|
||||||
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
||||||
.trim();
|
.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}"))
|
Ok(format!("{args} muvm -- {cmd}"))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,6 +6,7 @@ use std::{
|
|||||||
process::{Command, ExitStatus},
|
process::{Command, ExitStatus},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
|
thread::spawn,
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -15,10 +16,10 @@ use database::{
|
|||||||
};
|
};
|
||||||
use dynfmt::Format;
|
use dynfmt::Format;
|
||||||
use dynfmt::SimpleCurlyFormat;
|
use dynfmt::SimpleCurlyFormat;
|
||||||
use games::state::GameStatusManager;
|
use games::{library::push_game_update, state::GameStatusManager};
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, warn};
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use shared_child::SharedChild;
|
use shared_child::SharedChild;
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
PROCESS_MANAGER,
|
PROCESS_MANAGER,
|
||||||
@ -41,10 +42,11 @@ pub struct ProcessManager<'a> {
|
|||||||
(Platform, Platform),
|
(Platform, Platform),
|
||||||
&'a (dyn ProcessHandler + Sync + Send + 'static),
|
&'a (dyn ProcessHandler + Sync + Send + 'static),
|
||||||
)>,
|
)>,
|
||||||
|
app_handle: AppHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProcessManager<'_> {
|
impl ProcessManager<'_> {
|
||||||
pub fn new() -> Self {
|
pub fn new(app_handle: AppHandle) -> Self {
|
||||||
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
||||||
|
|
||||||
ProcessManager {
|
ProcessManager {
|
||||||
@ -82,6 +84,7 @@ impl ProcessManager<'_> {
|
|||||||
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
app_handle,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,13 +175,12 @@ impl ProcessManager<'_> {
|
|||||||
|
|
||||||
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
||||||
|
|
||||||
// TODO
|
push_game_update(
|
||||||
// push_game_update(
|
&self.app_handle,
|
||||||
// &self.app_handle,
|
&game_id,
|
||||||
// &game_id,
|
Some(version_data.clone()),
|
||||||
// Some(version_data.clone()),
|
status,
|
||||||
// status,
|
);
|
||||||
// );
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -363,13 +365,12 @@ impl ProcessManager<'_> {
|
|||||||
.transient_statuses
|
.transient_statuses
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
||||||
|
|
||||||
// TODO
|
push_game_update(
|
||||||
// push_game_update(
|
&self.app_handle,
|
||||||
// &self.app_handle,
|
&meta.id,
|
||||||
// &meta.id,
|
None,
|
||||||
// None,
|
(None, Some(ApplicationTransientStatus::Running {})),
|
||||||
// (None, Some(ApplicationTransientStatus::Running {})),
|
);
|
||||||
// );
|
|
||||||
|
|
||||||
let wait_thread_handle = launch_process_handle.clone();
|
let wait_thread_handle = launch_process_handle.clone();
|
||||||
let wait_thread_game_id = meta.clone();
|
let wait_thread_game_id = meta.clone();
|
||||||
@ -382,12 +383,14 @@ impl ProcessManager<'_> {
|
|||||||
manually_killed: false,
|
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
|
PROCESS_MANAGER
|
||||||
.lock()
|
.lock()
|
||||||
.on_process_finish(wait_thread_game_id.id, result)
|
.on_process_finish(wait_thread_game_id.id, result)
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2,14 +2,18 @@ use std::{collections::HashMap, env};
|
|||||||
|
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use client::{app_status::AppStatus, user::User};
|
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 droplet_rs::ssl::sign_nonce;
|
||||||
use gethostname::gethostname;
|
use gethostname::gethostname;
|
||||||
use log::{error, warn};
|
use log::{error, warn};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use url::Url;
|
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::{
|
use super::{
|
||||||
cache::{cache_object, get_cached_object},
|
cache::{cache_object, get_cached_object},
|
||||||
@ -31,19 +35,31 @@ struct InitiateRequestBody {
|
|||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct HandshakeRequestBody {
|
pub struct HandshakeRequestBody {
|
||||||
client_id: String,
|
client_id: String,
|
||||||
token: String,
|
token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl HandshakeRequestBody {
|
||||||
|
pub fn new(client_id: String, token: String) -> Self {
|
||||||
|
Self { client_id, token }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct HandshakeResponse {
|
pub struct HandshakeResponse {
|
||||||
private: String,
|
private: String,
|
||||||
certificate: String,
|
certificate: String,
|
||||||
id: 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 {
|
pub fn generate_authorization_header() -> String {
|
||||||
let certs = {
|
let certs = {
|
||||||
let db = borrow_db_checked();
|
let db = borrow_db_checked();
|
||||||
|
|||||||
@ -17,7 +17,7 @@ macro_rules! offline {
|
|||||||
|
|
||||||
async move {
|
async move {
|
||||||
if ::database::borrow_db_checked().settings.force_offline
|
if ::database::borrow_db_checked().settings.force_offline
|
||||||
|| ::utils::lock!($var).status == ::client::app_status::AppStatus::Offline {
|
|| $var.lock().status == ::client::app_status::AppStatus::Offline {
|
||||||
$func2( $( $arg ), *).await
|
$func2( $( $arg ), *).await
|
||||||
} else {
|
} else {
|
||||||
$func1( $( $arg ), *).await
|
$func1( $( $arg ), *).await
|
||||||
|
|||||||
@ -4,7 +4,7 @@ use std::{
|
|||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use http::{header::ToStrError, HeaderName, StatusCode};
|
use http::{HeaderName, StatusCode, header::ToStrError};
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
use url::ParseError;
|
use url::ParseError;
|
||||||
|
|
||||||
@ -19,7 +19,6 @@ pub struct DropServerError {
|
|||||||
// pub url: String,
|
// pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
#[derive(Debug, SerializeDisplay)]
|
||||||
pub enum RemoteAccessError {
|
pub enum RemoteAccessError {
|
||||||
FetchError(Arc<reqwest::Error>),
|
FetchError(Arc<reqwest::Error>),
|
||||||
@ -120,16 +119,24 @@ pub enum CacheError {
|
|||||||
HeaderNotFound(HeaderName),
|
HeaderNotFound(HeaderName),
|
||||||
ParseError(ToStrError),
|
ParseError(ToStrError),
|
||||||
Remote(RemoteAccessError),
|
Remote(RemoteAccessError),
|
||||||
ConstructionError(http::Error)
|
ConstructionError(http::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for CacheError {
|
impl Display for CacheError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
let s = match self {
|
let s = match self {
|
||||||
CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
|
CacheError::HeaderNotFound(header_name) => {
|
||||||
CacheError::ParseError(to_str_error) => format!("Could not parse cache with error {to_str_error}"),
|
format!("Could not find header {header_name} in cache")
|
||||||
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::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}")
|
write!(f, "{s}")
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
use database::{interface::DatabaseImpls, DB};
|
use database::{DB, interface::DatabaseImpls};
|
||||||
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
|
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
||||||
use log::{debug, warn};
|
use log::{debug, warn};
|
||||||
use tauri::UriSchemeResponder;
|
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),
|
Ok(r) => responder.respond(r),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Cache error: {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 /
|
// Drop leading /
|
||||||
let object_id = &request.uri().path()[1..];
|
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 {
|
let data = match r.bytes().await {
|
||||||
Ok(data) => Vec::from(data),
|
Ok(data) => Vec::from(data),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!(
|
warn!("Could not get data from cache object {object_id} with error {e}",);
|
||||||
"Could not get data from cache object {object_id} with error {e}",
|
|
||||||
);
|
|
||||||
Vec::new()
|
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()) {
|
if cache_result.map_or(true, |x| x.has_expired()) {
|
||||||
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
|
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
|
||||||
.expect("Failed to create cached object");
|
.expect("Failed to create cached object");
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
pub mod cache;
|
pub mod cache;
|
||||||
|
pub mod error;
|
||||||
pub mod fetch_object;
|
pub mod fetch_object;
|
||||||
pub mod requests;
|
pub mod requests;
|
||||||
pub mod server_proto;
|
pub mod server_proto;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
pub mod error;
|
|
||||||
|
|
||||||
pub use auth::setup;
|
pub use auth::setup;
|
||||||
@ -1,4 +1,4 @@
|
|||||||
use database::{interface::DatabaseImpls, DB};
|
use database::{DB, interface::DatabaseImpls};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
|||||||
@ -1,26 +1,30 @@
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use database::borrow_db_checked;
|
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 log::{error, warn};
|
||||||
use tauri::UriSchemeResponder;
|
use tauri::UriSchemeResponder;
|
||||||
use utils::webbrowser_open::webbrowser_open;
|
use utils::webbrowser_open::webbrowser_open;
|
||||||
|
|
||||||
use crate::utils::DROP_CLIENT_SYNC;
|
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 {
|
responder.respond(match handle_server_proto_offline(request).await {
|
||||||
Ok(res) => res,
|
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()
|
Ok(Response::builder()
|
||||||
.status(StatusCode::NOT_FOUND)
|
.status(StatusCode::NOT_FOUND)
|
||||||
.body(Vec::new())
|
.body(Vec::new())
|
||||||
.expect("Failed to build error response for proto offline"))
|
.expect("Failed to build error response for proto offline"))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
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),
|
Ok(r) => responder.respond(r),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Cache error: {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,
|
Some(auth) => auth,
|
||||||
None => {
|
None => {
|
||||||
error!("Could not find auth in database");
|
error!("Could not find auth in database");
|
||||||
return Err(StatusCode::UNAUTHORIZED)
|
return Err(StatusCode::UNAUTHORIZED);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let web_token = match &auth.web_token {
|
let web_token = match &auth.web_token {
|
||||||
Some(token) => token,
|
Some(token) => token,
|
||||||
None => return Err(StatusCode::UNAUTHORIZED),
|
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 path = request.uri().path();
|
||||||
|
|
||||||
let mut new_uri = request.uri().clone().into_parts();
|
let mut new_uri = request.uri().clone().into_parts();
|
||||||
new_uri.path_and_query =
|
new_uri.path_and_query = Some(
|
||||||
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
|
PathAndQuery::from_str(&format!("{path}?noWrapper=true"))
|
||||||
|
.expect("Failed to parse request path in proto"),
|
||||||
|
);
|
||||||
new_uri.authority = remote_uri.authority().cloned();
|
new_uri.authority = remote_uri.authority().cloned();
|
||||||
new_uri.scheme = remote_uri.scheme().cloned();
|
new_uri.scheme = remote_uri.scheme().cloned();
|
||||||
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
|
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)) {
|
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
|
||||||
webbrowser_open(new_uri.to_string());
|
webbrowser_open(new_uri.to_string());
|
||||||
return Ok(Response::new(Vec::new()))
|
return Ok(Response::new(Vec::new()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
let client = DROP_CLIENT_SYNC.clone();
|
||||||
@ -70,12 +84,13 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
|
|||||||
.request(request.method().clone(), new_uri.to_string())
|
.request(request.method().clone(), new_uri.to_string())
|
||||||
.header("Authorization", format!("Bearer {web_token}"))
|
.header("Authorization", format!("Bearer {web_token}"))
|
||||||
.headers(request.headers().clone())
|
.headers(request.headers().clone())
|
||||||
.send() {
|
.send()
|
||||||
|
{
|
||||||
Ok(response) => response,
|
Ok(response) => response,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Could not send response. Got {e} when sending");
|
warn!("Could not send response. Got {e} when sending");
|
||||||
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST))
|
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST));
|
||||||
},
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let response_status = response.status();
|
let response_status = response.status();
|
||||||
|
|||||||
@ -15,7 +15,7 @@ pub struct DropHealthcheck {
|
|||||||
app_name: String,
|
app_name: String,
|
||||||
}
|
}
|
||||||
impl DropHealthcheck {
|
impl DropHealthcheck {
|
||||||
pub fn app_name(&self) -> &String{
|
pub fn app_name(&self) -> &String {
|
||||||
&self.app_name
|
&self.app_name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -46,11 +46,13 @@ fn fetch_certificates() -> Vec<Certificate> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.read_to_end(&mut buf)
|
.read_to_end(&mut buf)
|
||||||
.unwrap_or_else(|e| panic!(
|
.unwrap_or_else(|e| {
|
||||||
|
panic!(
|
||||||
"Failed to read to end of certificate file {} with error {}",
|
"Failed to read to end of certificate file {} with error {}",
|
||||||
c.path().display(),
|
c.path().display(),
|
||||||
e
|
e
|
||||||
));
|
)
|
||||||
|
});
|
||||||
|
|
||||||
match Certificate::from_pem_bundle(&buf) {
|
match Certificate::from_pem_bundle(&buf) {
|
||||||
Ok(certificates) => {
|
Ok(certificates) => {
|
||||||
@ -87,7 +89,10 @@ pub fn get_client_sync() -> reqwest::blocking::Client {
|
|||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
for cert in DROP_CERT_BUNDLE.iter() {
|
||||||
client = client.add_root_certificate(cert.clone());
|
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 {
|
pub fn get_client_async() -> reqwest::Client {
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
let mut client = reqwest::ClientBuilder::new();
|
||||||
@ -95,7 +100,10 @@ pub fn get_client_async() -> reqwest::Client {
|
|||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
for cert in DROP_CERT_BUNDLE.iter() {
|
||||||
client = client.add_root_certificate(cert.clone());
|
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 {
|
pub fn get_client_ws() -> reqwest::Client {
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
let mut client = reqwest::ClientBuilder::new();
|
||||||
|
|||||||
@ -86,6 +86,7 @@ process = { path = "../process" }
|
|||||||
remote = { version = "0.1.0", path = "../remote" }
|
remote = { version = "0.1.0", path = "../remote" }
|
||||||
utils = { path = "../utils" }
|
utils = { path = "../utils" }
|
||||||
games = { version = "0.1.0", path = "../games" }
|
games = { version = "0.1.0", path = "../games" }
|
||||||
|
download_manager = { version = "0.1.0", path = "../download_manager" }
|
||||||
|
|
||||||
[dependencies.dynfmt]
|
[dependencies.dynfmt]
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
|
|||||||
@ -1,30 +1,29 @@
|
|||||||
|
use std::sync::nonpoison::Mutex;
|
||||||
|
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
use database::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
|
use download_manager::DOWNLOAD_MANAGER;
|
||||||
use log::{debug, error};
|
use log::{debug, error};
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
use tauri_plugin_autostart::ManagerExt;
|
use tauri_plugin_autostart::ManagerExt;
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::{AppState};
|
use crate::AppState;
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn fetch_state(
|
pub fn fetch_state(state: tauri::State<'_, Mutex<AppState>>) -> Result<String, String> {
|
||||||
state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>,
|
let guard = state.lock();
|
||||||
) -> Result<String, String> {
|
|
||||||
let guard = lock!(state);
|
|
||||||
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
||||||
drop(guard);
|
drop(guard);
|
||||||
Ok(cloned_state)
|
Ok(cloned_state)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
pub fn quit(app: tauri::AppHandle) {
|
||||||
cleanup_and_exit(&app, &state);
|
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");
|
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(res) => match res {
|
||||||
Ok(()) => debug!("download manager terminated correctly"),
|
Ok(()) => debug!("download manager terminated correctly"),
|
||||||
Err(()) => error!("download manager failed to terminate correctly"),
|
Err(()) => error!("download manager failed to terminate correctly"),
|
||||||
|
|||||||
@ -1,16 +1,12 @@
|
|||||||
use serde_json::json;
|
use games::collections::collection::{Collection, Collections};
|
||||||
|
use remote::{
|
||||||
use crate::{
|
|
||||||
error::remote_access_error::RemoteAccessError,
|
|
||||||
remote::{
|
|
||||||
auth::generate_authorization_header,
|
auth::generate_authorization_header,
|
||||||
cache::{cache_object, get_cached_object},
|
cache::{cache_object, get_cached_object},
|
||||||
|
error::RemoteAccessError,
|
||||||
requests::{generate_url, make_authenticated_get},
|
requests::{generate_url, make_authenticated_get},
|
||||||
utils::DROP_CLIENT_ASYNC,
|
utils::DROP_CLIENT_ASYNC,
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
use serde_json::json;
|
||||||
use super::collection::{Collection, Collections};
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn fetch_collections(
|
pub async fn fetch_collections(
|
||||||
|
|||||||
@ -1,27 +1,22 @@
|
|||||||
use std::sync::Mutex;
|
use database::DownloadableMetadata;
|
||||||
|
use download_manager::DOWNLOAD_MANAGER;
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
pub fn pause_downloads() {
|
||||||
lock!(state).download_manager.pause_downloads();
|
DOWNLOAD_MANAGER.pause_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
pub fn resume_downloads() {
|
||||||
lock!(state).download_manager.resume_downloads();
|
DOWNLOAD_MANAGER.resume_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn move_download_in_queue(
|
pub fn move_download_in_queue(old_index: usize, new_index: usize) {
|
||||||
state: tauri::State<'_, Mutex<AppState>>,
|
DOWNLOAD_MANAGER.rearrange(old_index, new_index);
|
||||||
old_index: usize,
|
|
||||||
new_index: usize,
|
|
||||||
) {
|
|
||||||
lock!(state)
|
|
||||||
.download_manager
|
|
||||||
.rearrange(old_index, new_index);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
|
pub fn cancel_game(meta: DownloadableMetadata) {
|
||||||
lock!(state).download_manager.cancel(meta);
|
DOWNLOAD_MANAGER.cancel(meta);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,34 +1,31 @@
|
|||||||
use std::{
|
use std::{path::PathBuf, sync::Arc};
|
||||||
path::PathBuf,
|
|
||||||
sync::{Arc, Mutex},
|
use database::{GameDownloadStatus, borrow_db_checked};
|
||||||
|
use download_manager::{
|
||||||
|
DOWNLOAD_MANAGER, downloadable::Downloadable, error::ApplicationDownloadError,
|
||||||
};
|
};
|
||||||
|
use games::downloads::download_agent::GameDownloadAgent;
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn download_game(
|
pub async fn download_game(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
game_version: String,
|
game_version: String,
|
||||||
install_dir: usize,
|
install_dir: usize,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<(), ApplicationDownloadError> {
|
) -> Result<(), ApplicationDownloadError> {
|
||||||
let sender = { lock!(state).download_manager.get_sender().clone() };
|
let sender = { DOWNLOAD_MANAGER.get_sender().clone() };
|
||||||
|
|
||||||
let game_download_agent =
|
let game_download_agent = GameDownloadAgent::new_from_index(
|
||||||
GameDownloadAgent::new_from_index(game_id.clone(), game_version.clone(), install_dir, sender).await?;
|
game_id.clone(),
|
||||||
|
game_version.clone(),
|
||||||
|
install_dir,
|
||||||
|
sender,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let game_download_agent =
|
let game_download_agent =
|
||||||
Arc::new(Box::new(game_download_agent) as Box<dyn Downloadable + Send + Sync>);
|
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())
|
.queue_download(game_download_agent.clone())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@ -36,10 +33,7 @@ pub async fn download_game(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn resume_download(
|
pub async fn resume_download(game_id: String) -> Result<(), ApplicationDownloadError> {
|
||||||
game_id: String,
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<(), ApplicationDownloadError> {
|
|
||||||
let s = borrow_db_checked()
|
let s = borrow_db_checked()
|
||||||
.applications
|
.applications
|
||||||
.game_statuses
|
.game_statuses
|
||||||
@ -57,21 +51,25 @@ pub async fn resume_download(
|
|||||||
} => (version_name, install_dir),
|
} => (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 parent_dir: PathBuf = install_dir.into();
|
||||||
|
|
||||||
let game_download_agent = Arc::new(Box::new(
|
let game_download_agent = Arc::new(Box::new(
|
||||||
GameDownloadAgent::new(
|
GameDownloadAgent::new(
|
||||||
game_id,
|
game_id,
|
||||||
version_name.clone(),
|
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,
|
sender,
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
) as Box<dyn Downloadable + Send + Sync>);
|
) as Box<dyn Downloadable + Send + Sync>);
|
||||||
|
|
||||||
lock!(state)
|
DOWNLOAD_MANAGER
|
||||||
.download_manager
|
|
||||||
.queue_download(game_download_agent)
|
.queue_download(game_download_agent)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@ -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 database::{GameDownloadStatus, GameVersion, borrow_db_checked, borrow_db_mut_checked};
|
||||||
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, Game}, state::{GameStatusManager, GameStatusWithTransient}};
|
use games::{
|
||||||
|
downloads::error::LibraryError,
|
||||||
|
library::{FetchGameStruct, FrontendGameOptions, Game, get_current_meta, uninstall_game_logic},
|
||||||
|
state::{GameStatusManager, GameStatusWithTransient},
|
||||||
|
};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
use process::PROCESS_MANAGER;
|
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 tauri::AppHandle;
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::AppState;
|
use crate::AppState;
|
||||||
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn fetch_library(
|
pub async fn fetch_library(
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
hard_refresh: Option<bool>,
|
hard_refresh: Option<bool>,
|
||||||
) -> Result<Vec<Game>, RemoteAccessError> {
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
offline!(
|
offline!(
|
||||||
@ -22,12 +31,12 @@ pub async fn fetch_library(
|
|||||||
fetch_library_logic_offline,
|
fetch_library_logic_offline,
|
||||||
state,
|
state,
|
||||||
hard_refresh
|
hard_refresh
|
||||||
).await
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub async fn fetch_library_logic(
|
pub async fn fetch_library_logic(
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
hard_fresh: Option<bool>,
|
hard_fresh: Option<bool>,
|
||||||
) -> Result<Vec<Game>, RemoteAccessError> {
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
let do_hard_refresh = hard_fresh.unwrap_or(false);
|
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 games: Vec<Game> = response.json().await?;
|
||||||
|
|
||||||
let mut handle = lock!(state);
|
let mut handle = state.lock();
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
|
||||||
@ -95,7 +104,7 @@ pub async fn fetch_library_logic(
|
|||||||
Ok(games)
|
Ok(games)
|
||||||
}
|
}
|
||||||
pub async fn fetch_library_logic_offline(
|
pub async fn fetch_library_logic_offline(
|
||||||
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
_state: tauri::State<'_, Mutex<AppState>>,
|
||||||
_hard_refresh: Option<bool>,
|
_hard_refresh: Option<bool>,
|
||||||
) -> Result<Vec<Game>, RemoteAccessError> {
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
let mut games: Vec<Game> = get_cached_object("library")?;
|
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(
|
pub async fn fetch_game_logic(
|
||||||
id: String,
|
id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
let version = {
|
let version = {
|
||||||
let state_handle = lock!(state);
|
let state_handle = state.lock();
|
||||||
|
|
||||||
let db_lock = borrow_db_checked();
|
let db_lock = borrow_db_checked();
|
||||||
|
|
||||||
@ -173,7 +182,7 @@ pub async fn fetch_game_logic(
|
|||||||
|
|
||||||
let game: Game = response.json().await?;
|
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());
|
state_handle.games.insert(id.clone(), game.clone());
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
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(
|
pub async fn fetch_game_version_options_logic(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
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 data: Vec<GameVersion> = response.json().await?;
|
||||||
|
|
||||||
let state_lock = lock!(state);
|
let state_lock = state.lock();
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
let process_manager_lock = PROCESS_MANAGER.lock();
|
||||||
let data: Vec<GameVersion> = data
|
let data: Vec<GameVersion> = data
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@ -228,10 +237,9 @@ pub async fn fetch_game_version_options_logic(
|
|||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
pub async fn fetch_game_logic_offline(
|
pub async fn fetch_game_logic_offline(
|
||||||
id: String,
|
id: String,
|
||||||
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
_state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
let db_handle = borrow_db_checked();
|
let db_handle = borrow_db_checked();
|
||||||
let metadata_option = db_handle.applications.installed_game_version.get(&id);
|
let metadata_option = db_handle.applications.installed_game_version.get(&id);
|
||||||
@ -256,7 +264,7 @@ pub async fn fetch_game_logic_offline(
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn fetch_game(
|
pub async fn fetch_game(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
offline!(
|
offline!(
|
||||||
state,
|
state,
|
||||||
@ -264,7 +272,8 @@ pub async fn fetch_game(
|
|||||||
fetch_game_logic_offline,
|
fetch_game_logic_offline,
|
||||||
game_id,
|
game_id,
|
||||||
state
|
state
|
||||||
).await
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -287,7 +296,49 @@ pub fn uninstall_game(game_id: String, app_handle: AppHandle) -> Result<(), Libr
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn fetch_game_version_options(
|
pub async fn fetch_game_version_options(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
||||||
fetch_game_version_options_logic(game_id, state).await
|
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(())
|
||||||
|
}
|
||||||
|
|||||||
@ -4,33 +4,78 @@
|
|||||||
#![feature(duration_millis_float)]
|
#![feature(duration_millis_float)]
|
||||||
#![feature(iterator_try_collect)]
|
#![feature(iterator_try_collect)]
|
||||||
#![feature(nonpoison_mutex)]
|
#![feature(nonpoison_mutex)]
|
||||||
|
#![feature(sync_nonpoison)]
|
||||||
#![deny(clippy::all)]
|
#![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 ::client::{app_status::AppStatus, autostart::sync_autostart_on_startup, user::User};
|
||||||
use database::{borrow_db_checked, GameDownloadStatus};
|
use ::download_manager::DownloadManagerWrapper;
|
||||||
use ::games::library::Game;
|
use ::games::{library::Game, scan::scan_install_dirs};
|
||||||
use ::remote::auth;
|
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 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 client;
|
||||||
|
mod collections;
|
||||||
|
mod download_manager;
|
||||||
|
mod downloads;
|
||||||
|
mod games;
|
||||||
mod process;
|
mod process;
|
||||||
mod remote;
|
mod remote;
|
||||||
|
mod settings;
|
||||||
|
|
||||||
|
use client::*;
|
||||||
|
use collections::*;
|
||||||
|
use download_manager::*;
|
||||||
|
use downloads::*;
|
||||||
|
use games::*;
|
||||||
|
use process::*;
|
||||||
|
use remote::*;
|
||||||
|
use settings::*;
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
#[derive(Clone, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct AppState<'a> {
|
pub struct AppState {
|
||||||
status: AppStatus,
|
status: AppStatus,
|
||||||
user: Option<User>,
|
user: Option<User>,
|
||||||
games: HashMap<String, Game>,
|
games: HashMap<String, Game>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn setup(handle: AppHandle) -> AppState<'static> {
|
async fn setup(handle: AppHandle) -> AppState {
|
||||||
let logfile = FileAppender::builder()
|
let logfile = FileAppender::builder()
|
||||||
.encoder(Box::new(PatternEncoder::new(
|
.encoder(Box::new(PatternEncoder::new(
|
||||||
"{d} | {l} | {f}:{L} - {m}{n}",
|
"{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");
|
log4rs::init_config(config).expect("Failed to initialise log4rs");
|
||||||
|
|
||||||
let games = HashMap::new();
|
let games = HashMap::new();
|
||||||
let download_manager = Arc::new(DownloadManagerBuilder::build(handle.clone()));
|
|
||||||
let process_manager = Arc::new(Mutex::new(ProcessManager::new(handle.clone())));
|
ProcessManagerWrapper::init(handle.clone());
|
||||||
let compat_info = create_new_compat_info();
|
DownloadManagerWrapper::init(handle.clone());
|
||||||
|
|
||||||
debug!("checking if database is set up");
|
debug!("checking if database is set up");
|
||||||
let is_set_up = DB.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,
|
status: AppStatus::NotConfigured,
|
||||||
user: None,
|
user: None,
|
||||||
games,
|
games,
|
||||||
download_manager,
|
|
||||||
process_manager,
|
|
||||||
compat_info,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,9 +183,6 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
|||||||
status: app_status,
|
status: app_status,
|
||||||
user,
|
user,
|
||||||
games,
|
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)]
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
panic::set_hook(Box::new(|e| {
|
std::panic::set_hook(Box::new(|e| {
|
||||||
let _ = custom_panic_handler(e);
|
let _ = custom_panic_handler(e);
|
||||||
println!("{e}");
|
println!("{e}");
|
||||||
}));
|
}));
|
||||||
@ -328,7 +367,7 @@ pub fn run() {
|
|||||||
.expect("Failed to show window");
|
.expect("Failed to show window");
|
||||||
}
|
}
|
||||||
"quit" => {
|
"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
|
// TODO: Refactor
|
||||||
pub async fn recieve_handshake(app: AppHandle, path: String) {
|
pub async fn recieve_handshake(app: AppHandle, path: String) {
|
||||||
// Tell the app we're processing
|
// 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;
|
let handshake_result = recieve_handshake_logic(&app, path).await;
|
||||||
if let Err(e) = handshake_result {
|
if let Err(e) = handshake_result {
|
||||||
warn!("error with authentication: {e}");
|
warn!("error with authentication: {e}");
|
||||||
app_emit!(app, "auth/failed", e.to_string());
|
app_emit!(&app, "auth/failed", e.to_string());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let app_state = app.state::<Mutex<AppState>>();
|
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.status = app_status;
|
||||||
state_lock.user = user;
|
state_lock.user = user;
|
||||||
@ -441,7 +480,7 @@ pub async fn recieve_handshake(app: AppHandle, path: String) {
|
|||||||
|
|
||||||
drop(state_lock);
|
drop(state_lock);
|
||||||
|
|
||||||
app_emit!(app, "auth/finished", ());
|
app_emit!(&app, "auth/finished", ());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Refactor
|
// TODO: Refactor
|
||||||
@ -465,10 +504,7 @@ async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), Re
|
|||||||
let token = path_chunks
|
let token = path_chunks
|
||||||
.get(2)
|
.get(2)
|
||||||
.expect("Failed to get token from path chunks");
|
.expect("Failed to get token from path chunks");
|
||||||
let body = HandshakeRequestBody {
|
let body = HandshakeRequestBody::new((client_id).to_string(), (token).to_string());
|
||||||
client_id: (client_id).to_string(),
|
|
||||||
token: (token).to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let endpoint = base_url.join("/api/v1/client/auth/handshake")?;
|
let endpoint = base_url.join("/api/v1/client/auth/handshake")?;
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
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();
|
let mut handle = borrow_db_mut_checked();
|
||||||
handle.auth = Some(DatabaseAuth {
|
handle.auth = Some(response_struct.into());
|
||||||
private: response_struct.private,
|
|
||||||
cert: response_struct.certificate,
|
|
||||||
client_id: response_struct.id,
|
|
||||||
web_token: None,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let web_token = {
|
let web_token = {
|
||||||
@ -504,4 +535,3 @@ async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), Re
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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::AppHandle;
|
||||||
use tauri_plugin_opener::OpenerExt;
|
use tauri_plugin_opener::OpenerExt;
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::AppState;
|
use crate::AppState;
|
||||||
|
|
||||||
@ -12,15 +11,15 @@ pub fn launch_game(
|
|||||||
id: String,
|
id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<(), ProcessError> {
|
) -> Result<(), ProcessError> {
|
||||||
let state_lock = lock!(state);
|
let state_lock = state.lock();
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
let mut process_manager_lock = PROCESS_MANAGER.lock();
|
||||||
//let meta = DownloadableMetadata {
|
//let meta = DownloadableMetadata {
|
||||||
// id,
|
// id,
|
||||||
// version: Some(version),
|
// version: Some(version),
|
||||||
// download_type: DownloadType::Game,
|
// download_type: DownloadType::Game,
|
||||||
//};
|
//};
|
||||||
|
|
||||||
match process_manager_lock.launch_process(id, &state_lock) {
|
match process_manager_lock.launch_process(id) {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
}
|
}
|
||||||
@ -32,9 +31,7 @@ pub fn launch_game(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn kill_game(
|
pub fn kill_game(game_id: String) -> Result<(), ProcessError> {
|
||||||
game_id: String,
|
|
||||||
) -> Result<(), ProcessError> {
|
|
||||||
PROCESS_MANAGER
|
PROCESS_MANAGER
|
||||||
.lock()
|
.lock()
|
||||||
.kill_game(game_id)
|
.kill_game(game_id)
|
||||||
@ -42,10 +39,7 @@ pub fn kill_game(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn open_process_logs(
|
pub fn open_process_logs(game_id: String, app_handle: AppHandle) -> Result<(), ProcessError> {
|
||||||
game_id: String,
|
|
||||||
app_handle: AppHandle
|
|
||||||
) -> Result<(), ProcessError> {
|
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
let process_manager_lock = PROCESS_MANAGER.lock();
|
||||||
|
|
||||||
let dir = process_manager_lock.get_log_dir(game_id);
|
let dir = process_manager_lock.get_log_dir(game_id);
|
||||||
|
|||||||
@ -1,22 +1,29 @@
|
|||||||
use std::{sync::Mutex, time::Duration};
|
use std::{sync::nonpoison::Mutex, time::Duration};
|
||||||
|
|
||||||
use client::app_status::AppStatus;
|
use client::app_status::AppStatus;
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
use database::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
use futures_lite::StreamExt;
|
use futures_lite::StreamExt;
|
||||||
use log::{debug, warn};
|
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 reqwest_websocket::{Message, RequestBuilderExt};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tauri::{AppHandle, Emitter, Manager};
|
use tauri::{AppHandle, Manager};
|
||||||
use url::Url;
|
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]
|
#[tauri::command]
|
||||||
pub async fn use_remote(
|
pub async fn use_remote(
|
||||||
url: String,
|
url: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<(), RemoteAccessError> {
|
) -> Result<(), RemoteAccessError> {
|
||||||
debug!("connecting to url {url}");
|
debug!("connecting to url {url}");
|
||||||
let base_url = Url::parse(&url)?;
|
let base_url = Url::parse(&url)?;
|
||||||
@ -37,7 +44,7 @@ pub async fn use_remote(
|
|||||||
return Err(RemoteAccessError::InvalidEndpoint);
|
return Err(RemoteAccessError::InvalidEndpoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut app_state = lock!(state);
|
let mut app_state = state.lock();
|
||||||
app_state.status = AppStatus::SignedOut;
|
app_state.status = AppStatus::SignedOut;
|
||||||
drop(app_state);
|
drop(app_state);
|
||||||
|
|
||||||
@ -91,21 +98,21 @@ pub fn sign_out(app: AppHandle) {
|
|||||||
|
|
||||||
// Update app state
|
// Update app state
|
||||||
{
|
{
|
||||||
let app_state = app.state::<Mutex<AppState>>();
|
let state = app.state::<Mutex<AppState>>();
|
||||||
let mut app_state_handle = lock!(app_state);
|
let mut app_state_handle = state.lock();
|
||||||
app_state_handle.status = AppStatus::SignedOut;
|
app_state_handle.status = AppStatus::SignedOut;
|
||||||
app_state_handle.user = None;
|
app_state_handle.user = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emit event for frontend
|
// Emit event for frontend
|
||||||
app_emit!(app, "auth/signedout", ());
|
app_emit!(&app, "auth/signedout", ());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[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 (app_status, user) = setup().await;
|
||||||
|
|
||||||
let mut guard = lock!(state);
|
let mut guard = state.lock();
|
||||||
guard.status = app_status;
|
guard.status = app_status;
|
||||||
guard.user = user;
|
guard.user = user;
|
||||||
drop(guard);
|
drop(guard);
|
||||||
@ -181,7 +188,7 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
|||||||
let result = load().await;
|
let result = load().await;
|
||||||
if let Err(err) = result {
|
if let Err(err) = result {
|
||||||
warn!("{err}");
|
warn!("{err}");
|
||||||
app_emit!(app, "auth/failed", err.to_string());
|
app_emit!(&app, "auth/failed", err.to_string());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -4,20 +4,14 @@ use std::{
|
|||||||
path::{Path, PathBuf},
|
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 log::error;
|
||||||
use serde_json::Value;
|
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
|
// Will, in future, return disk/remaining size
|
||||||
// Just returns the directories that have been set up
|
// Just returns the directories that have been set up
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|||||||
@ -7,7 +7,7 @@
|
|||||||
"beforeDevCommand": "yarn --cwd main dev --port 1432",
|
"beforeDevCommand": "yarn --cwd main dev --port 1432",
|
||||||
"devUrl": "http://localhost:1432/",
|
"devUrl": "http://localhost:1432/",
|
||||||
"beforeBuildCommand": "yarn build",
|
"beforeBuildCommand": "yarn build",
|
||||||
"frontendDist": "../../.output"
|
"frontendDist": "../.output"
|
||||||
},
|
},
|
||||||
"app": {
|
"app": {
|
||||||
"security": {
|
"security": {
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! app_emit {
|
macro_rules! app_emit {
|
||||||
($app:expr, $event:expr, $p:expr) => {
|
($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));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,6 +1,11 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! send {
|
macro_rules! send {
|
||||||
($download_manager:expr, $signal:expr) => {
|
($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)
|
||||||
|
)
|
||||||
|
})
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -1,6 +1,8 @@
|
|||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! lock {
|
macro_rules! lock {
|
||||||
($mutex:expr) => {
|
($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)))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -2,6 +2,10 @@ use log::warn;
|
|||||||
|
|
||||||
pub fn webbrowser_open<T: AsRef<str>>(url: T) {
|
pub fn webbrowser_open<T: AsRef<str>>(url: T) {
|
||||||
if let Err(e) = webbrowser::open(url.as_ref()) {
|
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
|
||||||
|
);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user