mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-13 16:22:43 +10:00
Compare commits
3 Commits
160-generi
...
5d22b883d5
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d22b883d5 | |||
| 62a2561539 | |||
| 59f040bc8b |
8288
Cargo.lock
generated
Normal file
8288
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
Normal file
14
Cargo.toml
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
[workspace]
|
||||||
|
members = [
|
||||||
|
"client",
|
||||||
|
"database",
|
||||||
|
"src-tauri",
|
||||||
|
"process",
|
||||||
|
"remote",
|
||||||
|
"utils",
|
||||||
|
"cloud_saves",
|
||||||
|
"download_manager",
|
||||||
|
"games",
|
||||||
|
]
|
||||||
|
|
||||||
|
resolver = "3"
|
||||||
@ -6,7 +6,6 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
bitcode = "0.6.7"
|
bitcode = "0.6.7"
|
||||||
database = { version = "0.1.0", path = "../database" }
|
database = { version = "0.1.0", path = "../database" }
|
||||||
drop-consts = { version = "0.1.0", path = "../drop-consts" }
|
|
||||||
log = "0.4.28"
|
log = "0.4.28"
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
tauri = "2.8.5"
|
tauri = "2.8.5"
|
||||||
@ -1,11 +1,5 @@
|
|||||||
use std::{
|
use std::{ffi::OsStr, path::PathBuf, process::{Command, Stdio}, sync::LazyLock};
|
||||||
ffi::OsStr,
|
|
||||||
path::PathBuf,
|
|
||||||
process::{Command, Stdio},
|
|
||||||
sync::LazyLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
use drop_consts::{UMU_BASE_LAUNCHER_EXECUTABLE, UMU_INSTALL_DIRS};
|
|
||||||
use log::info;
|
use log::info;
|
||||||
|
|
||||||
pub static COMPAT_INFO: LazyLock<Option<CompatInfo>> = LazyLock::new(create_new_compat_info);
|
pub static COMPAT_INFO: LazyLock<Option<CompatInfo>> = LazyLock::new(create_new_compat_info);
|
||||||
@ -31,6 +25,9 @@ fn create_new_compat_info() -> Option<CompatInfo> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const UMU_BASE_LAUNCHER_EXECUTABLE: &str = "umu-run";
|
||||||
|
const UMU_INSTALL_DIRS: [&str; 4] = ["/app/share", "/use/local/share", "/usr/share", "/opt"];
|
||||||
|
|
||||||
fn get_umu_executable() -> Option<PathBuf> {
|
fn get_umu_executable() -> Option<PathBuf> {
|
||||||
if check_executable_exists(UMU_BASE_LAUNCHER_EXECUTABLE) {
|
if check_executable_exists(UMU_BASE_LAUNCHER_EXECUTABLE) {
|
||||||
return Some(PathBuf::from(UMU_BASE_LAUNCHER_EXECUTABLE));
|
return Some(PathBuf::from(UMU_BASE_LAUNCHER_EXECUTABLE));
|
||||||
4
client/src/lib.rs
Normal file
4
client/src/lib.rs
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
pub mod autostart;
|
||||||
|
pub mod user;
|
||||||
|
pub mod app_status;
|
||||||
|
pub mod compat;
|
||||||
@ -10,3 +10,4 @@ pub struct User {
|
|||||||
display_name: String,
|
display_name: String,
|
||||||
profile_picture_object_id: String,
|
profile_picture_object_id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -6,7 +6,6 @@ edition = "2024"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
database = { version = "0.1.0", path = "../database" }
|
database = { version = "0.1.0", path = "../database" }
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
drop-consts = { version = "0.1.0", path = "../drop-consts" }
|
|
||||||
log = "0.4.28"
|
log = "0.4.28"
|
||||||
regex = "1.11.3"
|
regex = "1.11.3"
|
||||||
rustix = "1.1.2"
|
rustix = "1.1.2"
|
||||||
105
cloud_saves/src/backup_manager.rs
Normal file
105
cloud_saves/src/backup_manager.rs
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
use database::platform::Platform;
|
||||||
|
use database::{db::DATA_ROOT_DIR, GameVersion};
|
||||||
|
use log::warn;
|
||||||
|
|
||||||
|
use crate::error::BackupError;
|
||||||
|
|
||||||
|
use super::path::CommonPath;
|
||||||
|
|
||||||
|
pub struct BackupManager<'a> {
|
||||||
|
pub current_platform: Platform,
|
||||||
|
pub sources: HashMap<(Platform, Platform), &'a (dyn BackupHandler + Sync + Send)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BackupManager<'_> {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
BackupManager {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
current_platform: Platform::Windows,
|
||||||
|
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
current_platform: Platform::MacOs,
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
current_platform: Platform::Linux,
|
||||||
|
|
||||||
|
sources: HashMap::from([
|
||||||
|
// Current platform to target platform
|
||||||
|
(
|
||||||
|
(Platform::Windows, Platform::Windows),
|
||||||
|
&WindowsBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
(Platform::Linux, Platform::Linux),
|
||||||
|
&LinuxBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
(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()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
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_data_translate(&self, _path: &PathBuf,_game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(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_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_low_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> {
|
||||||
|
Ok(CommonPath::DataLocalLow.get().ok_or(BackupError::NotFound)?)
|
||||||
|
}
|
||||||
|
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_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)?)
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub struct MacBackupManager {}
|
||||||
|
impl BackupHandler for MacBackupManager {}
|
||||||
@ -2,6 +2,5 @@ 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 placeholder;
|
pub mod backup_manager;
|
||||||
pub mod resolver;
|
pub mod error;
|
||||||
@ -1,6 +1,7 @@
|
|||||||
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 {
|
||||||
@ -15,17 +16,15 @@ 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(
|
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
|
||||||
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,6 +5,7 @@ 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('\\', "/");
|
||||||
|
|
||||||
@ -13,25 +14,18 @@ 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> =
|
static UNNECESSARY_DOUBLE_STAR_1: 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 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> =
|
static APP_DATA_ROAMING: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Roaming").unwrap());
|
||||||
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: LazyLock<Regex> =
|
static APP_DATA_LOCAL_2: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/AppData/Local/").unwrap());
|
||||||
LazyLock::new(|| Regex::new(r"(?i)%localappdata%").unwrap());
|
static USER_PROFILE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%").unwrap());
|
||||||
static APP_DATA_LOCAL_2: LazyLock<Regex> =
|
static DOCUMENTS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)%userprofile%/Documents").unwrap());
|
||||||
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, "/"),
|
||||||
@ -72,9 +66,7 @@ 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 {
|
use {BASE, HOME, ROOT, STORE_USER_ID, WIN_APP_DATA, WIN_DIR, WIN_DOCUMENTS, XDG_CONFIG, XDG_DATA};
|
||||||
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();
|
||||||
|
|
||||||
@ -85,9 +77,7 @@ fn too_broad(path: &str) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for item in AVOID_WILDCARDS {
|
for item in AVOID_WILDCARDS {
|
||||||
if path.starts_with(&format!("{}/*", item))
|
if path.starts_with(&format!("{}/*", item)) || path.starts_with(&format!("{}/{}", item, STORE_USER_ID)) {
|
||||||
|| path.starts_with(&format!("{}/{}", item, STORE_USER_ID))
|
|
||||||
{
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -135,6 +125,7 @@ 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,13 +1,17 @@
|
|||||||
use std::{
|
use std::{
|
||||||
fs::{self, File, create_dir_all},
|
fs::{self, create_dir_all, File},
|
||||||
io::{self, Read, Write},
|
io::{self, ErrorKind, Read, Write},
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
|
thread::sleep,
|
||||||
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::error::BackupError;
|
use crate::error::BackupError;
|
||||||
|
|
||||||
use super::{backup_manager::BackupHandler, placeholder::*};
|
use super::{
|
||||||
use database::GameVersion;
|
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
||||||
|
};
|
||||||
|
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;
|
||||||
@ -26,7 +30,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()
|
||||||
{
|
{
|
||||||
@ -59,7 +63,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_all(serialized).unwrap();
|
file.write(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()
|
||||||
}
|
}
|
||||||
@ -92,7 +96,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()
|
||||||
{
|
{
|
||||||
@ -111,7 +115,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 {:?}",
|
||||||
@ -128,22 +132,23 @@ 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::other(
|
return Err(io::Error::new(
|
||||||
|
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),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@ -152,7 +157,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?;
|
||||||
@ -214,3 +219,43 @@ 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();
|
||||||
|
}
|
||||||
0
cloud_saves/src/strict_path.rs
Normal file
0
cloud_saves/src/strict_path.rs
Normal file
@ -4,10 +4,8 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bitcode = "0.6.7"
|
|
||||||
chrono = "0.4.42"
|
chrono = "0.4.42"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
drop-consts = { version = "0.1.0", path = "../drop-consts" }
|
|
||||||
log = "0.4.28"
|
log = "0.4.28"
|
||||||
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
||||||
rustbreak = "2.0.0"
|
rustbreak = "2.0.0"
|
||||||
@ -3,18 +3,25 @@ use std::{
|
|||||||
sync::{Arc, LazyLock},
|
sync::{Arc, LazyLock},
|
||||||
};
|
};
|
||||||
|
|
||||||
use drop_consts::DATA_ROOT_PREFIX;
|
|
||||||
use rustbreak::{DeSerError, DeSerializer};
|
use rustbreak::{DeSerError, DeSerializer};
|
||||||
use serde::{Serialize, de::DeserializeOwned};
|
use serde::{Serialize, de::DeserializeOwned};
|
||||||
|
|
||||||
use crate::{interface::DatabaseImpls, models::DatabaseInterface};
|
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);
|
||||||
|
|
||||||
pub static DATA_ROOT_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
|
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
static DATA_ROOT_PREFIX: &str = "drop";
|
||||||
|
#[cfg(debug_assertions)]
|
||||||
|
static DATA_ROOT_PREFIX: &str = "drop-debug";
|
||||||
|
|
||||||
|
pub static DATA_ROOT_DIR: LazyLock<Arc<PathBuf>> = LazyLock::new(|| {
|
||||||
|
Arc::new(
|
||||||
dirs::data_dir()
|
dirs::data_dir()
|
||||||
.expect("Failed to get data dir")
|
.expect("Failed to get data dir")
|
||||||
.join(DATA_ROOT_PREFIX)
|
.join(DATA_ROOT_PREFIX),
|
||||||
|
)
|
||||||
});
|
});
|
||||||
|
|
||||||
// Custom JSON serializer to support everything we need
|
// Custom JSON serializer to support everything we need
|
||||||
@ -25,15 +32,16 @@ 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).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> {
|
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) =
|
let (val, _version) = native_model::decode(buf)
|
||||||
native_model::decode(buf).map_err(|e| DeSerError::Internal(e.to_string()))?;
|
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||||
Ok(val)
|
Ok(val)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,22 +1,19 @@
|
|||||||
use std::{
|
use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}};
|
||||||
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 crate::{
|
use crate::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database};
|
||||||
db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB},
|
|
||||||
models::{Database, DatabaseInterface},
|
pub type DatabaseInterface =
|
||||||
};
|
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||||
|
|
||||||
pub trait DatabaseImpls {
|
pub trait DatabaseImpls {
|
||||||
fn set_up_database() -> DatabaseInterface;
|
fn set_up_database() -> DatabaseInterface;
|
||||||
|
fn database_is_set_up(&self) -> bool;
|
||||||
|
fn fetch_base_url(&self) -> Url;
|
||||||
}
|
}
|
||||||
impl DatabaseImpls for DatabaseInterface {
|
impl DatabaseImpls for DatabaseInterface {
|
||||||
fn set_up_database() -> DatabaseInterface {
|
fn set_up_database() -> DatabaseInterface {
|
||||||
@ -82,6 +79,16 @@ impl DatabaseImpls for DatabaseInterface {
|
|||||||
PathDatabase::create_at_path(db_path, default).expect("Database could not be created")
|
PathDatabase::create_at_path(db_path, default).expect("Database could not be created")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn database_is_set_up(&self) -> bool {
|
||||||
|
!borrow_db_checked().base_url.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fetch_base_url(&self) -> Url {
|
||||||
|
let handle = borrow_db_checked();
|
||||||
|
Url::parse(&handle.base_url)
|
||||||
|
.unwrap_or_else(|_| panic!("Failed to parse base url {}", handle.base_url))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Make the error relelvant rather than just assume that it's a Deserialize error
|
// TODO: Make the error relelvant rather than just assume that it's a Deserialize error
|
||||||
21
database/src/lib.rs
Normal file
21
database/src/lib.rs
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
#![feature(nonpoison_rwlock)]
|
||||||
|
|
||||||
|
pub mod db;
|
||||||
|
pub mod debug;
|
||||||
|
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};
|
||||||
363
database/src/models.rs
Normal file
363
database/src/models.rs
Normal file
@ -0,0 +1,363 @@
|
|||||||
|
pub mod data {
|
||||||
|
use std::{hash::Hash, path::PathBuf};
|
||||||
|
|
||||||
|
use native_model::native_model;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
pub type Database = v3::Database;
|
||||||
|
pub type Settings = v1::Settings;
|
||||||
|
pub type DatabaseAuth = v1::DatabaseAuth;
|
||||||
|
|
||||||
|
pub type GameDownloadStatus = v2::GameDownloadStatus;
|
||||||
|
pub type ApplicationTransientStatus = v1::ApplicationTransientStatus;
|
||||||
|
/**
|
||||||
|
* Need to be universally accessible by the ID, and the version is just a couple sprinkles on top
|
||||||
|
*/
|
||||||
|
pub type DownloadableMetadata = v1::DownloadableMetadata;
|
||||||
|
pub type DownloadType = v1::DownloadType;
|
||||||
|
pub type DatabaseApplications = v2::DatabaseApplications;
|
||||||
|
// pub type DatabaseCompatInfo = v2::DatabaseCompatInfo;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
impl PartialEq for DownloadableMetadata {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.id == other.id && self.download_type == other.download_type
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Hash for DownloadableMetadata {
|
||||||
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||||
|
self.id.hash(state);
|
||||||
|
self.download_type.hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod v1 {
|
||||||
|
use serde_with::serde_as;
|
||||||
|
use std::{collections::HashMap, path::PathBuf};
|
||||||
|
|
||||||
|
use crate::platform::Platform;
|
||||||
|
|
||||||
|
use super::{Deserialize, Serialize, native_model};
|
||||||
|
|
||||||
|
fn default_template() -> String {
|
||||||
|
"{}".to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[native_model(id = 2, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
pub struct GameVersion {
|
||||||
|
pub game_id: String,
|
||||||
|
pub version_name: String,
|
||||||
|
|
||||||
|
pub platform: Platform,
|
||||||
|
|
||||||
|
pub launch_command: String,
|
||||||
|
pub launch_args: Vec<String>,
|
||||||
|
#[serde(default = "default_template")]
|
||||||
|
pub launch_command_template: String,
|
||||||
|
|
||||||
|
pub setup_command: String,
|
||||||
|
pub setup_args: Vec<String>,
|
||||||
|
#[serde(default = "default_template")]
|
||||||
|
pub setup_command_template: String,
|
||||||
|
|
||||||
|
pub only_setup: bool,
|
||||||
|
|
||||||
|
pub version_index: usize,
|
||||||
|
pub delta: bool,
|
||||||
|
|
||||||
|
pub umu_id_override: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[serde_as]
|
||||||
|
#[derive(Serialize, Clone, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[native_model(id = 3, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
pub struct DatabaseApplications {
|
||||||
|
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, GameVersion>>,
|
||||||
|
pub installed_game_version: HashMap<String, DownloadableMetadata>,
|
||||||
|
|
||||||
|
#[serde(skip)]
|
||||||
|
pub transient_statuses: HashMap<DownloadableMetadata, ApplicationTransientStatus>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[native_model(id = 4, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
pub struct Settings {
|
||||||
|
pub autostart: bool,
|
||||||
|
pub max_download_threads: usize,
|
||||||
|
pub force_offline: bool, // ... other settings ...
|
||||||
|
}
|
||||||
|
impl Default for Settings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
autostart: false,
|
||||||
|
max_download_threads: 4,
|
||||||
|
force_offline: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strings are version names for a particular game
|
||||||
|
#[derive(Serialize, Clone, Deserialize)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
#[native_model(id = 5, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
pub enum GameDownloadStatus {
|
||||||
|
Remote {},
|
||||||
|
SetupRequired {
|
||||||
|
version_name: String,
|
||||||
|
install_dir: String,
|
||||||
|
},
|
||||||
|
Installed {
|
||||||
|
version_name: String,
|
||||||
|
install_dir: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stuff that shouldn't be synced to disk
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||||
|
pub enum ApplicationTransientStatus {
|
||||||
|
Queued { version_name: String },
|
||||||
|
Downloading { version_name: String },
|
||||||
|
Uninstalling {},
|
||||||
|
Updating { version_name: String },
|
||||||
|
Validating { version_name: String },
|
||||||
|
Running {},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, Clone, Deserialize)]
|
||||||
|
#[native_model(id = 6, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
pub struct DatabaseAuth {
|
||||||
|
pub private: String,
|
||||||
|
pub cert: String,
|
||||||
|
pub client_id: String,
|
||||||
|
pub web_token: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[native_model(id = 8, version = 1)]
|
||||||
|
#[derive(
|
||||||
|
Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Clone, Copy,
|
||||||
|
)]
|
||||||
|
pub enum DownloadType {
|
||||||
|
Game,
|
||||||
|
Tool,
|
||||||
|
Dlc,
|
||||||
|
Mod,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[native_model(id = 7, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
#[derive(Debug, Eq, PartialOrd, Ord, Serialize, Deserialize, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DownloadableMetadata {
|
||||||
|
pub id: String,
|
||||||
|
pub version: Option<String>,
|
||||||
|
pub download_type: DownloadType,
|
||||||
|
}
|
||||||
|
impl DownloadableMetadata {
|
||||||
|
pub fn new(id: String, version: Option<String>, download_type: DownloadType) -> Self {
|
||||||
|
Self {
|
||||||
|
id,
|
||||||
|
version,
|
||||||
|
download_type,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[native_model(id = 1, version = 1)]
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||||
|
pub struct Database {
|
||||||
|
#[serde(default)]
|
||||||
|
pub settings: Settings,
|
||||||
|
pub auth: Option<DatabaseAuth>,
|
||||||
|
pub base_url: String,
|
||||||
|
pub applications: DatabaseApplications,
|
||||||
|
pub prev_database: Option<PathBuf>,
|
||||||
|
pub cache_dir: PathBuf,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod v2 {
|
||||||
|
use std::{collections::HashMap, path::PathBuf};
|
||||||
|
|
||||||
|
use serde_with::serde_as;
|
||||||
|
|
||||||
|
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)]
|
||||||
|
pub struct Database {
|
||||||
|
#[serde(default)]
|
||||||
|
pub settings: v1::Settings,
|
||||||
|
pub auth: Option<v1::DatabaseAuth>,
|
||||||
|
pub base_url: String,
|
||||||
|
pub applications: v1::DatabaseApplications,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub prev_database: Option<PathBuf>,
|
||||||
|
pub cache_dir: PathBuf,
|
||||||
|
pub compat_info: Option<DatabaseCompatInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[native_model(id = 9, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||||
|
|
||||||
|
pub struct DatabaseCompatInfo {
|
||||||
|
pub umu_installed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<v1::Database> for Database {
|
||||||
|
fn from(value: v1::Database) -> Self {
|
||||||
|
Self {
|
||||||
|
settings: value.settings,
|
||||||
|
auth: value.auth,
|
||||||
|
base_url: value.base_url,
|
||||||
|
applications: value.applications,
|
||||||
|
prev_database: value.prev_database,
|
||||||
|
cache_dir: value.cache_dir,
|
||||||
|
compat_info: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Strings are version names for a particular game
|
||||||
|
#[derive(Serialize, Clone, Deserialize, Debug)]
|
||||||
|
#[serde(tag = "type")]
|
||||||
|
#[native_model(id = 5, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::GameDownloadStatus)]
|
||||||
|
pub enum GameDownloadStatus {
|
||||||
|
Remote {},
|
||||||
|
SetupRequired {
|
||||||
|
version_name: String,
|
||||||
|
install_dir: String,
|
||||||
|
},
|
||||||
|
Installed {
|
||||||
|
version_name: String,
|
||||||
|
install_dir: String,
|
||||||
|
},
|
||||||
|
PartiallyInstalled {
|
||||||
|
version_name: String,
|
||||||
|
install_dir: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
impl From<v1::GameDownloadStatus> for GameDownloadStatus {
|
||||||
|
fn from(value: v1::GameDownloadStatus) -> Self {
|
||||||
|
match value {
|
||||||
|
v1::GameDownloadStatus::Remote {} => Self::Remote {},
|
||||||
|
v1::GameDownloadStatus::SetupRequired {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
} => Self::SetupRequired {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
},
|
||||||
|
v1::GameDownloadStatus::Installed {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
} => Self::Installed {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[serde_as]
|
||||||
|
#[derive(Serialize, Clone, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
#[native_model(id = 3, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from=v1::DatabaseApplications)]
|
||||||
|
pub struct DatabaseApplications {
|
||||||
|
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>,
|
||||||
|
}
|
||||||
|
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
||||||
|
fn from(value: v1::DatabaseApplications) -> Self {
|
||||||
|
Self {
|
||||||
|
game_statuses: value
|
||||||
|
.game_statuses
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| (x.0, x.1.into()))
|
||||||
|
.collect::<HashMap<String, GameDownloadStatus>>(),
|
||||||
|
install_dirs: value.install_dirs,
|
||||||
|
game_versions: value.game_versions,
|
||||||
|
installed_game_version: value.installed_game_version,
|
||||||
|
transient_statuses: value.transient_statuses,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mod v3 {
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
Deserialize, Serialize,
|
||||||
|
native_model, v2, v1,
|
||||||
|
};
|
||||||
|
#[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 {
|
||||||
|
#[serde(default)]
|
||||||
|
pub settings: v1::Settings,
|
||||||
|
pub auth: Option<v1::DatabaseAuth>,
|
||||||
|
pub base_url: String,
|
||||||
|
pub applications: v2::DatabaseApplications,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub prev_database: Option<PathBuf>,
|
||||||
|
pub cache_dir: PathBuf,
|
||||||
|
pub compat_info: Option<v2::DatabaseCompatInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<v2::Database> for Database {
|
||||||
|
fn from(value: v2::Database) -> Self {
|
||||||
|
Self {
|
||||||
|
settings: value.settings,
|
||||||
|
auth: value.auth,
|
||||||
|
base_url: value.base_url,
|
||||||
|
applications: value.applications.into(),
|
||||||
|
prev_database: value.prev_database,
|
||||||
|
cache_dir: value.cache_dir,
|
||||||
|
compat_info: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Database {
|
||||||
|
pub fn new<T: Into<PathBuf>>(
|
||||||
|
games_base_dir: T,
|
||||||
|
prev_database: Option<PathBuf>,
|
||||||
|
cache_dir: PathBuf,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
applications: DatabaseApplications {
|
||||||
|
install_dirs: vec![games_base_dir.into()],
|
||||||
|
game_statuses: HashMap::new(),
|
||||||
|
game_versions: HashMap::new(),
|
||||||
|
installed_game_version: HashMap::new(),
|
||||||
|
transient_statuses: HashMap::new(),
|
||||||
|
},
|
||||||
|
prev_database,
|
||||||
|
base_url: String::new(),
|
||||||
|
auth: None,
|
||||||
|
settings: Settings::default(),
|
||||||
|
cache_dir,
|
||||||
|
compat_info: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,23 +1,24 @@
|
|||||||
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,
|
||||||
Linux,
|
Linux,
|
||||||
macOS,
|
MacOs,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Platform {
|
impl Platform {
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
pub const HOST: Platform = Self::Windows;
|
pub const HOST: Platform = Self::Windows;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub const HOST: Platform = Self::macOS;
|
pub const HOST: Platform = Self::MacOs;
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
pub const HOST: Platform = Self::Linux;
|
pub const HOST: Platform = Self::Linux;
|
||||||
|
|
||||||
pub fn is_case_sensitive(&self) -> bool {
|
pub fn is_case_sensitive(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Windows | Self::macOS => false,
|
Self::Windows | Self::MacOs => false,
|
||||||
Self::Linux => true,
|
Self::Linux => true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -28,7 +29,7 @@ impl From<&str> for Platform {
|
|||||||
match value.to_lowercase().trim() {
|
match value.to_lowercase().trim() {
|
||||||
"windows" => Self::Windows,
|
"windows" => Self::Windows,
|
||||||
"linux" => Self::Linux,
|
"linux" => Self::Linux,
|
||||||
"mac" | "macos" => Self::macOS,
|
"mac" | "macos" => Self::MacOs,
|
||||||
_ => unimplemented!(),
|
_ => unimplemented!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -39,7 +40,7 @@ impl From<whoami::Platform> for Platform {
|
|||||||
match value {
|
match value {
|
||||||
whoami::Platform::Windows => Platform::Windows,
|
whoami::Platform::Windows => Platform::Windows,
|
||||||
whoami::Platform::Linux => Platform::Linux,
|
whoami::Platform::Linux => Platform::Linux,
|
||||||
whoami::Platform::MacOS => Platform::macOS,
|
whoami::Platform::MacOS => Platform::MacOs,
|
||||||
platform => unimplemented!("Playform {} is not supported", platform),
|
platform => unimplemented!("Playform {} is not supported", platform),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -9,14 +9,11 @@ use std::{
|
|||||||
|
|
||||||
use database::DownloadableMetadata;
|
use database::DownloadableMetadata;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use tauri::AppHandle;
|
use tauri::{AppHandle, Emitter};
|
||||||
use utils::{app_emit, lock, send};
|
use utils::{app_emit, lock, send};
|
||||||
|
|
||||||
use crate::{
|
|
||||||
download_manager_frontend::DownloadStatus,
|
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
|
||||||
error::ApplicationDownloadError,
|
|
||||||
frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
||||||
@ -292,10 +289,7 @@ impl DownloadManagerBuilder {
|
|||||||
|
|
||||||
if validate_result {
|
if validate_result {
|
||||||
download_agent.on_complete(&app_handle);
|
download_agent.on_complete(&app_handle);
|
||||||
send!(
|
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
|
||||||
sender,
|
|
||||||
DownloadManagerSignal::Completed(download_agent.metadata())
|
|
||||||
);
|
|
||||||
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -376,7 +370,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();
|
||||||
@ -395,6 +389,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,6 +14,7 @@ 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::{
|
||||||
@ -79,7 +80,6 @@ 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,11 +124,8 @@ 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 =
|
let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
|
||||||
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 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,6 +3,7 @@ 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,9 +1,5 @@
|
|||||||
use humansize::{BINARY, format_size};
|
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
|
||||||
use std::{
|
use humansize::{format_size, BINARY};
|
||||||
fmt::{Display, Formatter},
|
|
||||||
io,
|
|
||||||
sync::{Arc, mpsc::SendError},
|
|
||||||
};
|
|
||||||
|
|
||||||
use remote::error::RemoteAccessError;
|
use remote::error::RemoteAccessError;
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
@ -48,9 +44,7 @@ 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 => {
|
ApplicationDownloadError::NotInitialized => write!(f, "Download not initalized, did something go wrong?"),
|
||||||
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.",
|
||||||
@ -66,9 +60,10 @@ 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) => {
|
ApplicationDownloadError::DownloadError(error) => write!(
|
||||||
write!(f, "Download failed with error {error:?}")
|
f,
|
||||||
}
|
"Download failed with error {error:?}"
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
16
download_manager/src/lib.rs
Normal file
16
download_manager/src/lib.rs
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
#![feature(duration_millis_float)]
|
||||||
|
#![feature(nonpoison_mutex)]
|
||||||
|
#![feature(sync_nonpoison)]
|
||||||
|
|
||||||
|
use std::sync::{nonpoison::Mutex, LazyLock};
|
||||||
|
|
||||||
|
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 static DOWNLOAD_MANAGER: LazyLock<Mutex<DownloadManager>> = LazyLock::new(|| todo!());
|
||||||
@ -1,6 +1,6 @@
|
|||||||
use std::sync::{
|
use std::sync::{
|
||||||
Arc,
|
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
|
Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(PartialEq, Eq, PartialOrd, Ord)]
|
||||||
@ -22,11 +22,7 @@ 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 {
|
if value { DownloadThreadControlFlag::Go } else { DownloadThreadControlFlag::Stop }
|
||||||
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, Debug)]
|
#[derive(Clone)]
|
||||||
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,9 +117,7 @@ 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()
|
let time_since_last_update = Instant::now().duration_since(last_update_time).as_millis_f64();
|
||||||
.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();
|
||||||
@ -127,8 +125,7 @@ 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 =
|
let bytes_since_last_update = current_bytes_downloaded.saturating_sub(bytes_at_last_update) as f64;
|
||||||
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, Debug)]
|
#[derive(Clone)]
|
||||||
pub struct Queue {
|
pub struct Queue {
|
||||||
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
|
inner: Arc<Mutex<VecDeque<DownloadableMetadata>>>,
|
||||||
}
|
}
|
||||||
@ -3,17 +3,11 @@ use std::sync::{
|
|||||||
atomic::{AtomicUsize, Ordering},
|
atomic::{AtomicUsize, Ordering},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone)]
|
||||||
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 {
|
||||||
@ -22,8 +22,5 @@ sysinfo = "0.37.2"
|
|||||||
tauri = "2.8.5"
|
tauri = "2.8.5"
|
||||||
throttle_my_fn = "0.2.6"
|
throttle_my_fn = "0.2.6"
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
utils = { version = "0.1.0", path = "../utils" }
|
||||||
native_model = { version = "0.6.4", features = [
|
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
||||||
"rmp_serde_1_3",
|
|
||||||
], git = "https://github.com/Drop-OSS/native_model.git" }
|
|
||||||
serde_json = "1.0.145"
|
serde_json = "1.0.145"
|
||||||
drop-consts = { version = "0.1.0", path = "../drop-consts" }
|
|
||||||
@ -1,7 +1,8 @@
|
|||||||
use bitcode::{Decode, Encode};
|
use bitcode::{Decode, Encode};
|
||||||
use database::models::Game;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::library::Game;
|
||||||
|
|
||||||
pub type Collections = Vec<Collection>;
|
pub type Collections = Vec<Collection>;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, Encode, Decode)]
|
#[derive(Serialize, Deserialize, Debug, Clone, Default, Encode, Decode)]
|
||||||
@ -14,7 +15,7 @@ pub struct Collection {
|
|||||||
entries: Vec<CollectionObject>,
|
entries: Vec<CollectionObject>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode)]
|
#[derive(Serialize, Deserialize, Debug, Clone, Default, Encode, Decode)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct CollectionObject {
|
pub struct CollectionObject {
|
||||||
collection_id: String,
|
collection_id: String,
|
||||||
@ -1,21 +1,16 @@
|
|||||||
use database::{
|
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata};
|
||||||
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::{
|
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
||||||
DownloadThreadControl, DownloadThreadControlFlag,
|
|
||||||
};
|
|
||||||
use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
||||||
use drop_consts::{MAX_FILES_PER_BUCKET, RETRY_COUNT, TARGET_BUCKET_SIZE};
|
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use rayon::ThreadPoolBuilder;
|
use rayon::ThreadPoolBuilder;
|
||||||
use remote::auth::generate_authorization_header;
|
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;
|
||||||
@ -23,15 +18,12 @@ 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;
|
use tauri::{AppHandle, Emitter};
|
||||||
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::{
|
use crate::downloads::manifest::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody};
|
||||||
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};
|
||||||
@ -40,6 +32,11 @@ use crate::state::GameStatusManager;
|
|||||||
use super::download_logic::download_game_bucket;
|
use super::download_logic::download_game_bucket;
|
||||||
use super::drop_data::DropData;
|
use super::drop_data::DropData;
|
||||||
|
|
||||||
|
static RETRY_COUNT: usize = 3;
|
||||||
|
|
||||||
|
const TARGET_BUCKET_SIZE: usize = 63 * 1000 * 1000;
|
||||||
|
const MAX_FILES_PER_BUCKET: usize = (1024 / 4) - 1;
|
||||||
|
|
||||||
pub struct GameDownloadAgent {
|
pub struct GameDownloadAgent {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub version: String,
|
pub version: String,
|
||||||
@ -100,7 +97,8 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
result.ensure_manifest_exists().await?;
|
result.ensure_manifest_exists().await?;
|
||||||
|
|
||||||
let required_space = lock!(result.manifest)
|
let required_space = lock!(result
|
||||||
|
.manifest)
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.values()
|
.values()
|
||||||
@ -449,13 +447,9 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
let sender = self.sender.clone();
|
let sender = self.sender.clone();
|
||||||
|
|
||||||
let download_context =
|
let download_context = download_contexts
|
||||||
download_contexts.get(&bucket.version).unwrap_or_else(|| {
|
.get(&bucket.version)
|
||||||
panic!(
|
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
|
||||||
"Could not get bucket version {}. Corrupted state.",
|
|
||||||
bucket.version
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
scope.spawn(move |_| {
|
scope.spawn(move |_| {
|
||||||
// 3 attempts
|
// 3 attempts
|
||||||
@ -693,10 +687,7 @@ 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!(
|
send!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e)));
|
||||||
self.sender,
|
|
||||||
DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -11,9 +11,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use download_manager::error::ApplicationDownloadError;
|
use download_manager::error::ApplicationDownloadError;
|
||||||
use download_manager::util::download_thread_control_flag::{
|
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
||||||
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};
|
||||||
@ -49,7 +47,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.finalize())
|
Ok(self.hasher.compute())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Write automatically pushes to file and hasher
|
// Write automatically pushes to file and hasher
|
||||||
@ -118,10 +116,7 @@ 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
|
let size = self.source.read(&mut copy_buffer[0..size]).inspect_err(|_| {
|
||||||
.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,17 +1,15 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap, fs::File, io::{self, Read, Write}, path::{Path, PathBuf}
|
||||||
fs::File,
|
|
||||||
io::{self, Read, Write},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use drop_consts::DROP_DATA_PATH;
|
|
||||||
use log::error;
|
use log::error;
|
||||||
use native_model::{Decode, Encode};
|
use native_model::{Decode, Encode};
|
||||||
use utils::lock;
|
use utils::lock;
|
||||||
|
|
||||||
pub type DropData = v1::DropData;
|
pub type DropData = v1::DropData;
|
||||||
|
|
||||||
|
pub static DROP_DATA_PATH: &str = ".dropdata";
|
||||||
|
|
||||||
pub mod v1 {
|
pub mod v1 {
|
||||||
use std::{collections::HashMap, path::PathBuf, sync::Mutex};
|
use std::{collections::HashMap, path::PathBuf, sync::Mutex};
|
||||||
|
|
||||||
@ -79,10 +77,7 @@ 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
|
*lock!(self.contexts) = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
|
||||||
.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);
|
||||||
21
games/src/downloads/error.rs
Normal file
21
games/src/downloads/error.rs
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
use std::fmt::{Display};
|
||||||
|
|
||||||
|
use serde_with::SerializeDisplay;
|
||||||
|
|
||||||
|
#[derive(SerializeDisplay)]
|
||||||
|
pub enum LibraryError {
|
||||||
|
MetaNotFound(String),
|
||||||
|
VersionNotFound(String),
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
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 drop_data;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
mod manifest;
|
mod manifest;
|
||||||
pub mod utils;
|
|
||||||
pub mod validate;
|
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());
|
return Ok(disk.available_space());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(ApplicationDownloadError::IoError(Arc::new(
|
Err(ApplicationDownloadError::IoError(Arc::new(io::Error::other(
|
||||||
io::Error::other("could not find disk of path"),
|
"could not find disk of path",
|
||||||
)))
|
))))
|
||||||
}
|
}
|
||||||
@ -3,13 +3,7 @@ use std::{
|
|||||||
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
||||||
};
|
};
|
||||||
|
|
||||||
use download_manager::{
|
use download_manager::{error::ApplicationDownloadError, util::{download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::ProgressHandle}};
|
||||||
error::ApplicationDownloadError,
|
|
||||||
util::{
|
|
||||||
download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag},
|
|
||||||
progress_object::ProgressHandle,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use md5::Context;
|
use md5::Context;
|
||||||
|
|
||||||
@ -22,10 +16,7 @@ pub fn validate_game_chunk(
|
|||||||
) -> Result<bool, ApplicationDownloadError> {
|
) -> Result<bool, ApplicationDownloadError> {
|
||||||
debug!(
|
debug!(
|
||||||
"Starting chunk validation {}, {}, {} #{}",
|
"Starting chunk validation {}, {}, {} #{}",
|
||||||
ctx.path.display(),
|
ctx.path.display(), ctx.index, ctx.offset, ctx.checksum
|
||||||
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 {
|
||||||
@ -45,12 +36,13 @@ pub fn validate_game_chunk(
|
|||||||
|
|
||||||
let mut hasher = md5::Context::new();
|
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 {
|
if !completed {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
let res = hex::encode(hasher.finalize().0);
|
let res = hex::encode(hasher.compute().0);
|
||||||
if res != ctx.checksum {
|
if res != ctx.checksum {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
@ -3,5 +3,4 @@
|
|||||||
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,18 +1,15 @@
|
|||||||
use database::{
|
|
||||||
borrow_db_checked, borrow_db_mut_checked, models::Game, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion
|
|
||||||
};
|
|
||||||
use log::{debug, error, warn};
|
|
||||||
use remote::{
|
|
||||||
auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url,
|
|
||||||
utils::DROP_CLIENT_SYNC,
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::fs::remove_dir_all;
|
use std::fs::remove_dir_all;
|
||||||
|
use std::sync::Mutex;
|
||||||
use std::thread::spawn;
|
use std::thread::spawn;
|
||||||
use tauri::AppHandle;
|
use bitcode::{Decode, Encode};
|
||||||
|
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion};
|
||||||
|
use log::{debug, error, warn};
|
||||||
|
use remote::{auth::generate_authorization_header, error::RemoteAccessError, requests::generate_url, utils::DROP_CLIENT_SYNC};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
use utils::app_emit;
|
use utils::app_emit;
|
||||||
|
|
||||||
use crate::state::{GameStatusManager, GameStatusWithTransient};
|
use crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
pub struct FetchGameStruct {
|
pub struct FetchGameStruct {
|
||||||
@ -23,14 +20,30 @@ 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 {
|
Self { game, status, version }
|
||||||
game,
|
|
||||||
status,
|
|
||||||
version,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug, Default, Encode, Decode)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Game {
|
||||||
|
id: String,
|
||||||
|
m_name: String,
|
||||||
|
m_short_description: String,
|
||||||
|
m_description: String,
|
||||||
|
// mDevelopers
|
||||||
|
// mPublishers
|
||||||
|
m_icon_object_id: String,
|
||||||
|
m_banner_object_id: String,
|
||||||
|
m_cover_object_id: String,
|
||||||
|
m_image_library_object_ids: Vec<String>,
|
||||||
|
m_image_carousel_object_ids: Vec<String>,
|
||||||
|
}
|
||||||
|
impl Game {
|
||||||
|
pub fn id(&self) -> &String {
|
||||||
|
&self.id
|
||||||
|
}
|
||||||
|
}
|
||||||
#[derive(serde::Serialize, Clone)]
|
#[derive(serde::Serialize, Clone)]
|
||||||
pub struct GameUpdateEvent {
|
pub struct GameUpdateEvent {
|
||||||
pub game_id: String,
|
pub game_id: String,
|
||||||
@ -155,7 +168,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 {
|
||||||
@ -271,8 +284,41 @@ pub struct FrontendGameOptions {
|
|||||||
launch_string: String,
|
launch_string: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FrontendGameOptions {
|
#[tauri::command]
|
||||||
pub fn launch_string(&self) -> &String {
|
pub fn update_game_configuration(
|
||||||
&self.launch_string
|
game_id: String,
|
||||||
}
|
options: FrontendGameOptions,
|
||||||
|
) -> Result<(), LibraryError> {
|
||||||
|
let mut handle = borrow_db_mut_checked();
|
||||||
|
let installed_version = handle
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.get(&game_id)
|
||||||
|
.ok_or(LibraryError::MetaNotFound(game_id))?;
|
||||||
|
|
||||||
|
let id = installed_version.id.clone();
|
||||||
|
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
|
||||||
|
|
||||||
|
let mut existing_configuration = handle
|
||||||
|
.applications
|
||||||
|
.game_versions
|
||||||
|
.get(&id)
|
||||||
|
.unwrap()
|
||||||
|
.get(&version)
|
||||||
|
.unwrap()
|
||||||
|
.clone();
|
||||||
|
|
||||||
|
// Add more options in here
|
||||||
|
existing_configuration.launch_command_template = options.launch_string;
|
||||||
|
|
||||||
|
// Add no more options past here
|
||||||
|
|
||||||
|
handle
|
||||||
|
.applications
|
||||||
|
.game_versions
|
||||||
|
.get_mut(&id)
|
||||||
|
.unwrap()
|
||||||
|
.insert(version.to_string(), existing_configuration);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -1,12 +1,16 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
use database::{DownloadType, DownloadableMetadata, borrow_db_mut_checked};
|
|
||||||
use drop_consts::DROP_DATA_PATH;
|
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
downloads::drop_data::DropData,
|
database::{
|
||||||
|
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() {
|
||||||
@ -1,4 +1,4 @@
|
|||||||
use database::{
|
use database::models::data::{
|
||||||
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
|
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -116,7 +116,7 @@ platformInfo.value = currentPlatform;
|
|||||||
async function openDataDir() {
|
async function openDataDir() {
|
||||||
if (!dataDir.value) return;
|
if (!dataDir.value) return;
|
||||||
try {
|
try {
|
||||||
await invoke("open_fs", { path: dataDir.value });
|
await open(dataDir.value);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to open data dir:", error);
|
console.error("Failed to open data dir:", error);
|
||||||
}
|
}
|
||||||
@ -126,7 +126,7 @@ async function openLogFile() {
|
|||||||
if (!dataDir.value) return;
|
if (!dataDir.value) return;
|
||||||
try {
|
try {
|
||||||
const logPath = `${dataDir.value}/drop.log`;
|
const logPath = `${dataDir.value}/drop.log`;
|
||||||
await invoke("open_fs", { path: logPath });
|
await open(logPath);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to open log file:", error);
|
console.error("Failed to open log file:", error);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,8 +9,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tauri-apps/api": "^2.7.0",
|
"@tauri-apps/api": "^2.7.0",
|
||||||
"@tauri-apps/plugin-deep-link": "^2.4.1",
|
"@tauri-apps/plugin-deep-link": "^2.4.1",
|
||||||
"@tauri-apps/plugin-dialog": "^2.4.0",
|
"@tauri-apps/plugin-dialog": "^2.3.2",
|
||||||
"@tauri-apps/plugin-opener": "^2.5.0",
|
"@tauri-apps/plugin-opener": "^2.4.0",
|
||||||
"@tauri-apps/plugin-os": "^2.3.0",
|
"@tauri-apps/plugin-os": "^2.3.0",
|
||||||
"@tauri-apps/plugin-shell": "^2.3.0",
|
"@tauri-apps/plugin-shell": "^2.3.0",
|
||||||
"pino": "^9.7.0",
|
"pino": "^9.7.0",
|
||||||
|
|||||||
@ -14,6 +14,5 @@ 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,12 +8,7 @@ pub struct DropFormatArgs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl DropFormatArgs {
|
impl DropFormatArgs {
|
||||||
pub fn new(
|
pub fn new(launch_string: String, working_dir: &String, executable_name: &String, absolute_executable_name: String) -> Self {
|
||||||
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();
|
||||||
|
|
||||||
14
process/src/lib.rs
Normal file
14
process/src/lib.rs
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
#![feature(nonpoison_mutex)]
|
||||||
|
#![feature(sync_nonpoison)]
|
||||||
|
|
||||||
|
use std::sync::{LazyLock, nonpoison::Mutex};
|
||||||
|
|
||||||
|
use crate::process_manager::ProcessManager;
|
||||||
|
|
||||||
|
pub static PROCESS_MANAGER: LazyLock<Mutex<ProcessManager>> =
|
||||||
|
LazyLock::new(|| Mutex::new(ProcessManager::new()));
|
||||||
|
|
||||||
|
pub mod error;
|
||||||
|
pub mod format;
|
||||||
|
pub mod process_handlers;
|
||||||
|
pub mod process_manager;
|
||||||
@ -1,7 +1,8 @@
|
|||||||
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
|
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
|
||||||
use database::{Database, DownloadableMetadata, GameVersion, platform::Platform};
|
use database::{platform::Platform, Database, DownloadableMetadata, GameVersion};
|
||||||
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;
|
||||||
@ -45,9 +46,7 @@ impl ProcessHandler for UMULauncher {
|
|||||||
};
|
};
|
||||||
Ok(format!(
|
Ok(format!(
|
||||||
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
||||||
umu = UMU_LAUNCHER_EXECUTABLE
|
umu = UMU_LAUNCHER_EXECUTABLE.as_ref().expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
|
||||||
.as_ref()
|
|
||||||
.expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
|
|
||||||
launch = launch_command,
|
launch = launch_command,
|
||||||
args = args.join(" ")
|
args = args.join(" ")
|
||||||
))
|
))
|
||||||
@ -87,12 +86,7 @@ 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!(
|
let cmd = format!("umu-run{}", args_cmd.next().ok_or(ProcessError::InvalidArguments(umu_string.clone()))?);
|
||||||
"umu-run{}",
|
|
||||||
args_cmd
|
|
||||||
.next()
|
|
||||||
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(format!("{args} muvm -- {cmd}"))
|
Ok(format!("{args} muvm -- {cmd}"))
|
||||||
}
|
}
|
||||||
@ -6,7 +6,6 @@ use std::{
|
|||||||
process::{Command, ExitStatus},
|
process::{Command, ExitStatus},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
thread::spawn,
|
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -16,10 +15,10 @@ use database::{
|
|||||||
};
|
};
|
||||||
use dynfmt::Format;
|
use dynfmt::Format;
|
||||||
use dynfmt::SimpleCurlyFormat;
|
use dynfmt::SimpleCurlyFormat;
|
||||||
use games::{library::push_game_update, state::GameStatusManager};
|
use games::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,
|
||||||
@ -42,11 +41,10 @@ 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(app_handle: AppHandle) -> Self {
|
pub fn new() -> Self {
|
||||||
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
||||||
|
|
||||||
ProcessManager {
|
ProcessManager {
|
||||||
@ -54,7 +52,7 @@ impl ProcessManager<'_> {
|
|||||||
current_platform: Platform::Windows,
|
current_platform: Platform::Windows,
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
current_platform: Platform::macOS,
|
current_platform: Platform::MacOs,
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
current_platform: Platform::Linux,
|
current_platform: Platform::Linux,
|
||||||
@ -72,7 +70,7 @@ impl ProcessManager<'_> {
|
|||||||
&NativeGameLauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
&NativeGameLauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
(Platform::macOS, Platform::macOS),
|
(Platform::MacOs, Platform::MacOs),
|
||||||
&NativeGameLauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
&NativeGameLauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
@ -84,7 +82,6 @@ impl ProcessManager<'_> {
|
|||||||
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
&UMULauncher {} as &(dyn ProcessHandler + Sync + Send + 'static),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
app_handle,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -175,12 +172,13 @@ impl ProcessManager<'_> {
|
|||||||
|
|
||||||
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
||||||
|
|
||||||
push_game_update(
|
// TODO
|
||||||
&self.app_handle,
|
// push_game_update(
|
||||||
&game_id,
|
// &self.app_handle,
|
||||||
Some(version_data.clone()),
|
// &game_id,
|
||||||
status,
|
// Some(version_data.clone()),
|
||||||
);
|
// status,
|
||||||
|
// );
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -365,12 +363,13 @@ impl ProcessManager<'_> {
|
|||||||
.transient_statuses
|
.transient_statuses
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
||||||
|
|
||||||
push_game_update(
|
// TODO
|
||||||
&self.app_handle,
|
// push_game_update(
|
||||||
&meta.id,
|
// &self.app_handle,
|
||||||
None,
|
// &meta.id,
|
||||||
(None, Some(ApplicationTransientStatus::Running {})),
|
// None,
|
||||||
);
|
// (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();
|
||||||
@ -383,14 +382,12 @@ 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,18 +2,14 @@ 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::{DatabaseAuth, interface::borrow_db_checked};
|
use database::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::{
|
use crate::{error::{DropServerError, RemoteAccessError}, requests::make_authenticated_get, utils::DROP_CLIENT_SYNC};
|
||||||
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},
|
||||||
@ -35,42 +31,35 @@ struct InitiateRequestBody {
|
|||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct HandshakeRequestBody {
|
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")]
|
||||||
pub struct HandshakeResponse {
|
struct HandshakeResponse {
|
||||||
private: String,
|
private: String,
|
||||||
certificate: String,
|
certificate: String,
|
||||||
id: String,
|
id: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<HandshakeResponse> for DatabaseAuth {
|
pub fn generate_authorization_header() -> String {
|
||||||
fn from(value: HandshakeResponse) -> Self {
|
let certs = {
|
||||||
DatabaseAuth::new(value.private, value.certificate, value.id, None)
|
let db = borrow_db_checked();
|
||||||
}
|
db.auth.clone().expect("Authorisation not initialised")
|
||||||
}
|
};
|
||||||
|
|
||||||
pub fn generate_authorization_header(auth: DatabaseAuth) -> String {
|
|
||||||
let nonce = Utc::now().timestamp_millis().to_string();
|
let nonce = Utc::now().timestamp_millis().to_string();
|
||||||
|
|
||||||
let signature =
|
let signature =
|
||||||
sign_nonce(auth.private, nonce.clone()).expect("Failed to generate authorisation header");
|
sign_nonce(certs.private, nonce.clone()).expect("Failed to generate authorisation header");
|
||||||
|
|
||||||
format!("Nonce {} {} {}", auth.client_id, nonce, signature)
|
format!("Nonce {} {} {}", certs.client_id, nonce, signature)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_user(auth: DatabaseAuth, base_url: Url) -> Result<User, RemoteAccessError> {
|
pub async fn fetch_user() -> Result<User, RemoteAccessError> {
|
||||||
let response = make_authenticated_get(generate_url(&["/api/v1/client/user"], &[], base_url)?, auth).await?;
|
let response = make_authenticated_get(generate_url(&["/api/v1/client/user"], &[])?).await?;
|
||||||
if response.status() != 200 {
|
if response.status() != 200 {
|
||||||
let err: DropServerError = response.json().await?;
|
let err: DropServerError = response.json().await?;
|
||||||
warn!("{err:?}");
|
warn!("{err:?}");
|
||||||
@ -88,7 +77,12 @@ pub async fn fetch_user(auth: DatabaseAuth, base_url: Url) -> Result<User, Remot
|
|||||||
.map_err(std::convert::Into::into)
|
.map_err(std::convert::Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn auth_initiate_logic(mode: String, base_url: Url) -> Result<String, RemoteAccessError> {
|
pub fn auth_initiate_logic(mode: String) -> Result<String, RemoteAccessError> {
|
||||||
|
let base_url = {
|
||||||
|
let db_lock = borrow_db_checked();
|
||||||
|
Url::parse(&db_lock.base_url.clone())?
|
||||||
|
};
|
||||||
|
|
||||||
let hostname = gethostname();
|
let hostname = gethostname();
|
||||||
|
|
||||||
let endpoint = base_url.join("/api/v1/client/auth/initiate")?;
|
let endpoint = base_url.join("/api/v1/client/auth/initiate")?;
|
||||||
@ -117,8 +111,14 @@ pub fn auth_initiate_logic(mode: String, base_url: Url) -> Result<String, Remote
|
|||||||
Ok(response)
|
Ok(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn setup(auth: DatabaseAuth, base_url: Url) -> (AppStatus, Option<User>) {
|
pub async fn setup() -> (AppStatus, Option<User>) {
|
||||||
let user_result = match fetch_user(auth, base_url).await {
|
let auth = {
|
||||||
|
let data = borrow_db_checked();
|
||||||
|
data.auth.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
if auth.is_some() {
|
||||||
|
let user_result = match fetch_user().await {
|
||||||
Ok(data) => data,
|
Ok(data) => data,
|
||||||
Err(RemoteAccessError::FetchError(_)) => {
|
Err(RemoteAccessError::FetchError(_)) => {
|
||||||
let user = get_cached_object::<User>("user").ok();
|
let user = get_cached_object::<User>("user").ok();
|
||||||
@ -130,4 +130,7 @@ pub async fn setup(auth: DatabaseAuth, base_url: Url) -> (AppStatus, Option<User
|
|||||||
warn!("Could not cache user object with error {e}");
|
warn!("Could not cache user object with error {e}");
|
||||||
}
|
}
|
||||||
return (AppStatus::SignedIn, Some(user_result));
|
return (AppStatus::SignedIn, Some(user_result));
|
||||||
|
}
|
||||||
|
|
||||||
|
(AppStatus::SignedOut, None)
|
||||||
}
|
}
|
||||||
@ -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
|
||||||
|| *$var.lock().status() == ::client::app_status::AppStatus::Offline {
|
|| ::utils::lock!($var).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::{HeaderName, StatusCode, header::ToStrError};
|
use http::{header::ToStrError, HeaderName, StatusCode};
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
use url::ParseError;
|
use url::ParseError;
|
||||||
|
|
||||||
@ -19,6 +19,7 @@ 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>),
|
||||||
@ -119,24 +120,16 @@ 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) => {
|
CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
|
||||||
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::ParseError(to_str_error) => {
|
CacheError::ConstructionError(error) => format!("Could not construct cache body with error {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,8 +1,7 @@
|
|||||||
use database::{DB, DatabaseAuth, interface::DatabaseImpls};
|
use database::{interface::DatabaseImpls, DB};
|
||||||
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
|
||||||
use log::{debug, warn};
|
use log::{debug, warn};
|
||||||
use tauri::UriSchemeResponder;
|
use tauri::UriSchemeResponder;
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{error::CacheError, utils::DROP_CLIENT_ASYNC};
|
use crate::{error::CacheError, utils::DROP_CLIENT_ASYNC};
|
||||||
|
|
||||||
@ -11,26 +10,18 @@ use super::{
|
|||||||
cache::{ObjectCache, cache_object, get_cached_object},
|
cache::{ObjectCache, cache_object, get_cached_object},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: UriSchemeResponder, auth: DatabaseAuth, base_url: Url) {
|
pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
match fetch_object(request, auth, base_url).await {
|
match fetch_object(request).await {
|
||||||
Ok(r) => responder.respond(r),
|
Ok(r) => responder.respond(r),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Cache error: {e}");
|
warn!("Cache error: {e}");
|
||||||
responder.respond(
|
responder.respond(Response::builder().status(500).body(Vec::new()).expect("Failed to build error response"));
|
||||||
Response::builder()
|
|
||||||
.status(500)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_object(
|
pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Vec<u8>>, CacheError>
|
||||||
request: http::Request<Vec<u8>>,
|
{
|
||||||
auth: DatabaseAuth,
|
|
||||||
base_url: Url
|
|
||||||
) -> Result<Response<Vec<u8>>, CacheError> {
|
|
||||||
// Drop leading /
|
// Drop leading /
|
||||||
let object_id = &request.uri().path()[1..];
|
let object_id = &request.uri().path()[1..];
|
||||||
|
|
||||||
@ -41,9 +32,9 @@ pub async fn fetch_object(
|
|||||||
return cache_result.try_into();
|
return cache_result.try_into();
|
||||||
}
|
}
|
||||||
|
|
||||||
let header = generate_authorization_header(auth);
|
let header = generate_authorization_header();
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
let url = format!("{}api/v1/client/object/{object_id}", base_url);
|
let url = format!("{}api/v1/client/object/{object_id}", DB.fetch_base_url());
|
||||||
let response = client.get(url).header("Authorization", header).send().await;
|
let response = client.get(url).header("Authorization", header).send().await;
|
||||||
|
|
||||||
match response {
|
match response {
|
||||||
@ -57,13 +48,13 @@ pub async fn fetch_object(
|
|||||||
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!("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()
|
Vec::new()
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let resp = resp_builder
|
let resp = resp_builder.body(data).expect("Failed to build object cache response body");
|
||||||
.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::{DB, DatabaseAuth, interface::DatabaseImpls};
|
use database::{interface::DatabaseImpls, DB};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@ -8,9 +8,8 @@ use crate::{
|
|||||||
pub fn generate_url<T: AsRef<str>>(
|
pub fn generate_url<T: AsRef<str>>(
|
||||||
path_components: &[T],
|
path_components: &[T],
|
||||||
query: &[(T, T)],
|
query: &[(T, T)],
|
||||||
base_url: Url
|
|
||||||
) -> Result<Url, RemoteAccessError> {
|
) -> Result<Url, RemoteAccessError> {
|
||||||
let mut base_url = base_url.clone();
|
let mut base_url = DB.fetch_base_url();
|
||||||
for endpoint in path_components {
|
for endpoint in path_components {
|
||||||
base_url = base_url.join(endpoint.as_ref())?;
|
base_url = base_url.join(endpoint.as_ref())?;
|
||||||
}
|
}
|
||||||
@ -23,10 +22,10 @@ pub fn generate_url<T: AsRef<str>>(
|
|||||||
Ok(base_url)
|
Ok(base_url)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn make_authenticated_get(url: Url, auth: DatabaseAuth) -> Result<reqwest::Response, reqwest::Error> {
|
pub async fn make_authenticated_get(url: Url) -> Result<reqwest::Response, reqwest::Error> {
|
||||||
DROP_CLIENT_ASYNC
|
DROP_CLIENT_ASYNC
|
||||||
.get(url)
|
.get(url)
|
||||||
.header("Authorization", generate_authorization_header(auth))
|
.header("Authorization", generate_authorization_header())
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@ -1,66 +1,58 @@
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use database::{DatabaseAuth, borrow_db_checked};
|
use database::borrow_db_checked;
|
||||||
use http::{Request, Response, StatusCode, Uri, uri::PathAndQuery};
|
use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
|
||||||
use log::warn;
|
use log::{error, warn};
|
||||||
use tauri::UriSchemeResponder;
|
use tauri::UriSchemeResponder;
|
||||||
use url::Url;
|
|
||||||
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(
|
pub async fn handle_server_proto_offline_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
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(
|
pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode>{
|
||||||
_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, auth: DatabaseAuth, base_url: Url) {
|
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
match handle_server_proto(request, auth, base_url).await {
|
match handle_server_proto(request).await {
|
||||||
Ok(r) => responder.respond(r),
|
Ok(r) => responder.respond(r),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
warn!("Cache error: {e}");
|
warn!("Cache error: {e}");
|
||||||
responder.respond(
|
responder.respond(Response::builder().status(e).body(Vec::new()).expect("Failed to build error response"));
|
||||||
Response::builder()
|
|
||||||
.status(e)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_server_proto(
|
async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode> {
|
||||||
request: Request<Vec<u8>>,
|
let db_handle = borrow_db_checked();
|
||||||
auth: DatabaseAuth,
|
let auth = match db_handle.auth.as_ref() {
|
||||||
base_url: Url,
|
Some(auth) => auth,
|
||||||
) -> Result<Response<Vec<u8>>, StatusCode> {
|
None => {
|
||||||
|
error!("Could not find auth in database");
|
||||||
|
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 = base_url.as_str().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 = Some(
|
new_uri.path_and_query =
|
||||||
PathAndQuery::from_str(&format!("{path}?noWrapper=true"))
|
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
|
||||||
.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:?}");
|
||||||
@ -70,7 +62,7 @@ async fn handle_server_proto(
|
|||||||
|
|
||||||
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();
|
||||||
@ -78,13 +70,12 @@ async fn handle_server_proto(
|
|||||||
.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,13 +46,11 @@ fn fetch_certificates() -> Vec<Certificate> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
.read_to_end(&mut buf)
|
.read_to_end(&mut buf)
|
||||||
.unwrap_or_else(|e| {
|
.unwrap_or_else(|e| panic!(
|
||||||
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) => {
|
||||||
@ -89,10 +87,7 @@ 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
|
client.use_rustls_tls().build().expect("Failed to build synchronous 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();
|
||||||
@ -100,10 +95,7 @@ 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
|
client.use_rustls_tls().build().expect("Failed to build asynchronous 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();
|
||||||
2292
src-tauri/Cargo.lock
generated
2292
src-tauri/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -65,9 +65,7 @@ whoami = "1.6.0"
|
|||||||
filetime = "0.2.25"
|
filetime = "0.2.25"
|
||||||
walkdir = "2.5.0"
|
walkdir = "2.5.0"
|
||||||
known-folders = "1.2.0"
|
known-folders = "1.2.0"
|
||||||
native_model = { version = "0.6.4", features = [
|
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
||||||
"rmp_serde_1_3",
|
|
||||||
], git = "https://github.com/Drop-OSS/native_model.git" }
|
|
||||||
tauri-plugin-opener = "2.4.0"
|
tauri-plugin-opener = "2.4.0"
|
||||||
bitcode = "0.6.6"
|
bitcode = "0.6.6"
|
||||||
reqwest-websocket = "0.5.0"
|
reqwest-websocket = "0.5.0"
|
||||||
@ -82,13 +80,12 @@ bytes = "1.10.1"
|
|||||||
|
|
||||||
|
|
||||||
# Workspaces
|
# Workspaces
|
||||||
client = { version = "0.1.0", path = "./client" }
|
client = { version = "0.1.0", path = "../client" }
|
||||||
database = { path = "./database" }
|
database = { path = "../database" }
|
||||||
process = { path = "./process" }
|
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"
|
||||||
@ -139,20 +136,3 @@ features = ["derive", "rc"]
|
|||||||
lto = true
|
lto = true
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
panic = 'abort'
|
panic = 'abort'
|
||||||
|
|
||||||
|
|
||||||
[workspace]
|
|
||||||
members = [
|
|
||||||
"client",
|
|
||||||
"database",
|
|
||||||
"process",
|
|
||||||
"remote",
|
|
||||||
"utils",
|
|
||||||
"cloud_saves",
|
|
||||||
"download_manager",
|
|
||||||
"games",
|
|
||||||
"library",
|
|
||||||
"drop-consts",
|
|
||||||
]
|
|
||||||
|
|
||||||
resolver = "3"
|
|
||||||
|
|||||||
@ -1,42 +0,0 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use database::models::Game;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
use crate::{app_status::AppStatus, user::User};
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct AppState {
|
|
||||||
status: AppStatus,
|
|
||||||
user: Option<User>,
|
|
||||||
games: HashMap<String, Game>,
|
|
||||||
}
|
|
||||||
impl AppState {
|
|
||||||
pub fn new(status: AppStatus, user: Option<User>, games: HashMap<String, Game>) -> Self {
|
|
||||||
Self {
|
|
||||||
status,
|
|
||||||
user,
|
|
||||||
games,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn status(&self) -> &AppStatus {
|
|
||||||
&self.status
|
|
||||||
}
|
|
||||||
pub fn status_mut(&mut self) -> &mut AppStatus {
|
|
||||||
&mut self.status
|
|
||||||
}
|
|
||||||
pub fn games(&self) -> &HashMap<String, Game> {
|
|
||||||
&self.games
|
|
||||||
}
|
|
||||||
pub fn games_mut(&mut self) -> &mut HashMap<String, Game> {
|
|
||||||
&mut self.games
|
|
||||||
}
|
|
||||||
pub fn user(&self) -> &Option<User> {
|
|
||||||
&self.user
|
|
||||||
}
|
|
||||||
pub fn user_mut(&mut self) -> &mut Option<User> {
|
|
||||||
&mut self.user
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
pub mod app_state;
|
|
||||||
pub mod app_status;
|
|
||||||
pub mod autostart;
|
|
||||||
pub mod compat;
|
|
||||||
pub mod user;
|
|
||||||
@ -1,234 +0,0 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
use database::platform::Platform;
|
|
||||||
use database::{db::DATA_ROOT_DIR, GameVersion};
|
|
||||||
use log::warn;
|
|
||||||
|
|
||||||
use crate::error::BackupError;
|
|
||||||
|
|
||||||
use super::path::CommonPath;
|
|
||||||
|
|
||||||
pub struct BackupManager<'a> {
|
|
||||||
pub current_platform: Platform,
|
|
||||||
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 {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
current_platform: Platform::Windows,
|
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
current_platform: Platform::macOS,
|
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
current_platform: Platform::Linux,
|
|
||||||
|
|
||||||
sources: HashMap::from([
|
|
||||||
// Current platform to target platform
|
|
||||||
(
|
|
||||||
(Platform::Windows, Platform::Windows),
|
|
||||||
&WindowsBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(Platform::Linux, Platform::Linux),
|
|
||||||
&LinuxBackupManager {} as &(dyn BackupHandler + Sync + Send),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
(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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct LinuxBackupManager {}
|
|
||||||
impl BackupHandler for LinuxBackupManager {
|
|
||||||
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> {
|
|
||||||
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> {
|
|
||||||
CommonPath::Config.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> {
|
|
||||||
CommonPath::DataLocalLow
|
|
||||||
.get()
|
|
||||||
.ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
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> {
|
|
||||||
CommonPath::Document.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
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> {
|
|
||||||
CommonPath::Public.get().ok_or(BackupError::NotFound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub struct MacBackupManager {}
|
|
||||||
impl BackupHandler for MacBackupManager {}
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
#![feature(nonpoison_rwlock)]
|
|
||||||
|
|
||||||
pub mod db;
|
|
||||||
pub mod debug;
|
|
||||||
pub mod interface;
|
|
||||||
pub mod models;
|
|
||||||
pub mod platform;
|
|
||||||
|
|
||||||
pub use db::DB;
|
|
||||||
pub use interface::{borrow_db_checked, borrow_db_mut_checked};
|
|
||||||
pub use models::{
|
|
||||||
ApplicationTransientStatus, Database, DatabaseApplications, DatabaseAuth, DownloadType,
|
|
||||||
DownloadableMetadata, GameDownloadStatus, GameVersion, Settings,
|
|
||||||
};
|
|
||||||
@ -1,110 +0,0 @@
|
|||||||
mod v1;
|
|
||||||
mod v2;
|
|
||||||
mod v3;
|
|
||||||
mod v4;
|
|
||||||
|
|
||||||
use std::{hash::Hash, path::PathBuf};
|
|
||||||
|
|
||||||
use native_model::native_model;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use crate::db::DropDatabaseSerializer;
|
|
||||||
|
|
||||||
|
|
||||||
// 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;
|
|
||||||
pub type Database = v4::Database;
|
|
||||||
pub type Settings = v1::Settings;
|
|
||||||
pub type DatabaseAuth = v1::DatabaseAuth;
|
|
||||||
|
|
||||||
pub type GameDownloadStatus = v2::GameDownloadStatus;
|
|
||||||
pub type ApplicationTransientStatus = v1::ApplicationTransientStatus;
|
|
||||||
/**
|
|
||||||
* Need to be universally accessible by the ID, and the version is just a couple sprinkles on top
|
|
||||||
*/
|
|
||||||
pub type DownloadableMetadata = v1::DownloadableMetadata;
|
|
||||||
pub type DownloadType = v1::DownloadType;
|
|
||||||
pub type DatabaseApplications = v2::DatabaseApplications;
|
|
||||||
// pub type DatabaseCompatInfo = v2::DatabaseCompatInfo;
|
|
||||||
|
|
||||||
pub type Game = v1::Game;
|
|
||||||
|
|
||||||
impl Game {
|
|
||||||
pub fn id(&self) -> &String {
|
|
||||||
&self.id
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type DatabaseInterface =
|
|
||||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
|
||||||
|
|
||||||
pub type LibraryMetadata = v1::LibraryMetadata;
|
|
||||||
pub type LibraryProviderMetadata = v1::LibraryProviderMetadata;
|
|
||||||
pub type ProviderType = v1::ProviderType;
|
|
||||||
|
|
||||||
pub type Collection = v1::Collection;
|
|
||||||
pub type CollectionObject = v1::CollectionObject;
|
|
||||||
|
|
||||||
impl PartialEq for DownloadableMetadata {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.id == other.id && self.download_type == other.download_type
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Hash for DownloadableMetadata {
|
|
||||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.id.hash(state);
|
|
||||||
self.download_type.hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl LibraryProviderMetadata {
|
|
||||||
pub fn provider(&self) -> &ProviderType {
|
|
||||||
&self.provider
|
|
||||||
}
|
|
||||||
pub fn id(&self) -> usize {
|
|
||||||
self.id
|
|
||||||
}
|
|
||||||
pub fn name(&self) -> &String {
|
|
||||||
&self.name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Database {
|
|
||||||
pub fn new<T: Into<PathBuf>>(
|
|
||||||
games_base_dir: T,
|
|
||||||
prev_database: Option<PathBuf>,
|
|
||||||
cache_dir: PathBuf,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
prev_database,
|
|
||||||
settings: Settings::default(),
|
|
||||||
cache_dir,
|
|
||||||
compat_info: None,
|
|
||||||
library: v1::LibraryMetadata { providers: vec![] },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl DatabaseAuth {
|
|
||||||
pub fn new(
|
|
||||||
private: String,
|
|
||||||
cert: String,
|
|
||||||
client_id: String,
|
|
||||||
web_token: Option<String>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
private,
|
|
||||||
cert,
|
|
||||||
client_id,
|
|
||||||
web_token,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LibraryMetadata {
|
|
||||||
pub fn providers(&self) -> &Vec<LibraryProviderMetadata> {
|
|
||||||
&self.providers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,201 +0,0 @@
|
|||||||
use bitcode::{Decode, Encode};
|
|
||||||
use serde_with::serde_as;
|
|
||||||
use std::{collections::HashMap, path::PathBuf};
|
|
||||||
|
|
||||||
use crate::{models::v1, platform::Platform};
|
|
||||||
|
|
||||||
use super::{Deserialize, Serialize, native_model};
|
|
||||||
|
|
||||||
fn default_template() -> String {
|
|
||||||
"{}".to_owned()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[native_model(id = 2, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
pub struct GameVersion {
|
|
||||||
pub game_id: String,
|
|
||||||
pub version_name: String,
|
|
||||||
|
|
||||||
pub platform: Platform,
|
|
||||||
|
|
||||||
pub launch_command: String,
|
|
||||||
pub launch_args: Vec<String>,
|
|
||||||
#[serde(default = "default_template")]
|
|
||||||
pub launch_command_template: String,
|
|
||||||
|
|
||||||
pub setup_command: String,
|
|
||||||
pub setup_args: Vec<String>,
|
|
||||||
#[serde(default = "default_template")]
|
|
||||||
pub setup_command_template: String,
|
|
||||||
|
|
||||||
pub only_setup: bool,
|
|
||||||
|
|
||||||
pub version_index: usize,
|
|
||||||
pub delta: bool,
|
|
||||||
|
|
||||||
pub umu_id_override: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[serde_as]
|
|
||||||
#[derive(Serialize, Clone, Deserialize, Default)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[native_model(id = 3, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
pub struct DatabaseApplications {
|
|
||||||
pub install_dirs: Vec<PathBuf>,
|
|
||||||
// Guaranteed to exist if the game also exists in the app state map
|
|
||||||
pub game_statuses: HashMap<String, v1::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>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[native_model(id = 4, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
pub struct Settings {
|
|
||||||
pub autostart: bool,
|
|
||||||
pub max_download_threads: usize,
|
|
||||||
pub force_offline: bool, // ... other settings ...
|
|
||||||
}
|
|
||||||
impl Default for Settings {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
autostart: false,
|
|
||||||
max_download_threads: 4,
|
|
||||||
force_offline: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strings are version names for a particular game
|
|
||||||
#[derive(Serialize, Clone, Deserialize, Debug)]
|
|
||||||
#[serde(tag = "type")]
|
|
||||||
#[native_model(id = 5, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
pub enum GameDownloadStatus {
|
|
||||||
Remote {},
|
|
||||||
SetupRequired {
|
|
||||||
version_name: String,
|
|
||||||
install_dir: String,
|
|
||||||
},
|
|
||||||
Installed {
|
|
||||||
version_name: String,
|
|
||||||
install_dir: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stuff that shouldn't be synced to disk
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
|
||||||
pub enum ApplicationTransientStatus {
|
|
||||||
Queued { version_name: String },
|
|
||||||
Downloading { version_name: String },
|
|
||||||
Uninstalling {},
|
|
||||||
Updating { version_name: String },
|
|
||||||
Validating { version_name: String },
|
|
||||||
Running {},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, Encode, Decode)]
|
|
||||||
#[native_model(id = 6, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
pub struct DatabaseAuth {
|
|
||||||
pub private: String,
|
|
||||||
pub cert: String,
|
|
||||||
pub client_id: String,
|
|
||||||
pub web_token: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 8, version = 1)]
|
|
||||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Clone, Copy)]
|
|
||||||
pub enum DownloadType {
|
|
||||||
Game,
|
|
||||||
Tool,
|
|
||||||
Dlc,
|
|
||||||
Mod,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 7, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Debug, Eq, PartialOrd, Ord, Serialize, Deserialize, Clone)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct DownloadableMetadata {
|
|
||||||
pub id: String,
|
|
||||||
pub version: Option<String>,
|
|
||||||
pub download_type: v1::DownloadType,
|
|
||||||
}
|
|
||||||
impl DownloadableMetadata {
|
|
||||||
pub fn new(id: String, version: Option<String>, download_type: v1::DownloadType) -> Self {
|
|
||||||
Self {
|
|
||||||
id,
|
|
||||||
version,
|
|
||||||
download_type,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 1, version = 1)]
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
|
||||||
pub struct Database {
|
|
||||||
#[serde(default)]
|
|
||||||
pub settings: Settings,
|
|
||||||
pub auth: Option<v1::DatabaseAuth>,
|
|
||||||
pub base_url: String,
|
|
||||||
pub applications: v1::DatabaseApplications,
|
|
||||||
pub prev_database: Option<PathBuf>,
|
|
||||||
pub cache_dir: PathBuf,
|
|
||||||
}
|
|
||||||
#[native_model(id = 15, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode, Default)]
|
|
||||||
pub struct LibraryMetadata {
|
|
||||||
pub(crate) providers: Vec<v1::LibraryProviderMetadata>
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#[native_model(id = 11, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode)]
|
|
||||||
pub struct LibraryProviderMetadata {
|
|
||||||
pub(crate) id: usize,
|
|
||||||
pub(crate) name: String,
|
|
||||||
pub(crate) provider: v1::ProviderType
|
|
||||||
}
|
|
||||||
#[native_model(id = 10, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode)]
|
|
||||||
pub enum ProviderType {
|
|
||||||
Drop(v1::DatabaseAuth),
|
|
||||||
}
|
|
||||||
#[native_model(id = 12, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode)]
|
|
||||||
pub struct Game {
|
|
||||||
pub library_id: LibraryProviderMetadata,
|
|
||||||
pub(crate) id: String,
|
|
||||||
m_name: String,
|
|
||||||
m_short_description: String,
|
|
||||||
m_description: String,
|
|
||||||
// mDevelopers
|
|
||||||
// mPublishers
|
|
||||||
m_icon_object_id: String,
|
|
||||||
m_banner_object_id: String,
|
|
||||||
m_cover_object_id: String,
|
|
||||||
m_image_library_object_ids: Vec<String>,
|
|
||||||
m_image_carousel_object_ids: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 13, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct Collection {
|
|
||||||
id: String,
|
|
||||||
name: String,
|
|
||||||
is_default: bool,
|
|
||||||
user_id: String,
|
|
||||||
entries: Vec<CollectionObject>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 14, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct CollectionObject {
|
|
||||||
collection_id: String,
|
|
||||||
game_id: String,
|
|
||||||
game: Game,
|
|
||||||
}
|
|
||||||
@ -1,111 +0,0 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf};
|
|
||||||
|
|
||||||
use serde_with::serde_as;
|
|
||||||
|
|
||||||
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)]
|
|
||||||
pub struct Database {
|
|
||||||
#[serde(default)]
|
|
||||||
pub settings: v1::Settings,
|
|
||||||
pub auth: Option<v1::DatabaseAuth>,
|
|
||||||
pub base_url: String,
|
|
||||||
pub applications: v1::DatabaseApplications,
|
|
||||||
#[serde(skip)]
|
|
||||||
pub prev_database: Option<PathBuf>,
|
|
||||||
pub cache_dir: PathBuf,
|
|
||||||
pub compat_info: Option<DatabaseCompatInfo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[native_model(id = 9, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
|
||||||
|
|
||||||
pub struct DatabaseCompatInfo {
|
|
||||||
pub umu_installed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<v1::Database> for Database {
|
|
||||||
fn from(value: v1::Database) -> Self {
|
|
||||||
Self {
|
|
||||||
settings: value.settings,
|
|
||||||
auth: value.auth,
|
|
||||||
base_url: value.base_url,
|
|
||||||
applications: value.applications,
|
|
||||||
prev_database: value.prev_database,
|
|
||||||
cache_dir: value.cache_dir,
|
|
||||||
compat_info: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Strings are version names for a particular game
|
|
||||||
#[derive(Serialize, Clone, Deserialize, Debug)]
|
|
||||||
#[serde(tag = "type")]
|
|
||||||
#[native_model(id = 5, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from = v1::GameDownloadStatus)]
|
|
||||||
pub enum GameDownloadStatus {
|
|
||||||
Remote {},
|
|
||||||
SetupRequired {
|
|
||||||
version_name: String,
|
|
||||||
install_dir: String,
|
|
||||||
},
|
|
||||||
Installed {
|
|
||||||
version_name: String,
|
|
||||||
install_dir: String,
|
|
||||||
},
|
|
||||||
PartiallyInstalled {
|
|
||||||
version_name: String,
|
|
||||||
install_dir: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
impl From<v1::GameDownloadStatus> for GameDownloadStatus {
|
|
||||||
fn from(value: v1::GameDownloadStatus) -> Self {
|
|
||||||
match value {
|
|
||||||
v1::GameDownloadStatus::Remote {} => Self::Remote {},
|
|
||||||
v1::GameDownloadStatus::SetupRequired {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Self::SetupRequired {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
},
|
|
||||||
v1::GameDownloadStatus::Installed {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Self::Installed {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[serde_as]
|
|
||||||
#[derive(Serialize, Clone, Deserialize, Default)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[native_model(id = 3, version = 2, with = native_model::rmp_serde_1_3::RmpSerde, from=v1::DatabaseApplications)]
|
|
||||||
pub struct DatabaseApplications {
|
|
||||||
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>,
|
|
||||||
}
|
|
||||||
impl From<v1::DatabaseApplications> for DatabaseApplications {
|
|
||||||
fn from(value: v1::DatabaseApplications) -> Self {
|
|
||||||
Self {
|
|
||||||
game_statuses: value
|
|
||||||
.game_statuses
|
|
||||||
.into_iter()
|
|
||||||
.map(|x| (x.0, x.1.into()))
|
|
||||||
.collect::<HashMap<String, GameDownloadStatus>>(),
|
|
||||||
install_dirs: value.install_dirs,
|
|
||||||
game_versions: value.game_versions,
|
|
||||||
installed_game_version: value.installed_game_version,
|
|
||||||
transient_statuses: value.transient_statuses,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,32 +0,0 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf};
|
|
||||||
|
|
||||||
use serde_with::serde_as;
|
|
||||||
|
|
||||||
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 {
|
|
||||||
#[serde(default)]
|
|
||||||
pub settings: v1::Settings,
|
|
||||||
pub auth: Option<v1::DatabaseAuth>,
|
|
||||||
pub base_url: String,
|
|
||||||
pub applications: v2::DatabaseApplications,
|
|
||||||
#[serde(skip)]
|
|
||||||
pub prev_database: Option<PathBuf>,
|
|
||||||
pub cache_dir: PathBuf,
|
|
||||||
pub compat_info: Option<v2::DatabaseCompatInfo>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<v2::Database> for Database {
|
|
||||||
fn from(value: v2::Database) -> Self {
|
|
||||||
Self {
|
|
||||||
settings: value.settings,
|
|
||||||
auth: value.auth,
|
|
||||||
base_url: value.base_url,
|
|
||||||
applications: value.applications.into(),
|
|
||||||
prev_database: value.prev_database,
|
|
||||||
cache_dir: value.cache_dir,
|
|
||||||
compat_info: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,43 +0,0 @@
|
|||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use native_model::native_model;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::models::{
|
|
||||||
v1::{self, LibraryMetadata},
|
|
||||||
v2, v3,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[native_model(id = 1, version = 4, with = native_model::rmp_serde_1_3::RmpSerde, from = v3::Database)]
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
|
||||||
pub struct Database {
|
|
||||||
#[serde(default)]
|
|
||||||
pub settings: v1::Settings,
|
|
||||||
#[serde(skip)]
|
|
||||||
pub prev_database: Option<PathBuf>,
|
|
||||||
pub cache_dir: PathBuf,
|
|
||||||
pub compat_info: Option<v2::DatabaseCompatInfo>,
|
|
||||||
pub library: v1::LibraryMetadata,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<v3::Database> for Database {
|
|
||||||
fn from(value: v3::Database) -> Self {
|
|
||||||
Self {
|
|
||||||
settings: value.settings,
|
|
||||||
prev_database: value.prev_database,
|
|
||||||
cache_dir: value.cache_dir,
|
|
||||||
compat_info: value.compat_info,
|
|
||||||
library: v1::LibraryMetadata {
|
|
||||||
providers: if let Some(auth) = value.auth {
|
|
||||||
vec![v1::LibraryProviderMetadata {
|
|
||||||
id: 0,
|
|
||||||
name: String::from("Default"),
|
|
||||||
provider: v1::ProviderType::Drop(auth),
|
|
||||||
}]
|
|
||||||
} else {
|
|
||||||
vec![]
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
#![feature(duration_millis_float)]
|
|
||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![feature(sync_nonpoison)]
|
|
||||||
|
|
||||||
use std::{ops::Deref, sync::OnceLock};
|
|
||||||
|
|
||||||
use tauri::AppHandle;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
download_manager_builder::DownloadManagerBuilder, download_manager_frontend::DownloadManager,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod download_manager_builder;
|
|
||||||
pub mod download_manager_frontend;
|
|
||||||
pub mod downloadable;
|
|
||||||
pub mod error;
|
|
||||||
pub mod frontend_updates;
|
|
||||||
pub mod util;
|
|
||||||
|
|
||||||
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,7 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "drop-consts"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
dirs = "6.0.0"
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
use std::{path::PathBuf, sync::LazyLock};
|
|
||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
pub const DATA_ROOT_PREFIX: &str = "drop";
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
pub const DATA_ROOT_PREFIX: &str = "drop-debug";
|
|
||||||
|
|
||||||
pub const DROP_DATA_PATH: &str = ".dropdata";
|
|
||||||
|
|
||||||
pub const RETRY_COUNT: usize = 3;
|
|
||||||
|
|
||||||
pub const TARGET_BUCKET_SIZE: usize = 63 * 1000 * 1000;
|
|
||||||
pub const MAX_FILES_PER_BUCKET: usize = (1024 / 4) - 1;
|
|
||||||
|
|
||||||
pub const UMU_BASE_LAUNCHER_EXECUTABLE: &str = "umu-run";
|
|
||||||
pub const UMU_INSTALL_DIRS: [&str; 4] = ["/app/share", "/use/local/share", "/usr/share", "/opt"];
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(SerializeDisplay)]
|
|
||||||
pub enum LibraryError {
|
|
||||||
MetaNotFound(String),
|
|
||||||
VersionNotFound(String),
|
|
||||||
}
|
|
||||||
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"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
LibraryError::VersionNotFound(game_id) => {
|
|
||||||
format!(
|
|
||||||
"Could not locate any installed version for game id {game_id} in the database"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "library"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
async-trait = "0.1.89"
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
futures = "0.3.31"
|
|
||||||
itertools = "0.14.0"
|
|
||||||
log = "0.4.28"
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
url = "2.5.7"
|
|
||||||
@ -1,134 +0,0 @@
|
|||||||
use std::sync::nonpoison::Mutex;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use client::app_state::AppState;
|
|
||||||
use database::{
|
|
||||||
DatabaseAuth, GameDownloadStatus, borrow_db_mut_checked,
|
|
||||||
models::{Collection, Game, LibraryProviderMetadata},
|
|
||||||
};
|
|
||||||
use log::warn;
|
|
||||||
use remote::{
|
|
||||||
auth::generate_authorization_header,
|
|
||||||
cache::{cache_object, get_cached_object, get_cached_object_db},
|
|
||||||
error::{DropServerError, RemoteAccessError},
|
|
||||||
requests::generate_url,
|
|
||||||
utils::DROP_CLIENT_ASYNC,
|
|
||||||
};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{error::LibraryError, provider::LibraryProvider};
|
|
||||||
|
|
||||||
pub struct DropLibraryProvider {
|
|
||||||
metadata: LibraryProviderMetadata,
|
|
||||||
auth: DatabaseAuth,
|
|
||||||
base_url: Url,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DropLibraryProvider {
|
|
||||||
pub fn new(metadata: LibraryProviderMetadata, auth: DatabaseAuth, base_url: Url) -> Self {
|
|
||||||
Self {
|
|
||||||
metadata,
|
|
||||||
auth,
|
|
||||||
base_url,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#[async_trait]
|
|
||||||
impl LibraryProvider for DropLibraryProvider {
|
|
||||||
async fn get_library(
|
|
||||||
&self,
|
|
||||||
state: &tauri::State<'_, Mutex<AppState>>,
|
|
||||||
) -> Result<Vec<Game>, LibraryError> {
|
|
||||||
// let do_hard_refresh = hard_fresh.unwrap_or(false);
|
|
||||||
if
|
|
||||||
/* !do_hard_refresh &&*/
|
|
||||||
let Ok(library) = get_cached_object("library") {
|
|
||||||
return Ok(library);
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let response = generate_url(&["/api/v1/client/user/library"], &[], self.base_url)?;
|
|
||||||
let response = client
|
|
||||||
.get(response)
|
|
||||||
.header("Authorization", generate_authorization_header(self.auth))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.map_err(|e| LibraryError::FetchError(RemoteAccessError::FetchError(e.into())))?;
|
|
||||||
|
|
||||||
if response.status() != 200 {
|
|
||||||
let err = response.json().await.unwrap_or(DropServerError {
|
|
||||||
status_code: 500,
|
|
||||||
status_message: "Invalid response from server.".to_owned(),
|
|
||||||
});
|
|
||||||
warn!("{err:?}");
|
|
||||||
return Err(LibraryError::FetchError(
|
|
||||||
RemoteAccessError::InvalidResponse(err),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut games: Vec<Game> = response
|
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.map_err(|e| RemoteAccessError::FetchError(e.into()))?;
|
|
||||||
|
|
||||||
let mut handle = state.lock();
|
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
|
|
||||||
for game in &games {
|
|
||||||
handle.games_mut().insert(game.id().clone(), game.clone());
|
|
||||||
if !db_handle.applications.game_statuses.contains_key(game.id()) {
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.insert(game.id().clone(), GameDownloadStatus::Remote {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add games that are installed but no longer in library
|
|
||||||
for meta in db_handle.applications.installed_game_version.values() {
|
|
||||||
if games.iter().any(|e| *e.id() == meta.id) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// We should always have a cache of the object
|
|
||||||
// Pass db_handle because otherwise we get a gridlock
|
|
||||||
let game = match get_cached_object_db::<Game>(&meta.id.clone(), &db_handle) {
|
|
||||||
Ok(game) => game,
|
|
||||||
Err(err) => {
|
|
||||||
warn!(
|
|
||||||
"{} is installed, but encountered error fetching its error: {}.",
|
|
||||||
meta.id, err
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
games.push(game);
|
|
||||||
}
|
|
||||||
|
|
||||||
drop(handle);
|
|
||||||
drop(db_handle);
|
|
||||||
cache_object("library", &games)?;
|
|
||||||
|
|
||||||
Ok(games)
|
|
||||||
}
|
|
||||||
async fn get_collections(&self) -> Result<Vec<Collection>, LibraryError> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn install(&mut self, game_id: String) {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn uninstall(&mut self, game_id: String) {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn metadata(&self) -> LibraryProviderMetadata {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fetch_library_logic(state: &Mutex<AppState>) -> Result<Vec<Game>, RemoteAccessError> {}
|
|
||||||
async fn fetch_library_logic_offline() -> Result<Vec<Game>, RemoteAccessError> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
@ -1 +0,0 @@
|
|||||||
pub mod drop;
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use database::models::LibraryProviderMetadata;
|
|
||||||
use remote::error::RemoteAccessError;
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
|
||||||
pub enum LibraryError {
|
|
||||||
ProviderConnection(ProviderError),
|
|
||||||
FetchError(RemoteAccessError)
|
|
||||||
}
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
|
||||||
pub struct ProviderError {
|
|
||||||
provider: LibraryProviderMetadata
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for LibraryError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Display for ProviderError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl From<RemoteAccessError> for LibraryError {
|
|
||||||
fn from(value: RemoteAccessError) -> Self {
|
|
||||||
LibraryError::FetchError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,69 +0,0 @@
|
|||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![feature(sync_nonpoison)]
|
|
||||||
|
|
||||||
use std::sync::{LazyLock, nonpoison::Mutex};
|
|
||||||
|
|
||||||
use client::app_state::AppState;
|
|
||||||
use database::{borrow_db_checked, models::{Game, LibraryProviderMetadata, ProviderType}};
|
|
||||||
use futures::{StreamExt, future::join_all};
|
|
||||||
use itertools::Itertools;
|
|
||||||
|
|
||||||
use crate::{drop::drop::DropLibraryProvider, error::LibraryError, provider::LibraryProvider};
|
|
||||||
|
|
||||||
pub mod drop;
|
|
||||||
pub mod error;
|
|
||||||
pub mod provider;
|
|
||||||
|
|
||||||
pub static LIBRARY: LazyLock<Library> = LazyLock::new(Library::init);
|
|
||||||
|
|
||||||
pub struct Library {
|
|
||||||
providers: Vec<Box<dyn LibraryProvider>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Library {
|
|
||||||
pub fn init() -> Self {
|
|
||||||
let metadata = borrow_db_checked();
|
|
||||||
let library = &metadata.library;
|
|
||||||
let providers = library.providers().iter().map(|provider| {
|
|
||||||
Library::construct(provider)
|
|
||||||
}).collect();
|
|
||||||
Self {
|
|
||||||
providers
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn construct(provider: &LibraryProviderMetadata) -> Box<dyn LibraryProvider> {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
pub async fn get_library(
|
|
||||||
&self,
|
|
||||||
state: &tauri::State<'_, Mutex<AppState>>,
|
|
||||||
) -> (Vec<Game>, Vec<LibraryError>) {
|
|
||||||
let res = join_all(
|
|
||||||
self.providers
|
|
||||||
.iter()
|
|
||||||
.map(|provider| provider.get_library(state)),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.into_iter()
|
|
||||||
.fold(
|
|
||||||
(Vec::new(), Vec::new()),
|
|
||||||
|(mut acc_ok, mut acc_err), res| {
|
|
||||||
match res {
|
|
||||||
Ok(games) => acc_ok.extend(games),
|
|
||||||
Err(e) => acc_err.push(e),
|
|
||||||
};
|
|
||||||
(acc_ok, acc_err)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
res
|
|
||||||
}
|
|
||||||
pub fn add(&mut self, provider: LibraryProviderMetadata) {
|
|
||||||
let new_provider = Box::new(match provider.provider() {
|
|
||||||
ProviderType::Drop(_) => DropLibraryProvider::new(provider),
|
|
||||||
});
|
|
||||||
self.providers.push(new_provider);
|
|
||||||
}
|
|
||||||
pub fn remove(&mut self, id: usize) {
|
|
||||||
self.providers.retain(|v| v.metadata().id() != id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
use std::sync::nonpoison::Mutex;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use client::app_state::AppState;
|
|
||||||
use database::models::{Collection, Game, LibraryProviderMetadata};
|
|
||||||
|
|
||||||
use crate::error::LibraryError;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
pub trait LibraryProvider: Sync + Send {
|
|
||||||
async fn get_library(&self, state: &tauri::State<'_, Mutex<AppState>>) -> Result<Vec<Game>, LibraryError>;
|
|
||||||
async fn get_collections(&self) -> Result<Vec<Collection>, LibraryError>;
|
|
||||||
fn install(&mut self, game_id: String);
|
|
||||||
fn uninstall(&mut self, game_id: String);
|
|
||||||
fn metadata(&self) -> LibraryProviderMetadata;
|
|
||||||
}
|
|
||||||
@ -1,41 +0,0 @@
|
|||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![feature(sync_nonpoison)]
|
|
||||||
|
|
||||||
use std::{
|
|
||||||
ops::Deref,
|
|
||||||
sync::{OnceLock, nonpoison::Mutex},
|
|
||||||
};
|
|
||||||
|
|
||||||
use tauri::AppHandle;
|
|
||||||
|
|
||||||
use crate::process_manager::ProcessManager;
|
|
||||||
|
|
||||||
pub static PROCESS_MANAGER: ProcessManagerWrapper = ProcessManagerWrapper::new();
|
|
||||||
|
|
||||||
pub mod error;
|
|
||||||
pub mod format;
|
|
||||||
pub mod process_handlers;
|
|
||||||
pub mod process_manager;
|
|
||||||
|
|
||||||
pub struct ProcessManagerWrapper(OnceLock<Mutex<ProcessManager<'static>>>);
|
|
||||||
impl ProcessManagerWrapper {
|
|
||||||
const fn new() -> Self {
|
|
||||||
ProcessManagerWrapper(OnceLock::new())
|
|
||||||
}
|
|
||||||
pub fn init(app_handle: AppHandle) {
|
|
||||||
PROCESS_MANAGER
|
|
||||||
.0
|
|
||||||
.set(Mutex::new(ProcessManager::new(app_handle)))
|
|
||||||
.unwrap_or_else(|_| panic!("Failed to initialise Process Manager")); // Using panic! here because we can't implement Debug
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Deref for ProcessManagerWrapper {
|
|
||||||
type Target = Mutex<ProcessManager<'static>>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self.0.get() {
|
|
||||||
Some(process_manager) => process_manager,
|
|
||||||
None => unreachable!("Download manager should always be initialised"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,29 +1,30 @@
|
|||||||
use std::sync::nonpoison::Mutex;
|
|
||||||
|
|
||||||
use client::app_state::AppState;
|
|
||||||
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 tauri_plugin_opener::OpenerExt;
|
use utils::lock;
|
||||||
|
|
||||||
|
use crate::{AppState};
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn fetch_state(state: tauri::State<'_, Mutex<AppState>>) -> Result<String, String> {
|
pub fn fetch_state(
|
||||||
let guard = state.lock();
|
state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>,
|
||||||
|
) -> 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) {
|
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
cleanup_and_exit(&app);
|
cleanup_and_exit(&app, &state);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cleanup_and_exit(app: &AppHandle) {
|
pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
debug!("cleaning up and exiting application");
|
debug!("cleaning up and exiting application");
|
||||||
match DOWNLOAD_MANAGER.ensure_terminated() {
|
let download_manager = lock!(state).download_manager.clone();
|
||||||
|
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"),
|
||||||
@ -72,10 +73,3 @@ pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autost
|
|||||||
|
|
||||||
Ok(db_state)
|
Ok(db_state)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn open_fs(path: String, app_handle: AppHandle) -> Result<(), tauri_plugin_opener::Error> {
|
|
||||||
app_handle
|
|
||||||
.opener()
|
|
||||||
.open_path(path, None::<&str>)
|
|
||||||
}
|
|
||||||
|
|||||||
@ -1,12 +1,16 @@
|
|||||||
use games::collections::collection::{Collection, Collections};
|
use serde_json::json;
|
||||||
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,22 +1,27 @@
|
|||||||
use database::DownloadableMetadata;
|
use std::sync::Mutex;
|
||||||
use download_manager::DOWNLOAD_MANAGER;
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn pause_downloads() {
|
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||||
DOWNLOAD_MANAGER.pause_downloads();
|
lock!(state).download_manager.pause_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn resume_downloads() {
|
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||||
DOWNLOAD_MANAGER.resume_downloads();
|
lock!(state).download_manager.resume_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn move_download_in_queue(old_index: usize, new_index: usize) {
|
pub fn move_download_in_queue(
|
||||||
DOWNLOAD_MANAGER.rearrange(old_index, new_index);
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
|
old_index: usize,
|
||||||
|
new_index: usize,
|
||||||
|
) {
|
||||||
|
lock!(state)
|
||||||
|
.download_manager
|
||||||
|
.rearrange(old_index, new_index);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn cancel_game(meta: DownloadableMetadata) {
|
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
|
||||||
DOWNLOAD_MANAGER.cancel(meta);
|
lock!(state).download_manager.cancel(meta);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,31 +1,34 @@
|
|||||||
use std::{path::PathBuf, sync::Arc};
|
use std::{
|
||||||
|
path::PathBuf,
|
||||||
use database::{GameDownloadStatus, borrow_db_checked};
|
sync::{Arc, Mutex},
|
||||||
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 = { DOWNLOAD_MANAGER.get_sender().clone() };
|
let sender = { lock!(state).download_manager.get_sender().clone() };
|
||||||
|
|
||||||
let game_download_agent = GameDownloadAgent::new_from_index(
|
let game_download_agent =
|
||||||
game_id.clone(),
|
GameDownloadAgent::new_from_index(game_id.clone(), game_version.clone(), install_dir, sender).await?;
|
||||||
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();
|
||||||
|
|
||||||
@ -33,7 +36,10 @@ pub async fn download_game(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn resume_download(game_id: String) -> Result<(), ApplicationDownloadError> {
|
pub async fn resume_download(
|
||||||
|
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
|
||||||
@ -51,25 +57,21 @@ pub async fn resume_download(game_id: String) -> Result<(), ApplicationDownloadE
|
|||||||
} => (version_name, install_dir),
|
} => (version_name, install_dir),
|
||||||
};
|
};
|
||||||
|
|
||||||
let sender = DOWNLOAD_MANAGER.get_sender();
|
let sender = lock!(state).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_dir.parent().unwrap_or_else(|| panic!("Failed to get parent directry of {}", parent_dir.display())).to_path_buf(),
|
||||||
.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>);
|
||||||
|
|
||||||
DOWNLOAD_MANAGER
|
lock!(state)
|
||||||
|
.download_manager
|
||||||
.queue_download(game_download_agent)
|
.queue_download(game_download_agent)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@ -1,28 +1,19 @@
|
|||||||
use std::sync::nonpoison::Mutex;
|
use std::sync::Mutex;
|
||||||
|
|
||||||
use database::{GameDownloadStatus, GameVersion, borrow_db_checked, borrow_db_mut_checked, models::Game};
|
use database::{borrow_db_checked, borrow_db_mut_checked, GameDownloadStatus, GameVersion};
|
||||||
use games::{
|
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, Game}, state::{GameStatusManager, GameStatusWithTransient}};
|
||||||
downloads::error::LibraryError,
|
|
||||||
library::{FetchGameStruct, FrontendGameOptions, 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::{
|
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};
|
||||||
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 client::app_state::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!(
|
||||||
@ -31,20 +22,82 @@ 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>,
|
||||||
) -> (Vec<Game>, Vec<LibraryError>) {
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
|
let do_hard_refresh = hard_fresh.unwrap_or(false);
|
||||||
|
if !do_hard_refresh && let Ok(library) = get_cached_object("library") {
|
||||||
|
return Ok(library);
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
let response = generate_url(&["/api/v1/client/user/library"], &[])?;
|
||||||
|
let response = client
|
||||||
|
.get(response)
|
||||||
|
.header("Authorization", generate_authorization_header())
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if response.status() != 200 {
|
||||||
|
let err = response.json().await.unwrap_or(DropServerError {
|
||||||
|
status_code: 500,
|
||||||
|
status_message: "Invalid response from server.".to_owned(),
|
||||||
|
});
|
||||||
|
warn!("{err:?}");
|
||||||
|
return Err(RemoteAccessError::InvalidResponse(err));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut games: Vec<Game> = response.json().await?;
|
||||||
|
|
||||||
|
let mut handle = lock!(state);
|
||||||
|
|
||||||
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
|
||||||
|
for game in &games {
|
||||||
|
handle.games.insert(game.id().clone(), game.clone());
|
||||||
|
if !db_handle.applications.game_statuses.contains_key(game.id()) {
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.game_statuses
|
||||||
|
.insert(game.id().clone(), GameDownloadStatus::Remote {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add games that are installed but no longer in library
|
||||||
|
for meta in db_handle.applications.installed_game_version.values() {
|
||||||
|
if games.iter().any(|e| *e.id() == meta.id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// We should always have a cache of the object
|
||||||
|
// Pass db_handle because otherwise we get a gridlock
|
||||||
|
let game = match get_cached_object_db::<Game>(&meta.id.clone(), &db_handle) {
|
||||||
|
Ok(game) => game,
|
||||||
|
Err(err) => {
|
||||||
|
warn!(
|
||||||
|
"{} is installed, but encountered error fetching its error: {}.",
|
||||||
|
meta.id, err
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
games.push(game);
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(handle);
|
||||||
|
drop(db_handle);
|
||||||
|
cache_object("library", &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>,
|
||||||
) -> (Vec<Game>, Vec<LibraryError>) {
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
let mut games: Vec<Game> = get_cached_object("library")?;
|
let mut games: Vec<Game> = get_cached_object("library")?;
|
||||||
|
|
||||||
let db_handle = borrow_db_checked();
|
let db_handle = borrow_db_checked();
|
||||||
@ -64,10 +117,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 = state.lock();
|
let state_handle = lock!(state);
|
||||||
|
|
||||||
let db_lock = borrow_db_checked();
|
let db_lock = borrow_db_checked();
|
||||||
|
|
||||||
@ -82,7 +135,7 @@ pub async fn fetch_game_logic(
|
|||||||
.cloned(),
|
.cloned(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let game = state_handle.games().get(&id);
|
let game = state_handle.games.get(&id);
|
||||||
if let Some(game) = game {
|
if let Some(game) = game {
|
||||||
let status = GameStatusManager::fetch_state(&id, &db_lock);
|
let status = GameStatusManager::fetch_state(&id, &db_lock);
|
||||||
|
|
||||||
@ -120,8 +173,8 @@ pub async fn fetch_game_logic(
|
|||||||
|
|
||||||
let game: Game = response.json().await?;
|
let game: Game = response.json().await?;
|
||||||
|
|
||||||
let mut state_handle = state.lock();
|
let mut state_handle = lock!(state);
|
||||||
state_handle.games_mut().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();
|
||||||
|
|
||||||
@ -144,7 +197,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();
|
||||||
|
|
||||||
@ -163,7 +216,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 = state.lock();
|
let state_lock = lock!(state);
|
||||||
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()
|
||||||
@ -175,9 +228,10 @@ 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);
|
||||||
@ -202,7 +256,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,
|
||||||
@ -210,8 +264,7 @@ 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]
|
||||||
@ -234,49 +287,7 @@ 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(())
|
|
||||||
}
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user