mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-10 04:22:13 +10:00
chore: Run cargo clippy && cargo fmt
Signed-off-by: quexeky <git@quexeky.dev>
This commit is contained in:
@ -9,4 +9,4 @@ pub enum AppStatus {
|
||||
SignedIn,
|
||||
SignedInNeedsReauth,
|
||||
ServerUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
@ -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;
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
pub mod autostart;
|
||||
pub mod user;
|
||||
pub mod app_status;
|
||||
pub mod compat;
|
||||
pub mod autostart;
|
||||
pub mod compat;
|
||||
pub mod user;
|
||||
|
||||
@ -10,4 +10,3 @@ pub struct User {
|
||||
display_name: String,
|
||||
profile_picture_object_id: String,
|
||||
}
|
||||
|
||||
|
||||
@ -2,7 +2,7 @@ use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use database::platform::Platform;
|
||||
use database::{db::DATA_ROOT_DIR, GameVersion};
|
||||
use database::{GameVersion, db::DATA_ROOT_DIR};
|
||||
use log::warn;
|
||||
|
||||
use crate::error::BackupError;
|
||||
@ -14,6 +14,12 @@ pub struct BackupManager<'a> {
|
||||
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
||||
}
|
||||
|
||||
impl Default for BackupManager<'_> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl BackupManager<'_> {
|
||||
pub fn new() -> Self {
|
||||
BackupManager {
|
||||
@ -40,66 +46,189 @@ impl BackupManager<'_> {
|
||||
(Platform::MacOs, Platform::MacOs),
|
||||
&MacBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||
),
|
||||
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
pub trait BackupHandler: Send + Sync {
|
||||
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.join("games")) }
|
||||
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) }
|
||||
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(self.root_translate(path, game)?.join(self.game_translate(path, game)?)) }
|
||||
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c }
|
||||
fn store_user_id_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError) }
|
||||
fn os_user_name_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&whoami::username()).unwrap()) }
|
||||
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winAppData>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppData>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDocuments>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winPublic>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winProgramData>"); Err(BackupError::InvalidSystem) }
|
||||
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected Windows Reference in Backup <winDir>"); Err(BackupError::InvalidSystem) }
|
||||
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgData>"); Err(BackupError::InvalidSystem) }
|
||||
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> { warn!("Unexpected XDG Reference in Backup <xdgConfig>"); Err(BackupError::InvalidSystem) }
|
||||
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::new()) }
|
||||
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(DATA_ROOT_DIR.join("games"))
|
||||
}
|
||||
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(PathBuf::from_str(&game.game_id).unwrap())
|
||||
}
|
||||
fn base_translate(&self, path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(self
|
||||
.root_translate(path, game)?
|
||||
.join(self.game_translate(path, game)?))
|
||||
}
|
||||
fn home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
let c = CommonPath::Home.get().ok_or(BackupError::NotFound);
|
||||
println!("{:?}", c);
|
||||
c
|
||||
}
|
||||
fn store_user_id_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
PathBuf::from_str(&game.game_id).map_err(|_| BackupError::ParseError)
|
||||
}
|
||||
fn os_user_name_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
Ok(PathBuf::from_str(&whoami::username()).unwrap())
|
||||
}
|
||||
fn win_app_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winAppData>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_local_app_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winLocalAppData>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_local_app_data_low_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winLocalAppDataLow>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_documents_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winDocuments>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_public_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winPublic>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_program_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winProgramData>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn win_dir_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected Windows Reference in Backup <winDir>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn xdg_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected XDG Reference in Backup <xdgData>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn xdg_config_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
warn!("Unexpected XDG Reference in Backup <xdgConfig>");
|
||||
Err(BackupError::InvalidSystem)
|
||||
}
|
||||
fn skip_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(PathBuf::new())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct LinuxBackupManager {}
|
||||
impl BackupHandler for LinuxBackupManager {
|
||||
fn xdg_config_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::Data.get().ok_or(BackupError::NotFound)?)
|
||||
fn xdg_config_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::Data.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
fn xdg_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
||||
fn xdg_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::Config.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
}
|
||||
pub struct WindowsBackupManager {}
|
||||
impl BackupHandler for WindowsBackupManager {
|
||||
fn win_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::Config.get().ok_or(BackupError::NotFound)?)
|
||||
fn win_app_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::Config.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
fn win_local_app_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::DataLocal.get().ok_or(BackupError::NotFound)?)
|
||||
fn win_local_app_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::DataLocal.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
fn win_local_app_data_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
|
||||
fn win_local_app_data_low_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::DataLocalLow
|
||||
.get()
|
||||
.ok_or(BackupError::NotFound)
|
||||
}
|
||||
fn win_dir_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
fn win_dir_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
Ok(PathBuf::from_str("C:/Windows").unwrap())
|
||||
}
|
||||
fn win_documents_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::Document.get().ok_or(BackupError::NotFound)?)
|
||||
|
||||
fn win_documents_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::Document.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
fn win_program_data_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
fn win_program_data_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
Ok(PathBuf::from_str("C:/ProgramData").unwrap())
|
||||
}
|
||||
fn win_public_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||
Ok(CommonPath::Public.get().ok_or(BackupError::NotFound)?)
|
||||
|
||||
fn win_public_translate(
|
||||
&self,
|
||||
_path: &PathBuf,
|
||||
_game: &GameVersion,
|
||||
) -> Result<PathBuf, BackupError> {
|
||||
CommonPath::Public.get().ok_or(BackupError::NotFound)
|
||||
}
|
||||
}
|
||||
pub struct MacBackupManager {}
|
||||
impl BackupHandler for MacBackupManager {}
|
||||
impl BackupHandler for MacBackupManager {}
|
||||
|
||||
@ -2,5 +2,6 @@ use database::platform::Platform;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Condition {
|
||||
Os(Platform)
|
||||
Os(Platform),
|
||||
Other
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
pub mod backup_manager;
|
||||
pub mod conditions;
|
||||
pub mod error;
|
||||
pub mod metadata;
|
||||
pub mod resolver;
|
||||
pub mod placeholder;
|
||||
pub mod normalise;
|
||||
pub mod path;
|
||||
pub mod backup_manager;
|
||||
pub mod error;
|
||||
pub mod placeholder;
|
||||
pub mod resolver;
|
||||
|
||||
@ -1,7 +1,6 @@
|
||||
use database::GameVersion;
|
||||
|
||||
use super::conditions::{Condition};
|
||||
|
||||
use super::conditions::Condition;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct CloudSaveMetadata {
|
||||
@ -16,15 +15,17 @@ pub struct GameFile {
|
||||
pub id: Option<String>,
|
||||
pub data_type: DataType,
|
||||
pub tags: Vec<Tag>,
|
||||
pub conditions: Vec<Condition>
|
||||
pub conditions: Vec<Condition>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DataType {
|
||||
Registry,
|
||||
File,
|
||||
Other
|
||||
Other,
|
||||
}
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(
|
||||
Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Tag {
|
||||
Config,
|
||||
@ -32,4 +33,4 @@ pub enum Tag {
|
||||
#[default]
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,7 +5,6 @@ use regex::Regex;
|
||||
|
||||
use super::placeholder::*;
|
||||
|
||||
|
||||
pub fn normalize(path: &str, os: Platform) -> String {
|
||||
let mut path = path.trim().trim_end_matches(['/', '\\']).replace('\\', "/");
|
||||
|
||||
@ -14,18 +13,25 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
||||
}
|
||||
|
||||
static CONSECUTIVE_SLASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"/{2,}").unwrap());
|
||||
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
|
||||
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
|
||||
static UNNECESSARY_DOUBLE_STAR_1: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"([^/*])\*{2,}").unwrap());
|
||||
static UNNECESSARY_DOUBLE_STAR_2: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"\*{2,}([^/*])").unwrap());
|
||||
static ENDING_WILDCARD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\*)+$").unwrap());
|
||||
static ENDING_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\.)$").unwrap());
|
||||
static INTERMEDIATE_DOT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\./)").unwrap());
|
||||
static BLANK_SEGMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(/\s+/)").unwrap());
|
||||
static APP_DATA: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%appdata%").unwrap());
|
||||
static APP_DATA_ROAMING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
||||
static APP_DATA_LOCAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
||||
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
||||
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
||||
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
|
||||
static APP_DATA_ROAMING: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
||||
static APP_DATA_LOCAL: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
||||
static APP_DATA_LOCAL_2: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
||||
static USER_PROFILE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
||||
static DOCUMENTS: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
|
||||
|
||||
for (pattern, replacement) in [
|
||||
(&CONSECUTIVE_SLASHES, "/"),
|
||||
@ -66,7 +72,9 @@ pub fn normalize(path: &str, os: Platform) -> String {
|
||||
|
||||
fn too_broad(path: &str) -> bool {
|
||||
println!("Path: {}", path);
|
||||
use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
|
||||
use {
|
||||
BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA,
|
||||
};
|
||||
|
||||
let path_lower = path.to_lowercase();
|
||||
|
||||
@ -77,7 +85,9 @@ fn too_broad(path: &str) -> bool {
|
||||
}
|
||||
|
||||
for item in AVOID_WILDCARDS {
|
||||
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
|
||||
if path.starts_with(&format!("{}/*", item))
|
||||
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -124,7 +134,6 @@ fn too_broad(path: &str) -> bool {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Drive letters:
|
||||
let drives: Regex = Regex::new(r"^[a-zA-Z]:$").unwrap();
|
||||
@ -159,4 +168,4 @@ pub fn usable(path: &str) -> bool {
|
||||
&& !path.starts_with("../")
|
||||
&& !too_broad(path)
|
||||
&& !unprintable.is_match(path)
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,12 +13,12 @@ pub enum CommonPath {
|
||||
|
||||
impl CommonPath {
|
||||
pub fn get(&self) -> Option<PathBuf> {
|
||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::config_dir());
|
||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_dir());
|
||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::data_local_dir());
|
||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::document_dir());
|
||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::home_dir());
|
||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(|| dirs::public_dir());
|
||||
static CONFIG: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::config_dir);
|
||||
static DATA: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_dir);
|
||||
static DATA_LOCAL: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::data_local_dir);
|
||||
static DOCUMENT: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::document_dir);
|
||||
static HOME: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::home_dir);
|
||||
static PUBLIC: LazyLock<Option<PathBuf>> = LazyLock::new(dirs::public_dir);
|
||||
|
||||
#[cfg(windows)]
|
||||
static DATA_LOCAL_LOW: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
||||
|
||||
@ -48,4 +48,4 @@ pub const XDG_DATA: &str = "<xdgData>"; // %WINDIR% on Windows
|
||||
pub const XDG_CONFIG: &str = "<xdgConfig>"; // $XDG_DATA_HOME on Linux
|
||||
pub const SKIP: &str = "<skip>"; // $XDG_CONFIG_HOME on Linux
|
||||
|
||||
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(|| whoami::username());
|
||||
pub static OS_USERNAME: LazyLock<String> = LazyLock::new(whoami::username);
|
||||
|
||||
@ -1,17 +1,13 @@
|
||||
use std::{
|
||||
fs::{self, create_dir_all, File},
|
||||
io::{self, ErrorKind, Read, Write},
|
||||
fs::{self, File, create_dir_all},
|
||||
io::{self, Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
thread::sleep,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crate::error::BackupError;
|
||||
|
||||
use super::{
|
||||
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
||||
};
|
||||
use database::{platform::Platform, GameVersion};
|
||||
use super::{backup_manager::BackupHandler, placeholder::*};
|
||||
use database::GameVersion;
|
||||
use log::{debug, warn};
|
||||
use rustix::path::Arg;
|
||||
use tempfile::tempfile;
|
||||
@ -30,7 +26,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
super::conditions::Condition::Os(os) => Some(os),
|
||||
_ => None,
|
||||
_ => None
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
@ -63,7 +59,7 @@ pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||
let binding = serde_json::to_string(meta).unwrap();
|
||||
let serialized = binding.as_bytes();
|
||||
let mut file = tempfile().unwrap();
|
||||
file.write(serialized).unwrap();
|
||||
file.write_all(serialized).unwrap();
|
||||
tarball.append_file("metadata", &mut file).unwrap();
|
||||
tarball.into_inner().unwrap().finish().unwrap()
|
||||
}
|
||||
@ -96,7 +92,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
||||
.iter()
|
||||
.find_map(|p| match p {
|
||||
super::conditions::Condition::Os(os) => Some(os),
|
||||
_ => None,
|
||||
_ => None
|
||||
})
|
||||
.cloned()
|
||||
{
|
||||
@ -115,7 +111,7 @@ pub fn extract(file: PathBuf) -> Result<(), BackupError> {
|
||||
};
|
||||
|
||||
let new_path = parse_path(file.path.into(), handler, &manifest.game_version)?;
|
||||
create_dir_all(&new_path.parent().unwrap()).unwrap();
|
||||
create_dir_all(new_path.parent().unwrap()).unwrap();
|
||||
|
||||
println!(
|
||||
"Current path {:?} copying to {:?}",
|
||||
@ -132,23 +128,22 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
|
||||
let src_path = src.as_ref();
|
||||
let dest_path = dest.as_ref();
|
||||
|
||||
let metadata = fs::metadata(&src_path)?;
|
||||
let metadata = fs::metadata(src_path)?;
|
||||
|
||||
if metadata.is_file() {
|
||||
// Ensure the parent directory of the destination exists for a file copy
|
||||
if let Some(parent) = dest_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::copy(&src_path, &dest_path)?;
|
||||
fs::copy(src_path, dest_path)?;
|
||||
} else if metadata.is_dir() {
|
||||
// For directories, we call the recursive helper function.
|
||||
// The destination for the recursive copy is the `dest_path` itself.
|
||||
copy_dir_recursive(&src_path, &dest_path)?;
|
||||
copy_dir_recursive(src_path, dest_path)?;
|
||||
} else {
|
||||
// Handle other file types like symlinks if necessary,
|
||||
// for now, return an error or skip.
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
return Err(io::Error::other(
|
||||
format!("Source {:?} is neither a file nor a directory", src_path),
|
||||
));
|
||||
}
|
||||
@ -157,7 +152,7 @@ pub fn copy_item<P: AsRef<Path>>(src: P, dest: P) -> io::Result<()> {
|
||||
}
|
||||
|
||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
|
||||
fs::create_dir_all(&dest)?;
|
||||
fs::create_dir_all(dest)?;
|
||||
|
||||
for entry in fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
@ -219,43 +214,3 @@ pub fn parse_path(
|
||||
println!("Final line: {:?}", &s);
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn test() {
|
||||
let mut meta = CloudSaveMetadata {
|
||||
files: vec![
|
||||
GameFile {
|
||||
path: String::from("<home>/favicon.png"),
|
||||
id: None,
|
||||
data_type: super::metadata::DataType::File,
|
||||
tags: Vec::new(),
|
||||
conditions: vec![Condition::Os(Platform::Linux)],
|
||||
},
|
||||
GameFile {
|
||||
path: String::from("<home>/Documents/Pixel Art"),
|
||||
id: None,
|
||||
data_type: super::metadata::DataType::File,
|
||||
tags: Vec::new(),
|
||||
conditions: vec![Condition::Os(Platform::Linux)],
|
||||
},
|
||||
],
|
||||
game_version: GameVersion {
|
||||
game_id: String::new(),
|
||||
version_name: String::new(),
|
||||
platform: Platform::Linux,
|
||||
launch_command: String::new(),
|
||||
launch_args: Vec::new(),
|
||||
launch_command_template: String::new(),
|
||||
setup_command: String::new(),
|
||||
setup_args: Vec::new(),
|
||||
setup_command_template: String::new(),
|
||||
only_setup: true,
|
||||
version_index: 0,
|
||||
delta: false,
|
||||
umu_id_override: None,
|
||||
},
|
||||
save_id: String::from("aaaaaaa"),
|
||||
};
|
||||
//resolve(&mut meta);
|
||||
|
||||
extract("save".into()).unwrap();
|
||||
}
|
||||
|
||||
@ -10,7 +10,6 @@ use crate::interface::{DatabaseImpls, DatabaseInterface};
|
||||
|
||||
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
||||
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
static DATA_ROOT_PREFIX: &str = "drop";
|
||||
#[cfg(debug_assertions)]
|
||||
@ -32,16 +31,15 @@ impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
||||
for DropDatabaseSerializer
|
||||
{
|
||||
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
||||
native_model::encode(val)
|
||||
.map_err(|e| DeSerError::Internal(e.to_string()))
|
||||
native_model::encode(val).map_err(|e| DeSerError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf)
|
||||
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
||||
let (val, _version) = native_model::decode(buf)
|
||||
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||
let (val, _version) =
|
||||
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||
Ok(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,20 @@
|
||||
use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}};
|
||||
use std::{
|
||||
fs::{self, create_dir_all},
|
||||
mem::ManuallyDrop,
|
||||
ops::{Deref, DerefMut},
|
||||
path::PathBuf,
|
||||
sync::{RwLockReadGuard, RwLockWriteGuard},
|
||||
};
|
||||
|
||||
use chrono::Utc;
|
||||
use log::{debug, error, info, warn};
|
||||
use rustbreak::{PathDatabase, RustbreakError};
|
||||
use url::Url;
|
||||
|
||||
use crate::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database};
|
||||
use crate::{
|
||||
db::{DATA_ROOT_DIR, DB, DropDatabaseSerializer},
|
||||
models::data::Database,
|
||||
};
|
||||
|
||||
pub type DatabaseInterface =
|
||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||
|
||||
@ -2,20 +2,13 @@
|
||||
|
||||
pub mod db;
|
||||
pub mod debug;
|
||||
pub mod interface;
|
||||
pub mod models;
|
||||
pub mod platform;
|
||||
pub mod interface;
|
||||
|
||||
pub use models::data::{
|
||||
ApplicationTransientStatus,
|
||||
Database,
|
||||
DatabaseApplications,
|
||||
DatabaseAuth,
|
||||
DownloadType,
|
||||
DownloadableMetadata,
|
||||
GameDownloadStatus,
|
||||
GameVersion,
|
||||
Settings
|
||||
};
|
||||
pub use db::DB;
|
||||
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
|
||||
pub use models::data::{
|
||||
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
|
||||
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
|
||||
};
|
||||
|
||||
@ -4,7 +4,7 @@ pub mod data {
|
||||
use native_model::native_model;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// NOTE: Within each version, you should NEVER use these types.
|
||||
// NOTE: Within each version, you should NEVER use these types.
|
||||
// Declare it using the actual version that it is from, i.e. v1::Settings rather than just Settings from here
|
||||
|
||||
pub type GameVersion = v1::GameVersion;
|
||||
@ -191,9 +191,7 @@ pub mod data {
|
||||
|
||||
use serde_with::serde_as;
|
||||
|
||||
use super::{
|
||||
Deserialize, Serialize, native_model, v1,
|
||||
};
|
||||
use super::{Deserialize, Serialize, native_model, v1};
|
||||
|
||||
#[native_model(id = 1, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::Database)]
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
@ -277,12 +275,13 @@ pub mod data {
|
||||
pub install_dirs: Vec<PathBuf>,
|
||||
// Guaranteed to exist if the game also exists in the app state map
|
||||
pub game_statuses: HashMap<String, GameDownloadStatus>,
|
||||
|
||||
|
||||
pub game_versions: HashMap<String, HashMap<String, v1::GameVersion>>,
|
||||
pub installed_game_version: HashMap<String, v1::DownloadableMetadata>,
|
||||
|
||||
#[serde(skip)]
|
||||
pub transient_statuses: HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
||||
pub transient_statuses:
|
||||
HashMap<v1::DownloadableMetadata, v1::ApplicationTransientStatus>,
|
||||
}
|
||||
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
||||
fn from(value: v1::DatabaseApplications) -> Self {
|
||||
@ -303,10 +302,7 @@ pub mod data {
|
||||
mod v3 {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::{
|
||||
Deserialize, Serialize,
|
||||
native_model, v2, v1,
|
||||
};
|
||||
use super::{Deserialize, Serialize, native_model, v1, v2};
|
||||
#[native_model(id = 1, version = 3, with = native_model::rmp_serde_1_3::RmpSerde, from = v2::Database)]
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
pub struct Database {
|
||||
@ -360,7 +356,12 @@ pub mod data {
|
||||
}
|
||||
}
|
||||
impl DatabaseAuth {
|
||||
pub fn new(private: String, cert: String, client_id: String, web_token: Option<String>) -> Self {
|
||||
pub fn new(
|
||||
private: String,
|
||||
cert: String,
|
||||
client_id: String,
|
||||
web_token: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
private,
|
||||
cert,
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
||||
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
||||
pub enum Platform {
|
||||
Windows,
|
||||
@ -44,4 +43,4 @@ impl From<whoami::Platform> for Platform {
|
||||
platform => unimplemented!("Playform {} is not supported", platform),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,11 +9,14 @@ use std::{
|
||||
|
||||
use database::DownloadableMetadata;
|
||||
use log::{debug, error, info, warn};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri::AppHandle;
|
||||
use utils::{app_emit, lock, send};
|
||||
|
||||
|
||||
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
|
||||
use crate::{
|
||||
download_manager_frontend::DownloadStatus,
|
||||
error::ApplicationDownloadError,
|
||||
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
|
||||
};
|
||||
|
||||
use super::{
|
||||
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
||||
@ -289,7 +292,10 @@ impl DownloadManagerBuilder {
|
||||
|
||||
if validate_result {
|
||||
download_agent.on_complete(&app_handle);
|
||||
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
|
||||
send!(
|
||||
sender,
|
||||
DownloadManagerSignal::Completed(download_agent.metadata())
|
||||
);
|
||||
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -14,7 +14,6 @@ use log::{debug, info};
|
||||
use serde::Serialize;
|
||||
use utils::{lock, send};
|
||||
|
||||
|
||||
use crate::error::ApplicationDownloadError;
|
||||
|
||||
use super::{
|
||||
@ -125,8 +124,11 @@ impl DownloadManager {
|
||||
}
|
||||
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
|
||||
let mut queue = self.edit();
|
||||
let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
|
||||
let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue");
|
||||
let current_index =
|
||||
get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
|
||||
let to_move = queue
|
||||
.remove(current_index)
|
||||
.expect("Failed to remove meta at index from queue");
|
||||
queue.insert(new_index, to_move);
|
||||
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
|
||||
}
|
||||
|
||||
@ -3,7 +3,6 @@ use std::sync::Arc;
|
||||
use database::DownloadableMetadata;
|
||||
use tauri::AppHandle;
|
||||
|
||||
|
||||
use crate::error::ApplicationDownloadError;
|
||||
|
||||
use super::{
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
|
||||
use humansize::{format_size, BINARY};
|
||||
use humansize::{BINARY, format_size};
|
||||
use std::{
|
||||
fmt::{Display, Formatter},
|
||||
io,
|
||||
sync::{Arc, mpsc::SendError},
|
||||
};
|
||||
|
||||
use remote::error::RemoteAccessError;
|
||||
use serde_with::SerializeDisplay;
|
||||
@ -44,7 +48,9 @@ pub enum ApplicationDownloadError {
|
||||
impl Display for ApplicationDownloadError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ApplicationDownloadError::NotInitialized => write!(f, "Download not initalized, did something go wrong?"),
|
||||
ApplicationDownloadError::NotInitialized => {
|
||||
write!(f, "Download not initalized, did something go wrong?")
|
||||
}
|
||||
ApplicationDownloadError::DiskFull(required, available) => write!(
|
||||
f,
|
||||
"Game requires {}, {} remaining left on disk.",
|
||||
@ -60,10 +66,9 @@ impl Display for ApplicationDownloadError {
|
||||
write!(f, "checksum failed to validate for download")
|
||||
}
|
||||
ApplicationDownloadError::IoError(error) => write!(f, "io error: {error}"),
|
||||
ApplicationDownloadError::DownloadError(error) => write!(
|
||||
f,
|
||||
"Download failed with error {error:?}"
|
||||
),
|
||||
ApplicationDownloadError::DownloadError(error) => {
|
||||
write!(f, "Download failed with error {error:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -72,4 +77,4 @@ impl From<io::Error> for ApplicationDownloadError {
|
||||
fn from(value: io::Error) -> Self {
|
||||
ApplicationDownloadError::IoError(Arc::new(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,18 +2,20 @@
|
||||
#![feature(nonpoison_mutex)]
|
||||
#![feature(sync_nonpoison)]
|
||||
|
||||
use std::{ops::Deref, sync::{nonpoison::Mutex, LazyLock, OnceLock}};
|
||||
use std::{ops::Deref, sync::OnceLock};
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
use crate::{download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager};
|
||||
use crate::{
|
||||
download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager,
|
||||
};
|
||||
|
||||
pub mod download_manager_builder;
|
||||
pub mod download_manager_frontend;
|
||||
pub mod downloadable;
|
||||
pub mod util;
|
||||
pub mod error;
|
||||
pub mod frontend_updates;
|
||||
pub mod util;
|
||||
|
||||
pub static DOWNLOAD_MANAGER: DownloadManagerWrapper = DownloadManagerWrapper::new();
|
||||
|
||||
@ -23,7 +25,10 @@ impl DownloadManagerWrapper {
|
||||
DownloadManagerWrapper(OnceLock::new())
|
||||
}
|
||||
pub fn init(app_handle: AppHandle) {
|
||||
DOWNLOAD_MANAGER.0.set(DownloadManagerBuilder::build(app_handle)).expect("Failed to initialise download manager");
|
||||
DOWNLOAD_MANAGER
|
||||
.0
|
||||
.set(DownloadManagerBuilder::build(app_handle))
|
||||
.expect("Failed to initialise download manager");
|
||||
}
|
||||
}
|
||||
|
||||
@ -36,4 +41,4 @@ impl Deref for DownloadManagerWrapper {
|
||||
None => unreachable!("Download manager should always be initialised"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||
@ -22,7 +22,11 @@ impl From<DownloadThreadControlFlag> for bool {
|
||||
/// false => Stop
|
||||
impl From<bool> for DownloadThreadControlFlag {
|
||||
fn from(value: bool) -> Self {
|
||||
if value { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop }
|
||||
if value {
|
||||
DownloadThreadControlFlag::Go
|
||||
} else {
|
||||
DownloadThreadControlFlag::Stop
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -117,7 +117,9 @@ pub fn calculate_update(progress: &ProgressObject) {
|
||||
let last_update_time = progress
|
||||
.last_update_time
|
||||
.swap(Instant::now(), Ordering::SeqCst);
|
||||
let time_since_last_update = Instant::now().duration_since(last_update_time).as_millis_f64();
|
||||
let time_since_last_update = Instant::now()
|
||||
.duration_since(last_update_time)
|
||||
.as_millis_f64();
|
||||
|
||||
let current_bytes_downloaded = progress.sum();
|
||||
let max = progress.get_max();
|
||||
@ -125,7 +127,8 @@ pub fn calculate_update(progress: &ProgressObject) {
|
||||
.bytes_last_update
|
||||
.swap(current_bytes_downloaded, Ordering::Acquire);
|
||||
|
||||
let bytes_since_last_update = current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
|
||||
let bytes_since_last_update =
|
||||
current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
|
||||
|
||||
let kilobytes_per_second = bytes_since_last_update / time_since_last_update;
|
||||
|
||||
|
||||
@ -8,6 +8,12 @@ pub struct RollingProgressWindow<const S: usize> {
|
||||
window: Arc<[AtomicUsize; S]>,
|
||||
current: Arc<AtomicUsize>,
|
||||
}
|
||||
impl<const S: usize> Default for RollingProgressWindow<S> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const S: usize> RollingProgressWindow<S> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
@ -31,7 +37,7 @@ impl<const S: usize> RollingProgressWindow<S> {
|
||||
.collect::<Vec<usize>>();
|
||||
let amount = valid.len();
|
||||
let sum = valid.into_iter().sum::<usize>();
|
||||
|
||||
|
||||
sum / amount
|
||||
}
|
||||
pub fn reset(&self) {
|
||||
|
||||
@ -1,8 +1,13 @@
|
||||
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata};
|
||||
use database::{
|
||||
ApplicationTransientStatus, DownloadType, DownloadableMetadata, borrow_db_checked,
|
||||
borrow_db_mut_checked,
|
||||
};
|
||||
use download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
|
||||
use download_manager::downloadable::Downloadable;
|
||||
use download_manager::error::ApplicationDownloadError;
|
||||
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
||||
use download_manager::util::download_thread_control_flag::{
|
||||
DownloadThreadControl, DownloadThreadControlFlag,
|
||||
};
|
||||
use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
||||
use log::{debug, error, info, warn};
|
||||
use rayon::ThreadPoolBuilder;
|
||||
@ -10,7 +15,6 @@ use remote::auth::generate_authorization_header;
|
||||
use remote::error::RemoteAccessError;
|
||||
use remote::requests::generate_url;
|
||||
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
|
||||
use utils::{app_emit, lock, send};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs::{OpenOptions, create_dir_all};
|
||||
use std::io;
|
||||
@ -18,12 +22,15 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Sender;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri::AppHandle;
|
||||
use utils::{app_emit, lock, send};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustix::fs::{FallocateFlags, fallocate};
|
||||
|
||||
use crate::downloads::manifest::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody};
|
||||
use crate::downloads::manifest::{
|
||||
DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody,
|
||||
};
|
||||
use crate::downloads::utils::get_disk_available;
|
||||
use crate::downloads::validate::validate_game_chunk;
|
||||
use crate::library::{on_game_complete, push_game_update, set_partially_installed};
|
||||
@ -97,8 +104,7 @@ impl GameDownloadAgent {
|
||||
|
||||
result.ensure_manifest_exists().await?;
|
||||
|
||||
let required_space = lock!(result
|
||||
.manifest)
|
||||
let required_space = lock!(result.manifest)
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.values()
|
||||
@ -447,9 +453,13 @@ impl GameDownloadAgent {
|
||||
|
||||
let sender = self.sender.clone();
|
||||
|
||||
let download_context = download_contexts
|
||||
.get(&bucket.version)
|
||||
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
|
||||
let download_context =
|
||||
download_contexts.get(&bucket.version).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"Could not get bucket version {}. Corrupted state.",
|
||||
bucket.version
|
||||
)
|
||||
});
|
||||
|
||||
scope.spawn(move |_| {
|
||||
// 3 attempts
|
||||
@ -687,7 +697,10 @@ impl Downloadable for GameDownloadAgent {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
error!("could not mark game as complete: {e}");
|
||||
send!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e)));
|
||||
send!(
|
||||
self.sender,
|
||||
DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,7 +11,9 @@ use std::{
|
||||
};
|
||||
|
||||
use download_manager::error::ApplicationDownloadError;
|
||||
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
||||
use download_manager::util::download_thread_control_flag::{
|
||||
DownloadThreadControl, DownloadThreadControlFlag,
|
||||
};
|
||||
use download_manager::util::progress_object::ProgressHandle;
|
||||
use log::{debug, info, warn};
|
||||
use md5::{Context, Digest};
|
||||
@ -47,7 +49,7 @@ impl DropWriter<File> {
|
||||
|
||||
fn finish(mut self) -> io::Result<Digest> {
|
||||
self.flush()?;
|
||||
Ok(self.hasher.compute())
|
||||
Ok(self.hasher.finalize())
|
||||
}
|
||||
}
|
||||
// Write automatically pushes to file and hasher
|
||||
@ -116,9 +118,12 @@ impl<'a> DropDownloadPipeline<'a, Response, File> {
|
||||
let mut last_bump = 0;
|
||||
loop {
|
||||
let size = MAX_PACKET_LENGTH.min(remaining);
|
||||
let size = self.source.read(&mut copy_buffer[0..size]).inspect_err(|_| {
|
||||
info!("got error from {}", drop.filename);
|
||||
})?;
|
||||
let size = self
|
||||
.source
|
||||
.read(&mut copy_buffer[0..size])
|
||||
.inspect_err(|_| {
|
||||
info!("got error from {}", drop.filename);
|
||||
})?;
|
||||
remaining -= size;
|
||||
last_bump += size;
|
||||
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
use std::{
|
||||
collections::HashMap, fs::File, io::{self, Read, Write}, path::{Path, PathBuf}
|
||||
collections::HashMap,
|
||||
fs::File,
|
||||
io::{self, Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use log::error;
|
||||
@ -77,7 +80,10 @@ impl DropData {
|
||||
}
|
||||
}
|
||||
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
|
||||
*lock!(self.contexts) = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
|
||||
*lock!(self.contexts) = completed_contexts
|
||||
.iter()
|
||||
.map(|s| (s.0.clone(), s.1))
|
||||
.collect();
|
||||
}
|
||||
pub fn set_context(&self, context: String, state: bool) {
|
||||
lock!(self.contexts).entry(context).insert_entry(state);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
use std::fmt::{Display};
|
||||
use std::fmt::Display;
|
||||
|
||||
use serde_with::SerializeDisplay;
|
||||
|
||||
@ -9,13 +9,21 @@ pub enum LibraryError {
|
||||
}
|
||||
impl Display for LibraryError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", match self {
|
||||
LibraryError::MetaNotFound(id) => {
|
||||
format!("Could not locate any installed version of game ID {id} in the database")
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match self {
|
||||
LibraryError::MetaNotFound(id) => {
|
||||
format!(
|
||||
"Could not locate any installed version of game ID {id} in the database"
|
||||
)
|
||||
}
|
||||
LibraryError::VersionNotFound(game_id) => {
|
||||
format!(
|
||||
"Could not locate any installed version for game id {game_id} in the database"
|
||||
)
|
||||
}
|
||||
}
|
||||
LibraryError::VersionNotFound(game_id) => {
|
||||
format!("Could not locate any installed version for game id {game_id} in the database")
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,5 +3,5 @@ mod download_logic;
|
||||
pub mod drop_data;
|
||||
pub mod error;
|
||||
mod manifest;
|
||||
pub mod utils;
|
||||
pub mod validate;
|
||||
pub mod utils;
|
||||
@ -19,7 +19,7 @@ pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownlo
|
||||
return Ok(disk.available_space());
|
||||
}
|
||||
}
|
||||
Err(ApplicationDownloadError::IoError(Arc::new(io::Error::other(
|
||||
"could not find disk of path",
|
||||
))))
|
||||
Err(ApplicationDownloadError::IoError(Arc::new(
|
||||
io::Error::other("could not find disk of path"),
|
||||
)))
|
||||
}
|
||||
|
||||
@ -3,7 +3,13 @@ use std::{
|
||||
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
||||
};
|
||||
|
||||
use download_manager::{error::ApplicationDownloadError, util::{download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::ProgressHandle}};
|
||||
use download_manager::{
|
||||
error::ApplicationDownloadError,
|
||||
util::{
|
||||
download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag},
|
||||
progress_object::ProgressHandle,
|
||||
},
|
||||
};
|
||||
use log::debug;
|
||||
use md5::Context;
|
||||
|
||||
@ -16,7 +22,10 @@ pub fn validate_game_chunk(
|
||||
) -> Result<bool, ApplicationDownloadError> {
|
||||
debug!(
|
||||
"Starting chunk validation {}, {}, {} #{}",
|
||||
ctx.path.display(), ctx.index, ctx.offset, ctx.checksum
|
||||
ctx.path.display(),
|
||||
ctx.index,
|
||||
ctx.offset,
|
||||
ctx.checksum
|
||||
);
|
||||
// If we're paused
|
||||
if control_flag.get() == DownloadThreadControlFlag::Stop {
|
||||
@ -36,13 +45,12 @@ pub fn validate_game_chunk(
|
||||
|
||||
let mut hasher = md5::Context::new();
|
||||
|
||||
let completed =
|
||||
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
|
||||
let completed = validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
|
||||
if !completed {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let res = hex::encode(hasher.compute().0);
|
||||
let res = hex::encode(hasher.finalize().0);
|
||||
if res != ctx.checksum {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
@ -3,5 +3,5 @@
|
||||
pub mod collections;
|
||||
pub mod downloads;
|
||||
pub mod library;
|
||||
pub mod scan;
|
||||
pub mod state;
|
||||
pub mod scan;
|
||||
@ -1,15 +1,20 @@
|
||||
use std::fs::remove_dir_all;
|
||||
use std::sync::Mutex;
|
||||
use std::thread::spawn;
|
||||
use bitcode::{Decode, Encode};
|
||||
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion};
|
||||
use database::{
|
||||
ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion,
|
||||
borrow_db_checked, borrow_db_mut_checked,
|
||||
};
|
||||
use log::{debug, error, warn};
|
||||
use remote::{auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url, utils::DROP_CLIENT_SYNC};
|
||||
use remote::{
|
||||
auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url,
|
||||
utils::DROP_CLIENT_SYNC,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use std::fs::remove_dir_all;
|
||||
use std::thread::spawn;
|
||||
use tauri::AppHandle;
|
||||
use utils::app_emit;
|
||||
|
||||
use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
|
||||
use crate::state::{GameStatusManager, GameStatusWithTransient};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct FetchGameStruct {
|
||||
@ -20,7 +25,11 @@ pub struct FetchGameStruct {
|
||||
|
||||
impl FetchGameStruct {
|
||||
pub fn new(game: Game, status: GameStatusWithTransient, version: Option<GameVersion>) -> Self {
|
||||
Self { game, status, version }
|
||||
Self {
|
||||
game,
|
||||
status,
|
||||
version,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -19,7 +19,7 @@ impl GameStatusManager {
|
||||
version: None,
|
||||
})
|
||||
.cloned();
|
||||
|
||||
|
||||
let offline_state = database.applications.game_statuses.get(game_id).cloned();
|
||||
|
||||
if online_state.is_some() {
|
||||
|
||||
@ -8,7 +8,12 @@ pub struct DropFormatArgs {
|
||||
}
|
||||
|
||||
impl DropFormatArgs {
|
||||
pub fn new(launch_string: String, working_dir: &String, executable_name: &String, absolute_executable_name: String) -> Self {
|
||||
pub fn new(
|
||||
launch_string: String,
|
||||
working_dir: &String,
|
||||
executable_name: &String,
|
||||
absolute_executable_name: String,
|
||||
) -> Self {
|
||||
let mut positional = Vec::new();
|
||||
let mut map: HashMap<&'static str, String> = HashMap::new();
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
|
||||
use std::{
|
||||
ops::Deref,
|
||||
sync::{LazyLock, OnceLock, nonpoison::Mutex},
|
||||
sync::{OnceLock, nonpoison::Mutex},
|
||||
};
|
||||
|
||||
use tauri::AppHandle;
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
|
||||
use database::{platform::Platform, Database, DownloadableMetadata, GameVersion};
|
||||
use database::{Database, DownloadableMetadata, GameVersion, platform::Platform};
|
||||
use log::debug;
|
||||
|
||||
|
||||
use crate::{error::ProcessError, process_manager::ProcessHandler};
|
||||
|
||||
pub struct NativeGameLauncher;
|
||||
@ -46,7 +45,9 @@ impl ProcessHandler for UMULauncher {
|
||||
};
|
||||
Ok(format!(
|
||||
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
||||
umu = UMU_LAUNCHER_EXECUTABLE.as_ref().expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
|
||||
umu = UMU_LAUNCHER_EXECUTABLE
|
||||
.as_ref()
|
||||
.expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
|
||||
launch = launch_command,
|
||||
args = args.join(" ")
|
||||
))
|
||||
@ -86,7 +87,12 @@ impl ProcessHandler for AsahiMuvmLauncher {
|
||||
.next()
|
||||
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
||||
.trim();
|
||||
let cmd = format!("umu-run{}", args_cmd.next().ok_or(ProcessError::InvalidArguments(umu_string.clone()))?);
|
||||
let cmd = format!(
|
||||
"umu-run{}",
|
||||
args_cmd
|
||||
.next()
|
||||
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
||||
);
|
||||
|
||||
Ok(format!("{args} muvm -- {cmd}"))
|
||||
}
|
||||
|
||||
@ -18,7 +18,6 @@ use dynfmt::Format;
|
||||
use dynfmt::SimpleCurlyFormat;
|
||||
use games::{library::push_game_update, state::GameStatusManager};
|
||||
use log::{debug, info, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use shared_child::SharedChild;
|
||||
use tauri::AppHandle;
|
||||
|
||||
|
||||
@ -2,14 +2,18 @@ use std::{collections::HashMap, env};
|
||||
|
||||
use chrono::Utc;
|
||||
use client::{app_status::AppStatus, user::User};
|
||||
use database::{interface::borrow_db_checked, DatabaseAuth};
|
||||
use database::{DatabaseAuth, interface::borrow_db_checked};
|
||||
use droplet_rs::ssl::sign_nonce;
|
||||
use gethostname::gethostname;
|
||||
use log::{error, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{error::{DropServerError, RemoteAccessError}, requests::make_authenticated_get, utils::DROP_CLIENT_SYNC};
|
||||
use crate::{
|
||||
error::{DropServerError, RemoteAccessError},
|
||||
requests::make_authenticated_get,
|
||||
utils::DROP_CLIENT_SYNC,
|
||||
};
|
||||
|
||||
use super::{
|
||||
cache::{cache_object, get_cached_object},
|
||||
|
||||
@ -15,8 +15,8 @@ use crate::error::{CacheError, RemoteAccessError};
|
||||
macro_rules! offline {
|
||||
($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => {
|
||||
|
||||
async move {
|
||||
if ::database::borrow_db_checked().settings.force_offline
|
||||
async move {
|
||||
if ::database::borrow_db_checked().settings.force_offline
|
||||
|| $var.lock().status == ::client::app_status::AppStatus::Offline {
|
||||
$func2( $( $arg ), *).await
|
||||
} else {
|
||||
|
||||
@ -4,7 +4,7 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use http::{header::ToStrError, HeaderName, StatusCode};
|
||||
use http::{HeaderName, StatusCode, header::ToStrError};
|
||||
use serde_with::SerializeDisplay;
|
||||
use url::ParseError;
|
||||
|
||||
@ -19,7 +19,6 @@ pub struct DropServerError {
|
||||
// pub url: String,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, SerializeDisplay)]
|
||||
pub enum RemoteAccessError {
|
||||
FetchError(Arc<reqwest::Error>),
|
||||
@ -120,17 +119,25 @@ pub enum CacheError {
|
||||
HeaderNotFound(HeaderName),
|
||||
ParseError(ToStrError),
|
||||
Remote(RemoteAccessError),
|
||||
ConstructionError(http::Error)
|
||||
ConstructionError(http::Error),
|
||||
}
|
||||
|
||||
impl Display for CacheError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let s = match self {
|
||||
CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
|
||||
CacheError::ParseError(to_str_error) => format!("Could not parse cache with error {to_str_error}"),
|
||||
CacheError::Remote(remote_access_error) => format!("Cache got remote access error: {remote_access_error}"),
|
||||
CacheError::ConstructionError(error) => format!("Could not construct cache body with error {error}"),
|
||||
CacheError::HeaderNotFound(header_name) => {
|
||||
format!("Could not find header {header_name} in cache")
|
||||
}
|
||||
CacheError::ParseError(to_str_error) => {
|
||||
format!("Could not parse cache with error {to_str_error}")
|
||||
}
|
||||
CacheError::Remote(remote_access_error) => {
|
||||
format!("Cache got remote access error: {remote_access_error}")
|
||||
}
|
||||
CacheError::ConstructionError(error) => {
|
||||
format!("Could not construct cache body with error {error}")
|
||||
}
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
use database::{interface::DatabaseImpls, DB};
|
||||
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
|
||||
use database::{DB, interface::DatabaseImpls};
|
||||
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
||||
use log::{debug, warn};
|
||||
use tauri::UriSchemeResponder;
|
||||
|
||||
@ -15,13 +15,19 @@ pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: Ur
|
||||
Ok(r) => responder.respond(r),
|
||||
Err(e) => {
|
||||
warn!("Cache error: {e}");
|
||||
responder.respond(Response::builder().status(500).body(Vec::new()).expect("Failed to build error response"));
|
||||
responder.respond(
|
||||
Response::builder()
|
||||
.status(500)
|
||||
.body(Vec::new())
|
||||
.expect("Failed to build error response"),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Vec<u8>>, CacheError>
|
||||
{
|
||||
pub async fn fetch_object(
|
||||
request: http::Request<Vec<u8>>,
|
||||
) -> Result<Response<Vec<u8>>, CacheError> {
|
||||
// Drop leading /
|
||||
let object_id = &request.uri().path()[1..];
|
||||
|
||||
@ -48,13 +54,13 @@ pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Ve
|
||||
let data = match r.bytes().await {
|
||||
Ok(data) => Vec::from(data),
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Could not get data from cache object {object_id} with error {e}",
|
||||
);
|
||||
warn!("Could not get data from cache object {object_id} with error {e}",);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let resp = resp_builder.body(data).expect("Failed to build object cache response body");
|
||||
let resp = resp_builder
|
||||
.body(data)
|
||||
.expect("Failed to build object cache response body");
|
||||
if cache_result.map_or(true, |x| x.has_expired()) {
|
||||
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
|
||||
.expect("Failed to create cached object");
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
pub mod auth;
|
||||
#[macro_use]
|
||||
pub mod cache;
|
||||
pub mod error;
|
||||
pub mod fetch_object;
|
||||
pub mod requests;
|
||||
pub mod server_proto;
|
||||
pub mod utils;
|
||||
pub mod error;
|
||||
|
||||
pub use auth::setup;
|
||||
pub use auth::setup;
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
use database::{interface::DatabaseImpls, DB};
|
||||
use database::{DB, interface::DatabaseImpls};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
|
||||
@ -1,26 +1,30 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use database::borrow_db_checked;
|
||||
use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
|
||||
use http::{Request, Response, StatusCode, Uri, uri::PathAndQuery};
|
||||
use log::{error, warn};
|
||||
use tauri::UriSchemeResponder;
|
||||
use utils::webbrowser_open::webbrowser_open;
|
||||
|
||||
use crate::utils::DROP_CLIENT_SYNC;
|
||||
|
||||
pub async fn handle_server_proto_offline_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||
pub async fn handle_server_proto_offline_wrapper(
|
||||
request: Request<Vec<u8>>,
|
||||
responder: UriSchemeResponder,
|
||||
) {
|
||||
responder.respond(match handle_server_proto_offline(request).await {
|
||||
Ok(res) => res,
|
||||
Err(_) => unreachable!()
|
||||
Err(_) => unreachable!(),
|
||||
});
|
||||
}
|
||||
|
||||
pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode>{
|
||||
pub async fn handle_server_proto_offline(
|
||||
_request: Request<Vec<u8>>,
|
||||
) -> Result<Response<Vec<u8>>, StatusCode> {
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Vec::new())
|
||||
.expect("Failed to build error response for proto offline"))
|
||||
|
||||
}
|
||||
|
||||
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||
@ -28,7 +32,12 @@ pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: U
|
||||
Ok(r) => responder.respond(r),
|
||||
Err(e) => {
|
||||
warn!("Cache error: {e}");
|
||||
responder.respond(Response::builder().status(e).body(Vec::new()).expect("Failed to build error response"));
|
||||
responder.respond(
|
||||
Response::builder()
|
||||
.status(e)
|
||||
.body(Vec::new())
|
||||
.expect("Failed to build error response"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -39,20 +48,25 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
|
||||
Some(auth) => auth,
|
||||
None => {
|
||||
error!("Could not find auth in database");
|
||||
return Err(StatusCode::UNAUTHORIZED)
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
};
|
||||
let web_token = match &auth.web_token {
|
||||
Some(token) => token,
|
||||
None => return Err(StatusCode::UNAUTHORIZED),
|
||||
};
|
||||
let remote_uri = db_handle.base_url.parse::<Uri>().expect("Failed to parse base url");
|
||||
let remote_uri = db_handle
|
||||
.base_url
|
||||
.parse::<Uri>()
|
||||
.expect("Failed to parse base url");
|
||||
|
||||
let path = request.uri().path();
|
||||
|
||||
let mut new_uri = request.uri().clone().into_parts();
|
||||
new_uri.path_and_query =
|
||||
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
|
||||
new_uri.path_and_query = Some(
|
||||
PathAndQuery::from_str(&format!("{path}?noWrapper=true"))
|
||||
.expect("Failed to parse request path in proto"),
|
||||
);
|
||||
new_uri.authority = remote_uri.authority().cloned();
|
||||
new_uri.scheme = remote_uri.scheme().cloned();
|
||||
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
|
||||
@ -62,7 +76,7 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
|
||||
|
||||
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
|
||||
webbrowser_open(new_uri.to_string());
|
||||
return Ok(Response::new(Vec::new()))
|
||||
return Ok(Response::new(Vec::new()));
|
||||
}
|
||||
|
||||
let client = DROP_CLIENT_SYNC.clone();
|
||||
@ -70,13 +84,14 @@ async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u
|
||||
.request(request.method().clone(), new_uri.to_string())
|
||||
.header("Authorization", format!("Bearer {web_token}"))
|
||||
.headers(request.headers().clone())
|
||||
.send() {
|
||||
Ok(response) => response,
|
||||
Err(e) => {
|
||||
warn!("Could not send response. Got {e} when sending");
|
||||
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST))
|
||||
},
|
||||
};
|
||||
.send()
|
||||
{
|
||||
Ok(response) => response,
|
||||
Err(e) => {
|
||||
warn!("Could not send response. Got {e} when sending");
|
||||
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST));
|
||||
}
|
||||
};
|
||||
|
||||
let response_status = response.status();
|
||||
let response_body = match response.bytes() {
|
||||
|
||||
@ -15,7 +15,7 @@ pub struct DropHealthcheck {
|
||||
app_name: String,
|
||||
}
|
||||
impl DropHealthcheck {
|
||||
pub fn app_name(&self) -> &String{
|
||||
pub fn app_name(&self) -> &String {
|
||||
&self.app_name
|
||||
}
|
||||
}
|
||||
@ -46,11 +46,13 @@ fn fetch_certificates() -> Vec<Certificate> {
|
||||
}
|
||||
}
|
||||
.read_to_end(&mut buf)
|
||||
.unwrap_or_else(|e| panic!(
|
||||
"Failed to read to end of certificate file {} with error {}",
|
||||
c.path().display(),
|
||||
e
|
||||
));
|
||||
.unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Failed to read to end of certificate file {} with error {}",
|
||||
c.path().display(),
|
||||
e
|
||||
)
|
||||
});
|
||||
|
||||
match Certificate::from_pem_bundle(&buf) {
|
||||
Ok(certificates) => {
|
||||
@ -87,7 +89,10 @@ pub fn get_client_sync() -> reqwest::blocking::Client {
|
||||
for cert in DROP_CERT_BUNDLE.iter() {
|
||||
client = client.add_root_certificate(cert.clone());
|
||||
}
|
||||
client.use_rustls_tls().build().expect("Failed to build synchronous client")
|
||||
client
|
||||
.use_rustls_tls()
|
||||
.build()
|
||||
.expect("Failed to build synchronous client")
|
||||
}
|
||||
pub fn get_client_async() -> reqwest::Client {
|
||||
let mut client = reqwest::ClientBuilder::new();
|
||||
@ -95,7 +100,10 @@ pub fn get_client_async() -> reqwest::Client {
|
||||
for cert in DROP_CERT_BUNDLE.iter() {
|
||||
client = client.add_root_certificate(cert.clone());
|
||||
}
|
||||
client.use_rustls_tls().build().expect("Failed to build asynchronous client")
|
||||
client
|
||||
.use_rustls_tls()
|
||||
.build()
|
||||
.expect("Failed to build asynchronous client")
|
||||
}
|
||||
pub fn get_client_ws() -> reqwest::Client {
|
||||
let mut client = reqwest::ClientBuilder::new();
|
||||
@ -108,4 +116,4 @@ pub fn get_client_ws() -> reqwest::Client {
|
||||
.http1_only()
|
||||
.build()
|
||||
.expect("Failed to build websocket client")
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,14 +5,11 @@ use download_manager::DOWNLOAD_MANAGER;
|
||||
use log::{debug, error};
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_autostart::ManagerExt;
|
||||
use utils::lock;
|
||||
|
||||
use crate::{AppState};
|
||||
use crate::AppState;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn fetch_state(
|
||||
state: tauri::State<'_, Mutex<AppState>>,
|
||||
) -> Result<String, String> {
|
||||
pub fn fetch_state(state: tauri::State<'_, Mutex<AppState>>) -> Result<String, String> {
|
||||
let guard = state.lock();
|
||||
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
||||
drop(guard);
|
||||
@ -20,7 +17,7 @@ pub fn fetch_state(
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
|
||||
@ -1,8 +1,13 @@
|
||||
use games::collections::collection::{Collection, Collections};
|
||||
use remote::{auth::generate_authorization_header, cache::{cache_object, get_cached_object}, error::RemoteAccessError, requests::{generate_url, make_authenticated_get}, utils::DROP_CLIENT_ASYNC};
|
||||
use remote::{
|
||||
auth::generate_authorization_header,
|
||||
cache::{cache_object, get_cached_object},
|
||||
error::RemoteAccessError,
|
||||
requests::{generate_url, make_authenticated_get},
|
||||
utils::DROP_CLIENT_ASYNC,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn fetch_collections(
|
||||
hard_refresh: Option<bool>,
|
||||
|
||||
@ -12,10 +12,7 @@ pub fn resume_downloads() {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn move_download_in_queue(
|
||||
old_index: usize,
|
||||
new_index: usize,
|
||||
) {
|
||||
pub fn move_download_in_queue(old_index: usize, new_index: usize) {
|
||||
DOWNLOAD_MANAGER.rearrange(old_index, new_index);
|
||||
}
|
||||
|
||||
|
||||
@ -1,9 +1,6 @@
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use database::{borrow_db_checked, GameDownloadStatus};
|
||||
use database::{GameDownloadStatus, borrow_db_checked};
|
||||
use download_manager::{
|
||||
DOWNLOAD_MANAGER, downloadable::Downloadable, error::ApplicationDownloadError,
|
||||
};
|
||||
|
||||
@ -1,16 +1,25 @@
|
||||
use std::sync::nonpoison::Mutex;
|
||||
|
||||
use database::{borrow_db_checked, borrow_db_mut_checked, GameDownloadStatus, GameVersion};
|
||||
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, FrontendGameOptions, Game}, state::{GameStatusManager, GameStatusWithTransient}};
|
||||
use database::{GameDownloadStatus, GameVersion, borrow_db_checked, borrow_db_mut_checked};
|
||||
use games::{
|
||||
downloads::error::LibraryError,
|
||||
library::{FetchGameStruct, FrontendGameOptions, Game, get_current_meta, uninstall_game_logic},
|
||||
state::{GameStatusManager, GameStatusWithTransient},
|
||||
};
|
||||
use log::warn;
|
||||
use process::PROCESS_MANAGER;
|
||||
use remote::{auth::generate_authorization_header, cache::{cache_object, cache_object_db, get_cached_object, get_cached_object_db}, error::{DropServerError, RemoteAccessError}, offline, requests::generate_url, utils::DROP_CLIENT_ASYNC};
|
||||
use remote::{
|
||||
auth::generate_authorization_header,
|
||||
cache::{cache_object, cache_object_db, get_cached_object, get_cached_object_db},
|
||||
error::{DropServerError, RemoteAccessError},
|
||||
offline,
|
||||
requests::generate_url,
|
||||
utils::DROP_CLIENT_ASYNC,
|
||||
};
|
||||
use tauri::AppHandle;
|
||||
use utils::lock;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn fetch_library(
|
||||
state: tauri::State<'_, Mutex<AppState>>,
|
||||
@ -22,10 +31,10 @@ pub async fn fetch_library(
|
||||
fetch_library_logic_offline,
|
||||
state,
|
||||
hard_refresh
|
||||
).await
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
|
||||
pub async fn fetch_library_logic(
|
||||
state: tauri::State<'_, Mutex<AppState>>,
|
||||
hard_fresh: Option<bool>,
|
||||
@ -228,7 +237,6 @@ pub async fn fetch_game_version_options_logic(
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
|
||||
pub async fn fetch_game_logic_offline(
|
||||
id: String,
|
||||
_state: tauri::State<'_, Mutex<AppState>>,
|
||||
@ -264,7 +272,8 @@ pub async fn fetch_game(
|
||||
fetch_game_logic_offline,
|
||||
game_id,
|
||||
state
|
||||
).await
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@ -305,7 +314,10 @@ pub fn update_game_configuration(
|
||||
.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 version = installed_version
|
||||
.version
|
||||
.clone()
|
||||
.ok_or(LibraryError::VersionNotFound(id.clone()))?;
|
||||
|
||||
let mut existing_configuration = handle
|
||||
.applications
|
||||
|
||||
@ -8,25 +8,16 @@
|
||||
#![deny(clippy::all)]
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env,
|
||||
fs::File,
|
||||
io::Write,
|
||||
panic::PanicHookInfo,
|
||||
path::Path,
|
||||
str::FromStr,
|
||||
sync::nonpoison::Mutex,
|
||||
time::SystemTime,
|
||||
collections::HashMap, env, fs::File, io::Write, panic::PanicHookInfo, path::Path, str::FromStr,
|
||||
sync::nonpoison::Mutex, time::SystemTime,
|
||||
};
|
||||
|
||||
use ::client::{
|
||||
app_status::AppStatus, autostart::sync_autostart_on_startup, compat::CompatInfo, user::User,
|
||||
};
|
||||
use ::client::{app_status::AppStatus, autostart::sync_autostart_on_startup, user::User};
|
||||
use ::download_manager::DownloadManagerWrapper;
|
||||
use ::games::{library::Game, scan::scan_install_dirs};
|
||||
use ::process::ProcessManagerWrapper;
|
||||
use ::remote::{
|
||||
auth::{self, generate_authorization_header, HandshakeRequestBody, HandshakeResponse},
|
||||
auth::{self, HandshakeRequestBody, HandshakeResponse, generate_authorization_header},
|
||||
cache::clear_cached_object,
|
||||
error::RemoteAccessError,
|
||||
fetch_object::fetch_object_wrapper,
|
||||
@ -54,17 +45,17 @@ use tauri::{
|
||||
use tauri_plugin_deep_link::DeepLinkExt;
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
use url::Url;
|
||||
use utils::{app_emit, lock};
|
||||
use utils::app_emit;
|
||||
|
||||
use crate::client::cleanup_and_exit;
|
||||
|
||||
mod games;
|
||||
mod client;
|
||||
mod process;
|
||||
mod remote;
|
||||
mod collections;
|
||||
mod download_manager;
|
||||
mod downloads;
|
||||
mod games;
|
||||
mod process;
|
||||
mod remote;
|
||||
mod settings;
|
||||
|
||||
use client::*;
|
||||
@ -76,7 +67,6 @@ use process::*;
|
||||
use remote::*;
|
||||
use settings::*;
|
||||
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AppState {
|
||||
@ -330,7 +320,6 @@ pub fn run() {
|
||||
}
|
||||
};
|
||||
if let Some("handshake") = url.host_str() {
|
||||
|
||||
tauri::async_runtime::spawn(recieve_handshake(
|
||||
handle.clone(),
|
||||
url.path().to_string(),
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
use std::sync::nonpoison::Mutex;
|
||||
|
||||
use process::{error::ProcessError, PROCESS_MANAGER};
|
||||
use process::{PROCESS_MANAGER, error::ProcessError};
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
use utils::lock;
|
||||
|
||||
use crate::AppState;
|
||||
|
||||
@ -32,9 +31,7 @@ pub fn launch_game(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn kill_game(
|
||||
game_id: String,
|
||||
) -> Result<(), ProcessError> {
|
||||
pub fn kill_game(game_id: String) -> Result<(), ProcessError> {
|
||||
PROCESS_MANAGER
|
||||
.lock()
|
||||
.kill_game(game_id)
|
||||
@ -42,10 +39,7 @@ pub fn kill_game(
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn open_process_logs(
|
||||
game_id: String,
|
||||
app_handle: AppHandle
|
||||
) -> Result<(), ProcessError> {
|
||||
pub fn open_process_logs(game_id: String, app_handle: AppHandle) -> Result<(), ProcessError> {
|
||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
||||
|
||||
let dir = process_manager_lock.get_log_dir(game_id);
|
||||
|
||||
@ -4,14 +4,21 @@ use client::app_status::AppStatus;
|
||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
||||
use futures_lite::StreamExt;
|
||||
use log::{debug, warn};
|
||||
use remote::{auth::{auth_initiate_logic, generate_authorization_header}, cache::{cache_object, get_cached_object}, error::RemoteAccessError, requests::generate_url, setup, utils::{DropHealthcheck, DROP_CLIENT_ASYNC, DROP_CLIENT_WS_CLIENT}};
|
||||
use remote::{
|
||||
auth::{auth_initiate_logic, generate_authorization_header},
|
||||
cache::{cache_object, get_cached_object},
|
||||
error::RemoteAccessError,
|
||||
requests::generate_url,
|
||||
setup,
|
||||
utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_WS_CLIENT, DropHealthcheck},
|
||||
};
|
||||
use reqwest_websocket::{Message, RequestBuilderExt};
|
||||
use serde::Deserialize;
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use tauri::{AppHandle, Manager};
|
||||
use url::Url;
|
||||
use utils::{app_emit, lock, webbrowser_open::webbrowser_open};
|
||||
use utils::{app_emit, webbrowser_open::webbrowser_open};
|
||||
|
||||
use crate::{recieve_handshake, AppState};
|
||||
use crate::{AppState, recieve_handshake};
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn use_remote(
|
||||
|
||||
@ -4,7 +4,9 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use database::{borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, debug::SystemData, Settings};
|
||||
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;
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
#[macro_export]
|
||||
macro_rules! app_emit {
|
||||
($app:expr, $event:expr, $p:expr) => {
|
||||
::tauri::Emitter::emit($app, $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_rules! send {
|
||||
($download_manager:expr, $signal:expr) => {
|
||||
$download_manager.send($signal).unwrap_or_else(|_| panic!("Failed to send signal {} to the download manager", stringify!(signal)))
|
||||
$download_manager.send($signal).unwrap_or_else(|_| {
|
||||
panic!(
|
||||
"Failed to send signal {} to the download manager",
|
||||
stringify!(signal)
|
||||
)
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
#[macro_export]
|
||||
macro_rules! lock {
|
||||
($mutex:expr) => {
|
||||
$mutex.lock().unwrap_or_else(|_| panic!("Failed to lock onto {}", stringify!($mutex)))
|
||||
$mutex
|
||||
.lock()
|
||||
.unwrap_or_else(|_| panic!("Failed to lock onto {}", stringify!($mutex)))
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,10 @@ use log::warn;
|
||||
|
||||
pub fn webbrowser_open<T: AsRef<str>>(url: T) {
|
||||
if let Err(e) = webbrowser::open(url.as_ref()) {
|
||||
warn!("Could not open web browser to url {} with error {}", url.as_ref(), e);
|
||||
warn!(
|
||||
"Could not open web browser to url {} with error {}",
|
||||
url.as_ref(),
|
||||
e
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user