mirror of
https://github.com/Drop-OSS/drop-app.git
synced 2025-11-13 00:02:41 +10:00
Compare commits
4 Commits
5d22b883d5
...
113-bug-li
| Author | SHA1 | Date | |
|---|---|---|---|
| fe456cc2ef | |||
| 42ff3b1331 | |||
| db485b946b | |||
| 346ee1dddc |
2
.gitignore
vendored
2
.gitignore
vendored
@ -30,5 +30,3 @@ src-tauri/perf*
|
|||||||
|
|
||||||
/*.AppImage
|
/*.AppImage
|
||||||
/squashfs-root
|
/squashfs-root
|
||||||
|
|
||||||
/target/
|
|
||||||
|
|||||||
8288
Cargo.lock
generated
8288
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
14
Cargo.toml
14
Cargo.toml
@ -1,14 +0,0 @@
|
|||||||
[workspace]
|
|
||||||
members = [
|
|
||||||
"client",
|
|
||||||
"database",
|
|
||||||
"src-tauri",
|
|
||||||
"process",
|
|
||||||
"remote",
|
|
||||||
"utils",
|
|
||||||
"cloud_saves",
|
|
||||||
"download_manager",
|
|
||||||
"games",
|
|
||||||
]
|
|
||||||
|
|
||||||
resolver = "3"
|
|
||||||
4862
client/Cargo.lock
generated
4862
client/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,12 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "client"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
log = "0.4.28"
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
tauri = "2.8.5"
|
|
||||||
tauri-plugin-autostart = "2.5.0"
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Serialize, Eq, PartialEq)]
|
|
||||||
pub enum AppStatus {
|
|
||||||
NotConfigured,
|
|
||||||
Offline,
|
|
||||||
ServerError,
|
|
||||||
SignedOut,
|
|
||||||
SignedIn,
|
|
||||||
SignedInNeedsReauth,
|
|
||||||
ServerUnavailable,
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
use database::borrow_db_checked;
|
|
||||||
use log::debug;
|
|
||||||
use tauri::AppHandle;
|
|
||||||
use tauri_plugin_autostart::ManagerExt;
|
|
||||||
|
|
||||||
// New function to sync state on startup
|
|
||||||
pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
let should_be_enabled = db_handle.settings.autostart;
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
let manager = app.autolaunch();
|
|
||||||
let current_state = manager.is_enabled().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
if current_state != should_be_enabled {
|
|
||||||
if should_be_enabled {
|
|
||||||
manager.enable().map_err(|e| e.to_string())?;
|
|
||||||
debug!("synced autostart: enabled");
|
|
||||||
} else {
|
|
||||||
manager.disable().map_err(|e| e.to_string())?;
|
|
||||||
debug!("synced autostart: disabled");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
use std::{ffi::OsStr, path::PathBuf, process::{Command, Stdio}, sync::LazyLock};
|
|
||||||
|
|
||||||
use log::info;
|
|
||||||
|
|
||||||
pub static COMPAT_INFO: LazyLock<Option<CompatInfo>> = LazyLock::new(create_new_compat_info);
|
|
||||||
|
|
||||||
pub static UMU_LAUNCHER_EXECUTABLE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
|
||||||
let x = get_umu_executable();
|
|
||||||
info!("{:?}", &x);
|
|
||||||
x
|
|
||||||
});
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CompatInfo {
|
|
||||||
pub umu_installed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn create_new_compat_info() -> Option<CompatInfo> {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
return None;
|
|
||||||
|
|
||||||
let has_umu_installed = UMU_LAUNCHER_EXECUTABLE.is_some();
|
|
||||||
Some(CompatInfo {
|
|
||||||
umu_installed: has_umu_installed,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
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> {
|
|
||||||
if check_executable_exists(UMU_BASE_LAUNCHER_EXECUTABLE) {
|
|
||||||
return Some(PathBuf::from(UMU_BASE_LAUNCHER_EXECUTABLE));
|
|
||||||
}
|
|
||||||
|
|
||||||
for dir in UMU_INSTALL_DIRS {
|
|
||||||
let p = PathBuf::from(dir).join(UMU_BASE_LAUNCHER_EXECUTABLE);
|
|
||||||
if check_executable_exists(&p) {
|
|
||||||
return Some(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
fn check_executable_exists<P: AsRef<OsStr>>(exec: P) -> bool {
|
|
||||||
let has_umu_installed = Command::new(exec).stdout(Stdio::null()).output();
|
|
||||||
has_umu_installed.is_ok()
|
|
||||||
}
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
pub mod autostart;
|
|
||||||
pub mod user;
|
|
||||||
pub mod app_status;
|
|
||||||
pub mod compat;
|
|
||||||
@ -1,13 +0,0 @@
|
|||||||
use bitcode::{Decode, Encode};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Encode, Decode)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct User {
|
|
||||||
id: String,
|
|
||||||
username: String,
|
|
||||||
admin: bool,
|
|
||||||
display_name: String,
|
|
||||||
profile_picture_object_id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "cloud_saves"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
dirs = "6.0.0"
|
|
||||||
log = "0.4.28"
|
|
||||||
regex = "1.11.3"
|
|
||||||
rustix = "1.1.2"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_json = "1.0.145"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tar = "0.4.44"
|
|
||||||
tempfile = "3.23.0"
|
|
||||||
uuid = "1.18.1"
|
|
||||||
whoami = "1.6.1"
|
|
||||||
zstd = "0.13.3"
|
|
||||||
@ -1,27 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay, Clone, Copy)]
|
|
||||||
|
|
||||||
pub enum BackupError {
|
|
||||||
InvalidSystem,
|
|
||||||
|
|
||||||
NotFound,
|
|
||||||
|
|
||||||
ParseError,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for BackupError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
let s = match self {
|
|
||||||
BackupError::InvalidSystem => "Attempted to generate path for invalid system",
|
|
||||||
|
|
||||||
BackupError::NotFound => "Could not generate or find path",
|
|
||||||
|
|
||||||
BackupError::ParseError => "Failed to parse path",
|
|
||||||
};
|
|
||||||
|
|
||||||
write!(f, "{}", s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
pub mod conditions;
|
|
||||||
pub mod metadata;
|
|
||||||
pub mod resolver;
|
|
||||||
pub mod placeholder;
|
|
||||||
pub mod normalise;
|
|
||||||
pub mod path;
|
|
||||||
pub mod backup_manager;
|
|
||||||
pub mod error;
|
|
||||||
@ -1,15 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "database"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
chrono = "0.4.42"
|
|
||||||
dirs = "6.0.0"
|
|
||||||
log = "0.4.28"
|
|
||||||
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
|
||||||
rustbreak = "2.0.0"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
url = "2.5.7"
|
|
||||||
whoami = "1.6.1"
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
use std::{
|
|
||||||
path::PathBuf,
|
|
||||||
sync::{Arc, LazyLock},
|
|
||||||
};
|
|
||||||
|
|
||||||
use rustbreak::{DeSerError, DeSerializer};
|
|
||||||
use serde::{Serialize, de::DeserializeOwned};
|
|
||||||
|
|
||||||
use crate::interface::{DatabaseImpls, DatabaseInterface};
|
|
||||||
|
|
||||||
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
|
||||||
|
|
||||||
|
|
||||||
#[cfg(not(debug_assertions))]
|
|
||||||
static DATA_ROOT_PREFIX: &str = "drop";
|
|
||||||
#[cfg(debug_assertions)]
|
|
||||||
static DATA_ROOT_PREFIX: &str = "drop-debug";
|
|
||||||
|
|
||||||
pub static DATA_ROOT_DIR: LazyLock<Arc<PathBuf>> = LazyLock::new(|| {
|
|
||||||
Arc::new(
|
|
||||||
dirs::data_dir()
|
|
||||||
.expect("Failed to get data dir")
|
|
||||||
.join(DATA_ROOT_PREFIX),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
// Custom JSON serializer to support everything we need
|
|
||||||
#[derive(Debug, Default, Clone)]
|
|
||||||
pub struct DropDatabaseSerializer;
|
|
||||||
|
|
||||||
impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
|
||||||
for DropDatabaseSerializer
|
|
||||||
{
|
|
||||||
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
|
||||||
native_model::encode(val)
|
|
||||||
.map_err(|e| DeSerError::Internal(e.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
s.read_to_end(&mut buf)
|
|
||||||
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
|
||||||
let (val, _version) = native_model::decode(buf)
|
|
||||||
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
|
||||||
Ok(val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,21 +0,0 @@
|
|||||||
#![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};
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
|
||||||
pub enum Platform {
|
|
||||||
Windows,
|
|
||||||
Linux,
|
|
||||||
MacOs,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Platform {
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
pub const HOST: Platform = Self::Windows;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
pub const HOST: Platform = Self::MacOs;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
pub const HOST: Platform = Self::Linux;
|
|
||||||
|
|
||||||
pub fn is_case_sensitive(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::Windows | Self::MacOs => false,
|
|
||||||
Self::Linux => true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<&str> for Platform {
|
|
||||||
fn from(value: &str) -> Self {
|
|
||||||
match value.to_lowercase().trim() {
|
|
||||||
"windows" => Self::Windows,
|
|
||||||
"linux" => Self::Linux,
|
|
||||||
"mac" | "macos" => Self::MacOs,
|
|
||||||
_ => unimplemented!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<whoami::Platform> for Platform {
|
|
||||||
fn from(value: whoami::Platform) -> Self {
|
|
||||||
match value {
|
|
||||||
whoami::Platform::Windows => Platform::Windows,
|
|
||||||
whoami::Platform::Linux => Platform::Linux,
|
|
||||||
whoami::Platform::MacOS => Platform::MacOs,
|
|
||||||
platform => unimplemented!("Playform {} is not supported", platform),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "download_manager"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
atomic-instant-full = "0.1.0"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
humansize = "2.1.3"
|
|
||||||
log = "0.4.28"
|
|
||||||
parking_lot = "0.12.5"
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
throttle_my_fn = "0.2.6"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,24 +0,0 @@
|
|||||||
use database::DownloadableMetadata;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
use crate::download_manager_frontend::DownloadStatus;
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct QueueUpdateEventQueueData {
|
|
||||||
pub meta: DownloadableMetadata,
|
|
||||||
pub status: DownloadStatus,
|
|
||||||
pub progress: f64,
|
|
||||||
pub current: usize,
|
|
||||||
pub max: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct QueueUpdateEvent {
|
|
||||||
pub queue: Vec<QueueUpdateEventQueueData>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Clone)]
|
|
||||||
pub struct StatsUpdateEvent {
|
|
||||||
pub speed: usize,
|
|
||||||
pub time: usize,
|
|
||||||
}
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
#![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,26 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "games"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
atomic-instant-full = "0.1.0"
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
boxcar = "0.2.14"
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
download_manager = { version = "0.1.0", path = "../download_manager" }
|
|
||||||
hex = "0.4.3"
|
|
||||||
log = "0.4.28"
|
|
||||||
md5 = "0.8.0"
|
|
||||||
rayon = "1.11.0"
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
reqwest = "0.12.23"
|
|
||||||
rustix = "1.1.2"
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
sysinfo = "0.37.2"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
throttle_my_fn = "0.2.6"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
native_model = { version = "0.6.4", features = ["rmp_serde_1_3"], git = "https://github.com/Drop-OSS/native_model.git"}
|
|
||||||
serde_json = "1.0.145"
|
|
||||||
@ -1,21 +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,324 +0,0 @@
|
|||||||
use std::fs::remove_dir_all;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
use std::thread::spawn;
|
|
||||||
use bitcode::{Decode, Encode};
|
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, Database, DownloadableMetadata, GameDownloadStatus, GameVersion};
|
|
||||||
use 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 crate::{downloads::error::LibraryError, state::{GameStatusManager, GameStatusWithTransient}};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug)]
|
|
||||||
pub struct FetchGameStruct {
|
|
||||||
game: Game,
|
|
||||||
status: GameStatusWithTransient,
|
|
||||||
version: Option<GameVersion>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FetchGameStruct {
|
|
||||||
pub fn new(game: Game, status: GameStatusWithTransient, version: Option<GameVersion>) -> Self {
|
|
||||||
Self { 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)]
|
|
||||||
pub struct GameUpdateEvent {
|
|
||||||
pub game_id: String,
|
|
||||||
pub status: (
|
|
||||||
Option<GameDownloadStatus>,
|
|
||||||
Option<ApplicationTransientStatus>,
|
|
||||||
),
|
|
||||||
pub version: Option<GameVersion>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Called by:
|
|
||||||
* - on_cancel, when cancelled, for obvious reasons
|
|
||||||
* - when downloading, so if drop unexpectedly quits, we can resume the download. hidden by the "Downloading..." transient state, though
|
|
||||||
* - when scanning, to import the game
|
|
||||||
*/
|
|
||||||
pub fn set_partially_installed(
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: Option<&AppHandle>,
|
|
||||||
) {
|
|
||||||
set_partially_installed_db(&mut borrow_db_mut_checked(), meta, install_dir, app_handle);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_partially_installed_db(
|
|
||||||
db_lock: &mut Database,
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: Option<&AppHandle>,
|
|
||||||
) {
|
|
||||||
db_lock.applications.transient_statuses.remove(meta);
|
|
||||||
db_lock.applications.game_statuses.insert(
|
|
||||||
meta.id.clone(),
|
|
||||||
GameDownloadStatus::PartiallyInstalled {
|
|
||||||
version_name: meta.version.as_ref().unwrap().clone(),
|
|
||||||
install_dir,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
db_lock
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.insert(meta.id.clone(), meta.clone());
|
|
||||||
|
|
||||||
if let Some(app_handle) = app_handle {
|
|
||||||
push_game_update(
|
|
||||||
app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, db_lock),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle) {
|
|
||||||
debug!("triggered uninstall for agent");
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.transient_statuses
|
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
|
||||||
|
|
||||||
push_game_update(
|
|
||||||
app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
|
||||||
);
|
|
||||||
|
|
||||||
let previous_state = db_handle.applications.game_statuses.get(&meta.id).cloned();
|
|
||||||
|
|
||||||
let previous_state = if let Some(state) = previous_state {
|
|
||||||
state
|
|
||||||
} else {
|
|
||||||
warn!("uninstall job doesn't have previous state, failing silently");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
if let Some((_, install_dir)) = match previous_state {
|
|
||||||
GameDownloadStatus::Installed {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
GameDownloadStatus::SetupRequired {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
GameDownloadStatus::PartiallyInstalled {
|
|
||||||
version_name,
|
|
||||||
install_dir,
|
|
||||||
} => Some((version_name, install_dir)),
|
|
||||||
_ => None,
|
|
||||||
} {
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.transient_statuses
|
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
|
||||||
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
let app_handle = app_handle.clone();
|
|
||||||
spawn(move || {
|
|
||||||
if let Err(e) = remove_dir_all(install_dir) {
|
|
||||||
error!("{e}");
|
|
||||||
} else {
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle.applications.transient_statuses.remove(&meta);
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.remove(&meta.id);
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.insert(meta.id.clone(), GameDownloadStatus::Remote {});
|
|
||||||
let _ = db_handle.applications.transient_statuses.remove(&meta);
|
|
||||||
|
|
||||||
push_game_update(
|
|
||||||
&app_handle,
|
|
||||||
&meta.id,
|
|
||||||
None,
|
|
||||||
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
|
||||||
);
|
|
||||||
|
|
||||||
debug!("uninstalled game id {}", &meta.id);
|
|
||||||
app_emit!(app_handle, "update_library", ());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
warn!("invalid previous state for uninstall, failing silently.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_current_meta(game_id: &String) -> Option<DownloadableMetadata> {
|
|
||||||
borrow_db_checked()
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.get(game_id)
|
|
||||||
.cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_game_complete(
|
|
||||||
meta: &DownloadableMetadata,
|
|
||||||
install_dir: String,
|
|
||||||
app_handle: &AppHandle,
|
|
||||||
) -> Result<(), RemoteAccessError> {
|
|
||||||
// Fetch game version information from remote
|
|
||||||
if meta.version.is_none() {
|
|
||||||
return Err(RemoteAccessError::GameNotFound(meta.id.clone()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = generate_url(
|
|
||||||
&["/api/v1/client/game/version"],
|
|
||||||
&[
|
|
||||||
("id", &meta.id),
|
|
||||||
("version", meta.version.as_ref().unwrap()),
|
|
||||||
],
|
|
||||||
)?;
|
|
||||||
let response = client
|
|
||||||
.get(response)
|
|
||||||
.header("Authorization", generate_authorization_header())
|
|
||||||
.send()?;
|
|
||||||
|
|
||||||
let game_version: GameVersion = response.json()?;
|
|
||||||
|
|
||||||
let mut handle = borrow_db_mut_checked();
|
|
||||||
handle
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.entry(meta.id.clone())
|
|
||||||
.or_default()
|
|
||||||
.insert(meta.version.clone().unwrap(), game_version.clone());
|
|
||||||
handle
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.insert(meta.id.clone(), meta.clone());
|
|
||||||
|
|
||||||
drop(handle);
|
|
||||||
|
|
||||||
let status = if game_version.setup_command.is_empty() {
|
|
||||||
GameDownloadStatus::Installed {
|
|
||||||
version_name: meta.version.clone().unwrap(),
|
|
||||||
install_dir,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
GameDownloadStatus::SetupRequired {
|
|
||||||
version_name: meta.version.clone().unwrap(),
|
|
||||||
install_dir,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.insert(meta.id.clone(), status.clone());
|
|
||||||
drop(db_handle);
|
|
||||||
app_emit!(
|
|
||||||
app_handle,
|
|
||||||
&format!("update_game/{}", meta.id),
|
|
||||||
GameUpdateEvent {
|
|
||||||
game_id: meta.id.clone(),
|
|
||||||
status: (Some(status), None),
|
|
||||||
version: Some(game_version),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn push_game_update(
|
|
||||||
app_handle: &AppHandle,
|
|
||||||
game_id: &String,
|
|
||||||
version: Option<GameVersion>,
|
|
||||||
status: GameStatusWithTransient,
|
|
||||||
) {
|
|
||||||
if let Some(GameDownloadStatus::Installed { .. } | GameDownloadStatus::SetupRequired { .. }) =
|
|
||||||
&status.0
|
|
||||||
&& version.is_none()
|
|
||||||
{
|
|
||||||
panic!("pushed game for installed game that doesn't have version information");
|
|
||||||
}
|
|
||||||
|
|
||||||
app_emit!(
|
|
||||||
app_handle,
|
|
||||||
&format!("update_game/{game_id}"),
|
|
||||||
GameUpdateEvent {
|
|
||||||
game_id: game_id.clone(),
|
|
||||||
status,
|
|
||||||
version,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct FrontendGameOptions {
|
|
||||||
launch_string: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn update_game_configuration(
|
|
||||||
game_id: String,
|
|
||||||
options: FrontendGameOptions,
|
|
||||||
) -> Result<(), LibraryError> {
|
|
||||||
let mut handle = borrow_db_mut_checked();
|
|
||||||
let installed_version = handle
|
|
||||||
.applications
|
|
||||||
.installed_game_version
|
|
||||||
.get(&game_id)
|
|
||||||
.ok_or(LibraryError::MetaNotFound(game_id))?;
|
|
||||||
|
|
||||||
let id = installed_version.id.clone();
|
|
||||||
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
|
|
||||||
|
|
||||||
let mut existing_configuration = handle
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.get(&id)
|
|
||||||
.unwrap()
|
|
||||||
.get(&version)
|
|
||||||
.unwrap()
|
|
||||||
.clone();
|
|
||||||
|
|
||||||
// Add more options in here
|
|
||||||
existing_configuration.launch_command_template = options.launch_string;
|
|
||||||
|
|
||||||
// Add no more options past here
|
|
||||||
|
|
||||||
handle
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.get_mut(&id)
|
|
||||||
.unwrap()
|
|
||||||
.insert(version.to_string(), existing_configuration);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@ -14,8 +14,7 @@
|
|||||||
"@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",
|
||||||
"pino-pretty": "^13.1.1",
|
"pino-pretty": "^13.1.1"
|
||||||
"tauri": "^0.15.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@tauri-apps/cli": "^2.7.1"
|
"@tauri-apps/cli": "^2.7.1"
|
||||||
|
|||||||
@ -1,18 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "process"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
chrono = "0.4.42"
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
dynfmt = "0.1.5"
|
|
||||||
games = { version = "0.1.0", path = "../games" }
|
|
||||||
log = "0.4.28"
|
|
||||||
page_size = "0.6.0"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
shared_child = "1.1.1"
|
|
||||||
tauri-plugin-opener = "2.5.0"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
#![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,23 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "remote"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bitcode = "0.6.7"
|
|
||||||
chrono = "0.4.42"
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { version = "0.1.0", path = "../database" }
|
|
||||||
droplet-rs = "0.7.3"
|
|
||||||
gethostname = "1.0.2"
|
|
||||||
hex = "0.4.3"
|
|
||||||
http = "1.3.1"
|
|
||||||
log = "0.4.28"
|
|
||||||
md5 = "0.8.0"
|
|
||||||
reqwest = "0.12.23"
|
|
||||||
reqwest-websocket = "0.5.1"
|
|
||||||
serde = "1.0.228"
|
|
||||||
serde_with = "3.15.0"
|
|
||||||
tauri = "2.8.5"
|
|
||||||
url = "2.5.7"
|
|
||||||
utils = { version = "0.1.0", path = "../utils" }
|
|
||||||
@ -1,136 +0,0 @@
|
|||||||
use std::{collections::HashMap, env};
|
|
||||||
|
|
||||||
use chrono::Utc;
|
|
||||||
use client::{app_status::AppStatus, user::User};
|
|
||||||
use database::interface::borrow_db_checked;
|
|
||||||
use droplet_rs::ssl::sign_nonce;
|
|
||||||
use gethostname::gethostname;
|
|
||||||
use log::{error, warn};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use url::Url;
|
|
||||||
|
|
||||||
use crate::{error::{DropServerError, RemoteAccessError}, requests::make_authenticated_get, utils::DROP_CLIENT_SYNC};
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
cache::{cache_object, get_cached_object},
|
|
||||||
requests::generate_url,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct CapabilityConfiguration {}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct InitiateRequestBody {
|
|
||||||
name: String,
|
|
||||||
platform: String,
|
|
||||||
capabilities: HashMap<String, CapabilityConfiguration>,
|
|
||||||
mode: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct HandshakeRequestBody {
|
|
||||||
client_id: String,
|
|
||||||
token: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct HandshakeResponse {
|
|
||||||
private: String,
|
|
||||||
certificate: String,
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn generate_authorization_header() -> String {
|
|
||||||
let certs = {
|
|
||||||
let db = borrow_db_checked();
|
|
||||||
db.auth.clone().expect("Authorisation not initialised")
|
|
||||||
};
|
|
||||||
|
|
||||||
let nonce = Utc::now().timestamp_millis().to_string();
|
|
||||||
|
|
||||||
let signature =
|
|
||||||
sign_nonce(certs.private, nonce.clone()).expect("Failed to generate authorisation header");
|
|
||||||
|
|
||||||
format!("Nonce {} {} {}", certs.client_id, nonce, signature)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_user() -> Result<User, RemoteAccessError> {
|
|
||||||
let response = make_authenticated_get(generate_url(&["/api/v1/client/user"], &[])?).await?;
|
|
||||||
if response.status() != 200 {
|
|
||||||
let err: DropServerError = response.json().await?;
|
|
||||||
warn!("{err:?}");
|
|
||||||
|
|
||||||
if err.status_message == "Nonce expired" {
|
|
||||||
return Err(RemoteAccessError::OutOfSync);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Err(RemoteAccessError::InvalidResponse(err));
|
|
||||||
}
|
|
||||||
|
|
||||||
response
|
|
||||||
.json::<User>()
|
|
||||||
.await
|
|
||||||
.map_err(std::convert::Into::into)
|
|
||||||
}
|
|
||||||
|
|
||||||
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 endpoint = base_url.join("/api/v1/client/auth/initiate")?;
|
|
||||||
let body = InitiateRequestBody {
|
|
||||||
name: format!("{} (Desktop)", hostname.display()),
|
|
||||||
platform: env::consts::OS.to_string(),
|
|
||||||
capabilities: HashMap::from([
|
|
||||||
("peerAPI".to_owned(), CapabilityConfiguration {}),
|
|
||||||
("cloudSaves".to_owned(), CapabilityConfiguration {}),
|
|
||||||
]),
|
|
||||||
mode,
|
|
||||||
};
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = client.post(endpoint.to_string()).json(&body).send()?;
|
|
||||||
|
|
||||||
if response.status() != 200 {
|
|
||||||
let data: DropServerError = response.json()?;
|
|
||||||
error!("could not start handshake: {}", data.status_message);
|
|
||||||
|
|
||||||
return Err(RemoteAccessError::HandshakeFailed(data.status_message));
|
|
||||||
}
|
|
||||||
|
|
||||||
let response = response.text()?;
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn setup() -> (AppStatus, Option<User>) {
|
|
||||||
let auth = {
|
|
||||||
let data = borrow_db_checked();
|
|
||||||
data.auth.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
if auth.is_some() {
|
|
||||||
let user_result = match fetch_user().await {
|
|
||||||
Ok(data) => data,
|
|
||||||
Err(RemoteAccessError::FetchError(_)) => {
|
|
||||||
let user = get_cached_object::<User>("user").ok();
|
|
||||||
return (AppStatus::Offline, user);
|
|
||||||
}
|
|
||||||
Err(_) => return (AppStatus::SignedInNeedsReauth, None),
|
|
||||||
};
|
|
||||||
if let Err(e) = cache_object("user", &user_result) {
|
|
||||||
warn!("Could not cache user object with error {e}");
|
|
||||||
}
|
|
||||||
return (AppStatus::SignedIn, Some(user_result));
|
|
||||||
}
|
|
||||||
|
|
||||||
(AppStatus::SignedOut, None)
|
|
||||||
}
|
|
||||||
@ -1,76 +0,0 @@
|
|||||||
use database::{interface::DatabaseImpls, DB};
|
|
||||||
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder, Response};
|
|
||||||
use log::{debug, warn};
|
|
||||||
use tauri::UriSchemeResponder;
|
|
||||||
|
|
||||||
use crate::{error::CacheError, utils::DROP_CLIENT_ASYNC};
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
auth::generate_authorization_header,
|
|
||||||
cache::{ObjectCache, cache_object, get_cached_object},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub async fn fetch_object_wrapper(request: http::Request<Vec<u8>>, responder: UriSchemeResponder) {
|
|
||||||
match fetch_object(request).await {
|
|
||||||
Ok(r) => responder.respond(r),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Cache error: {e}");
|
|
||||||
responder.respond(Response::builder().status(500).body(Vec::new()).expect("Failed to build error response"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_object(request: http::Request<Vec<u8>>) -> Result<Response<Vec<u8>>, CacheError>
|
|
||||||
{
|
|
||||||
// Drop leading /
|
|
||||||
let object_id = &request.uri().path()[1..];
|
|
||||||
|
|
||||||
let cache_result = get_cached_object::<ObjectCache>(object_id);
|
|
||||||
if let Ok(cache_result) = &cache_result
|
|
||||||
&& !cache_result.has_expired()
|
|
||||||
{
|
|
||||||
return cache_result.try_into();
|
|
||||||
}
|
|
||||||
|
|
||||||
let header = generate_authorization_header();
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let url = format!("{}api/v1/client/object/{object_id}", DB.fetch_base_url());
|
|
||||||
let response = client.get(url).header("Authorization", header).send().await;
|
|
||||||
|
|
||||||
match response {
|
|
||||||
Ok(r) => {
|
|
||||||
let resp_builder = ResponseBuilder::new().header(
|
|
||||||
CONTENT_TYPE,
|
|
||||||
r.headers()
|
|
||||||
.get("Content-Type")
|
|
||||||
.expect("Failed get Content-Type header"),
|
|
||||||
);
|
|
||||||
let data = match r.bytes().await {
|
|
||||||
Ok(data) => Vec::from(data),
|
|
||||||
Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Could not get data from cache object {object_id} with error {e}",
|
|
||||||
);
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let resp = resp_builder.body(data).expect("Failed to build object cache response body");
|
|
||||||
if cache_result.map_or(true, |x| x.has_expired()) {
|
|
||||||
cache_object::<ObjectCache>(object_id, &resp.clone().try_into()?)
|
|
||||||
.expect("Failed to create cached object");
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(resp)
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!("Object fetch failed with error {e}. Attempting to download from cache");
|
|
||||||
match cache_result {
|
|
||||||
Ok(cache_result) => cache_result.try_into(),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("{e}");
|
|
||||||
Err(CacheError::Remote(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,93 +0,0 @@
|
|||||||
use std::str::FromStr;
|
|
||||||
|
|
||||||
use database::borrow_db_checked;
|
|
||||||
use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
|
|
||||||
use log::{error, warn};
|
|
||||||
use tauri::UriSchemeResponder;
|
|
||||||
use utils::webbrowser_open::webbrowser_open;
|
|
||||||
|
|
||||||
use crate::utils::DROP_CLIENT_SYNC;
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_offline_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
|
||||||
responder.respond(match handle_server_proto_offline(request).await {
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(_) => unreachable!()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode>{
|
|
||||||
Ok(Response::builder()
|
|
||||||
.status(StatusCode::NOT_FOUND)
|
|
||||||
.body(Vec::new())
|
|
||||||
.expect("Failed to build error response for proto offline"))
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn handle_server_proto_wrapper(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
|
||||||
match handle_server_proto(request).await {
|
|
||||||
Ok(r) => responder.respond(r),
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Cache error: {e}");
|
|
||||||
responder.respond(Response::builder().status(e).body(Vec::new()).expect("Failed to build error response"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_server_proto(request: Request<Vec<u8>>) -> Result<Response<Vec<u8>>, StatusCode> {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
let auth = match db_handle.auth.as_ref() {
|
|
||||||
Some(auth) => auth,
|
|
||||||
None => {
|
|
||||||
error!("Could not find auth in database");
|
|
||||||
return Err(StatusCode::UNAUTHORIZED)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let web_token = match &auth.web_token {
|
|
||||||
Some(token) => token,
|
|
||||||
None => return Err(StatusCode::UNAUTHORIZED),
|
|
||||||
};
|
|
||||||
let remote_uri = db_handle.base_url.parse::<Uri>().expect("Failed to parse base url");
|
|
||||||
|
|
||||||
let path = request.uri().path();
|
|
||||||
|
|
||||||
let mut new_uri = request.uri().clone().into_parts();
|
|
||||||
new_uri.path_and_query =
|
|
||||||
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).expect("Failed to parse request path in proto"));
|
|
||||||
new_uri.authority = remote_uri.authority().cloned();
|
|
||||||
new_uri.scheme = remote_uri.scheme().cloned();
|
|
||||||
let err_msg = &format!("Failed to build new uri from parts {new_uri:?}");
|
|
||||||
let new_uri = Uri::from_parts(new_uri).expect(err_msg);
|
|
||||||
|
|
||||||
let whitelist_prefix = ["/store", "/api", "/_", "/fonts"];
|
|
||||||
|
|
||||||
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
|
|
||||||
webbrowser_open(new_uri.to_string());
|
|
||||||
return Ok(Response::new(Vec::new()))
|
|
||||||
}
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_SYNC.clone();
|
|
||||||
let response = match client
|
|
||||||
.request(request.method().clone(), new_uri.to_string())
|
|
||||||
.header("Authorization", format!("Bearer {web_token}"))
|
|
||||||
.headers(request.headers().clone())
|
|
||||||
.send() {
|
|
||||||
Ok(response) => response,
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Could not send response. Got {e} when sending");
|
|
||||||
return Err(e.status().unwrap_or(StatusCode::BAD_REQUEST))
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let response_status = response.status();
|
|
||||||
let response_body = match response.bytes() {
|
|
||||||
Ok(bytes) => bytes,
|
|
||||||
Err(e) => return Err(e.status().unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
|
|
||||||
};
|
|
||||||
|
|
||||||
let http_response = Response::builder()
|
|
||||||
.status(response_status)
|
|
||||||
.body(response_body.to_vec())
|
|
||||||
.expect("Failed to build server proto response");
|
|
||||||
|
|
||||||
Ok(http_response)
|
|
||||||
}
|
|
||||||
@ -1,111 +0,0 @@
|
|||||||
use std::{
|
|
||||||
fs::{self, File},
|
|
||||||
io::Read,
|
|
||||||
sync::LazyLock,
|
|
||||||
};
|
|
||||||
|
|
||||||
use database::db::DATA_ROOT_DIR;
|
|
||||||
use log::{debug, info, warn};
|
|
||||||
use reqwest::Certificate;
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct DropHealthcheck {
|
|
||||||
app_name: String,
|
|
||||||
}
|
|
||||||
impl DropHealthcheck {
|
|
||||||
pub fn app_name(&self) -> &String{
|
|
||||||
&self.app_name
|
|
||||||
}
|
|
||||||
}
|
|
||||||
static DROP_CERT_BUNDLE: LazyLock<Vec<Certificate>> = LazyLock::new(fetch_certificates);
|
|
||||||
pub static DROP_CLIENT_SYNC: LazyLock<reqwest::blocking::Client> = LazyLock::new(get_client_sync);
|
|
||||||
pub static DROP_CLIENT_ASYNC: LazyLock<reqwest::Client> = LazyLock::new(get_client_async);
|
|
||||||
pub static DROP_CLIENT_WS_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(get_client_ws);
|
|
||||||
|
|
||||||
fn fetch_certificates() -> Vec<Certificate> {
|
|
||||||
let certificate_dir = DATA_ROOT_DIR.join("certificates");
|
|
||||||
|
|
||||||
let mut certs = Vec::new();
|
|
||||||
match fs::read_dir(certificate_dir) {
|
|
||||||
Ok(c) => {
|
|
||||||
for entry in c {
|
|
||||||
match entry {
|
|
||||||
Ok(c) => {
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
match File::open(c.path()) {
|
|
||||||
Ok(f) => f,
|
|
||||||
Err(e) => {
|
|
||||||
warn!(
|
|
||||||
"Failed to open file at {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.read_to_end(&mut buf)
|
|
||||||
.unwrap_or_else(|e| panic!(
|
|
||||||
"Failed to read to end of certificate file {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
));
|
|
||||||
|
|
||||||
match Certificate::from_pem_bundle(&buf) {
|
|
||||||
Ok(certificates) => {
|
|
||||||
for cert in certificates {
|
|
||||||
certs.push(cert);
|
|
||||||
}
|
|
||||||
info!(
|
|
||||||
"added {} certificate(s) from {}",
|
|
||||||
certs.len(),
|
|
||||||
c.file_name().display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Err(e) => warn!(
|
|
||||||
"Invalid certificate file {} with error {}",
|
|
||||||
c.path().display(),
|
|
||||||
e
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(_) => todo!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
debug!("not loading certificates due to error: {e}");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
certs
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_client_sync() -> reqwest::blocking::Client {
|
|
||||||
let mut client = reqwest::blocking::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client.use_rustls_tls().build().expect("Failed to build synchronous client")
|
|
||||||
}
|
|
||||||
pub fn get_client_async() -> reqwest::Client {
|
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client.use_rustls_tls().build().expect("Failed to build asynchronous client")
|
|
||||||
}
|
|
||||||
pub fn get_client_ws() -> reqwest::Client {
|
|
||||||
let mut client = reqwest::ClientBuilder::new();
|
|
||||||
|
|
||||||
for cert in DROP_CERT_BUNDLE.iter() {
|
|
||||||
client = client.add_root_certificate(cert.clone());
|
|
||||||
}
|
|
||||||
client
|
|
||||||
.use_rustls_tls()
|
|
||||||
.http1_only()
|
|
||||||
.build()
|
|
||||||
.expect("Failed to build websocket client")
|
|
||||||
}
|
|
||||||
278
src-tauri/Cargo.lock
generated
278
src-tauri/Cargo.lock
generated
@ -740,7 +740,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "02260d489095346e5cafd04dea8e8cb54d1d74fcd759022a9b72986ebe9a1257"
|
checksum = "02260d489095346e5cafd04dea8e8cb54d1d74fcd759022a9b72986ebe9a1257"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"toml 0.8.22",
|
"toml",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -808,16 +808,6 @@ dependencies = [
|
|||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "client"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"database 0.5.0",
|
|
||||||
"log",
|
|
||||||
"tauri",
|
|
||||||
"tauri-plugin-autostart",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "combine"
|
name = "combine"
|
||||||
version = "4.6.7"
|
version = "4.6.7"
|
||||||
@ -1069,16 +1059,6 @@ version = "2.9.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
|
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "database"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "database"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f4851b30af1e6d2db292e4873b486fa2ad00a6fb6466da44f827e18bdac62f50"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "der-parser"
|
name = "der-parser"
|
||||||
version = "9.0.0"
|
version = "9.0.0"
|
||||||
@ -1257,9 +1237,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dlopen2"
|
name = "dlopen2"
|
||||||
version = "0.8.0"
|
version = "0.7.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b54f373ccf864bf587a89e880fb7610f8d73f3045f13580948ccbcaff26febff"
|
checksum = "9e1297103d2bbaea85724fcee6294c2d50b1081f9ad47d0f6f6f61eda65315a6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"dlopen2_derive",
|
"dlopen2_derive",
|
||||||
"libc",
|
"libc",
|
||||||
@ -1312,8 +1292,6 @@ dependencies = [
|
|||||||
"bytes",
|
"bytes",
|
||||||
"cacache 13.1.0",
|
"cacache 13.1.0",
|
||||||
"chrono",
|
"chrono",
|
||||||
"client",
|
|
||||||
"database 0.1.0",
|
|
||||||
"deranged",
|
"deranged",
|
||||||
"dirs 6.0.0",
|
"dirs 6.0.0",
|
||||||
"droplet-rs",
|
"droplet-rs",
|
||||||
@ -1333,11 +1311,9 @@ dependencies = [
|
|||||||
"native_model",
|
"native_model",
|
||||||
"page_size",
|
"page_size",
|
||||||
"parking_lot 0.12.3",
|
"parking_lot 0.12.3",
|
||||||
"process",
|
|
||||||
"rand 0.9.1",
|
"rand 0.9.1",
|
||||||
"rayon",
|
"rayon",
|
||||||
"regex",
|
"regex",
|
||||||
"remote",
|
|
||||||
"reqwest 0.12.22",
|
"reqwest 0.12.22",
|
||||||
"reqwest-middleware 0.4.2",
|
"reqwest-middleware 0.4.2",
|
||||||
"reqwest-middleware-cache",
|
"reqwest-middleware-cache",
|
||||||
@ -1369,7 +1345,6 @@ dependencies = [
|
|||||||
"umu-wrapper-lib",
|
"umu-wrapper-lib",
|
||||||
"url",
|
"url",
|
||||||
"urlencoding",
|
"urlencoding",
|
||||||
"utils",
|
|
||||||
"uuid",
|
"uuid",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
"webbrowser",
|
"webbrowser",
|
||||||
@ -1448,7 +1423,7 @@ dependencies = [
|
|||||||
"cc",
|
"cc",
|
||||||
"memchr",
|
"memchr",
|
||||||
"rustc_version",
|
"rustc_version",
|
||||||
"toml 0.8.22",
|
"toml",
|
||||||
"vswhom",
|
"vswhom",
|
||||||
"winreg 0.52.0",
|
"winreg 0.52.0",
|
||||||
]
|
]
|
||||||
@ -2138,7 +2113,7 @@ dependencies = [
|
|||||||
"futures-sink",
|
"futures-sink",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"http 0.2.12",
|
"http 0.2.12",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"slab",
|
"slab",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
@ -2157,7 +2132,7 @@ dependencies = [
|
|||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-sink",
|
"futures-sink",
|
||||||
"http 1.3.1",
|
"http 1.3.1",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"slab",
|
"slab",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
@ -2617,14 +2592,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "indexmap"
|
name = "indexmap"
|
||||||
version = "2.11.4"
|
version = "2.9.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
|
checksum = "cea70ddb795996207ad57735b50c5982d8844f38ba9ee5f1aedcfb708a2aa11e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"equivalent",
|
"equivalent",
|
||||||
"hashbrown 0.15.3",
|
"hashbrown 0.15.3",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_core",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -2801,7 +2775,7 @@ checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cssparser",
|
"cssparser",
|
||||||
"html5ever",
|
"html5ever",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"selectors",
|
"selectors",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -2907,9 +2881,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "log"
|
name = "log"
|
||||||
version = "0.4.28"
|
version = "0.4.27"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
|
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"value-bag",
|
"value-bag",
|
||||||
@ -3463,16 +3437,6 @@ dependencies = [
|
|||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "objc2-javascript-core"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9052cb1bb50a4c161d934befcf879526fb87ae9a68858f241e693ca46225cf5a"
|
|
||||||
dependencies = [
|
|
||||||
"objc2 0.6.1",
|
|
||||||
"objc2-core-foundation",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-metal"
|
name = "objc2-metal"
|
||||||
version = "0.2.2"
|
version = "0.2.2"
|
||||||
@ -3509,17 +3473,6 @@ dependencies = [
|
|||||||
"objc2-foundation 0.3.1",
|
"objc2-foundation 0.3.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "objc2-security"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e1f8e0ef3ab66b08c42644dcb34dba6ec0a574bbd8adbb8bdbdc7a2779731a44"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags 2.9.1",
|
|
||||||
"objc2 0.6.1",
|
|
||||||
"objc2-core-foundation",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2-ui-kit"
|
name = "objc2-ui-kit"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@ -3544,8 +3497,6 @@ dependencies = [
|
|||||||
"objc2-app-kit",
|
"objc2-app-kit",
|
||||||
"objc2-core-foundation",
|
"objc2-core-foundation",
|
||||||
"objc2-foundation 0.3.1",
|
"objc2-foundation 0.3.1",
|
||||||
"objc2-javascript-core",
|
|
||||||
"objc2-security",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -3992,7 +3943,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "eac26e981c03a6e53e0aee43c113e3202f5581d5360dae7bd2c70e800dd0451d"
|
checksum = "eac26e981c03a6e53e0aee43c113e3202f5581d5360dae7bd2c70e800dd0451d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"quick-xml",
|
"quick-xml",
|
||||||
"serde",
|
"serde",
|
||||||
"time",
|
"time",
|
||||||
@ -4123,10 +4074,6 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "process"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quick-xml"
|
name = "quick-xml"
|
||||||
version = "0.32.0"
|
version = "0.32.0"
|
||||||
@ -4437,10 +4384,6 @@ version = "0.8.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "remote"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
version = "0.11.27"
|
version = "0.11.27"
|
||||||
@ -4909,11 +4852,10 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.228"
|
version = "1.0.219"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_core",
|
|
||||||
"serde_derive",
|
"serde_derive",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -4938,20 +4880,11 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_core"
|
|
||||||
version = "1.0.228"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
|
||||||
dependencies = [
|
|
||||||
"serde_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_derive"
|
name = "serde_derive"
|
||||||
version = "1.0.228"
|
version = "1.0.219"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@ -5001,15 +4934,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_spanned"
|
|
||||||
version = "1.0.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5417783452c2be558477e104686f7de5dae53dba813c28435e0e70f82d9b04ee"
|
|
||||||
dependencies = [
|
|
||||||
"serde_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde_urlencoded"
|
name = "serde_urlencoded"
|
||||||
version = "0.7.1"
|
version = "0.7.1"
|
||||||
@ -5032,7 +4956,7 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"hex 0.4.3",
|
"hex 0.4.3",
|
||||||
"indexmap 1.9.3",
|
"indexmap 1.9.3",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_derive",
|
"serde_derive",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@ -5058,7 +4982,7 @@ version = "0.9.34+deprecated"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
|
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"itoa",
|
"itoa",
|
||||||
"ryu",
|
"ryu",
|
||||||
"serde",
|
"serde",
|
||||||
@ -5067,9 +4991,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serialize-to-javascript"
|
name = "serialize-to-javascript"
|
||||||
version = "0.1.2"
|
version = "0.1.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"
|
checksum = "c9823f2d3b6a81d98228151fdeaf848206a7855a7a042bbf9bf870449a66cafb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@ -5078,13 +5002,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serialize-to-javascript-impl"
|
name = "serialize-to-javascript-impl"
|
||||||
version = "0.1.2"
|
version = "0.1.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"
|
checksum = "74064874e9f6a15f04c1f3cb627902d0e6b410abbf36668afa873c61889f1763"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn 2.0.101",
|
"syn 1.0.109",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -5500,18 +5424,17 @@ dependencies = [
|
|||||||
"cfg-expr",
|
"cfg-expr",
|
||||||
"heck 0.5.0",
|
"heck 0.5.0",
|
||||||
"pkg-config",
|
"pkg-config",
|
||||||
"toml 0.8.22",
|
"toml",
|
||||||
"version-compare",
|
"version-compare",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tao"
|
name = "tao"
|
||||||
version = "0.34.3"
|
version = "0.34.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "959469667dbcea91e5485fc48ba7dd6023face91bb0f1a14681a70f99847c3f7"
|
checksum = "49c380ca75a231b87b6c9dd86948f035012e7171d1a7c40a9c2890489a7ffd8a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.9.1",
|
"bitflags 2.9.1",
|
||||||
"block2 0.6.1",
|
|
||||||
"core-foundation 0.10.1",
|
"core-foundation 0.10.1",
|
||||||
"core-graphics",
|
"core-graphics",
|
||||||
"crossbeam-channel",
|
"crossbeam-channel",
|
||||||
@ -5583,13 +5506,12 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri"
|
name = "tauri"
|
||||||
version = "2.8.5"
|
version = "2.7.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d4d1d3b3dc4c101ac989fd7db77e045cc6d91a25349cd410455cb5c57d510c1c"
|
checksum = "352a4bc7bf6c25f5624227e3641adf475a6535707451b09bb83271df8b7a6ac7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"bytes",
|
"bytes",
|
||||||
"cookie",
|
|
||||||
"dirs 6.0.0",
|
"dirs 6.0.0",
|
||||||
"dunce",
|
"dunce",
|
||||||
"embed_plist",
|
"embed_plist",
|
||||||
@ -5608,7 +5530,6 @@ dependencies = [
|
|||||||
"objc2-app-kit",
|
"objc2-app-kit",
|
||||||
"objc2-foundation 0.3.1",
|
"objc2-foundation 0.3.1",
|
||||||
"objc2-ui-kit",
|
"objc2-ui-kit",
|
||||||
"objc2-web-kit",
|
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"plist",
|
"plist",
|
||||||
"raw-window-handle",
|
"raw-window-handle",
|
||||||
@ -5636,9 +5557,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-build"
|
name = "tauri-build"
|
||||||
version = "2.4.1"
|
version = "2.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9c432ccc9ff661803dab74c6cd78de11026a578a9307610bbc39d3c55be7943f"
|
checksum = "182d688496c06bf08ea896459bf483eb29cdff35c1c4c115fb14053514303064"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"cargo_toml",
|
"cargo_toml",
|
||||||
@ -5652,15 +5573,15 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"tauri-winres",
|
"tauri-winres",
|
||||||
"toml 0.9.7",
|
"toml",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-codegen"
|
name = "tauri-codegen"
|
||||||
version = "2.4.0"
|
version = "2.3.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1ab3a62cf2e6253936a8b267c2e95839674e7439f104fa96ad0025e149d54d8a"
|
checksum = "b54a99a6cd8e01abcfa61508177e6096a4fe2681efecee9214e962f2f073ae4a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"brotli",
|
"brotli",
|
||||||
@ -5685,9 +5606,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-macros"
|
name = "tauri-macros"
|
||||||
version = "2.4.0"
|
version = "2.3.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4368ea8094e7045217edb690f493b55b30caf9f3e61f79b4c24b6db91f07995e"
|
checksum = "7945b14dc45e23532f2ded6e120170bbdd4af5ceaa45784a6b33d250fbce3f9e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.5.0",
|
"heck 0.5.0",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
@ -5699,9 +5620,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin"
|
name = "tauri-plugin"
|
||||||
version = "2.4.0"
|
version = "2.3.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9946a3cede302eac0c6eb6c6070ac47b1768e326092d32efbb91f21ed58d978f"
|
checksum = "1d9a0bd00bf1930ad1a604d08b0eb6b2a9c1822686d65d7f4731a7723b8901d3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"glob",
|
"glob",
|
||||||
@ -5710,15 +5631,15 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"toml 0.9.7",
|
"toml",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-autostart"
|
name = "tauri-plugin-autostart"
|
||||||
version = "2.5.0"
|
version = "2.3.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "062cdcd483d5e3148c9a64dabf8c574e239e2aa1193cf208d95cf89a676f87a5"
|
checksum = "c58593aafcb03892dbf9998b35a96ead3b8e597435c7af46aff1654d076d5d03"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"auto-launch",
|
"auto-launch",
|
||||||
"serde",
|
"serde",
|
||||||
@ -5750,9 +5671,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-dialog"
|
name = "tauri-plugin-dialog"
|
||||||
version = "2.3.2"
|
version = "2.2.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "37e5858cc7b455a73ab4ea2ebc08b5be33682c00ff1bf4cad5537d4fb62499d9"
|
checksum = "a33318fe222fc2a612961de8b0419e2982767f213f54a4d3a21b0d7b85c41df8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"log",
|
"log",
|
||||||
"raw-window-handle",
|
"raw-window-handle",
|
||||||
@ -5768,9 +5689,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-fs"
|
name = "tauri-plugin-fs"
|
||||||
version = "2.4.1"
|
version = "2.3.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8c6ef84ee2f2094ce093e55106d90d763ba343fad57566992962e8f76d113f99"
|
checksum = "33ead0daec5d305adcefe05af9d970fc437bcc7996052d564e7393eb291252da"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"dunce",
|
"dunce",
|
||||||
@ -5784,7 +5705,7 @@ dependencies = [
|
|||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.12",
|
"thiserror 2.0.12",
|
||||||
"toml 0.8.22",
|
"toml",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -5812,9 +5733,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-os"
|
name = "tauri-plugin-os"
|
||||||
version = "2.3.1"
|
version = "2.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "77a1c77ebf6f20417ab2a74e8c310820ba52151406d0c80fbcea7df232e3f6ba"
|
checksum = "424f19432397850c2ddd42aa58078630c15287bbce3866eb1d90e7dbee680637"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gethostname",
|
"gethostname",
|
||||||
"log",
|
"log",
|
||||||
@ -5830,9 +5751,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-plugin-shell"
|
name = "tauri-plugin-shell"
|
||||||
version = "2.3.0"
|
version = "2.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2b9ffadec5c3523f11e8273465cacb3d86ea7652a28e6e2a2e9b5c182f791d25"
|
checksum = "69d5eb3368b959937ad2aeaf6ef9a8f5d11e01ffe03629d3530707bbcb27ff5d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
"log",
|
"log",
|
||||||
@ -5867,9 +5788,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.8.0"
|
version = "2.7.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d4cfc9ad45b487d3fded5a4731a567872a4812e9552e3964161b08edabf93846"
|
checksum = "2b1cc885be806ea15ff7b0eb47098a7b16323d9228876afda329e34e2d6c4676"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cookie",
|
"cookie",
|
||||||
"dpi",
|
"dpi",
|
||||||
@ -5878,23 +5799,20 @@ dependencies = [
|
|||||||
"jni",
|
"jni",
|
||||||
"objc2 0.6.1",
|
"objc2 0.6.1",
|
||||||
"objc2-ui-kit",
|
"objc2-ui-kit",
|
||||||
"objc2-web-kit",
|
|
||||||
"raw-window-handle",
|
"raw-window-handle",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.12",
|
"thiserror 2.0.12",
|
||||||
"url",
|
"url",
|
||||||
"webkit2gtk",
|
|
||||||
"webview2-com",
|
|
||||||
"windows",
|
"windows",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime-wry"
|
name = "tauri-runtime-wry"
|
||||||
version = "2.8.1"
|
version = "2.7.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c1fe9d48bd122ff002064e88cfcd7027090d789c4302714e68fcccba0f4b7807"
|
checksum = "fe653a2fbbef19fe898efc774bc52c8742576342a33d3d028c189b57eb1d2439"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"gtk",
|
"gtk",
|
||||||
"http 1.3.1",
|
"http 1.3.1",
|
||||||
@ -5919,9 +5837,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-utils"
|
name = "tauri-utils"
|
||||||
version = "2.7.0"
|
version = "2.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "41a3852fdf9a4f8fbeaa63dc3e9a85284dd6ef7200751f0bd66ceee30c93f212"
|
checksum = "9330c15cabfe1d9f213478c9e8ec2b0c76dab26bb6f314b8ad1c8a568c1d186e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"brotli",
|
"brotli",
|
||||||
@ -5948,7 +5866,7 @@ dependencies = [
|
|||||||
"serde_with",
|
"serde_with",
|
||||||
"swift-rs",
|
"swift-rs",
|
||||||
"thiserror 2.0.12",
|
"thiserror 2.0.12",
|
||||||
"toml 0.9.7",
|
"toml",
|
||||||
"url",
|
"url",
|
||||||
"urlpattern",
|
"urlpattern",
|
||||||
"uuid",
|
"uuid",
|
||||||
@ -5962,8 +5880,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "e8d321dbc6f998d825ab3f0d62673e810c861aac2d0de2cc2c395328f1d113b4"
|
checksum = "e8d321dbc6f998d825ab3f0d62673e810c861aac2d0de2cc2c395328f1d113b4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"embed-resource",
|
"embed-resource",
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"toml 0.8.22",
|
"toml",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -6187,26 +6105,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "05ae329d1f08c4d17a59bed7ff5b5a769d062e64a62d34a3261b219e62cd5aae"
|
checksum = "05ae329d1f08c4d17a59bed7ff5b5a769d062e64a62d34a3261b219e62cd5aae"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_spanned 0.6.8",
|
"serde_spanned",
|
||||||
"toml_datetime 0.6.9",
|
"toml_datetime",
|
||||||
"toml_edit 0.22.26",
|
"toml_edit 0.22.26",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml"
|
|
||||||
version = "0.9.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "00e5e5d9bf2475ac9d4f0d9edab68cc573dc2fd644b0dba36b0c30a92dd9eaa0"
|
|
||||||
dependencies = [
|
|
||||||
"indexmap 2.11.4",
|
|
||||||
"serde_core",
|
|
||||||
"serde_spanned 1.0.2",
|
|
||||||
"toml_datetime 0.7.2",
|
|
||||||
"toml_parser",
|
|
||||||
"toml_writer",
|
|
||||||
"winnow 0.7.13",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_datetime"
|
name = "toml_datetime"
|
||||||
version = "0.6.9"
|
version = "0.6.9"
|
||||||
@ -6216,23 +6119,14 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml_datetime"
|
|
||||||
version = "0.7.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "32f1085dec27c2b6632b04c80b3bb1b4300d6495d1e129693bdda7d91e72eec1"
|
|
||||||
dependencies = [
|
|
||||||
"serde_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_edit"
|
name = "toml_edit"
|
||||||
version = "0.19.15"
|
version = "0.19.15"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
|
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"toml_datetime 0.6.9",
|
"toml_datetime",
|
||||||
"winnow 0.5.40",
|
"winnow 0.5.40",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -6242,8 +6136,8 @@ version = "0.20.7"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81"
|
checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"toml_datetime 0.6.9",
|
"toml_datetime",
|
||||||
"winnow 0.5.40",
|
"winnow 0.5.40",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -6253,21 +6147,12 @@ version = "0.22.26"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e"
|
checksum = "310068873db2c5b3e7659d2cc35d21855dbafa50d1ce336397c666e3cb08137e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap 2.11.4",
|
"indexmap 2.9.0",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_spanned 0.6.8",
|
"serde_spanned",
|
||||||
"toml_datetime 0.6.9",
|
"toml_datetime",
|
||||||
"toml_write",
|
"toml_write",
|
||||||
"winnow 0.7.13",
|
"winnow 0.7.10",
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml_parser"
|
|
||||||
version = "1.0.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4cf893c33be71572e0e9aa6dd15e6677937abd686b066eac3f8cd3531688a627"
|
|
||||||
dependencies = [
|
|
||||||
"winnow 0.7.13",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@ -6276,12 +6161,6 @@ version = "0.1.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bfb942dfe1d8e29a7ee7fcbde5bd2b9a25fb89aa70caea2eba3bee836ff41076"
|
checksum = "bfb942dfe1d8e29a7ee7fcbde5bd2b9a25fb89aa70caea2eba3bee836ff41076"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "toml_writer"
|
|
||||||
version = "1.0.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d163a63c116ce562a22cda521fcc4d79152e7aba014456fb5eb442f6d6a10109"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tower"
|
name = "tower"
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
@ -6575,10 +6454,6 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "utils"
|
|
||||||
version = "0.1.0"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.17.0"
|
version = "1.17.0"
|
||||||
@ -7327,9 +7202,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "0.7.13"
|
version = "0.7.10"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
|
checksum = "c06928c8748d81b05c9be96aad92e1b6ff01833332f281e8cfca3be4b35fc9ec"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
@ -7380,15 +7255,14 @@ checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wry"
|
name = "wry"
|
||||||
version = "0.53.4"
|
version = "0.52.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6d78ec082b80fa088569a970d043bb3050abaabf4454101d44514ee8d9a8c9f6"
|
checksum = "12a714d9ba7075aae04a6e50229d6109e3d584774b99a6a8c60de1698ca111b9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"block2 0.6.1",
|
"block2 0.6.1",
|
||||||
"cookie",
|
"cookie",
|
||||||
"crossbeam-channel",
|
"crossbeam-channel",
|
||||||
"dirs 6.0.0",
|
|
||||||
"dpi",
|
"dpi",
|
||||||
"dunce",
|
"dunce",
|
||||||
"gdkx11",
|
"gdkx11",
|
||||||
@ -7557,7 +7431,7 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"uds_windows",
|
"uds_windows",
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.59.0",
|
||||||
"winnow 0.7.13",
|
"winnow 0.7.10",
|
||||||
"zbus_macros",
|
"zbus_macros",
|
||||||
"zbus_names",
|
"zbus_names",
|
||||||
"zvariant",
|
"zvariant",
|
||||||
@ -7586,7 +7460,7 @@ checksum = "7be68e64bf6ce8db94f63e72f0c7eb9a60d733f7e0499e628dfab0f84d6bcb97"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"static_assertions",
|
"static_assertions",
|
||||||
"winnow 0.7.13",
|
"winnow 0.7.10",
|
||||||
"zvariant",
|
"zvariant",
|
||||||
]
|
]
|
||||||
|
|
||||||
@ -7708,7 +7582,7 @@ dependencies = [
|
|||||||
"enumflags2",
|
"enumflags2",
|
||||||
"serde",
|
"serde",
|
||||||
"url",
|
"url",
|
||||||
"winnow 0.7.13",
|
"winnow 0.7.10",
|
||||||
"zvariant_derive",
|
"zvariant_derive",
|
||||||
"zvariant_utils",
|
"zvariant_utils",
|
||||||
]
|
]
|
||||||
@ -7737,5 +7611,5 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"static_assertions",
|
"static_assertions",
|
||||||
"syn 2.0.101",
|
"syn 2.0.101",
|
||||||
"winnow 0.7.13",
|
"winnow 0.7.10",
|
||||||
]
|
]
|
||||||
|
|||||||
@ -78,15 +78,6 @@ futures-core = "0.3.31"
|
|||||||
bytes = "1.10.1"
|
bytes = "1.10.1"
|
||||||
# tailscale = { path = "./tailscale" }
|
# tailscale = { path = "./tailscale" }
|
||||||
|
|
||||||
|
|
||||||
# Workspaces
|
|
||||||
client = { version = "0.1.0", path = "../client" }
|
|
||||||
database = { path = "../database" }
|
|
||||||
process = { path = "../process" }
|
|
||||||
remote = { version = "0.1.0", path = "../remote" }
|
|
||||||
utils = { path = "../utils" }
|
|
||||||
games = { version = "0.1.0", path = "../games" }
|
|
||||||
|
|
||||||
[dependencies.dynfmt]
|
[dependencies.dynfmt]
|
||||||
version = "0.1.5"
|
version = "0.1.5"
|
||||||
features = ["curly"]
|
features = ["curly"]
|
||||||
|
|||||||
@ -1,42 +1,9 @@
|
|||||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
use log::{debug, error};
|
use log::debug;
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
use tauri_plugin_autostart::ManagerExt;
|
use tauri_plugin_autostart::ManagerExt;
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::{AppState};
|
pub fn toggle_autostart_logic(app: AppHandle, enabled: bool) -> Result<(), String> {
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn fetch_state(
|
|
||||||
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())?;
|
|
||||||
drop(guard);
|
|
||||||
Ok(cloned_state)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
|
||||||
cleanup_and_exit(&app, &state);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
|
||||||
debug!("cleaning up and exiting application");
|
|
||||||
let download_manager = lock!(state).download_manager.clone();
|
|
||||||
match download_manager.ensure_terminated() {
|
|
||||||
Ok(res) => match res {
|
|
||||||
Ok(()) => debug!("download manager terminated correctly"),
|
|
||||||
Err(()) => error!("download manager failed to terminate correctly"),
|
|
||||||
},
|
|
||||||
Err(e) => panic!("{e:?}"),
|
|
||||||
}
|
|
||||||
|
|
||||||
app.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
|
||||||
let manager = app.autolaunch();
|
let manager = app.autolaunch();
|
||||||
if enabled {
|
if enabled {
|
||||||
manager.enable().map_err(|e| e.to_string())?;
|
manager.enable().map_err(|e| e.to_string())?;
|
||||||
@ -49,11 +16,13 @@ pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
|||||||
// Store the state in DB
|
// Store the state in DB
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
db_handle.settings.autostart = enabled;
|
db_handle.settings.autostart = enabled;
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
pub fn get_autostart_enabled_logic(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||||
pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
// First check DB state
|
||||||
let db_handle = borrow_db_checked();
|
let db_handle = borrow_db_checked();
|
||||||
let db_state = db_handle.settings.autostart;
|
let db_state = db_handle.settings.autostart;
|
||||||
drop(db_handle);
|
drop(db_handle);
|
||||||
@ -73,3 +42,34 @@ pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autost
|
|||||||
|
|
||||||
Ok(db_state)
|
Ok(db_state)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New function to sync state on startup
|
||||||
|
pub fn sync_autostart_on_startup(app: &AppHandle) -> Result<(), String> {
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
let should_be_enabled = db_handle.settings.autostart;
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
let manager = app.autolaunch();
|
||||||
|
let current_state = manager.is_enabled().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if current_state != should_be_enabled {
|
||||||
|
if should_be_enabled {
|
||||||
|
manager.enable().map_err(|e| e.to_string())?;
|
||||||
|
debug!("synced autostart: enabled");
|
||||||
|
} else {
|
||||||
|
manager.disable().map_err(|e| e.to_string())?;
|
||||||
|
debug!("synced autostart: disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn toggle_autostart(app: AppHandle, enabled: bool) -> Result<(), String> {
|
||||||
|
toggle_autostart_logic(app, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_autostart_enabled(app: AppHandle) -> Result<bool, tauri_plugin_autostart::Error> {
|
||||||
|
get_autostart_enabled_logic(app)
|
||||||
|
}
|
||||||
23
src-tauri/src/client/cleanup.rs
Normal file
23
src-tauri/src/client/cleanup.rs
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
use log::{debug, error};
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn quit(app: tauri::AppHandle, state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
|
cleanup_and_exit(&app, &state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mutex<AppState<'_>>>) {
|
||||||
|
debug!("cleaning up and exiting application");
|
||||||
|
let download_manager = state.lock().unwrap().download_manager.clone();
|
||||||
|
match download_manager.ensure_terminated() {
|
||||||
|
Ok(res) => match res {
|
||||||
|
Ok(()) => debug!("download manager terminated correctly"),
|
||||||
|
Err(()) => error!("download manager failed to terminate correctly"),
|
||||||
|
},
|
||||||
|
Err(e) => panic!("{e:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
app.exit(0);
|
||||||
|
}
|
||||||
11
src-tauri/src/client/commands.rs
Normal file
11
src-tauri/src/client/commands.rs
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn fetch_state(
|
||||||
|
state: tauri::State<'_, std::sync::Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<String, String> {
|
||||||
|
let guard = state.lock().unwrap();
|
||||||
|
let cloned_state = serde_json::to_string(&guard.clone()).map_err(|e| e.to_string())?;
|
||||||
|
drop(guard);
|
||||||
|
Ok(cloned_state)
|
||||||
|
}
|
||||||
3
src-tauri/src/client/mod.rs
Normal file
3
src-tauri/src/client/mod.rs
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
pub mod autostart;
|
||||||
|
pub mod cleanup;
|
||||||
|
pub mod commands;
|
||||||
@ -1,11 +1,8 @@
|
|||||||
use std::{collections::HashMap, path::PathBuf, str::FromStr};
|
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 log::warn;
|
||||||
|
|
||||||
use crate::error::BackupError;
|
use crate::{database::db::{GameVersion, DATA_ROOT_DIR}, error::backup_error::BackupError, process::process_manager::Platform};
|
||||||
|
|
||||||
use super::path::CommonPath;
|
use super::path::CommonPath;
|
||||||
|
|
||||||
@ -48,7 +45,7 @@ impl BackupManager<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait BackupHandler: Send + Sync {
|
pub trait BackupHandler: Send + Sync {
|
||||||
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.join("games")) }
|
fn root_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(DATA_ROOT_DIR.lock().unwrap().join("games")) }
|
||||||
fn game_translate(&self, _path: &PathBuf, game: &GameVersion) -> Result<PathBuf, BackupError> { Ok(PathBuf::from_str(&game.game_id).unwrap()) }
|
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 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 home_translate(&self, _path: &PathBuf, _game: &GameVersion) -> Result<PathBuf, BackupError> { let c = CommonPath::Home.get().ok_or(BackupError::NotFound); println!("{:?}", c); c }
|
||||||
@ -1,4 +1,4 @@
|
|||||||
use database::platform::Platform;
|
use crate::process::process_manager::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 {
|
||||||
@ -1,4 +1,4 @@
|
|||||||
use database::GameVersion;
|
use crate::database::db::GameVersion;
|
||||||
|
|
||||||
use super::conditions::{Condition};
|
use super::conditions::{Condition};
|
||||||
|
|
||||||
@ -1,7 +1,7 @@
|
|||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
use database::platform::Platform;
|
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
use crate::process::process_manager::Platform;
|
||||||
|
|
||||||
use super::placeholder::*;
|
use super::placeholder::*;
|
||||||
|
|
||||||
@ -6,16 +6,17 @@ use std::{
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::error::BackupError;
|
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
backup_manager::BackupHandler, conditions::Condition, metadata::GameFile, placeholder::*,
|
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;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
database::db::GameVersion, error::backup_error::BackupError, process::process_manager::Platform,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{backup_manager::BackupManager, metadata::CloudSaveMetadata, normalise::normalize};
|
use super::{backup_manager::BackupManager, metadata::CloudSaveMetadata, normalise::normalize};
|
||||||
|
|
||||||
pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
pub fn resolve(meta: &mut CloudSaveMetadata) -> File {
|
||||||
@ -4,16 +4,14 @@ use std::{
|
|||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
};
|
};
|
||||||
|
|
||||||
use log::error;
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{db::borrow_db_mut_checked, scan::scan_install_dirs},
|
database::{db::borrow_db_mut_checked, scan::scan_install_dirs}, error::download_manager_error::DownloadManagerError,
|
||||||
error::download_manager_error::DownloadManagerError,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
db::{DATA_ROOT_DIR, borrow_db_checked},
|
db::{borrow_db_checked, DATA_ROOT_DIR},
|
||||||
debug::SystemData,
|
debug::SystemData,
|
||||||
models::data::Settings,
|
models::data::Settings,
|
||||||
};
|
};
|
||||||
@ -69,25 +67,11 @@ pub fn add_download_dir(new_dir: PathBuf) -> Result<(), DownloadManagerError<()>
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn update_settings(new_settings: Value) {
|
pub fn update_settings(new_settings: Value) {
|
||||||
let mut db_lock = borrow_db_mut_checked();
|
let mut db_lock = borrow_db_mut_checked();
|
||||||
let mut current_settings =
|
let mut current_settings = serde_json::to_value(db_lock.settings.clone()).unwrap();
|
||||||
serde_json::to_value(db_lock.settings.clone()).expect("Failed to parse existing settings");
|
for (key, value) in new_settings.as_object().unwrap() {
|
||||||
let values = match new_settings.as_object() {
|
|
||||||
Some(values) => values,
|
|
||||||
None => {
|
|
||||||
error!("Could not parse settings values into object");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (key, value) in values {
|
|
||||||
current_settings[key] = value.clone();
|
current_settings[key] = value.clone();
|
||||||
}
|
}
|
||||||
let new_settings: Settings = match serde_json::from_value(current_settings) {
|
let new_settings: Settings = serde_json::from_value(current_settings).unwrap();
|
||||||
Ok(settings) => settings,
|
|
||||||
Err(e) => {
|
|
||||||
error!("Could not parse settings with error {}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
db_lock.settings = new_settings;
|
db_lock.settings = new_settings;
|
||||||
}
|
}
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -1,11 +1,50 @@
|
|||||||
use std::{fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, sync::{RwLockReadGuard, RwLockWriteGuard}};
|
use std::{
|
||||||
|
fs::{self, create_dir_all},
|
||||||
|
mem::ManuallyDrop,
|
||||||
|
ops::{Deref, DerefMut},
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{Arc, LazyLock, 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::{DeSerError, DeSerializer, PathDatabase, RustbreakError};
|
||||||
|
use serde::{Serialize, de::DeserializeOwned};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{db::{DropDatabaseSerializer, DATA_ROOT_DIR, DB}, models::data::Database};
|
use crate::DB;
|
||||||
|
|
||||||
|
use super::models::data::Database;
|
||||||
|
|
||||||
|
#[cfg(not(debug_assertions))]
|
||||||
|
static DATA_ROOT_PREFIX: &'static 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().unwrap().join(DATA_ROOT_PREFIX)));
|
||||||
|
|
||||||
|
// Custom JSON serializer to support everything we need
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct DropDatabaseSerializer;
|
||||||
|
|
||||||
|
impl<T: native_model::Model + Serialize + DeserializeOwned> DeSerializer<T>
|
||||||
|
for DropDatabaseSerializer
|
||||||
|
{
|
||||||
|
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
||||||
|
native_model::encode(val)
|
||||||
|
.map_err(|e| DeSerError::Internal(e.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize<R: std::io::Read>(&self, mut s: R) -> rustbreak::error::DeSerResult<T> {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
s.read_to_end(&mut buf)
|
||||||
|
.map_err(|e| rustbreak::error::DeSerError::Other(e.into()))?;
|
||||||
|
let (val, _version) = native_model::decode(buf)
|
||||||
|
.map_err(|e| DeSerError::Internal(e.to_string()))?;
|
||||||
|
Ok(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub type DatabaseInterface =
|
pub type DatabaseInterface =
|
||||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||||
@ -24,49 +63,13 @@ impl DatabaseImpls for DatabaseInterface {
|
|||||||
let pfx_dir = DATA_ROOT_DIR.join("pfx");
|
let pfx_dir = DATA_ROOT_DIR.join("pfx");
|
||||||
|
|
||||||
debug!("creating data directory at {DATA_ROOT_DIR:?}");
|
debug!("creating data directory at {DATA_ROOT_DIR:?}");
|
||||||
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap_or_else(|e| {
|
create_dir_all(DATA_ROOT_DIR.as_path()).unwrap();
|
||||||
panic!(
|
create_dir_all(&games_base_dir).unwrap();
|
||||||
"Failed to create directory {} with error {}",
|
create_dir_all(&logs_root_dir).unwrap();
|
||||||
DATA_ROOT_DIR.display(),
|
create_dir_all(&cache_dir).unwrap();
|
||||||
e
|
create_dir_all(&pfx_dir).unwrap();
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&games_base_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
games_base_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&logs_root_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
logs_root_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&cache_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
cache_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
create_dir_all(&pfx_dir).unwrap_or_else(|e| {
|
|
||||||
panic!(
|
|
||||||
"Failed to create directory {} with error {}",
|
|
||||||
pfx_dir.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let exists = fs::exists(db_path.clone()).unwrap_or_else(|e| {
|
let exists = fs::exists(db_path.clone()).unwrap();
|
||||||
panic!(
|
|
||||||
"Failed to find if {} exists with error {}",
|
|
||||||
db_path.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
if exists {
|
if exists {
|
||||||
match PathDatabase::load_from_path(db_path.clone()) {
|
match PathDatabase::load_from_path(db_path.clone()) {
|
||||||
@ -75,19 +78,21 @@ impl DatabaseImpls for DatabaseInterface {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let default = Database::new(games_base_dir, None, cache_dir);
|
let default = Database::new(games_base_dir, None, cache_dir);
|
||||||
debug!("Creating database at path {}", db_path.display());
|
debug!(
|
||||||
|
"Creating database at path {}",
|
||||||
|
db_path.as_os_str().to_str().unwrap()
|
||||||
|
);
|
||||||
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 {
|
fn database_is_set_up(&self) -> bool {
|
||||||
!borrow_db_checked().base_url.is_empty()
|
!self.borrow_data().unwrap().base_url.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fetch_base_url(&self) -> Url {
|
fn fetch_base_url(&self) -> Url {
|
||||||
let handle = borrow_db_checked();
|
let handle = self.borrow_data().unwrap();
|
||||||
Url::parse(&handle.base_url)
|
Url::parse(&handle.base_url).unwrap()
|
||||||
.unwrap_or_else(|_| panic!("Failed to parse base url {}", handle.base_url))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -106,16 +111,13 @@ fn handle_invalid_database(
|
|||||||
base
|
base
|
||||||
};
|
};
|
||||||
info!("old database stored at: {}", new_path.to_string_lossy());
|
info!("old database stored at: {}", new_path.to_string_lossy());
|
||||||
fs::rename(&db_path, &new_path).unwrap_or_else(|e| {
|
fs::rename(&db_path, &new_path).unwrap();
|
||||||
panic!(
|
|
||||||
"Could not rename database {} to {} with error {}",
|
|
||||||
db_path.display(),
|
|
||||||
new_path.display(),
|
|
||||||
e
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
let db = Database::new(games_base_dir, Some(new_path), cache_dir);
|
let db = Database::new(
|
||||||
|
games_base_dir.into_os_string().into_string().unwrap(),
|
||||||
|
Some(new_path),
|
||||||
|
cache_dir,
|
||||||
|
);
|
||||||
|
|
||||||
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
|
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
|
||||||
}
|
}
|
||||||
5
src-tauri/src/database/mod.rs
Normal file
5
src-tauri/src/database/mod.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
pub mod commands;
|
||||||
|
pub mod db;
|
||||||
|
pub mod debug;
|
||||||
|
pub mod models;
|
||||||
|
pub mod scan;
|
||||||
@ -37,18 +37,17 @@ pub mod data {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod v1 {
|
mod v1 {
|
||||||
|
use crate::process::process_manager::Platform;
|
||||||
use serde_with::serde_as;
|
use serde_with::serde_as;
|
||||||
use std::{collections::HashMap, path::PathBuf};
|
use std::{collections::HashMap, path::PathBuf};
|
||||||
|
|
||||||
use crate::platform::Platform;
|
|
||||||
|
|
||||||
use super::{Deserialize, Serialize, native_model};
|
use super::{Deserialize, Serialize, native_model};
|
||||||
|
|
||||||
fn default_template() -> String {
|
fn default_template() -> String {
|
||||||
"{}".to_owned()
|
"{}".to_owned()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[native_model(id = 2, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
#[native_model(id = 2, version = 1, with = native_model::rmp_serde_1_3::RmpSerde)]
|
||||||
pub struct GameVersion {
|
pub struct GameVersion {
|
||||||
@ -24,11 +24,11 @@ pub fn scan_install_dirs() {
|
|||||||
if !drop_data_file.exists() {
|
if !drop_data_file.exists() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let game_id = game.file_name().display().to_string();
|
let game_id = game.file_name().into_string().unwrap();
|
||||||
let Ok(drop_data) = DropData::read(&game.path()) else {
|
let Ok(drop_data) = DropData::read(&game.path()) else {
|
||||||
warn!(
|
warn!(
|
||||||
".dropdata exists for {}, but couldn't read it. is it corrupted?",
|
".dropdata exists for {}, but couldn't read it. is it corrupted?",
|
||||||
game.file_name().display()
|
game.file_name().into_string().unwrap()
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@ -1,13 +1,15 @@
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use crate::{database::models::data::DownloadableMetadata, AppState};
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
pub fn pause_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||||
lock!(state).download_manager.pause_downloads();
|
state.lock().unwrap().download_manager.pause_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
pub fn resume_downloads(state: tauri::State<'_, Mutex<AppState>>) {
|
||||||
lock!(state).download_manager.resume_downloads();
|
state.lock().unwrap().download_manager.resume_downloads();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -16,12 +18,14 @@ pub fn move_download_in_queue(
|
|||||||
old_index: usize,
|
old_index: usize,
|
||||||
new_index: usize,
|
new_index: usize,
|
||||||
) {
|
) {
|
||||||
lock!(state)
|
state
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.download_manager
|
.download_manager
|
||||||
.rearrange(old_index, new_index);
|
.rearrange(old_index, new_index);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
|
pub fn cancel_game(state: tauri::State<'_, Mutex<AppState>>, meta: DownloadableMetadata) {
|
||||||
lock!(state).download_manager.cancel(meta);
|
state.lock().unwrap().download_manager.cancel(meta);
|
||||||
}
|
}
|
||||||
@ -7,13 +7,15 @@ use std::{
|
|||||||
thread::{JoinHandle, spawn},
|
thread::{JoinHandle, spawn},
|
||||||
};
|
};
|
||||||
|
|
||||||
use database::DownloadableMetadata;
|
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use tauri::{AppHandle, Emitter};
|
use tauri::{AppHandle, Emitter};
|
||||||
use utils::{app_emit, lock, send};
|
|
||||||
|
|
||||||
|
use crate::{
|
||||||
use crate::{download_manager_frontend::DownloadStatus, error::ApplicationDownloadError, frontend_updates::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent}};
|
database::models::data::DownloadableMetadata,
|
||||||
|
download_manager::download_manager_frontend::DownloadStatus,
|
||||||
|
error::application_download_error::ApplicationDownloadError,
|
||||||
|
games::library::{QueueUpdateEvent, QueueUpdateEventQueueData, StatsUpdateEvent},
|
||||||
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus},
|
||||||
@ -103,7 +105,7 @@ impl DownloadManagerBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_status(&self, status: DownloadManagerStatus) {
|
fn set_status(&self, status: DownloadManagerStatus) {
|
||||||
*lock!(self.status) = status;
|
*self.status.lock().unwrap() = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_and_cleanup_front_download(&mut self, meta: &DownloadableMetadata) -> DownloadAgent {
|
fn remove_and_cleanup_front_download(&mut self, meta: &DownloadableMetadata) -> DownloadAgent {
|
||||||
@ -117,9 +119,9 @@ impl DownloadManagerBuilder {
|
|||||||
// Make sure the download thread is terminated
|
// Make sure the download thread is terminated
|
||||||
fn cleanup_current_download(&mut self) {
|
fn cleanup_current_download(&mut self) {
|
||||||
self.active_control_flag = None;
|
self.active_control_flag = None;
|
||||||
*lock!(self.progress) = None;
|
*self.progress.lock().unwrap() = None;
|
||||||
|
|
||||||
let mut download_thread_lock = lock!(self.current_download_thread);
|
let mut download_thread_lock = self.current_download_thread.lock().unwrap();
|
||||||
|
|
||||||
if let Some(unfinished_thread) = download_thread_lock.take()
|
if let Some(unfinished_thread) = download_thread_lock.take()
|
||||||
&& !unfinished_thread.is_finished()
|
&& !unfinished_thread.is_finished()
|
||||||
@ -135,7 +137,7 @@ impl DownloadManagerBuilder {
|
|||||||
current_flag.set(DownloadThreadControlFlag::Stop);
|
current_flag.set(DownloadThreadControlFlag::Stop);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut download_thread_lock = lock!(self.current_download_thread);
|
let mut download_thread_lock = self.current_download_thread.lock().unwrap();
|
||||||
if let Some(current_download_thread) = download_thread_lock.take() {
|
if let Some(current_download_thread) = download_thread_lock.take() {
|
||||||
return current_download_thread.join().is_ok();
|
return current_download_thread.join().is_ok();
|
||||||
};
|
};
|
||||||
@ -197,7 +199,9 @@ impl DownloadManagerBuilder {
|
|||||||
self.download_queue.append(meta.clone());
|
self.download_queue.append(meta.clone());
|
||||||
self.download_agent_registry.insert(meta, download_agent);
|
self.download_agent_registry.insert(meta, download_agent);
|
||||||
|
|
||||||
send!(self.sender, DownloadManagerSignal::UpdateUIQueue);
|
self.sender
|
||||||
|
.send(DownloadManagerSignal::UpdateUIQueue)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn manage_go_signal(&mut self) {
|
fn manage_go_signal(&mut self) {
|
||||||
@ -243,7 +247,7 @@ impl DownloadManagerBuilder {
|
|||||||
|
|
||||||
let sender = self.sender.clone();
|
let sender = self.sender.clone();
|
||||||
|
|
||||||
let mut download_thread_lock = lock!(self.current_download_thread);
|
let mut download_thread_lock = self.current_download_thread.lock().unwrap();
|
||||||
let app_handle = self.app_handle.clone();
|
let app_handle = self.app_handle.clone();
|
||||||
|
|
||||||
*download_thread_lock = Some(spawn(move || {
|
*download_thread_lock = Some(spawn(move || {
|
||||||
@ -254,7 +258,7 @@ impl DownloadManagerBuilder {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("download {:?} has error {}", download_agent.metadata(), &e);
|
error!("download {:?} has error {}", download_agent.metadata(), &e);
|
||||||
download_agent.on_error(&app_handle, &e);
|
download_agent.on_error(&app_handle, &e);
|
||||||
send!(sender, DownloadManagerSignal::Error(e));
|
sender.send(DownloadManagerSignal::Error(e)).unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -278,7 +282,7 @@ impl DownloadManagerBuilder {
|
|||||||
&e
|
&e
|
||||||
);
|
);
|
||||||
download_agent.on_error(&app_handle, &e);
|
download_agent.on_error(&app_handle, &e);
|
||||||
send!(sender, DownloadManagerSignal::Error(e));
|
sender.send(DownloadManagerSignal::Error(e)).unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -289,8 +293,10 @@ impl DownloadManagerBuilder {
|
|||||||
|
|
||||||
if validate_result {
|
if validate_result {
|
||||||
download_agent.on_complete(&app_handle);
|
download_agent.on_complete(&app_handle);
|
||||||
send!(sender, DownloadManagerSignal::Completed(download_agent.metadata()));
|
sender
|
||||||
send!(sender, DownloadManagerSignal::UpdateUIQueue);
|
.send(DownloadManagerSignal::Completed(download_agent.metadata()))
|
||||||
|
.unwrap();
|
||||||
|
sender.send(DownloadManagerSignal::UpdateUIQueue).unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -317,7 +323,7 @@ impl DownloadManagerBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.push_ui_queue_update();
|
self.push_ui_queue_update();
|
||||||
send!(self.sender, DownloadManagerSignal::Go);
|
self.sender.send(DownloadManagerSignal::Go).unwrap();
|
||||||
}
|
}
|
||||||
fn manage_error_signal(&mut self, error: ApplicationDownloadError) {
|
fn manage_error_signal(&mut self, error: ApplicationDownloadError) {
|
||||||
debug!("got signal Error");
|
debug!("got signal Error");
|
||||||
@ -355,7 +361,7 @@ impl DownloadManagerBuilder {
|
|||||||
let index = self.download_queue.get_by_meta(meta);
|
let index = self.download_queue.get_by_meta(meta);
|
||||||
if let Some(index) = index {
|
if let Some(index) = index {
|
||||||
download_agent.on_cancelled(&self.app_handle);
|
download_agent.on_cancelled(&self.app_handle);
|
||||||
let _ = self.download_queue.edit().remove(index);
|
let _ = self.download_queue.edit().remove(index).unwrap();
|
||||||
let removed = self.download_agent_registry.remove(meta);
|
let removed = self.download_agent_registry.remove(meta);
|
||||||
debug!(
|
debug!(
|
||||||
"removed {:?} from queue {:?}",
|
"removed {:?} from queue {:?}",
|
||||||
@ -370,7 +376,7 @@ impl DownloadManagerBuilder {
|
|||||||
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
|
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
|
||||||
let event_data = StatsUpdateEvent { speed: kbs, time };
|
let event_data = StatsUpdateEvent { speed: kbs, time };
|
||||||
|
|
||||||
app_emit!(self.app_handle, "update_stats", event_data);
|
self.app_handle.emit("update_stats", event_data).unwrap();
|
||||||
}
|
}
|
||||||
fn push_ui_queue_update(&self) {
|
fn push_ui_queue_update(&self) {
|
||||||
let queue = &self.download_queue.read();
|
let queue = &self.download_queue.read();
|
||||||
@ -389,6 +395,6 @@ impl DownloadManagerBuilder {
|
|||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let event_data = QueueUpdateEvent { queue: queue_objs };
|
let event_data = QueueUpdateEvent { queue: queue_objs };
|
||||||
app_emit!(self.app_handle, "update_queue", event_data);
|
self.app_handle.emit("update_queue", event_data).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -3,19 +3,19 @@ use std::{
|
|||||||
collections::VecDeque,
|
collections::VecDeque,
|
||||||
fmt::Debug,
|
fmt::Debug,
|
||||||
sync::{
|
sync::{
|
||||||
Mutex, MutexGuard,
|
|
||||||
mpsc::{SendError, Sender},
|
mpsc::{SendError, Sender},
|
||||||
|
Mutex, MutexGuard,
|
||||||
},
|
},
|
||||||
thread::JoinHandle,
|
thread::JoinHandle,
|
||||||
};
|
};
|
||||||
|
|
||||||
use database::DownloadableMetadata;
|
|
||||||
use log::{debug, info};
|
use log::{debug, info};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use utils::{lock, send};
|
|
||||||
|
|
||||||
|
use crate::{
|
||||||
use crate::error::ApplicationDownloadError;
|
database::models::data::DownloadableMetadata,
|
||||||
|
error::application_download_error::ApplicationDownloadError,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
download_manager_builder::{CurrentProgressObject, DownloadAgent},
|
download_manager_builder::{CurrentProgressObject, DownloadAgent},
|
||||||
@ -119,18 +119,22 @@ impl DownloadManager {
|
|||||||
self.download_queue.read()
|
self.download_queue.read()
|
||||||
}
|
}
|
||||||
pub fn get_current_download_progress(&self) -> Option<f64> {
|
pub fn get_current_download_progress(&self) -> Option<f64> {
|
||||||
let progress_object = (*lock!(self.progress)).clone()?;
|
let progress_object = (*self.progress.lock().unwrap()).clone()?;
|
||||||
Some(progress_object.get_progress())
|
Some(progress_object.get_progress())
|
||||||
}
|
}
|
||||||
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
|
pub fn rearrange_string(&self, meta: &DownloadableMetadata, new_index: usize) {
|
||||||
let mut queue = self.edit();
|
let mut queue = self.edit();
|
||||||
let current_index = get_index_from_id(&mut queue, meta).expect("Failed to get meta index from id");
|
let current_index = get_index_from_id(&mut queue, meta).unwrap();
|
||||||
let to_move = queue.remove(current_index).expect("Failed to remove meta at index from queue");
|
let to_move = queue.remove(current_index).unwrap();
|
||||||
queue.insert(new_index, to_move);
|
queue.insert(new_index, to_move);
|
||||||
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
|
self.command_sender
|
||||||
|
.send(DownloadManagerSignal::UpdateUIQueue)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
pub fn cancel(&self, meta: DownloadableMetadata) {
|
pub fn cancel(&self, meta: DownloadableMetadata) {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Cancel(meta));
|
self.command_sender
|
||||||
|
.send(DownloadManagerSignal::Cancel(meta))
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
pub fn rearrange(&self, current_index: usize, new_index: usize) {
|
pub fn rearrange(&self, current_index: usize, new_index: usize) {
|
||||||
if current_index == new_index {
|
if current_index == new_index {
|
||||||
@ -139,31 +143,39 @@ impl DownloadManager {
|
|||||||
|
|
||||||
let needs_pause = current_index == 0 || new_index == 0;
|
let needs_pause = current_index == 0 || new_index == 0;
|
||||||
if needs_pause {
|
if needs_pause {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Stop);
|
self.command_sender
|
||||||
|
.send(DownloadManagerSignal::Stop)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("moving download at index {current_index} to index {new_index}");
|
debug!("moving download at index {current_index} to index {new_index}");
|
||||||
|
|
||||||
let mut queue = self.edit();
|
let mut queue = self.edit();
|
||||||
let to_move = queue.remove(current_index).expect("Failed to get");
|
let to_move = queue.remove(current_index).unwrap();
|
||||||
queue.insert(new_index, to_move);
|
queue.insert(new_index, to_move);
|
||||||
drop(queue);
|
drop(queue);
|
||||||
|
|
||||||
if needs_pause {
|
if needs_pause {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Go);
|
self.command_sender.send(DownloadManagerSignal::Go).unwrap();
|
||||||
}
|
}
|
||||||
send!(self.command_sender, DownloadManagerSignal::UpdateUIQueue);
|
self.command_sender
|
||||||
send!(self.command_sender, DownloadManagerSignal::Go);
|
.send(DownloadManagerSignal::UpdateUIQueue)
|
||||||
|
.unwrap();
|
||||||
|
self.command_sender.send(DownloadManagerSignal::Go).unwrap();
|
||||||
}
|
}
|
||||||
pub fn pause_downloads(&self) {
|
pub fn pause_downloads(&self) {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Stop);
|
self.command_sender
|
||||||
|
.send(DownloadManagerSignal::Stop)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
pub fn resume_downloads(&self) {
|
pub fn resume_downloads(&self) {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Go);
|
self.command_sender.send(DownloadManagerSignal::Go).unwrap();
|
||||||
}
|
}
|
||||||
pub fn ensure_terminated(&self) -> Result<Result<(), ()>, Box<dyn Any + Send>> {
|
pub fn ensure_terminated(&self) -> Result<Result<(), ()>, Box<dyn Any + Send>> {
|
||||||
send!(self.command_sender, DownloadManagerSignal::Finish);
|
self.command_sender
|
||||||
let terminator = lock!(self.terminator).take();
|
.send(DownloadManagerSignal::Finish)
|
||||||
|
.unwrap();
|
||||||
|
let terminator = self.terminator.lock().unwrap().take();
|
||||||
terminator.unwrap().join()
|
terminator.unwrap().join()
|
||||||
}
|
}
|
||||||
pub fn get_sender(&self) -> Sender<DownloadManagerSignal> {
|
pub fn get_sender(&self) -> Sender<DownloadManagerSignal> {
|
||||||
@ -1,10 +1,11 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use database::DownloadableMetadata;
|
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
use crate::error::ApplicationDownloadError;
|
database::models::data::DownloadableMetadata,
|
||||||
|
error::application_download_error::ApplicationDownloadError,
|
||||||
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
download_manager_frontend::DownloadStatus,
|
download_manager_frontend::DownloadStatus,
|
||||||
5
src-tauri/src/download_manager/mod.rs
Normal file
5
src-tauri/src/download_manager/mod.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
pub mod commands;
|
||||||
|
pub mod download_manager_builder;
|
||||||
|
pub mod download_manager_frontend;
|
||||||
|
pub mod downloadable;
|
||||||
|
pub mod util;
|
||||||
@ -9,9 +9,8 @@ use std::{
|
|||||||
|
|
||||||
use atomic_instant_full::AtomicInstant;
|
use atomic_instant_full::AtomicInstant;
|
||||||
use throttle_my_fn::throttle;
|
use throttle_my_fn::throttle;
|
||||||
use utils::{lock, send};
|
|
||||||
|
|
||||||
use crate::download_manager_frontend::DownloadManagerSignal;
|
use crate::download_manager::download_manager_frontend::DownloadManagerSignal;
|
||||||
|
|
||||||
use super::rolling_progress_updates::RollingProgressWindow;
|
use super::rolling_progress_updates::RollingProgressWindow;
|
||||||
|
|
||||||
@ -75,10 +74,12 @@ impl ProgressObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_time_now(&self) {
|
pub fn set_time_now(&self) {
|
||||||
*lock!(self.start) = Instant::now();
|
*self.start.lock().unwrap() = Instant::now();
|
||||||
}
|
}
|
||||||
pub fn sum(&self) -> usize {
|
pub fn sum(&self) -> usize {
|
||||||
lock!(self.progress_instances)
|
self.progress_instances
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|instance| instance.load(Ordering::Acquire))
|
.map(|instance| instance.load(Ordering::Acquire))
|
||||||
.sum()
|
.sum()
|
||||||
@ -87,25 +88,27 @@ impl ProgressObject {
|
|||||||
self.set_time_now();
|
self.set_time_now();
|
||||||
self.bytes_last_update.store(0, Ordering::Release);
|
self.bytes_last_update.store(0, Ordering::Release);
|
||||||
self.rolling.reset();
|
self.rolling.reset();
|
||||||
lock!(self.progress_instances)
|
self.progress_instances
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.iter()
|
.iter()
|
||||||
.for_each(|x| x.store(0, Ordering::SeqCst));
|
.for_each(|x| x.store(0, Ordering::SeqCst));
|
||||||
}
|
}
|
||||||
pub fn get_max(&self) -> usize {
|
pub fn get_max(&self) -> usize {
|
||||||
*lock!(self.max)
|
*self.max.lock().unwrap()
|
||||||
}
|
}
|
||||||
pub fn set_max(&self, new_max: usize) {
|
pub fn set_max(&self, new_max: usize) {
|
||||||
*lock!(self.max) = new_max;
|
*self.max.lock().unwrap() = new_max;
|
||||||
}
|
}
|
||||||
pub fn set_size(&self, length: usize) {
|
pub fn set_size(&self, length: usize) {
|
||||||
*lock!(self.progress_instances) =
|
*self.progress_instances.lock().unwrap() =
|
||||||
(0..length).map(|_| Arc::new(AtomicUsize::new(0))).collect();
|
(0..length).map(|_| Arc::new(AtomicUsize::new(0))).collect();
|
||||||
}
|
}
|
||||||
pub fn get_progress(&self) -> f64 {
|
pub fn get_progress(&self) -> f64 {
|
||||||
self.sum() as f64 / self.get_max() as f64
|
self.sum() as f64 / self.get_max() as f64
|
||||||
}
|
}
|
||||||
pub fn get(&self, index: usize) -> Arc<AtomicUsize> {
|
pub fn get(&self, index: usize) -> Arc<AtomicUsize> {
|
||||||
lock!(self.progress_instances)[index].clone()
|
self.progress_instances.lock().unwrap()[index].clone()
|
||||||
}
|
}
|
||||||
fn update_window(&self, kilobytes_per_second: usize) {
|
fn update_window(&self, kilobytes_per_second: usize) {
|
||||||
self.rolling.update(kilobytes_per_second);
|
self.rolling.update(kilobytes_per_second);
|
||||||
@ -145,12 +148,18 @@ pub fn push_update(progress: &ProgressObject, bytes_remaining: usize) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn update_ui(progress_object: &ProgressObject, kilobytes_per_second: usize, time_remaining: usize) {
|
fn update_ui(progress_object: &ProgressObject, kilobytes_per_second: usize, time_remaining: usize) {
|
||||||
send!(
|
progress_object
|
||||||
progress_object.sender,
|
.sender
|
||||||
DownloadManagerSignal::UpdateUIStats(kilobytes_per_second, time_remaining)
|
.send(DownloadManagerSignal::UpdateUIStats(
|
||||||
);
|
kilobytes_per_second,
|
||||||
|
time_remaining,
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_queue(progress: &ProgressObject) {
|
fn update_queue(progress: &ProgressObject) {
|
||||||
send!(progress.sender, DownloadManagerSignal::UpdateUIQueue)
|
progress
|
||||||
|
.sender
|
||||||
|
.send(DownloadManagerSignal::UpdateUIQueue)
|
||||||
|
.unwrap();
|
||||||
}
|
}
|
||||||
@ -3,8 +3,7 @@ use std::{
|
|||||||
sync::{Arc, Mutex, MutexGuard},
|
sync::{Arc, Mutex, MutexGuard},
|
||||||
};
|
};
|
||||||
|
|
||||||
use database::DownloadableMetadata;
|
use crate::database::models::data::DownloadableMetadata;
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Queue {
|
pub struct Queue {
|
||||||
@ -25,10 +24,10 @@ impl Queue {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn read(&self) -> VecDeque<DownloadableMetadata> {
|
pub fn read(&self) -> VecDeque<DownloadableMetadata> {
|
||||||
lock!(self.inner).clone()
|
self.inner.lock().unwrap().clone()
|
||||||
}
|
}
|
||||||
pub fn edit(&self) -> MutexGuard<'_, VecDeque<DownloadableMetadata>> {
|
pub fn edit(&self) -> MutexGuard<'_, VecDeque<DownloadableMetadata>> {
|
||||||
lock!(self.inner)
|
self.inner.lock().unwrap()
|
||||||
}
|
}
|
||||||
pub fn pop_front(&self) -> Option<DownloadableMetadata> {
|
pub fn pop_front(&self) -> Option<DownloadableMetadata> {
|
||||||
self.edit().pop_front()
|
self.edit().pop_front()
|
||||||
@ -1,32 +1,12 @@
|
|||||||
use std::{fmt::{Display, Formatter}, io, sync::{mpsc::SendError, Arc}};
|
use std::{
|
||||||
|
fmt::{Display, Formatter},
|
||||||
|
io, sync::Arc,
|
||||||
|
};
|
||||||
|
|
||||||
|
use serde_with::SerializeDisplay;
|
||||||
use humansize::{format_size, BINARY};
|
use humansize::{format_size, BINARY};
|
||||||
|
|
||||||
use remote::error::RemoteAccessError;
|
use super::remote_access_error::RemoteAccessError;
|
||||||
use serde_with::SerializeDisplay;
|
|
||||||
|
|
||||||
#[derive(SerializeDisplay)]
|
|
||||||
pub enum DownloadManagerError<T> {
|
|
||||||
IOError(io::Error),
|
|
||||||
SignalError(SendError<T>),
|
|
||||||
}
|
|
||||||
impl<T> Display for DownloadManagerError<T> {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
DownloadManagerError::IOError(error) => write!(f, "{error}"),
|
|
||||||
DownloadManagerError::SignalError(send_error) => write!(f, "{send_error}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<T> From<SendError<T>> for DownloadManagerError<T> {
|
|
||||||
fn from(value: SendError<T>) -> Self {
|
|
||||||
DownloadManagerError::SignalError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl<T> From<io::Error> for DownloadManagerError<T> {
|
|
||||||
fn from(value: io::Error) -> Self {
|
|
||||||
DownloadManagerError::IOError(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Rename / separate from downloads
|
// TODO: Rename / separate from downloads
|
||||||
#[derive(Debug, SerializeDisplay)]
|
#[derive(Debug, SerializeDisplay)]
|
||||||
@ -38,7 +18,7 @@ pub enum ApplicationDownloadError {
|
|||||||
Checksum,
|
Checksum,
|
||||||
Lock,
|
Lock,
|
||||||
IoError(Arc<io::Error>),
|
IoError(Arc<io::Error>),
|
||||||
DownloadError(RemoteAccessError),
|
DownloadError,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for ApplicationDownloadError {
|
impl Display for ApplicationDownloadError {
|
||||||
@ -60,16 +40,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) => write!(
|
ApplicationDownloadError::DownloadError => write!(
|
||||||
f,
|
f,
|
||||||
"Download failed with error {error:?}"
|
"Download failed. See Download Manager status for specific error"
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<io::Error> for ApplicationDownloadError {
|
|
||||||
fn from(value: io::Error) -> Self {
|
|
||||||
ApplicationDownloadError::IoError(Arc::new(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
27
src-tauri/src/error/download_manager_error.rs
Normal file
27
src-tauri/src/error/download_manager_error.rs
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
use std::{fmt::Display, io, sync::mpsc::SendError};
|
||||||
|
|
||||||
|
use serde_with::SerializeDisplay;
|
||||||
|
|
||||||
|
#[derive(SerializeDisplay)]
|
||||||
|
pub enum DownloadManagerError<T> {
|
||||||
|
IOError(io::Error),
|
||||||
|
SignalError(SendError<T>),
|
||||||
|
}
|
||||||
|
impl<T> Display for DownloadManagerError<T> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
DownloadManagerError::IOError(error) => write!(f, "{error}"),
|
||||||
|
DownloadManagerError::SignalError(send_error) => write!(f, "{send_error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> From<SendError<T>> for DownloadManagerError<T> {
|
||||||
|
fn from(value: SendError<T>) -> Self {
|
||||||
|
DownloadManagerError::SignalError(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> From<io::Error> for DownloadManagerError<T> {
|
||||||
|
fn from(value: io::Error) -> Self {
|
||||||
|
DownloadManagerError::IOError(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src-tauri/src/error/drop_server_error.rs
Normal file
10
src-tauri/src/error/drop_server_error.rs
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DropServerError {
|
||||||
|
pub status_code: usize,
|
||||||
|
pub status_message: String,
|
||||||
|
// pub message: String,
|
||||||
|
// pub url: String,
|
||||||
|
}
|
||||||
18
src-tauri/src/error/library_error.rs
Normal file
18
src-tauri/src/error/library_error.rs
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
use std::fmt::Display;
|
||||||
|
|
||||||
|
use serde_with::SerializeDisplay;
|
||||||
|
|
||||||
|
#[derive(SerializeDisplay)]
|
||||||
|
pub enum LibraryError {
|
||||||
|
MetaNotFound(String),
|
||||||
|
}
|
||||||
|
impl Display for LibraryError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
LibraryError::MetaNotFound(id) => write!(
|
||||||
|
f,
|
||||||
|
"Could not locate any installed version of game ID {id} in the database"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
src-tauri/src/error/mod.rs
Normal file
6
src-tauri/src/error/mod.rs
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
pub mod application_download_error;
|
||||||
|
pub mod download_manager_error;
|
||||||
|
pub mod drop_server_error;
|
||||||
|
pub mod library_error;
|
||||||
|
pub mod process_error;
|
||||||
|
pub mod remote_access_error;
|
||||||
@ -11,9 +11,7 @@ pub enum ProcessError {
|
|||||||
IOError(Error),
|
IOError(Error),
|
||||||
FormatError(String), // String errors supremacy
|
FormatError(String), // String errors supremacy
|
||||||
InvalidPlatform,
|
InvalidPlatform,
|
||||||
OpenerError(tauri_plugin_opener::Error),
|
OpenerError(tauri_plugin_opener::Error)
|
||||||
InvalidArguments(String),
|
|
||||||
FailedLaunch(String),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for ProcessError {
|
impl Display for ProcessError {
|
||||||
@ -25,15 +23,9 @@ impl Display for ProcessError {
|
|||||||
ProcessError::InvalidVersion => "Invalid game version",
|
ProcessError::InvalidVersion => "Invalid game version",
|
||||||
ProcessError::IOError(error) => &error.to_string(),
|
ProcessError::IOError(error) => &error.to_string(),
|
||||||
ProcessError::InvalidPlatform => "This game cannot be played on the current platform",
|
ProcessError::InvalidPlatform => "This game cannot be played on the current platform",
|
||||||
ProcessError::FormatError(error) => &format!("Could not format template: {error:?}"),
|
ProcessError::FormatError(e) => &format!("Failed to format template: {e}"),
|
||||||
ProcessError::OpenerError(error) => &format!("Could not open directory: {error:?}"),
|
ProcessError::OpenerError(error) => &format!("Failed to open directory: {error}"),
|
||||||
ProcessError::InvalidArguments(arguments) => {
|
};
|
||||||
&format!("Invalid arguments in command {arguments}")
|
|
||||||
}
|
|
||||||
ProcessError::FailedLaunch(game_id) => {
|
|
||||||
&format!("Drop detected that the game {game_id} may have failed to launch properly")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
write!(f, "{s}")
|
write!(f, "{s}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -4,21 +4,11 @@ use std::{
|
|||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use http::{header::ToStrError, HeaderName, StatusCode};
|
use http::StatusCode;
|
||||||
use serde_with::SerializeDisplay;
|
use serde_with::SerializeDisplay;
|
||||||
use url::ParseError;
|
use url::ParseError;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use super::drop_server_error::DropServerError;
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct DropServerError {
|
|
||||||
pub status_code: usize,
|
|
||||||
pub status_message: String,
|
|
||||||
// pub message: String,
|
|
||||||
// pub url: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
#[derive(Debug, SerializeDisplay)]
|
||||||
pub enum RemoteAccessError {
|
pub enum RemoteAccessError {
|
||||||
@ -54,7 +44,8 @@ impl Display for RemoteAccessError {
|
|||||||
error
|
error
|
||||||
.source()
|
.source()
|
||||||
.map(std::string::ToString::to_string)
|
.map(std::string::ToString::to_string)
|
||||||
.unwrap_or("Unknown error".to_string())
|
.or_else(|| Some("Unknown error".to_string()))
|
||||||
|
.unwrap()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
RemoteAccessError::FetchErrorWS(error) => write!(
|
RemoteAccessError::FetchErrorWS(error) => write!(
|
||||||
@ -63,8 +54,9 @@ impl Display for RemoteAccessError {
|
|||||||
error,
|
error,
|
||||||
error
|
error
|
||||||
.source()
|
.source()
|
||||||
.map(std::string::ToString::to_string)
|
.map(|e| e.to_string())
|
||||||
.unwrap_or("Unknown error".to_string())
|
.or_else(|| Some("Unknown error".to_string()))
|
||||||
|
.unwrap()
|
||||||
),
|
),
|
||||||
RemoteAccessError::ParsingError(parse_error) => {
|
RemoteAccessError::ParsingError(parse_error) => {
|
||||||
write!(f, "{parse_error}")
|
write!(f, "{parse_error}")
|
||||||
@ -114,23 +106,3 @@ impl From<ParseError> for RemoteAccessError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::error::Error for RemoteAccessError {}
|
impl std::error::Error for RemoteAccessError {}
|
||||||
|
|
||||||
#[derive(Debug, SerializeDisplay)]
|
|
||||||
pub enum CacheError {
|
|
||||||
HeaderNotFound(HeaderName),
|
|
||||||
ParseError(ToStrError),
|
|
||||||
Remote(RemoteAccessError),
|
|
||||||
ConstructionError(http::Error)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for CacheError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
let s = match self {
|
|
||||||
CacheError::HeaderNotFound(header_name) => format!("Could not find header {header_name} in cache"),
|
|
||||||
CacheError::ParseError(to_str_error) => format!("Could not parse cache with error {to_str_error}"),
|
|
||||||
CacheError::Remote(remote_access_error) => format!("Cache got remote access error: {remote_access_error}"),
|
|
||||||
CacheError::ConstructionError(error) => format!("Could not construct cache body with error {error}"),
|
|
||||||
};
|
|
||||||
write!(f, "{s}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,293 +0,0 @@
|
|||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked, GameDownloadStatus, GameVersion};
|
|
||||||
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, Game}, state::{GameStatusManager, GameStatusWithTransient}};
|
|
||||||
use log::warn;
|
|
||||||
use process::PROCESS_MANAGER;
|
|
||||||
use remote::{auth::generate_authorization_header, cache::{cache_object, cache_object_db, get_cached_object, get_cached_object_db}, error::{DropServerError, RemoteAccessError}, offline, requests::generate_url, utils::DROP_CLIENT_ASYNC};
|
|
||||||
use tauri::AppHandle;
|
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn fetch_library(
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
hard_refresh: Option<bool>,
|
|
||||||
) -> Result<Vec<Game>, RemoteAccessError> {
|
|
||||||
offline!(
|
|
||||||
state,
|
|
||||||
fetch_library_logic,
|
|
||||||
fetch_library_logic_offline,
|
|
||||||
state,
|
|
||||||
hard_refresh
|
|
||||||
).await
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
pub async fn fetch_library_logic(
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
hard_fresh: Option<bool>,
|
|
||||||
) -> 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(
|
|
||||||
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
_hard_refresh: Option<bool>,
|
|
||||||
) -> Result<Vec<Game>, RemoteAccessError> {
|
|
||||||
let mut games: Vec<Game> = get_cached_object("library")?;
|
|
||||||
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
|
|
||||||
games.retain(|game| {
|
|
||||||
matches!(
|
|
||||||
&db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.get(game.id())
|
|
||||||
.unwrap_or(&GameDownloadStatus::Remote {}),
|
|
||||||
GameDownloadStatus::Installed { .. } | GameDownloadStatus::SetupRequired { .. }
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(games)
|
|
||||||
}
|
|
||||||
pub async fn fetch_game_logic(
|
|
||||||
id: String,
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
|
||||||
let version = {
|
|
||||||
let state_handle = lock!(state);
|
|
||||||
|
|
||||||
let db_lock = borrow_db_checked();
|
|
||||||
|
|
||||||
let metadata_option = db_lock.applications.installed_game_version.get(&id);
|
|
||||||
let version = match metadata_option {
|
|
||||||
None => None,
|
|
||||||
Some(metadata) => db_lock
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.get(&metadata.id)
|
|
||||||
.map(|v| v.get(metadata.version.as_ref().unwrap()).unwrap())
|
|
||||||
.cloned(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let game = state_handle.games.get(&id);
|
|
||||||
if let Some(game) = game {
|
|
||||||
let status = GameStatusManager::fetch_state(&id, &db_lock);
|
|
||||||
|
|
||||||
let data = FetchGameStruct::new(game.clone(), status, version);
|
|
||||||
|
|
||||||
cache_object_db(&id, game, &db_lock)?;
|
|
||||||
|
|
||||||
return Ok(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
version
|
|
||||||
};
|
|
||||||
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let response = generate_url(&["/api/v1/client/game/", &id], &[])?;
|
|
||||||
let response = client
|
|
||||||
.get(response)
|
|
||||||
.header("Authorization", generate_authorization_header())
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if response.status() == 404 {
|
|
||||||
let offline_fetch = fetch_game_logic_offline(id.clone(), state).await;
|
|
||||||
if let Ok(fetch_data) = offline_fetch {
|
|
||||||
return Ok(fetch_data);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Err(RemoteAccessError::GameNotFound(id));
|
|
||||||
}
|
|
||||||
if response.status() != 200 {
|
|
||||||
let err = response.json().await?;
|
|
||||||
warn!("{err:?}");
|
|
||||||
return Err(RemoteAccessError::InvalidResponse(err));
|
|
||||||
}
|
|
||||||
|
|
||||||
let game: Game = response.json().await?;
|
|
||||||
|
|
||||||
let mut state_handle = lock!(state);
|
|
||||||
state_handle.games.insert(id.clone(), game.clone());
|
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
|
||||||
|
|
||||||
db_handle
|
|
||||||
.applications
|
|
||||||
.game_statuses
|
|
||||||
.entry(id.clone())
|
|
||||||
.or_insert(GameDownloadStatus::Remote {});
|
|
||||||
|
|
||||||
let status = GameStatusManager::fetch_state(&id, &db_handle);
|
|
||||||
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
let data = FetchGameStruct::new(game.clone(), status, version);
|
|
||||||
|
|
||||||
cache_object(&id, &game)?;
|
|
||||||
|
|
||||||
Ok(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn fetch_game_version_options_logic(
|
|
||||||
game_id: String,
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
|
|
||||||
let response = generate_url(&["/api/v1/client/game/versions"], &[("id", &game_id)])?;
|
|
||||||
let response = client
|
|
||||||
.get(response)
|
|
||||||
.header("Authorization", generate_authorization_header())
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if response.status() != 200 {
|
|
||||||
let err = response.json().await?;
|
|
||||||
warn!("{err:?}");
|
|
||||||
return Err(RemoteAccessError::InvalidResponse(err));
|
|
||||||
}
|
|
||||||
|
|
||||||
let data: Vec<GameVersion> = response.json().await?;
|
|
||||||
|
|
||||||
let state_lock = lock!(state);
|
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
|
||||||
let data: Vec<GameVersion> = data
|
|
||||||
.into_iter()
|
|
||||||
.filter(|v| process_manager_lock.valid_platform(&v.platform))
|
|
||||||
.collect();
|
|
||||||
drop(process_manager_lock);
|
|
||||||
drop(state_lock);
|
|
||||||
|
|
||||||
Ok(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
pub async fn fetch_game_logic_offline(
|
|
||||||
id: String,
|
|
||||||
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
let metadata_option = db_handle.applications.installed_game_version.get(&id);
|
|
||||||
let version = match metadata_option {
|
|
||||||
None => None,
|
|
||||||
Some(metadata) => db_handle
|
|
||||||
.applications
|
|
||||||
.game_versions
|
|
||||||
.get(&metadata.id)
|
|
||||||
.map(|v| v.get(metadata.version.as_ref().unwrap()).unwrap())
|
|
||||||
.cloned(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let status = GameStatusManager::fetch_state(&id, &db_handle);
|
|
||||||
let game = get_cached_object::<Game>(&id)?;
|
|
||||||
|
|
||||||
drop(db_handle);
|
|
||||||
|
|
||||||
Ok(FetchGameStruct::new(game, status, version))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn fetch_game(
|
|
||||||
game_id: String,
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<FetchGameStruct, RemoteAccessError> {
|
|
||||||
offline!(
|
|
||||||
state,
|
|
||||||
fetch_game_logic,
|
|
||||||
fetch_game_logic_offline,
|
|
||||||
game_id,
|
|
||||||
state
|
|
||||||
).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn fetch_game_status(id: String) -> GameStatusWithTransient {
|
|
||||||
let db_handle = borrow_db_checked();
|
|
||||||
GameStatusManager::fetch_state(&id, &db_handle)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn uninstall_game(game_id: String, app_handle: AppHandle) -> Result<(), LibraryError> {
|
|
||||||
let meta = match get_current_meta(&game_id) {
|
|
||||||
Some(data) => data,
|
|
||||||
None => return Err(LibraryError::MetaNotFound(game_id)),
|
|
||||||
};
|
|
||||||
uninstall_game_logic(meta, &app_handle);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn fetch_game_version_options(
|
|
||||||
game_id: String,
|
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
|
||||||
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
|
||||||
fetch_game_version_options_logic(game_id, state).await
|
|
||||||
}
|
|
||||||
@ -1,7 +1,7 @@
|
|||||||
use bitcode::{Decode, Encode};
|
use bitcode::{Decode, Encode};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::library::Game;
|
use crate::games::library::Game;
|
||||||
|
|
||||||
pub type Collections = Vec<Collection>;
|
pub type Collections = Vec<Collection>;
|
||||||
|
|
||||||
@ -1 +1,2 @@
|
|||||||
pub mod collection;
|
pub mod collection;
|
||||||
|
pub mod commands;
|
||||||
78
src-tauri/src/games/commands.rs
Normal file
78
src-tauri/src/games/commands.rs
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use tauri::AppHandle;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
AppState,
|
||||||
|
database::{
|
||||||
|
db::borrow_db_checked,
|
||||||
|
models::data::GameVersion,
|
||||||
|
},
|
||||||
|
error::{library_error::LibraryError, remote_access_error::RemoteAccessError},
|
||||||
|
games::library::{
|
||||||
|
fetch_game_logic_offline, fetch_library_logic_offline, get_current_meta,
|
||||||
|
uninstall_game_logic,
|
||||||
|
},
|
||||||
|
offline,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
library::{
|
||||||
|
FetchGameStruct, Game, fetch_game_logic, fetch_game_version_options_logic,
|
||||||
|
fetch_library_logic,
|
||||||
|
},
|
||||||
|
state::{GameStatusManager, GameStatusWithTransient},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn fetch_library(
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
hard_refresh: Option<bool>,
|
||||||
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
|
offline!(
|
||||||
|
state,
|
||||||
|
fetch_library_logic,
|
||||||
|
fetch_library_logic_offline,
|
||||||
|
state,
|
||||||
|
hard_refresh
|
||||||
|
).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn fetch_game(
|
||||||
|
game_id: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
|
offline!(
|
||||||
|
state,
|
||||||
|
fetch_game_logic,
|
||||||
|
fetch_game_logic_offline,
|
||||||
|
game_id,
|
||||||
|
state
|
||||||
|
).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn fetch_game_status(id: String) -> GameStatusWithTransient {
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
GameStatusManager::fetch_state(&id, &db_handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn uninstall_game(game_id: String, app_handle: AppHandle) -> Result<(), LibraryError> {
|
||||||
|
let meta = match get_current_meta(&game_id) {
|
||||||
|
Some(data) => data,
|
||||||
|
None => return Err(LibraryError::MetaNotFound(game_id)),
|
||||||
|
};
|
||||||
|
uninstall_game_logic(meta, &app_handle);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn fetch_game_version_options(
|
||||||
|
game_id: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
||||||
|
fetch_game_version_options_logic(game_id, state).await
|
||||||
|
}
|
||||||
@ -5,10 +5,13 @@ use std::{
|
|||||||
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
AppState,
|
||||||
database::{
|
database::{
|
||||||
db::borrow_db_checked,
|
db::borrow_db_checked,
|
||||||
models::data::GameDownloadStatus,
|
models::data::GameDownloadStatus,
|
||||||
}, download_manager::downloadable::Downloadable, error::application_download_error::ApplicationDownloadError, lock, AppState
|
},
|
||||||
|
download_manager::downloadable::Downloadable,
|
||||||
|
error::application_download_error::ApplicationDownloadError,
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::download_agent::GameDownloadAgent;
|
use super::download_agent::GameDownloadAgent;
|
||||||
@ -20,14 +23,16 @@ pub async fn download_game(
|
|||||||
install_dir: usize,
|
install_dir: usize,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
) -> Result<(), ApplicationDownloadError> {
|
) -> Result<(), ApplicationDownloadError> {
|
||||||
let sender = { lock!(state).download_manager.get_sender().clone() };
|
let sender = { state.lock().unwrap().download_manager.get_sender().clone() };
|
||||||
|
|
||||||
let game_download_agent =
|
let game_download_agent =
|
||||||
GameDownloadAgent::new_from_index(game_id.clone(), game_version.clone(), install_dir, sender).await?;
|
GameDownloadAgent::new_from_index(game_id.clone(), game_version.clone(), install_dir, sender).await?;
|
||||||
|
|
||||||
let game_download_agent =
|
let game_download_agent =
|
||||||
Arc::new(Box::new(game_download_agent) as Box<dyn Downloadable + Send + Sync>);
|
Arc::new(Box::new(game_download_agent) as Box<dyn Downloadable + Send + Sync>);
|
||||||
lock!(state)
|
state
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.download_manager
|
.download_manager
|
||||||
.queue_download(game_download_agent.clone())
|
.queue_download(game_download_agent.clone())
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@ -57,20 +62,22 @@ pub async fn resume_download(
|
|||||||
} => (version_name, install_dir),
|
} => (version_name, install_dir),
|
||||||
};
|
};
|
||||||
|
|
||||||
let sender = lock!(state).download_manager.get_sender();
|
let sender = state.lock().unwrap().download_manager.get_sender();
|
||||||
let parent_dir: PathBuf = install_dir.into();
|
let parent_dir: PathBuf = install_dir.into();
|
||||||
|
|
||||||
let game_download_agent = Arc::new(Box::new(
|
let game_download_agent = Arc::new(Box::new(
|
||||||
GameDownloadAgent::new(
|
GameDownloadAgent::new(
|
||||||
game_id,
|
game_id,
|
||||||
version_name.clone(),
|
version_name.clone(),
|
||||||
parent_dir.parent().unwrap_or_else(|| panic!("Failed to get parent directry of {}", parent_dir.display())).to_path_buf(),
|
parent_dir.parent().unwrap().to_path_buf(),
|
||||||
sender,
|
sender,
|
||||||
)
|
)
|
||||||
.await?,
|
.await?,
|
||||||
) as Box<dyn Downloadable + Send + Sync>);
|
) as Box<dyn Downloadable + Send + Sync>);
|
||||||
|
|
||||||
lock!(state)
|
state
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.download_manager
|
.download_manager
|
||||||
.queue_download(game_download_agent)
|
.queue_download(game_download_agent)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@ -1,19 +1,29 @@
|
|||||||
use database::{borrow_db_checked, borrow_db_mut_checked, ApplicationTransientStatus, DownloadType, DownloadableMetadata};
|
use crate::auth::generate_authorization_header;
|
||||||
use download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
|
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
use download_manager::downloadable::Downloadable;
|
use crate::database::models::data::{
|
||||||
use download_manager::error::ApplicationDownloadError;
|
ApplicationTransientStatus, DownloadType, DownloadableMetadata,
|
||||||
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
};
|
||||||
use download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
use crate::download_manager::download_manager_frontend::{DownloadManagerSignal, DownloadStatus};
|
||||||
|
use crate::download_manager::downloadable::Downloadable;
|
||||||
|
use crate::download_manager::util::download_thread_control_flag::{
|
||||||
|
DownloadThreadControl, DownloadThreadControlFlag,
|
||||||
|
};
|
||||||
|
use crate::download_manager::util::progress_object::{ProgressHandle, ProgressObject};
|
||||||
|
use crate::error::application_download_error::ApplicationDownloadError;
|
||||||
|
use crate::error::remote_access_error::RemoteAccessError;
|
||||||
|
use crate::games::downloads::manifest::{
|
||||||
|
DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody,
|
||||||
|
};
|
||||||
|
use crate::games::downloads::validate::validate_game_chunk;
|
||||||
|
use crate::games::library::{on_game_complete, push_game_update, set_partially_installed};
|
||||||
|
use crate::games::state::GameStatusManager;
|
||||||
|
use crate::process::utils::get_disk_available;
|
||||||
|
use crate::remote::requests::generate_url;
|
||||||
|
use crate::remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
|
||||||
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::error::RemoteAccessError;
|
|
||||||
use remote::requests::generate_url;
|
|
||||||
use remote::utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC};
|
|
||||||
use utils::{app_emit, lock, send};
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::fs::{OpenOptions, create_dir_all};
|
use std::fs::{OpenOptions, create_dir_all};
|
||||||
use std::io;
|
|
||||||
use std::path::{Path, PathBuf};
|
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};
|
||||||
@ -23,12 +33,6 @@ use tauri::{AppHandle, Emitter};
|
|||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
use rustix::fs::{FallocateFlags, fallocate};
|
use rustix::fs::{FallocateFlags, fallocate};
|
||||||
|
|
||||||
use crate::downloads::manifest::{DownloadBucket, DownloadContext, DownloadDrop, DropManifest, DropValidateContext, ManifestBody};
|
|
||||||
use crate::downloads::utils::get_disk_available;
|
|
||||||
use crate::downloads::validate::validate_game_chunk;
|
|
||||||
use crate::library::{on_game_complete, push_game_update, set_partially_installed};
|
|
||||||
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;
|
||||||
|
|
||||||
@ -97,8 +101,10 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
result.ensure_manifest_exists().await?;
|
result.ensure_manifest_exists().await?;
|
||||||
|
|
||||||
let required_space = lock!(result
|
let required_space = result
|
||||||
.manifest)
|
.manifest
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.values()
|
.values()
|
||||||
@ -166,11 +172,11 @@ impl GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_manifest_exists(&self) -> bool {
|
pub fn check_manifest_exists(&self) -> bool {
|
||||||
lock!(self.manifest).is_some()
|
self.manifest.lock().unwrap().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn ensure_manifest_exists(&self) -> Result<(), ApplicationDownloadError> {
|
pub async fn ensure_manifest_exists(&self) -> Result<(), ApplicationDownloadError> {
|
||||||
if lock!(self.manifest).is_some() {
|
if self.manifest.lock().unwrap().is_some() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -201,10 +207,7 @@ impl GameDownloadAgent {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let manifest_download: DropManifest = response
|
let manifest_download: DropManifest = response.json().await.unwrap();
|
||||||
.json()
|
|
||||||
.await
|
|
||||||
.map_err(|e| ApplicationDownloadError::Communication(e.into()))?;
|
|
||||||
|
|
||||||
if let Ok(mut manifest) = self.manifest.lock() {
|
if let Ok(mut manifest) = self.manifest.lock() {
|
||||||
*manifest = Some(manifest_download);
|
*manifest = Some(manifest_download);
|
||||||
@ -216,7 +219,7 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
// Sets it up for both download and validate
|
// Sets it up for both download and validate
|
||||||
fn setup_progress(&self) {
|
fn setup_progress(&self) {
|
||||||
let buckets = lock!(self.buckets);
|
let buckets = self.buckets.lock().unwrap();
|
||||||
|
|
||||||
let chunk_count = buckets.iter().map(|e| e.drops.len()).sum();
|
let chunk_count = buckets.iter().map(|e| e.drops.len()).sum();
|
||||||
|
|
||||||
@ -231,23 +234,21 @@ impl GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn ensure_buckets(&self) -> Result<(), ApplicationDownloadError> {
|
pub fn ensure_buckets(&self) -> Result<(), ApplicationDownloadError> {
|
||||||
if lock!(self.buckets).is_empty() {
|
if self.buckets.lock().unwrap().is_empty() {
|
||||||
self.generate_buckets()?;
|
self.generate_buckets()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
*lock!(self.context_map) = self.dropdata.get_contexts();
|
*self.context_map.lock().unwrap() = self.dropdata.get_contexts();
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn generate_buckets(&self) -> Result<(), ApplicationDownloadError> {
|
pub fn generate_buckets(&self) -> Result<(), ApplicationDownloadError> {
|
||||||
let manifest = lock!(self.manifest)
|
let manifest = self.manifest.lock().unwrap().clone().unwrap();
|
||||||
.clone()
|
|
||||||
.ok_or(ApplicationDownloadError::NotInitialized)?;
|
|
||||||
let game_id = self.id.clone();
|
let game_id = self.id.clone();
|
||||||
|
|
||||||
let base_path = Path::new(&self.dropdata.base_path);
|
let base_path = Path::new(&self.dropdata.base_path);
|
||||||
create_dir_all(base_path)?;
|
create_dir_all(base_path).unwrap();
|
||||||
|
|
||||||
let mut buckets = Vec::new();
|
let mut buckets = Vec::new();
|
||||||
|
|
||||||
@ -257,13 +258,8 @@ impl GameDownloadAgent {
|
|||||||
for (raw_path, chunk) in manifest {
|
for (raw_path, chunk) in manifest {
|
||||||
let path = base_path.join(Path::new(&raw_path));
|
let path = base_path.join(Path::new(&raw_path));
|
||||||
|
|
||||||
let container = path
|
let container = path.parent().unwrap();
|
||||||
.parent()
|
create_dir_all(container).unwrap();
|
||||||
.ok_or(ApplicationDownloadError::IoError(Arc::new(io::Error::new(
|
|
||||||
io::ErrorKind::NotFound,
|
|
||||||
"no parent directory",
|
|
||||||
))))?;
|
|
||||||
create_dir_all(container)?;
|
|
||||||
|
|
||||||
let already_exists = path.exists();
|
let already_exists = path.exists();
|
||||||
let file = OpenOptions::new()
|
let file = OpenOptions::new()
|
||||||
@ -271,7 +267,8 @@ impl GameDownloadAgent {
|
|||||||
.write(true)
|
.write(true)
|
||||||
.create(true)
|
.create(true)
|
||||||
.truncate(false)
|
.truncate(false)
|
||||||
.open(&path)?;
|
.open(path.clone())
|
||||||
|
.unwrap();
|
||||||
let mut file_running_offset = 0;
|
let mut file_running_offset = 0;
|
||||||
|
|
||||||
for (index, length) in chunk.lengths.iter().enumerate() {
|
for (index, length) in chunk.lengths.iter().enumerate() {
|
||||||
@ -355,7 +352,7 @@ impl GameDownloadAgent {
|
|||||||
.collect::<Vec<(String, bool)>>(),
|
.collect::<Vec<(String, bool)>>(),
|
||||||
);
|
);
|
||||||
|
|
||||||
*lock!(self.buckets) = buckets;
|
*self.buckets.lock().unwrap() = buckets;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -371,11 +368,9 @@ impl GameDownloadAgent {
|
|||||||
let pool = ThreadPoolBuilder::new()
|
let pool = ThreadPoolBuilder::new()
|
||||||
.num_threads(max_download_threads)
|
.num_threads(max_download_threads)
|
||||||
.build()
|
.build()
|
||||||
.unwrap_or_else(|_| {
|
.unwrap();
|
||||||
panic!("failed to build thread pool with {max_download_threads} threads")
|
|
||||||
});
|
|
||||||
|
|
||||||
let buckets = lock!(self.buckets);
|
let buckets = self.buckets.lock().unwrap();
|
||||||
|
|
||||||
let mut download_contexts = HashMap::<String, DownloadContext>::new();
|
let mut download_contexts = HashMap::<String, DownloadContext>::new();
|
||||||
|
|
||||||
@ -394,7 +389,7 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
for version in versions {
|
for version in versions {
|
||||||
let download_context = DROP_CLIENT_SYNC
|
let download_context = DROP_CLIENT_SYNC
|
||||||
.post(generate_url(&["/api/v2/client/context"], &[])?)
|
.post(generate_url(&["/api/v2/client/context"], &[]).unwrap())
|
||||||
.json(&ManifestBody {
|
.json(&ManifestBody {
|
||||||
game: self.id.clone(),
|
game: self.id.clone(),
|
||||||
version: version.clone(),
|
version: version.clone(),
|
||||||
@ -417,7 +412,7 @@ impl GameDownloadAgent {
|
|||||||
let download_contexts = &download_contexts;
|
let download_contexts = &download_contexts;
|
||||||
|
|
||||||
pool.scope(|scope| {
|
pool.scope(|scope| {
|
||||||
let context_map = lock!(self.context_map);
|
let context_map = self.context_map.lock().unwrap();
|
||||||
for (index, bucket) in buckets.iter().enumerate() {
|
for (index, bucket) in buckets.iter().enumerate() {
|
||||||
let mut bucket = (*bucket).clone();
|
let mut bucket = (*bucket).clone();
|
||||||
let completed_contexts = completed_indexes_loop_arc.clone();
|
let completed_contexts = completed_indexes_loop_arc.clone();
|
||||||
@ -449,7 +444,8 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
let download_context = download_contexts
|
let download_context = download_contexts
|
||||||
.get(&bucket.version)
|
.get(&bucket.version)
|
||||||
.unwrap_or_else(|| panic!("Could not get bucket version {}. Corrupted state.", bucket.version));
|
.ok_or(RemoteAccessError::CorruptedState)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
scope.spawn(move |_| {
|
scope.spawn(move |_| {
|
||||||
// 3 attempts
|
// 3 attempts
|
||||||
@ -481,7 +477,7 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
if i == RETRY_COUNT - 1 || !retry {
|
if i == RETRY_COUNT - 1 || !retry {
|
||||||
warn!("retry logic failed, not re-attempting.");
|
warn!("retry logic failed, not re-attempting.");
|
||||||
send!(sender, DownloadManagerSignal::Error(e));
|
sender.send(DownloadManagerSignal::Error(e)).unwrap();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -494,7 +490,7 @@ impl GameDownloadAgent {
|
|||||||
let newly_completed = completed_contexts.clone();
|
let newly_completed = completed_contexts.clone();
|
||||||
|
|
||||||
let completed_lock_len = {
|
let completed_lock_len = {
|
||||||
let mut context_map_lock = lock!(self.context_map);
|
let mut context_map_lock = self.context_map.lock().unwrap();
|
||||||
for (_, item) in newly_completed.iter() {
|
for (_, item) in newly_completed.iter() {
|
||||||
context_map_lock.insert(item.clone(), true);
|
context_map_lock.insert(item.clone(), true);
|
||||||
}
|
}
|
||||||
@ -502,7 +498,7 @@ impl GameDownloadAgent {
|
|||||||
context_map_lock.values().filter(|x| **x).count()
|
context_map_lock.values().filter(|x| **x).count()
|
||||||
};
|
};
|
||||||
|
|
||||||
let context_map_lock = lock!(self.context_map);
|
let context_map_lock = self.context_map.lock().unwrap();
|
||||||
let contexts = buckets
|
let contexts = buckets
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|x| x.drops.iter().map(|e| e.checksum.clone()))
|
.flat_map(|x| x.drops.iter().map(|e| e.checksum.clone()))
|
||||||
@ -551,7 +547,7 @@ impl GameDownloadAgent {
|
|||||||
pub fn validate(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
pub fn validate(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
||||||
self.setup_validate(app_handle);
|
self.setup_validate(app_handle);
|
||||||
|
|
||||||
let buckets = lock!(self.buckets);
|
let buckets = self.buckets.lock().unwrap();
|
||||||
let contexts: Vec<DropValidateContext> = buckets
|
let contexts: Vec<DropValidateContext> = buckets
|
||||||
.clone()
|
.clone()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@ -563,9 +559,7 @@ impl GameDownloadAgent {
|
|||||||
let pool = ThreadPoolBuilder::new()
|
let pool = ThreadPoolBuilder::new()
|
||||||
.num_threads(max_download_threads)
|
.num_threads(max_download_threads)
|
||||||
.build()
|
.build()
|
||||||
.unwrap_or_else(|_| {
|
.unwrap();
|
||||||
panic!("failed to build thread pool with {max_download_threads} threads")
|
|
||||||
});
|
|
||||||
|
|
||||||
let invalid_chunks = Arc::new(boxcar::Vec::new());
|
let invalid_chunks = Arc::new(boxcar::Vec::new());
|
||||||
pool.scope(|scope| {
|
pool.scope(|scope| {
|
||||||
@ -583,7 +577,7 @@ impl GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("{e}");
|
error!("{e}");
|
||||||
send!(sender, DownloadManagerSignal::Error(e));
|
sender.send(DownloadManagerSignal::Error(e)).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -610,7 +604,7 @@ impl GameDownloadAgent {
|
|||||||
// See docs on usage
|
// See docs on usage
|
||||||
set_partially_installed(
|
set_partially_installed(
|
||||||
&self.metadata(),
|
&self.metadata(),
|
||||||
self.dropdata.base_path.display().to_string(),
|
self.dropdata.base_path.to_str().unwrap().to_string(),
|
||||||
Some(app_handle),
|
Some(app_handle),
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -620,12 +614,12 @@ impl GameDownloadAgent {
|
|||||||
|
|
||||||
impl Downloadable for GameDownloadAgent {
|
impl Downloadable for GameDownloadAgent {
|
||||||
fn download(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
fn download(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
||||||
*lock!(self.status) = DownloadStatus::Downloading;
|
*self.status.lock().unwrap() = DownloadStatus::Downloading;
|
||||||
self.download(app_handle)
|
self.download(app_handle)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
fn validate(&self, app_handle: &AppHandle) -> Result<bool, ApplicationDownloadError> {
|
||||||
*lock!(self.status) = DownloadStatus::Validating;
|
*self.status.lock().unwrap() = DownloadStatus::Validating;
|
||||||
self.validate(app_handle)
|
self.validate(app_handle)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -659,8 +653,10 @@ impl Downloadable for GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn on_error(&self, app_handle: &tauri::AppHandle, error: &ApplicationDownloadError) {
|
fn on_error(&self, app_handle: &tauri::AppHandle, error: &ApplicationDownloadError) {
|
||||||
*lock!(self.status) = DownloadStatus::Error;
|
*self.status.lock().unwrap() = DownloadStatus::Error;
|
||||||
app_emit!(app_handle, "download_error", error.to_string());
|
app_handle
|
||||||
|
.emit("download_error", error.to_string())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
error!("error while managing download: {error:?}");
|
error!("error while managing download: {error:?}");
|
||||||
|
|
||||||
@ -679,17 +675,12 @@ impl Downloadable for GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn on_complete(&self, app_handle: &tauri::AppHandle) {
|
fn on_complete(&self, app_handle: &tauri::AppHandle) {
|
||||||
match on_game_complete(
|
on_game_complete(
|
||||||
&self.metadata(),
|
&self.metadata(),
|
||||||
self.dropdata.base_path.to_string_lossy().to_string(),
|
self.dropdata.base_path.to_string_lossy().to_string(),
|
||||||
app_handle,
|
app_handle,
|
||||||
) {
|
)
|
||||||
Ok(_) => {}
|
.unwrap();
|
||||||
Err(e) => {
|
|
||||||
error!("could not mark game as complete: {e}");
|
|
||||||
send!(self.sender, DownloadManagerSignal::Error(ApplicationDownloadError::DownloadError(e)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_cancelled(&self, app_handle: &tauri::AppHandle) {
|
fn on_cancelled(&self, app_handle: &tauri::AppHandle) {
|
||||||
@ -698,6 +689,6 @@ impl Downloadable for GameDownloadAgent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn status(&self) -> DownloadStatus {
|
fn status(&self) -> DownloadStatus {
|
||||||
lock!(self.status).clone()
|
self.status.lock().unwrap().clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,3 +1,18 @@
|
|||||||
|
use crate::download_manager::util::download_thread_control_flag::{
|
||||||
|
DownloadThreadControl, DownloadThreadControlFlag,
|
||||||
|
};
|
||||||
|
use crate::download_manager::util::progress_object::ProgressHandle;
|
||||||
|
use crate::error::application_download_error::ApplicationDownloadError;
|
||||||
|
use crate::error::drop_server_error::DropServerError;
|
||||||
|
use crate::error::remote_access_error::RemoteAccessError;
|
||||||
|
use crate::games::downloads::manifest::{ChunkBody, DownloadBucket, DownloadContext, DownloadDrop};
|
||||||
|
use crate::remote::auth::generate_authorization_header;
|
||||||
|
use crate::remote::requests::generate_url;
|
||||||
|
use crate::remote::utils::DROP_CLIENT_SYNC;
|
||||||
|
use log::{debug, info, warn};
|
||||||
|
use md5::{Context, Digest};
|
||||||
|
use reqwest::blocking::Response;
|
||||||
|
|
||||||
use std::fs::{Permissions, set_permissions};
|
use std::fs::{Permissions, set_permissions};
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@ -10,19 +25,6 @@ use std::{
|
|||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
};
|
};
|
||||||
|
|
||||||
use download_manager::error::ApplicationDownloadError;
|
|
||||||
use download_manager::util::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
|
|
||||||
use download_manager::util::progress_object::ProgressHandle;
|
|
||||||
use log::{debug, info, warn};
|
|
||||||
use md5::{Context, Digest};
|
|
||||||
use remote::auth::generate_authorization_header;
|
|
||||||
use remote::error::{DropServerError, RemoteAccessError};
|
|
||||||
use remote::requests::generate_url;
|
|
||||||
use remote::utils::DROP_CLIENT_SYNC;
|
|
||||||
use reqwest::blocking::Response;
|
|
||||||
|
|
||||||
use crate::downloads::manifest::{ChunkBody, DownloadBucket, DownloadContext, DownloadDrop};
|
|
||||||
|
|
||||||
static MAX_PACKET_LENGTH: usize = 4096 * 4;
|
static MAX_PACKET_LENGTH: usize = 4096 * 4;
|
||||||
static BUMP_SIZE: usize = 4096 * 16;
|
static BUMP_SIZE: usize = 4096 * 16;
|
||||||
|
|
||||||
@ -108,10 +110,11 @@ impl<'a> DropDownloadPipeline<'a, Response, File> {
|
|||||||
let destination = self
|
let destination = self
|
||||||
.destination
|
.destination
|
||||||
.get_mut(index)
|
.get_mut(index)
|
||||||
.ok_or(io::Error::other("no destination"))?;
|
.ok_or(io::Error::other("no destination"))
|
||||||
|
.unwrap();
|
||||||
let mut remaining = drop.length;
|
let mut remaining = drop.length;
|
||||||
if drop.start != 0 {
|
if drop.start != 0 {
|
||||||
destination.seek(SeekFrom::Start(drop.start as u64))?;
|
destination.seek(SeekFrom::Start(drop.start.try_into().unwrap()))?;
|
||||||
}
|
}
|
||||||
let mut last_bump = 0;
|
let mut last_bump = 0;
|
||||||
loop {
|
loop {
|
||||||
@ -212,39 +215,20 @@ pub fn download_game_bucket(
|
|||||||
RemoteAccessError::UnparseableResponse("missing Content-Lengths header".to_owned()),
|
RemoteAccessError::UnparseableResponse("missing Content-Lengths header".to_owned()),
|
||||||
))?
|
))?
|
||||||
.to_str()
|
.to_str()
|
||||||
.map_err(|e| {
|
.unwrap();
|
||||||
ApplicationDownloadError::Communication(RemoteAccessError::UnparseableResponse(
|
|
||||||
e.to_string(),
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
for (i, raw_length) in lengths.split(",").enumerate() {
|
for (i, raw_length) in lengths.split(",").enumerate() {
|
||||||
let length = raw_length.parse::<usize>().unwrap_or(0);
|
let length = raw_length.parse::<usize>().unwrap_or(0);
|
||||||
let Some(drop) = bucket.drops.get(i) else {
|
let Some(drop) = bucket.drops.get(i) else {
|
||||||
warn!("invalid number of Content-Lengths recieved: {i}, {lengths}");
|
warn!("invalid number of Content-Lengths recieved: {i}, {lengths}");
|
||||||
return Err(ApplicationDownloadError::DownloadError(
|
return Err(ApplicationDownloadError::DownloadError);
|
||||||
RemoteAccessError::InvalidResponse(DropServerError {
|
|
||||||
status_code: 400,
|
|
||||||
status_message: format!(
|
|
||||||
"invalid number of Content-Lengths recieved: {i}, {lengths}"
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
));
|
|
||||||
};
|
};
|
||||||
if drop.length != length {
|
if drop.length != length {
|
||||||
warn!(
|
warn!(
|
||||||
"for {}, expected {}, got {} ({})",
|
"for {}, expected {}, got {} ({})",
|
||||||
drop.filename, drop.length, raw_length, length
|
drop.filename, drop.length, raw_length, length
|
||||||
);
|
);
|
||||||
return Err(ApplicationDownloadError::DownloadError(
|
return Err(ApplicationDownloadError::DownloadError);
|
||||||
RemoteAccessError::InvalidResponse(DropServerError {
|
|
||||||
status_code: 400,
|
|
||||||
status_message: format!(
|
|
||||||
"for {}, expected {}, got {} ({})",
|
|
||||||
drop.filename, drop.length, raw_length, length
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -4,7 +4,6 @@ use std::{
|
|||||||
|
|
||||||
use log::error;
|
use log::error;
|
||||||
use native_model::{Decode, Encode};
|
use native_model::{Decode, Encode};
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
pub type DropData = v1::DropData;
|
pub type DropData = v1::DropData;
|
||||||
|
|
||||||
@ -50,12 +49,7 @@ impl DropData {
|
|||||||
let mut s = Vec::new();
|
let mut s = Vec::new();
|
||||||
file.read_to_end(&mut s)?;
|
file.read_to_end(&mut s)?;
|
||||||
|
|
||||||
native_model::rmp_serde_1_3::RmpSerde::decode(s).map_err(|e| {
|
Ok(native_model::rmp_serde_1_3::RmpSerde::decode(s).unwrap())
|
||||||
io::Error::new(
|
|
||||||
io::ErrorKind::InvalidData,
|
|
||||||
format!("Failed to decode drop data: {e}"),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
pub fn write(&self) {
|
pub fn write(&self) {
|
||||||
let manifest_raw = match native_model::rmp_serde_1_3::RmpSerde::encode(&self) {
|
let manifest_raw = match native_model::rmp_serde_1_3::RmpSerde::encode(&self) {
|
||||||
@ -77,12 +71,12 @@ impl DropData {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
|
pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) {
|
||||||
*lock!(self.contexts) = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
|
*self.contexts.lock().unwrap() = completed_contexts.iter().map(|s| (s.0.clone(), s.1)).collect();
|
||||||
}
|
}
|
||||||
pub fn set_context(&self, context: String, state: bool) {
|
pub fn set_context(&self, context: String, state: bool) {
|
||||||
lock!(self.contexts).entry(context).insert_entry(state);
|
self.contexts.lock().unwrap().entry(context).insert_entry(state);
|
||||||
}
|
}
|
||||||
pub fn get_contexts(&self) -> HashMap<String, bool> {
|
pub fn get_contexts(&self) -> HashMap<String, bool> {
|
||||||
lock!(self.contexts).clone()
|
self.contexts.lock().unwrap().clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,7 +1,6 @@
|
|||||||
|
pub mod commands;
|
||||||
pub mod download_agent;
|
pub mod download_agent;
|
||||||
mod download_logic;
|
mod download_logic;
|
||||||
pub mod drop_data;
|
pub mod drop_data;
|
||||||
pub mod error;
|
|
||||||
mod manifest;
|
mod manifest;
|
||||||
pub mod validate;
|
pub mod validate;
|
||||||
pub mod utils;
|
|
||||||
@ -3,11 +3,17 @@ use std::{
|
|||||||
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
io::{self, BufWriter, Read, Seek, SeekFrom, Write},
|
||||||
};
|
};
|
||||||
|
|
||||||
use download_manager::{error::ApplicationDownloadError, util::{download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::ProgressHandle}};
|
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use md5::Context;
|
use md5::Context;
|
||||||
|
|
||||||
use crate::downloads::manifest::DropValidateContext;
|
use crate::{
|
||||||
|
download_manager::util::{
|
||||||
|
download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag},
|
||||||
|
progress_object::ProgressHandle,
|
||||||
|
},
|
||||||
|
error::application_download_error::ApplicationDownloadError,
|
||||||
|
games::downloads::manifest::DropValidateContext,
|
||||||
|
};
|
||||||
|
|
||||||
pub fn validate_game_chunk(
|
pub fn validate_game_chunk(
|
||||||
ctx: &DropValidateContext,
|
ctx: &DropValidateContext,
|
||||||
@ -30,14 +36,14 @@ pub fn validate_game_chunk(
|
|||||||
|
|
||||||
if ctx.offset != 0 {
|
if ctx.offset != 0 {
|
||||||
source
|
source
|
||||||
.seek(SeekFrom::Start(ctx.offset as u64))
|
.seek(SeekFrom::Start(ctx.offset.try_into().unwrap()))
|
||||||
.expect("Failed to seek to file offset");
|
.expect("Failed to seek to file offset");
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut hasher = md5::Context::new();
|
let mut hasher = md5::Context::new();
|
||||||
|
|
||||||
let completed =
|
let completed =
|
||||||
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress)?;
|
validate_copy(&mut source, &mut hasher, ctx.length, control_flag, progress).unwrap();
|
||||||
if !completed {
|
if !completed {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
591
src-tauri/src/games/library.rs
Normal file
591
src-tauri/src/games/library.rs
Normal file
@ -0,0 +1,591 @@
|
|||||||
|
use std::fs::remove_dir_all;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::thread::spawn;
|
||||||
|
|
||||||
|
use log::{debug, error, warn};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tauri::AppHandle;
|
||||||
|
use tauri::Emitter;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::database::db::{borrow_db_checked, borrow_db_mut_checked};
|
||||||
|
use crate::database::models::data::Database;
|
||||||
|
use crate::database::models::data::{
|
||||||
|
ApplicationTransientStatus, DownloadableMetadata, GameDownloadStatus, GameVersion,
|
||||||
|
};
|
||||||
|
use crate::download_manager::download_manager_frontend::DownloadStatus;
|
||||||
|
use crate::error::drop_server_error::DropServerError;
|
||||||
|
use crate::error::library_error::LibraryError;
|
||||||
|
use crate::error::remote_access_error::RemoteAccessError;
|
||||||
|
use crate::games::state::{GameStatusManager, GameStatusWithTransient};
|
||||||
|
use crate::remote::auth::generate_authorization_header;
|
||||||
|
use crate::remote::cache::cache_object_db;
|
||||||
|
use crate::remote::cache::{cache_object, get_cached_object, get_cached_object_db};
|
||||||
|
use crate::remote::requests::generate_url;
|
||||||
|
use crate::remote::utils::DROP_CLIENT_ASYNC;
|
||||||
|
use crate::remote::utils::DROP_CLIENT_SYNC;
|
||||||
|
use bitcode::{Decode, Encode};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
pub struct FetchGameStruct {
|
||||||
|
game: Game,
|
||||||
|
status: GameStatusWithTransient,
|
||||||
|
version: Option<GameVersion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>,
|
||||||
|
}
|
||||||
|
#[derive(serde::Serialize, Clone)]
|
||||||
|
pub struct GameUpdateEvent {
|
||||||
|
pub game_id: String,
|
||||||
|
pub status: (
|
||||||
|
Option<GameDownloadStatus>,
|
||||||
|
Option<ApplicationTransientStatus>,
|
||||||
|
),
|
||||||
|
pub version: Option<GameVersion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone)]
|
||||||
|
pub struct QueueUpdateEventQueueData {
|
||||||
|
pub meta: DownloadableMetadata,
|
||||||
|
pub status: DownloadStatus,
|
||||||
|
pub progress: f64,
|
||||||
|
pub current: usize,
|
||||||
|
pub max: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, Clone)]
|
||||||
|
pub struct QueueUpdateEvent {
|
||||||
|
pub queue: Vec<QueueUpdateEventQueueData>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, Clone)]
|
||||||
|
pub struct StatsUpdateEvent {
|
||||||
|
pub speed: usize,
|
||||||
|
pub time: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_library_logic(
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
hard_fresh: Option<bool>,
|
||||||
|
) -> 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 = state.lock().unwrap();
|
||||||
|
|
||||||
|
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(
|
||||||
|
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
_hard_refresh: Option<bool>,
|
||||||
|
) -> Result<Vec<Game>, RemoteAccessError> {
|
||||||
|
let mut games: Vec<Game> = get_cached_object("library")?;
|
||||||
|
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
|
||||||
|
games.retain(|game| {
|
||||||
|
matches!(
|
||||||
|
&db_handle
|
||||||
|
.applications
|
||||||
|
.game_statuses
|
||||||
|
.get(&game.id)
|
||||||
|
.unwrap_or(&GameDownloadStatus::Remote {}),
|
||||||
|
GameDownloadStatus::Installed { .. } | GameDownloadStatus::SetupRequired { .. }
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(games)
|
||||||
|
}
|
||||||
|
pub async fn fetch_game_logic(
|
||||||
|
id: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
|
let version = {
|
||||||
|
let state_handle = state.lock().unwrap();
|
||||||
|
|
||||||
|
let db_lock = borrow_db_checked();
|
||||||
|
|
||||||
|
let metadata_option = db_lock.applications.installed_game_version.get(&id);
|
||||||
|
let version = match metadata_option {
|
||||||
|
None => None,
|
||||||
|
Some(metadata) => db_lock
|
||||||
|
.applications
|
||||||
|
.game_versions
|
||||||
|
.get(&metadata.id)
|
||||||
|
.map(|v| v.get(metadata.version.as_ref().unwrap()).unwrap())
|
||||||
|
.cloned(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let game = state_handle.games.get(&id);
|
||||||
|
if let Some(game) = game {
|
||||||
|
let status = GameStatusManager::fetch_state(&id, &db_lock);
|
||||||
|
|
||||||
|
let data = FetchGameStruct {
|
||||||
|
game: game.clone(),
|
||||||
|
status,
|
||||||
|
version,
|
||||||
|
};
|
||||||
|
|
||||||
|
cache_object_db(&id, game, &db_lock)?;
|
||||||
|
|
||||||
|
return Ok(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
version
|
||||||
|
};
|
||||||
|
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
let response = generate_url(&["/api/v1/client/game/", &id], &[])?;
|
||||||
|
let response = client
|
||||||
|
.get(response)
|
||||||
|
.header("Authorization", generate_authorization_header())
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if response.status() == 404 {
|
||||||
|
let offline_fetch = fetch_game_logic_offline(id.clone(), state).await;
|
||||||
|
if let Ok(fetch_data) = offline_fetch {
|
||||||
|
return Ok(fetch_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Err(RemoteAccessError::GameNotFound(id));
|
||||||
|
}
|
||||||
|
if response.status() != 200 {
|
||||||
|
let err = response.json().await.unwrap();
|
||||||
|
warn!("{err:?}");
|
||||||
|
return Err(RemoteAccessError::InvalidResponse(err));
|
||||||
|
}
|
||||||
|
|
||||||
|
let game: Game = response.json().await?;
|
||||||
|
|
||||||
|
let mut state_handle = state.lock().unwrap();
|
||||||
|
state_handle.games.insert(id.clone(), game.clone());
|
||||||
|
|
||||||
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.game_statuses
|
||||||
|
.entry(id.clone())
|
||||||
|
.or_insert(GameDownloadStatus::Remote {});
|
||||||
|
|
||||||
|
let status = GameStatusManager::fetch_state(&id, &db_handle);
|
||||||
|
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
let data = FetchGameStruct {
|
||||||
|
game: game.clone(),
|
||||||
|
status,
|
||||||
|
version,
|
||||||
|
};
|
||||||
|
|
||||||
|
cache_object(&id, &game)?;
|
||||||
|
|
||||||
|
Ok(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_game_logic_offline(
|
||||||
|
id: String,
|
||||||
|
_state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<FetchGameStruct, RemoteAccessError> {
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
let metadata_option = db_handle.applications.installed_game_version.get(&id);
|
||||||
|
let version = match metadata_option {
|
||||||
|
None => None,
|
||||||
|
Some(metadata) => db_handle
|
||||||
|
.applications
|
||||||
|
.game_versions
|
||||||
|
.get(&metadata.id)
|
||||||
|
.map(|v| v.get(metadata.version.as_ref().unwrap()).unwrap())
|
||||||
|
.cloned(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let status = GameStatusManager::fetch_state(&id, &db_handle);
|
||||||
|
let game = get_cached_object::<Game>(&id)?;
|
||||||
|
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
Ok(FetchGameStruct {
|
||||||
|
game,
|
||||||
|
status,
|
||||||
|
version,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_game_version_options_logic(
|
||||||
|
game_id: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<Vec<GameVersion>, RemoteAccessError> {
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
|
||||||
|
let response = generate_url(&["/api/v1/client/game/versions"], &[("id", &game_id)])?;
|
||||||
|
let response = client
|
||||||
|
.get(response)
|
||||||
|
.header("Authorization", generate_authorization_header())
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if response.status() != 200 {
|
||||||
|
let err = response.json().await.unwrap();
|
||||||
|
warn!("{err:?}");
|
||||||
|
return Err(RemoteAccessError::InvalidResponse(err));
|
||||||
|
}
|
||||||
|
|
||||||
|
let data: Vec<GameVersion> = response.json().await?;
|
||||||
|
|
||||||
|
let state_lock = state.lock().unwrap();
|
||||||
|
let process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||||
|
let data: Vec<GameVersion> = data
|
||||||
|
.into_iter()
|
||||||
|
.filter(|v| {
|
||||||
|
process_manager_lock
|
||||||
|
.valid_platform(&v.platform, &state_lock)
|
||||||
|
.unwrap()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
drop(process_manager_lock);
|
||||||
|
drop(state_lock);
|
||||||
|
|
||||||
|
Ok(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called by:
|
||||||
|
* - on_cancel, when cancelled, for obvious reasons
|
||||||
|
* - when downloading, so if drop unexpectedly quits, we can resume the download. hidden by the "Downloading..." transient state, though
|
||||||
|
* - when scanning, to import the game
|
||||||
|
*/
|
||||||
|
pub fn set_partially_installed(
|
||||||
|
meta: &DownloadableMetadata,
|
||||||
|
install_dir: String,
|
||||||
|
app_handle: Option<&AppHandle>,
|
||||||
|
) {
|
||||||
|
set_partially_installed_db(&mut borrow_db_mut_checked(), meta, install_dir, app_handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_partially_installed_db(
|
||||||
|
db_lock: &mut Database,
|
||||||
|
meta: &DownloadableMetadata,
|
||||||
|
install_dir: String,
|
||||||
|
app_handle: Option<&AppHandle>,
|
||||||
|
) {
|
||||||
|
db_lock.applications.transient_statuses.remove(meta);
|
||||||
|
db_lock.applications.game_statuses.insert(
|
||||||
|
meta.id.clone(),
|
||||||
|
GameDownloadStatus::PartiallyInstalled {
|
||||||
|
version_name: meta.version.as_ref().unwrap().clone(),
|
||||||
|
install_dir,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
db_lock
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.insert(meta.id.clone(), meta.clone());
|
||||||
|
|
||||||
|
if let Some(app_handle) = app_handle {
|
||||||
|
push_game_update(
|
||||||
|
app_handle,
|
||||||
|
&meta.id,
|
||||||
|
None,
|
||||||
|
GameStatusManager::fetch_state(&meta.id, db_lock),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle) {
|
||||||
|
debug!("triggered uninstall for agent");
|
||||||
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.transient_statuses
|
||||||
|
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
||||||
|
|
||||||
|
push_game_update(
|
||||||
|
app_handle,
|
||||||
|
&meta.id,
|
||||||
|
None,
|
||||||
|
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
||||||
|
);
|
||||||
|
|
||||||
|
let previous_state = db_handle.applications.game_statuses.get(&meta.id).cloned();
|
||||||
|
if previous_state.is_none() {
|
||||||
|
warn!("uninstall job doesn't have previous state, failing silently");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let previous_state = previous_state.unwrap();
|
||||||
|
|
||||||
|
if let Some((_, install_dir)) = match previous_state {
|
||||||
|
GameDownloadStatus::Installed {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
} => Some((version_name, install_dir)),
|
||||||
|
GameDownloadStatus::SetupRequired {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
} => Some((version_name, install_dir)),
|
||||||
|
GameDownloadStatus::PartiallyInstalled {
|
||||||
|
version_name,
|
||||||
|
install_dir,
|
||||||
|
} => Some((version_name, install_dir)),
|
||||||
|
_ => None,
|
||||||
|
} {
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.transient_statuses
|
||||||
|
.insert(meta.clone(), ApplicationTransientStatus::Uninstalling {});
|
||||||
|
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
let app_handle = app_handle.clone();
|
||||||
|
spawn(move || {
|
||||||
|
if let Err(e) = remove_dir_all(install_dir) {
|
||||||
|
error!("{e}");
|
||||||
|
} else {
|
||||||
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
db_handle.applications.transient_statuses.remove(&meta);
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.remove(&meta.id);
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.game_statuses
|
||||||
|
.insert(meta.id.clone(), GameDownloadStatus::Remote {});
|
||||||
|
let _ = db_handle.applications.transient_statuses.remove(&meta);
|
||||||
|
|
||||||
|
push_game_update(
|
||||||
|
&app_handle,
|
||||||
|
&meta.id,
|
||||||
|
None,
|
||||||
|
GameStatusManager::fetch_state(&meta.id, &db_handle),
|
||||||
|
);
|
||||||
|
|
||||||
|
debug!("uninstalled game id {}", &meta.id);
|
||||||
|
app_handle.emit("update_library", ()).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
warn!("invalid previous state for uninstall, failing silently.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_current_meta(game_id: &String) -> Option<DownloadableMetadata> {
|
||||||
|
borrow_db_checked()
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.get(game_id)
|
||||||
|
.cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn on_game_complete(
|
||||||
|
meta: &DownloadableMetadata,
|
||||||
|
install_dir: String,
|
||||||
|
app_handle: &AppHandle,
|
||||||
|
) -> Result<(), RemoteAccessError> {
|
||||||
|
// Fetch game version information from remote
|
||||||
|
if meta.version.is_none() {
|
||||||
|
return Err(RemoteAccessError::GameNotFound(meta.id.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = DROP_CLIENT_SYNC.clone();
|
||||||
|
let response = generate_url(
|
||||||
|
&["/api/v1/client/game/version"],
|
||||||
|
&[
|
||||||
|
("id", &meta.id),
|
||||||
|
("version", meta.version.as_ref().unwrap()),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
let response = client
|
||||||
|
.get(response)
|
||||||
|
.header("Authorization", generate_authorization_header())
|
||||||
|
.send()?;
|
||||||
|
|
||||||
|
let game_version: GameVersion = response.json()?;
|
||||||
|
|
||||||
|
let mut handle = borrow_db_mut_checked();
|
||||||
|
handle
|
||||||
|
.applications
|
||||||
|
.game_versions
|
||||||
|
.entry(meta.id.clone())
|
||||||
|
.or_default()
|
||||||
|
.insert(meta.version.clone().unwrap(), game_version.clone());
|
||||||
|
handle
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.insert(meta.id.clone(), meta.clone());
|
||||||
|
|
||||||
|
drop(handle);
|
||||||
|
|
||||||
|
let status = if game_version.setup_command.is_empty() {
|
||||||
|
GameDownloadStatus::Installed {
|
||||||
|
version_name: meta.version.clone().unwrap(),
|
||||||
|
install_dir,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
GameDownloadStatus::SetupRequired {
|
||||||
|
version_name: meta.version.clone().unwrap(),
|
||||||
|
install_dir,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
|
db_handle
|
||||||
|
.applications
|
||||||
|
.game_statuses
|
||||||
|
.insert(meta.id.clone(), status.clone());
|
||||||
|
drop(db_handle);
|
||||||
|
|
||||||
|
app_handle
|
||||||
|
.emit(
|
||||||
|
&format!("update_game/{}", meta.id),
|
||||||
|
GameUpdateEvent {
|
||||||
|
game_id: meta.id.clone(),
|
||||||
|
status: (Some(status), None),
|
||||||
|
version: Some(game_version),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_game_update(
|
||||||
|
app_handle: &AppHandle,
|
||||||
|
game_id: &String,
|
||||||
|
version: Option<GameVersion>,
|
||||||
|
status: GameStatusWithTransient,
|
||||||
|
) {
|
||||||
|
if let Some(GameDownloadStatus::Installed { .. } | GameDownloadStatus::SetupRequired { .. }) =
|
||||||
|
&status.0
|
||||||
|
&& version.is_none()
|
||||||
|
{
|
||||||
|
panic!("pushed game for installed game that doesn't have version information");
|
||||||
|
}
|
||||||
|
|
||||||
|
app_handle
|
||||||
|
.emit(
|
||||||
|
&format!("update_game/{game_id}"),
|
||||||
|
GameUpdateEvent {
|
||||||
|
game_id: game_id.clone(),
|
||||||
|
status,
|
||||||
|
version,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FrontendGameOptions {
|
||||||
|
launch_string: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn update_game_configuration(
|
||||||
|
game_id: String,
|
||||||
|
options: FrontendGameOptions,
|
||||||
|
) -> Result<(), LibraryError> {
|
||||||
|
let mut handle = borrow_db_mut_checked();
|
||||||
|
let installed_version = handle
|
||||||
|
.applications
|
||||||
|
.installed_game_version
|
||||||
|
.get(&game_id)
|
||||||
|
.ok_or(LibraryError::MetaNotFound(game_id))?;
|
||||||
|
|
||||||
|
let id = installed_version.id.clone();
|
||||||
|
let version = installed_version.version.clone().unwrap();
|
||||||
|
|
||||||
|
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,6 +1,5 @@
|
|||||||
#![feature(iterator_try_collect)]
|
|
||||||
|
|
||||||
pub mod collections;
|
pub mod collections;
|
||||||
|
pub mod commands;
|
||||||
pub mod downloads;
|
pub mod downloads;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
@ -1,4 +1,4 @@
|
|||||||
use database::models::data::{
|
use crate::database::models::data::{
|
||||||
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
|
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -3,24 +3,117 @@
|
|||||||
#![feature(duration_constructors)]
|
#![feature(duration_constructors)]
|
||||||
#![feature(duration_millis_float)]
|
#![feature(duration_millis_float)]
|
||||||
#![feature(iterator_try_collect)]
|
#![feature(iterator_try_collect)]
|
||||||
#![feature(nonpoison_mutex)]
|
|
||||||
#![deny(clippy::all)]
|
#![deny(clippy::all)]
|
||||||
|
|
||||||
use std::collections::HashMap;
|
mod database;
|
||||||
|
|
||||||
use ::client::{app_status::AppStatus, compat::CompatInfo, user::User};
|
|
||||||
use database::{borrow_db_checked, GameDownloadStatus};
|
|
||||||
use ::games::library::Game;
|
|
||||||
use ::remote::auth;
|
|
||||||
use serde::Serialize;
|
|
||||||
use tauri::AppHandle;
|
|
||||||
|
|
||||||
mod games;
|
mod games;
|
||||||
|
|
||||||
mod client;
|
mod client;
|
||||||
|
mod download_manager;
|
||||||
|
mod error;
|
||||||
mod process;
|
mod process;
|
||||||
mod remote;
|
mod remote;
|
||||||
|
|
||||||
|
use crate::database::scan::scan_install_dirs;
|
||||||
|
use crate::process::commands::open_process_logs;
|
||||||
|
use crate::process::process_handlers::UMU_LAUNCHER_EXECUTABLE;
|
||||||
|
use crate::remote::commands::auth_initiate_code;
|
||||||
|
use crate::{database::db::DatabaseImpls, games::downloads::commands::resume_download};
|
||||||
|
use bitcode::{Decode, Encode};
|
||||||
|
use client::commands::fetch_state;
|
||||||
|
use client::{
|
||||||
|
autostart::{get_autostart_enabled, sync_autostart_on_startup, toggle_autostart},
|
||||||
|
cleanup::{cleanup_and_exit, quit},
|
||||||
|
};
|
||||||
|
use database::commands::{
|
||||||
|
add_download_dir, delete_download_dir, fetch_download_dir_stats, fetch_settings,
|
||||||
|
fetch_system_data, update_settings,
|
||||||
|
};
|
||||||
|
use database::db::{DATA_ROOT_DIR, DatabaseInterface, borrow_db_checked, borrow_db_mut_checked};
|
||||||
|
use database::models::data::GameDownloadStatus;
|
||||||
|
use download_manager::commands::{
|
||||||
|
cancel_game, move_download_in_queue, pause_downloads, resume_downloads,
|
||||||
|
};
|
||||||
|
use download_manager::download_manager_builder::DownloadManagerBuilder;
|
||||||
|
use download_manager::download_manager_frontend::DownloadManager;
|
||||||
|
use games::collections::commands::{
|
||||||
|
add_game_to_collection, create_collection, delete_collection, delete_game_in_collection,
|
||||||
|
fetch_collection, fetch_collections,
|
||||||
|
};
|
||||||
|
use games::commands::{
|
||||||
|
fetch_game, fetch_game_status, fetch_game_version_options, fetch_library, uninstall_game,
|
||||||
|
};
|
||||||
|
use games::downloads::commands::download_game;
|
||||||
|
use games::library::{Game, update_game_configuration};
|
||||||
|
use log::{LevelFilter, debug, info, warn};
|
||||||
|
use log4rs::Config;
|
||||||
|
use log4rs::append::console::ConsoleAppender;
|
||||||
|
use log4rs::append::file::FileAppender;
|
||||||
|
use log4rs::config::{Appender, Root};
|
||||||
|
use log4rs::encode::pattern::PatternEncoder;
|
||||||
|
use process::commands::{kill_game, launch_game};
|
||||||
|
use process::process_manager::ProcessManager;
|
||||||
|
use remote::auth::{self, recieve_handshake};
|
||||||
|
use remote::commands::{
|
||||||
|
auth_initiate, fetch_drop_object, gen_drop_url, manual_recieve_handshake, retry_connect,
|
||||||
|
sign_out, use_remote,
|
||||||
|
};
|
||||||
|
use remote::fetch_object::fetch_object;
|
||||||
|
use remote::server_proto::{handle_server_proto, handle_server_proto_offline};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::panic::PanicHookInfo;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::SystemTime;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
sync::{LazyLock, Mutex},
|
||||||
|
};
|
||||||
|
use std::{env, panic};
|
||||||
|
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
|
||||||
|
use tauri::tray::TrayIconBuilder;
|
||||||
|
use tauri::{AppHandle, Manager, RunEvent, WindowEvent};
|
||||||
|
use tauri_plugin_deep_link::DeepLinkExt;
|
||||||
|
use tauri_plugin_dialog::DialogExt;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Serialize, Eq, PartialEq)]
|
||||||
|
pub enum AppStatus {
|
||||||
|
NotConfigured,
|
||||||
|
Offline,
|
||||||
|
ServerError,
|
||||||
|
SignedOut,
|
||||||
|
SignedIn,
|
||||||
|
SignedInNeedsReauth,
|
||||||
|
ServerUnavailable,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Encode, Decode)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct User {
|
||||||
|
id: String,
|
||||||
|
username: String,
|
||||||
|
admin: bool,
|
||||||
|
display_name: String,
|
||||||
|
profile_picture_object_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CompatInfo {
|
||||||
|
umu_installed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_new_compat_info() -> Option<CompatInfo> {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
return None;
|
||||||
|
|
||||||
|
let has_umu_installed = UMU_LAUNCHER_EXECUTABLE.is_some();
|
||||||
|
Some(CompatInfo {
|
||||||
|
umu_installed: has_umu_installed,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize)]
|
#[derive(Clone, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@ -28,6 +121,13 @@ pub struct AppState<'a> {
|
|||||||
status: AppStatus,
|
status: AppStatus,
|
||||||
user: Option<User>,
|
user: Option<User>,
|
||||||
games: HashMap<String, Game>,
|
games: HashMap<String, Game>,
|
||||||
|
|
||||||
|
#[serde(skip_serializing)]
|
||||||
|
download_manager: Arc<DownloadManager>,
|
||||||
|
#[serde(skip_serializing)]
|
||||||
|
process_manager: Arc<Mutex<ProcessManager<'a>>>,
|
||||||
|
#[serde(skip_serializing)]
|
||||||
|
compat_info: Option<CompatInfo>,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn setup(handle: AppHandle) -> AppState<'static> {
|
async fn setup(handle: AppHandle) -> AppState<'static> {
|
||||||
@ -37,7 +137,7 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
|||||||
)))
|
)))
|
||||||
.append(false)
|
.append(false)
|
||||||
.build(DATA_ROOT_DIR.join("./drop.log"))
|
.build(DATA_ROOT_DIR.join("./drop.log"))
|
||||||
.expect("Failed to setup logfile");
|
.unwrap();
|
||||||
|
|
||||||
let console = ConsoleAppender::builder()
|
let console = ConsoleAppender::builder()
|
||||||
.encoder(Box::new(PatternEncoder::new(
|
.encoder(Box::new(PatternEncoder::new(
|
||||||
@ -57,9 +157,9 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
|||||||
.appenders(vec!["logfile", "console"])
|
.appenders(vec!["logfile", "console"])
|
||||||
.build(LevelFilter::from_str(&log_level).expect("Invalid log level")),
|
.build(LevelFilter::from_str(&log_level).expect("Invalid log level")),
|
||||||
)
|
)
|
||||||
.expect("Failed to build config");
|
.unwrap();
|
||||||
|
|
||||||
log4rs::init_config(config).expect("Failed to initialise log4rs");
|
log4rs::init_config(config).unwrap();
|
||||||
|
|
||||||
let games = HashMap::new();
|
let games = HashMap::new();
|
||||||
let download_manager = Arc::new(DownloadManagerBuilder::build(handle.clone()));
|
let download_manager = Arc::new(DownloadManagerBuilder::build(handle.clone()));
|
||||||
@ -147,6 +247,8 @@ async fn setup(handle: AppHandle) -> AppState<'static> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub static DB: LazyLock<DatabaseInterface> = LazyLock::new(DatabaseInterface::set_up_database);
|
||||||
|
|
||||||
pub fn custom_panic_handler(e: &PanicHookInfo) -> Option<()> {
|
pub fn custom_panic_handler(e: &PanicHookInfo) -> Option<()> {
|
||||||
let crash_file = DATA_ROOT_DIR.join(format!(
|
let crash_file = DATA_ROOT_DIR.join(format!(
|
||||||
"crash-{}.log",
|
"crash-{}.log",
|
||||||
@ -268,64 +370,42 @@ pub fn run() {
|
|||||||
.shadow(false)
|
.shadow(false)
|
||||||
.data_directory(DATA_ROOT_DIR.join(".webview"))
|
.data_directory(DATA_ROOT_DIR.join(".webview"))
|
||||||
.build()
|
.build()
|
||||||
.expect("Failed to build main window");
|
.unwrap();
|
||||||
|
|
||||||
app.deep_link().on_open_url(move |event| {
|
app.deep_link().on_open_url(move |event| {
|
||||||
debug!("handling drop:// url");
|
debug!("handling drop:// url");
|
||||||
let binding = event.urls();
|
let binding = event.urls();
|
||||||
let url = match binding.first() {
|
let url = binding.first().unwrap();
|
||||||
Some(url) => url,
|
if url.host_str().unwrap() == "handshake" {
|
||||||
None => {
|
|
||||||
warn!("No value recieved from deep link. Is this a drop server?");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some("handshake") = url.host_str() {
|
|
||||||
tauri::async_runtime::spawn(recieve_handshake(
|
tauri::async_runtime::spawn(recieve_handshake(
|
||||||
handle.clone(),
|
handle.clone(),
|
||||||
url.path().to_string(),
|
url.path().to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let open_menu_item = MenuItem::with_id(app, "open", "Open", true, None::<&str>)
|
|
||||||
.expect("Failed to generate open menu item");
|
|
||||||
|
|
||||||
let sep = PredefinedMenuItem::separator(app)
|
|
||||||
.expect("Failed to generate menu separator item");
|
|
||||||
|
|
||||||
let quit_menu_item = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)
|
|
||||||
.expect("Failed to generate quit menu item");
|
|
||||||
|
|
||||||
let menu = Menu::with_items(
|
let menu = Menu::with_items(
|
||||||
app,
|
app,
|
||||||
&[
|
&[
|
||||||
&open_menu_item,
|
&MenuItem::with_id(app, "open", "Open", true, None::<&str>).unwrap(),
|
||||||
&sep,
|
&PredefinedMenuItem::separator(app).unwrap(),
|
||||||
/*
|
/*
|
||||||
&MenuItem::with_id(app, "show_library", "Library", true, None::<&str>)?,
|
&MenuItem::with_id(app, "show_library", "Library", true, None::<&str>)?,
|
||||||
&MenuItem::with_id(app, "show_settings", "Settings", true, None::<&str>)?,
|
&MenuItem::with_id(app, "show_settings", "Settings", true, None::<&str>)?,
|
||||||
&PredefinedMenuItem::separator(app)?,
|
&PredefinedMenuItem::separator(app)?,
|
||||||
*/
|
*/
|
||||||
&quit_menu_item,
|
&MenuItem::with_id(app, "quit", "Quit", true, None::<&str>).unwrap(),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
.expect("Failed to generate menu");
|
.unwrap();
|
||||||
|
|
||||||
run_on_tray(|| {
|
run_on_tray(|| {
|
||||||
TrayIconBuilder::new()
|
TrayIconBuilder::new()
|
||||||
.icon(
|
.icon(app.default_window_icon().unwrap().clone())
|
||||||
app.default_window_icon()
|
|
||||||
.expect("Failed to get default window icon")
|
|
||||||
.clone(),
|
|
||||||
)
|
|
||||||
.menu(&menu)
|
.menu(&menu)
|
||||||
.on_menu_event(|app, event| match event.id.as_ref() {
|
.on_menu_event(|app, event| match event.id.as_ref() {
|
||||||
"open" => {
|
"open" => {
|
||||||
app.webview_windows()
|
app.webview_windows().get("main").unwrap().show().unwrap();
|
||||||
.get("main")
|
|
||||||
.expect("Failed to get webview")
|
|
||||||
.show()
|
|
||||||
.expect("Failed to show window");
|
|
||||||
}
|
}
|
||||||
"quit" => {
|
"quit" => {
|
||||||
cleanup_and_exit(app, &app.state());
|
cleanup_and_exit(app, &app.state());
|
||||||
@ -342,19 +422,15 @@ pub fn run() {
|
|||||||
{
|
{
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
if let Some(original) = db_handle.prev_database.take() {
|
if let Some(original) = db_handle.prev_database.take() {
|
||||||
let canonicalised = match original.canonicalize() {
|
|
||||||
Ok(o) => o,
|
|
||||||
Err(_) => original,
|
|
||||||
};
|
|
||||||
warn!(
|
warn!(
|
||||||
"Database corrupted. Original file at {}",
|
"Database corrupted. Original file at {}",
|
||||||
canonicalised.display()
|
original.canonicalize().unwrap().to_string_lossy()
|
||||||
);
|
);
|
||||||
app.dialog()
|
app.dialog()
|
||||||
.message(format!(
|
.message(
|
||||||
"Database corrupted. A copy has been saved at: {}",
|
"Database corrupted. A copy has been saved at: ".to_string()
|
||||||
canonicalised.display()
|
+ original.to_str().unwrap(),
|
||||||
))
|
)
|
||||||
.title("Database corrupted")
|
.title("Database corrupted")
|
||||||
.show(|_| {});
|
.show(|_| {});
|
||||||
}
|
}
|
||||||
@ -365,7 +441,7 @@ pub fn run() {
|
|||||||
})
|
})
|
||||||
.register_asynchronous_uri_scheme_protocol("object", move |_ctx, request, responder| {
|
.register_asynchronous_uri_scheme_protocol("object", move |_ctx, request, responder| {
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
fetch_object_wrapper(request, responder).await;
|
fetch_object(request, responder).await;
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.register_asynchronous_uri_scheme_protocol("server", |ctx, request, responder| {
|
.register_asynchronous_uri_scheme_protocol("server", |ctx, request, responder| {
|
||||||
@ -376,8 +452,8 @@ pub fn run() {
|
|||||||
|
|
||||||
offline!(
|
offline!(
|
||||||
state,
|
state,
|
||||||
handle_server_proto_wrapper,
|
handle_server_proto,
|
||||||
handle_server_proto_offline_wrapper,
|
handle_server_proto_offline,
|
||||||
request,
|
request,
|
||||||
responder
|
responder
|
||||||
)
|
)
|
||||||
@ -387,7 +463,7 @@ pub fn run() {
|
|||||||
.on_window_event(|window, event| {
|
.on_window_event(|window, event| {
|
||||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
run_on_tray(|| {
|
run_on_tray(|| {
|
||||||
window.hide().expect("Failed to close window in tray");
|
window.hide().unwrap();
|
||||||
api.prevent_close();
|
api.prevent_close();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -410,98 +486,10 @@ fn run_on_tray<T: FnOnce()>(f: T) {
|
|||||||
if match std::env::var("NO_TRAY_ICON") {
|
if match std::env::var("NO_TRAY_ICON") {
|
||||||
Ok(s) => s.to_lowercase() != "true",
|
Ok(s) => s.to_lowercase() != "true",
|
||||||
Err(_) => true,
|
Err(_) => true,
|
||||||
|
} || match option_env!("NO_TRAY_ICON") {
|
||||||
|
Some(s) => s.to_lowercase() != "true",
|
||||||
|
None => true,
|
||||||
} {
|
} {
|
||||||
(f)();
|
(f)();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Refactor
|
|
||||||
pub async fn recieve_handshake(app: AppHandle, path: String) {
|
|
||||||
// Tell the app we're processing
|
|
||||||
app_emit!(app, "auth/processing", ());
|
|
||||||
|
|
||||||
let handshake_result = recieve_handshake_logic(&app, path).await;
|
|
||||||
if let Err(e) = handshake_result {
|
|
||||||
warn!("error with authentication: {e}");
|
|
||||||
app_emit!(app, "auth/failed", e.to_string());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let app_state = app.state::<Mutex<AppState>>();
|
|
||||||
|
|
||||||
let (app_status, user) = remote::setup().await;
|
|
||||||
|
|
||||||
let mut state_lock = lock!(app_state);
|
|
||||||
|
|
||||||
state_lock.status = app_status;
|
|
||||||
state_lock.user = user;
|
|
||||||
|
|
||||||
let _ = clear_cached_object("collections");
|
|
||||||
let _ = clear_cached_object("library");
|
|
||||||
|
|
||||||
drop(state_lock);
|
|
||||||
|
|
||||||
app_emit!(app, "auth/finished", ());
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Refactor
|
|
||||||
async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), RemoteAccessError> {
|
|
||||||
let path_chunks: Vec<&str> = path.split('/').collect();
|
|
||||||
if path_chunks.len() != 3 {
|
|
||||||
app_emit!(app, "auth/failed", ());
|
|
||||||
return Err(RemoteAccessError::HandshakeFailed(
|
|
||||||
"failed to parse token".to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let base_url = {
|
|
||||||
let handle = borrow_db_checked();
|
|
||||||
Url::parse(handle.base_url.as_str())?
|
|
||||||
};
|
|
||||||
|
|
||||||
let client_id = path_chunks
|
|
||||||
.get(1)
|
|
||||||
.expect("Failed to get client id from path chunks");
|
|
||||||
let token = path_chunks
|
|
||||||
.get(2)
|
|
||||||
.expect("Failed to get token from path chunks");
|
|
||||||
let body = HandshakeRequestBody {
|
|
||||||
client_id: (client_id).to_string(),
|
|
||||||
token: (token).to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let endpoint = base_url.join("/api/v1/client/auth/handshake")?;
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let response = client.post(endpoint).json(&body).send().await?;
|
|
||||||
debug!("handshake responsded with {}", response.status().as_u16());
|
|
||||||
if !response.status().is_success() {
|
|
||||||
return Err(RemoteAccessError::InvalidResponse(response.json().await?));
|
|
||||||
}
|
|
||||||
let response_struct: HandshakeResponse = response.json().await?;
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut handle = borrow_db_mut_checked();
|
|
||||||
handle.auth = Some(DatabaseAuth {
|
|
||||||
private: response_struct.private,
|
|
||||||
cert: response_struct.certificate,
|
|
||||||
client_id: response_struct.id,
|
|
||||||
web_token: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let web_token = {
|
|
||||||
let header = generate_authorization_header();
|
|
||||||
let token = client
|
|
||||||
.post(base_url.join("/api/v1/client/user/webtoken")?)
|
|
||||||
.header("Authorization", header)
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
token.text().await?
|
|
||||||
};
|
|
||||||
let mut handle = borrow_db_mut_checked();
|
|
||||||
handle.auth.as_mut().unwrap().web_token = Some(web_token);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
@ -1,19 +1,15 @@
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
|
|
||||||
use process::{error::ProcessError, PROCESS_MANAGER};
|
use crate::{error::process_error::ProcessError, AppState};
|
||||||
use tauri::AppHandle;
|
|
||||||
use tauri_plugin_opener::OpenerExt;
|
|
||||||
use utils::lock;
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn launch_game(
|
pub fn launch_game(
|
||||||
id: String,
|
id: String,
|
||||||
state: tauri::State<'_, Mutex<AppState>>,
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<(), ProcessError> {
|
) -> Result<(), ProcessError> {
|
||||||
let state_lock = lock!(state);
|
let state_lock = state.lock().unwrap();
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||||
|
|
||||||
//let meta = DownloadableMetadata {
|
//let meta = DownloadableMetadata {
|
||||||
// id,
|
// id,
|
||||||
// version: Some(version),
|
// version: Some(version),
|
||||||
@ -34,9 +30,11 @@ pub fn launch_game(
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn kill_game(
|
pub fn kill_game(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<(), ProcessError> {
|
) -> Result<(), ProcessError> {
|
||||||
PROCESS_MANAGER
|
let state_lock = state.lock().unwrap();
|
||||||
.lock()
|
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||||
|
process_manager_lock
|
||||||
.kill_game(game_id)
|
.kill_game(game_id)
|
||||||
.map_err(ProcessError::IOError)
|
.map_err(ProcessError::IOError)
|
||||||
}
|
}
|
||||||
@ -44,13 +42,9 @@ pub fn kill_game(
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn open_process_logs(
|
pub fn open_process_logs(
|
||||||
game_id: String,
|
game_id: String,
|
||||||
app_handle: AppHandle
|
state: tauri::State<'_, Mutex<AppState>>,
|
||||||
) -> Result<(), ProcessError> {
|
) -> Result<(), ProcessError> {
|
||||||
let process_manager_lock = PROCESS_MANAGER.lock();
|
let state_lock = state.lock().unwrap();
|
||||||
|
let mut process_manager_lock = state_lock.process_manager.lock().unwrap();
|
||||||
let dir = process_manager_lock.get_log_dir(game_id);
|
process_manager_lock.open_process_logs(game_id)
|
||||||
app_handle
|
|
||||||
.opener()
|
|
||||||
.open_path(dir.display().to_string(), None::<&str>)
|
|
||||||
.map_err(ProcessError::OpenerError)
|
|
||||||
}
|
}
|
||||||
5
src-tauri/src/process/mod.rs
Normal file
5
src-tauri/src/process/mod.rs
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
pub mod commands;
|
||||||
|
pub mod process_manager;
|
||||||
|
pub mod process_handlers;
|
||||||
|
pub mod format;
|
||||||
|
pub mod utils;
|
||||||
@ -1,9 +1,17 @@
|
|||||||
use client::compat::{COMPAT_INFO, UMU_LAUNCHER_EXECUTABLE};
|
use std::{
|
||||||
use database::{platform::Platform, Database, DownloadableMetadata, GameVersion};
|
ffi::OsStr,
|
||||||
use log::debug;
|
path::PathBuf,
|
||||||
|
process::{Command, Stdio},
|
||||||
|
sync::LazyLock,
|
||||||
|
};
|
||||||
|
|
||||||
|
use log::{debug, info};
|
||||||
|
|
||||||
use crate::{error::ProcessError, process_manager::ProcessHandler};
|
use crate::{
|
||||||
|
AppState,
|
||||||
|
database::models::data::{Database, DownloadableMetadata, GameVersion},
|
||||||
|
process::process_manager::{Platform, ProcessHandler},
|
||||||
|
};
|
||||||
|
|
||||||
pub struct NativeGameLauncher;
|
pub struct NativeGameLauncher;
|
||||||
impl ProcessHandler for NativeGameLauncher {
|
impl ProcessHandler for NativeGameLauncher {
|
||||||
@ -14,15 +22,40 @@ impl ProcessHandler for NativeGameLauncher {
|
|||||||
args: Vec<String>,
|
args: Vec<String>,
|
||||||
_game_version: &GameVersion,
|
_game_version: &GameVersion,
|
||||||
_current_dir: &str,
|
_current_dir: &str,
|
||||||
) -> Result<String, ProcessError> {
|
) -> String {
|
||||||
Ok(format!("\"{}\" {}", launch_command, args.join(" ")))
|
format!("\"{}\" {}", launch_command, args.join(" "))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool {
|
fn valid_for_platform(&self, _db: &Database, _state: &AppState, _target: &Platform) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub static UMU_LAUNCHER_EXECUTABLE: LazyLock<Option<PathBuf>> = LazyLock::new(|| {
|
||||||
|
let x = get_umu_executable();
|
||||||
|
info!("{:?}", &x);
|
||||||
|
x
|
||||||
|
});
|
||||||
|
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> {
|
||||||
|
if check_executable_exists(UMU_BASE_LAUNCHER_EXECUTABLE) {
|
||||||
|
return Some(PathBuf::from(UMU_BASE_LAUNCHER_EXECUTABLE));
|
||||||
|
}
|
||||||
|
|
||||||
|
for dir in UMU_INSTALL_DIRS {
|
||||||
|
let p = PathBuf::from(dir).join(UMU_BASE_LAUNCHER_EXECUTABLE);
|
||||||
|
if check_executable_exists(&p) {
|
||||||
|
return Some(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
fn check_executable_exists<P: AsRef<OsStr>>(exec: P) -> bool {
|
||||||
|
let has_umu_installed = Command::new(exec).stdout(Stdio::null()).output();
|
||||||
|
has_umu_installed.is_ok()
|
||||||
|
}
|
||||||
pub struct UMULauncher;
|
pub struct UMULauncher;
|
||||||
impl ProcessHandler for UMULauncher {
|
impl ProcessHandler for UMULauncher {
|
||||||
fn create_launch_process(
|
fn create_launch_process(
|
||||||
@ -32,7 +65,7 @@ impl ProcessHandler for UMULauncher {
|
|||||||
args: Vec<String>,
|
args: Vec<String>,
|
||||||
game_version: &GameVersion,
|
game_version: &GameVersion,
|
||||||
_current_dir: &str,
|
_current_dir: &str,
|
||||||
) -> Result<String, ProcessError> {
|
) -> String {
|
||||||
debug!("Game override: \"{:?}\"", &game_version.umu_id_override);
|
debug!("Game override: \"{:?}\"", &game_version.umu_id_override);
|
||||||
let game_id = match &game_version.umu_id_override {
|
let game_id = match &game_version.umu_id_override {
|
||||||
Some(game_override) => {
|
Some(game_override) => {
|
||||||
@ -44,16 +77,16 @@ impl ProcessHandler for UMULauncher {
|
|||||||
}
|
}
|
||||||
None => game_version.game_id.clone(),
|
None => game_version.game_id.clone(),
|
||||||
};
|
};
|
||||||
Ok(format!(
|
format!(
|
||||||
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
"GAMEID={game_id} {umu:?} \"{launch}\" {args}",
|
||||||
umu = UMU_LAUNCHER_EXECUTABLE.as_ref().expect("Failed to get UMU_LAUNCHER_EXECUTABLE as ref"),
|
umu = UMU_LAUNCHER_EXECUTABLE.as_ref().unwrap(),
|
||||||
launch = launch_command,
|
launch = launch_command,
|
||||||
args = args.join(" ")
|
args = args.join(" ")
|
||||||
))
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool {
|
fn valid_for_platform(&self, _db: &Database, state: &AppState, _target: &Platform) -> bool {
|
||||||
let Some(compat_info) = &*COMPAT_INFO else {
|
let Some(ref compat_info) = state.compat_info else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
compat_info.umu_installed
|
compat_info.umu_installed
|
||||||
@ -69,7 +102,7 @@ impl ProcessHandler for AsahiMuvmLauncher {
|
|||||||
args: Vec<String>,
|
args: Vec<String>,
|
||||||
game_version: &GameVersion,
|
game_version: &GameVersion,
|
||||||
current_dir: &str,
|
current_dir: &str,
|
||||||
) -> Result<String, ProcessError> {
|
) -> String {
|
||||||
let umu_launcher = UMULauncher {};
|
let umu_launcher = UMULauncher {};
|
||||||
let umu_string = umu_launcher.create_launch_process(
|
let umu_string = umu_launcher.create_launch_process(
|
||||||
meta,
|
meta,
|
||||||
@ -77,23 +110,20 @@ impl ProcessHandler for AsahiMuvmLauncher {
|
|||||||
args,
|
args,
|
||||||
game_version,
|
game_version,
|
||||||
current_dir,
|
current_dir,
|
||||||
)?;
|
);
|
||||||
let mut args_cmd = umu_string
|
let mut args_cmd = umu_string
|
||||||
.split("umu-run")
|
.split("umu-run")
|
||||||
.collect::<Vec<&str>>()
|
.collect::<Vec<&str>>()
|
||||||
.into_iter();
|
.into_iter();
|
||||||
let args = args_cmd
|
let args = args_cmd.next().unwrap().trim();
|
||||||
.next()
|
let cmd = format!("umu-run{}", args_cmd.next().unwrap());
|
||||||
.ok_or(ProcessError::InvalidArguments(umu_string.clone()))?
|
|
||||||
.trim();
|
|
||||||
let cmd = format!("umu-run{}", args_cmd.next().ok_or(ProcessError::InvalidArguments(umu_string.clone()))?);
|
|
||||||
|
|
||||||
Ok(format!("{args} muvm -- {cmd}"))
|
format!("{args} muvm -- {cmd}")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(unreachable_code)]
|
#[allow(unreachable_code)]
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
fn valid_for_platform(&self, _db: &Database, _target: &Platform) -> bool {
|
fn valid_for_platform(&self, _db: &Database, state: &AppState, _target: &Platform) -> bool {
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -105,7 +135,7 @@ impl ProcessHandler for AsahiMuvmLauncher {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(compat_info) = &*COMPAT_INFO else {
|
let Some(ref compat_info) = state.compat_info else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -1,30 +1,38 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
fs::{OpenOptions, create_dir_all},
|
fs::{OpenOptions, create_dir_all},
|
||||||
io,
|
io::{self},
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
process::{Command, ExitStatus},
|
process::{Command, ExitStatus},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
sync::Arc,
|
sync::{Arc, Mutex},
|
||||||
|
thread::spawn,
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
use database::{
|
|
||||||
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata, GameDownloadStatus,
|
|
||||||
GameVersion, borrow_db_checked, borrow_db_mut_checked, db::DATA_ROOT_DIR, platform::Platform,
|
|
||||||
};
|
|
||||||
use dynfmt::Format;
|
use dynfmt::Format;
|
||||||
use dynfmt::SimpleCurlyFormat;
|
use dynfmt::SimpleCurlyFormat;
|
||||||
use games::state::GameStatusManager;
|
|
||||||
use log::{debug, info, warn};
|
use log::{debug, info, warn};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use shared_child::SharedChild;
|
use shared_child::SharedChild;
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
use tauri_plugin_opener::OpenerExt;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
PROCESS_MANAGER,
|
AppState, DB,
|
||||||
error::ProcessError,
|
database::{
|
||||||
format::DropFormatArgs,
|
db::{DATA_ROOT_DIR, borrow_db_checked, borrow_db_mut_checked},
|
||||||
process_handlers::{AsahiMuvmLauncher, NativeGameLauncher, UMULauncher},
|
models::data::{
|
||||||
|
ApplicationTransientStatus, Database, DownloadType, DownloadableMetadata,
|
||||||
|
GameDownloadStatus, GameVersion,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
error::process_error::ProcessError,
|
||||||
|
games::{library::push_game_update, state::GameStatusManager},
|
||||||
|
process::{
|
||||||
|
format::DropFormatArgs,
|
||||||
|
process_handlers::{AsahiMuvmLauncher, NativeGameLauncher, UMULauncher},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub struct RunningProcess {
|
pub struct RunningProcess {
|
||||||
@ -37,6 +45,7 @@ pub struct ProcessManager<'a> {
|
|||||||
current_platform: Platform,
|
current_platform: Platform,
|
||||||
log_output_dir: PathBuf,
|
log_output_dir: PathBuf,
|
||||||
processes: HashMap<String, RunningProcess>,
|
processes: HashMap<String, RunningProcess>,
|
||||||
|
app_handle: AppHandle,
|
||||||
game_launchers: Vec<(
|
game_launchers: Vec<(
|
||||||
(Platform, Platform),
|
(Platform, Platform),
|
||||||
&'a (dyn ProcessHandler + Sync + Send + 'static),
|
&'a (dyn ProcessHandler + Sync + Send + 'static),
|
||||||
@ -44,7 +53,7 @@ pub struct ProcessManager<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ProcessManager<'_> {
|
impl ProcessManager<'_> {
|
||||||
pub fn new() -> Self {
|
pub fn new(app_handle: AppHandle) -> Self {
|
||||||
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
let log_output_dir = DATA_ROOT_DIR.join("logs");
|
||||||
|
|
||||||
ProcessManager {
|
ProcessManager {
|
||||||
@ -57,6 +66,7 @@ impl ProcessManager<'_> {
|
|||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
current_platform: Platform::Linux,
|
current_platform: Platform::Linux,
|
||||||
|
|
||||||
|
app_handle,
|
||||||
processes: HashMap::new(),
|
processes: HashMap::new(),
|
||||||
log_output_dir,
|
log_output_dir,
|
||||||
game_launchers: vec![
|
game_launchers: vec![
|
||||||
@ -100,31 +110,30 @@ impl ProcessManager<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_log_dir(&self, game_id: String) -> PathBuf {
|
fn get_log_dir(&self, game_id: String) -> PathBuf {
|
||||||
self.log_output_dir.join(game_id)
|
self.log_output_dir.join(game_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn on_process_finish(
|
pub fn open_process_logs(&mut self, game_id: String) -> Result<(), ProcessError> {
|
||||||
&mut self,
|
let dir = self.get_log_dir(game_id);
|
||||||
game_id: String,
|
self.app_handle
|
||||||
result: Result<ExitStatus, std::io::Error>,
|
.opener()
|
||||||
) -> Result<(), ProcessError> {
|
.open_path(dir.to_str().unwrap(), None::<&str>)
|
||||||
|
.map_err(ProcessError::OpenerError)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn on_process_finish(&mut self, game_id: String, result: Result<ExitStatus, std::io::Error>) {
|
||||||
if !self.processes.contains_key(&game_id) {
|
if !self.processes.contains_key(&game_id) {
|
||||||
warn!(
|
warn!(
|
||||||
"process on_finish was called, but game_id is no longer valid. finished with result: {result:?}"
|
"process on_finish was called, but game_id is no longer valid. finished with result: {result:?}"
|
||||||
);
|
);
|
||||||
return Ok(());
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
debug!("process for {:?} exited with {:?}", &game_id, result);
|
debug!("process for {:?} exited with {:?}", &game_id, result);
|
||||||
|
|
||||||
let process = match self.processes.remove(&game_id) {
|
let process = self.processes.remove(&game_id).unwrap();
|
||||||
Some(process) => process,
|
|
||||||
None => {
|
|
||||||
info!("Attempted to stop process {game_id} which didn't exist");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut db_handle = borrow_db_mut_checked();
|
let mut db_handle = borrow_db_mut_checked();
|
||||||
let meta = db_handle
|
let meta = db_handle
|
||||||
@ -132,7 +141,7 @@ impl ProcessManager<'_> {
|
|||||||
.installed_game_version
|
.installed_game_version
|
||||||
.get(&game_id)
|
.get(&game_id)
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or_else(|| panic!("Could not get installed version of {}", &game_id));
|
.unwrap();
|
||||||
db_handle.applications.transient_statuses.remove(&meta);
|
db_handle.applications.transient_statuses.remove(&meta);
|
||||||
|
|
||||||
let current_state = db_handle.applications.game_statuses.get(&game_id).cloned();
|
let current_state = db_handle.applications.game_statuses.get(&game_id).cloned();
|
||||||
@ -157,34 +166,35 @@ impl ProcessManager<'_> {
|
|||||||
// Or if the status isn't 0
|
// Or if the status isn't 0
|
||||||
// Or if it's an error
|
// Or if it's an error
|
||||||
if !process.manually_killed
|
if !process.manually_killed
|
||||||
&& (elapsed.as_secs() <= 2 || result.map_or(true, |r| !r.success()))
|
&& (elapsed.as_secs() <= 2 || result.is_err() || !result.unwrap().success())
|
||||||
{
|
{
|
||||||
warn!("drop detected that the game {game_id} may have failed to launch properly");
|
warn!("drop detected that the game {game_id} may have failed to launch properly");
|
||||||
return Err(ProcessError::FailedLaunch(game_id));
|
let _ = self.app_handle.emit("launch_external_error", &game_id);
|
||||||
// let _ = self.app_handle.emit("launch_external_error", &game_id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let version_data = match db_handle.applications.game_versions.get(&game_id) {
|
// This is too many unwraps for me to be comfortable
|
||||||
// This unwrap here should be resolved by just making the hashmap accept an option rather than just a String
|
let version_data = db_handle
|
||||||
Some(res) => res.get(&meta.version.unwrap()).expect("Failed to get game version from installed game versions. Is the database corrupted?"),
|
.applications
|
||||||
None => todo!(),
|
.game_versions
|
||||||
};
|
.get(&game_id)
|
||||||
|
.unwrap()
|
||||||
|
.get(&meta.version.unwrap())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
let status = GameStatusManager::fetch_state(&game_id, &db_handle);
|
||||||
|
|
||||||
// TODO
|
push_game_update(
|
||||||
// push_game_update(
|
&self.app_handle,
|
||||||
// &self.app_handle,
|
&game_id,
|
||||||
// &game_id,
|
Some(version_data.clone()),
|
||||||
// Some(version_data.clone()),
|
status,
|
||||||
// status,
|
);
|
||||||
// );
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fetch_process_handler(
|
fn fetch_process_handler(
|
||||||
&self,
|
&self,
|
||||||
db_lock: &Database,
|
db_lock: &Database,
|
||||||
|
state: &AppState,
|
||||||
target_platform: &Platform,
|
target_platform: &Platform,
|
||||||
) -> Result<&(dyn ProcessHandler + Send + Sync), ProcessError> {
|
) -> Result<&(dyn ProcessHandler + Send + Sync), ProcessError> {
|
||||||
Ok(self
|
Ok(self
|
||||||
@ -194,25 +204,30 @@ impl ProcessManager<'_> {
|
|||||||
let (e_current, e_target) = e.0;
|
let (e_current, e_target) = e.0;
|
||||||
e_current == self.current_platform
|
e_current == self.current_platform
|
||||||
&& e_target == *target_platform
|
&& e_target == *target_platform
|
||||||
&& e.1.valid_for_platform(db_lock, target_platform)
|
&& e.1.valid_for_platform(db_lock, state, target_platform)
|
||||||
})
|
})
|
||||||
.ok_or(ProcessError::InvalidPlatform)?
|
.ok_or(ProcessError::InvalidPlatform)?
|
||||||
.1)
|
.1)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn valid_platform(&self, platform: &Platform) -> bool {
|
pub fn valid_platform(&self, platform: &Platform, state: &AppState) -> Result<bool, String> {
|
||||||
let db_lock = borrow_db_checked();
|
let db_lock = borrow_db_checked();
|
||||||
let process_handler = self.fetch_process_handler(&db_lock, platform);
|
let process_handler = self.fetch_process_handler(&db_lock, state, platform);
|
||||||
process_handler.is_ok()
|
Ok(process_handler.is_ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Must be called through spawn as it is currently blocking
|
pub fn launch_process(
|
||||||
pub fn launch_process(&mut self, game_id: String) -> Result<(), ProcessError> {
|
&mut self,
|
||||||
|
game_id: String,
|
||||||
|
state: &AppState,
|
||||||
|
) -> Result<(), ProcessError> {
|
||||||
if self.processes.contains_key(&game_id) {
|
if self.processes.contains_key(&game_id) {
|
||||||
return Err(ProcessError::AlreadyRunning);
|
return Err(ProcessError::AlreadyRunning);
|
||||||
}
|
}
|
||||||
|
|
||||||
let version = match borrow_db_checked()
|
let version = match DB
|
||||||
|
.borrow_data()
|
||||||
|
.unwrap()
|
||||||
.applications
|
.applications
|
||||||
.game_statuses
|
.game_statuses
|
||||||
.get(&game_id)
|
.get(&game_id)
|
||||||
@ -251,7 +266,7 @@ impl ProcessManager<'_> {
|
|||||||
debug!(
|
debug!(
|
||||||
"Launching process {:?} with version {:?}",
|
"Launching process {:?} with version {:?}",
|
||||||
&game_id,
|
&game_id,
|
||||||
db_lock.applications.game_versions.get(&game_id)
|
db_lock.applications.game_versions.get(&game_id).unwrap()
|
||||||
);
|
);
|
||||||
|
|
||||||
let game_version = db_lock
|
let game_version = db_lock
|
||||||
@ -289,7 +304,7 @@ impl ProcessManager<'_> {
|
|||||||
|
|
||||||
let target_platform = game_version.platform;
|
let target_platform = game_version.platform;
|
||||||
|
|
||||||
let process_handler = self.fetch_process_handler(&db_lock, &target_platform)?;
|
let process_handler = self.fetch_process_handler(&db_lock, state, &target_platform)?;
|
||||||
|
|
||||||
let (launch, args) = match game_status {
|
let (launch, args) = match game_status {
|
||||||
GameDownloadStatus::Installed {
|
GameDownloadStatus::Installed {
|
||||||
@ -307,9 +322,8 @@ impl ProcessManager<'_> {
|
|||||||
GameDownloadStatus::Remote {} => unreachable!("Game registered as 'Remote'"),
|
GameDownloadStatus::Remote {} => unreachable!("Game registered as 'Remote'"),
|
||||||
};
|
};
|
||||||
|
|
||||||
#[allow(clippy::unwrap_used)]
|
|
||||||
let launch = PathBuf::from_str(install_dir).unwrap().join(launch);
|
let launch = PathBuf::from_str(install_dir).unwrap().join(launch);
|
||||||
let launch = launch.display().to_string();
|
let launch = launch.to_str().unwrap();
|
||||||
|
|
||||||
let launch_string = process_handler.create_launch_process(
|
let launch_string = process_handler.create_launch_process(
|
||||||
&meta,
|
&meta,
|
||||||
@ -317,7 +331,7 @@ impl ProcessManager<'_> {
|
|||||||
args.clone(),
|
args.clone(),
|
||||||
game_version,
|
game_version,
|
||||||
install_dir,
|
install_dir,
|
||||||
)?;
|
);
|
||||||
|
|
||||||
let format_args = DropFormatArgs::new(
|
let format_args = DropFormatArgs::new(
|
||||||
launch_string,
|
launch_string,
|
||||||
@ -363,17 +377,32 @@ impl ProcessManager<'_> {
|
|||||||
.transient_statuses
|
.transient_statuses
|
||||||
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
.insert(meta.clone(), ApplicationTransientStatus::Running {});
|
||||||
|
|
||||||
// TODO
|
push_game_update(
|
||||||
// push_game_update(
|
&self.app_handle,
|
||||||
// &self.app_handle,
|
&meta.id,
|
||||||
// &meta.id,
|
None,
|
||||||
// None,
|
(None, Some(ApplicationTransientStatus::Running {})),
|
||||||
// (None, Some(ApplicationTransientStatus::Running {})),
|
);
|
||||||
// );
|
|
||||||
|
|
||||||
let wait_thread_handle = launch_process_handle.clone();
|
let wait_thread_handle = launch_process_handle.clone();
|
||||||
|
let wait_thread_apphandle = self.app_handle.clone();
|
||||||
let wait_thread_game_id = meta.clone();
|
let wait_thread_game_id = meta.clone();
|
||||||
|
|
||||||
|
spawn(move || {
|
||||||
|
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
|
||||||
|
|
||||||
|
let app_state = wait_thread_apphandle.state::<Mutex<AppState>>();
|
||||||
|
let app_state_handle = app_state.lock().unwrap();
|
||||||
|
|
||||||
|
let mut process_manager_handle = app_state_handle.process_manager.lock().unwrap();
|
||||||
|
process_manager_handle.on_process_finish(wait_thread_game_id.id, result);
|
||||||
|
|
||||||
|
// As everything goes out of scope, they should get dropped
|
||||||
|
// But just to explicit about it
|
||||||
|
drop(process_manager_handle);
|
||||||
|
drop(app_state_handle);
|
||||||
|
});
|
||||||
|
|
||||||
self.processes.insert(
|
self.processes.insert(
|
||||||
meta.id,
|
meta.id,
|
||||||
RunningProcess {
|
RunningProcess {
|
||||||
@ -382,12 +411,52 @@ impl ProcessManager<'_> {
|
|||||||
manually_killed: false,
|
manually_killed: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let result: Result<ExitStatus, std::io::Error> = launch_process_handle.wait();
|
#[derive(Eq, Hash, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]
|
||||||
|
pub enum Platform {
|
||||||
|
Windows,
|
||||||
|
Linux,
|
||||||
|
MacOs,
|
||||||
|
}
|
||||||
|
|
||||||
PROCESS_MANAGER
|
impl Platform {
|
||||||
.lock()
|
#[cfg(target_os = "windows")]
|
||||||
.on_process_finish(wait_thread_game_id.id, result)
|
pub const HOST: Platform = Self::Windows;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
pub const HOST: Platform = Self::MacOs;
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
pub const HOST: Platform = Self::Linux;
|
||||||
|
|
||||||
|
pub fn is_case_sensitive(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::Windows | Self::MacOs => false,
|
||||||
|
Self::Linux => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for Platform {
|
||||||
|
fn from(value: &str) -> Self {
|
||||||
|
match value.to_lowercase().trim() {
|
||||||
|
"windows" => Self::Windows,
|
||||||
|
"linux" => Self::Linux,
|
||||||
|
"mac" | "macos" => Self::MacOs,
|
||||||
|
_ => unimplemented!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<whoami::Platform> for Platform {
|
||||||
|
fn from(value: whoami::Platform) -> Self {
|
||||||
|
match value {
|
||||||
|
whoami::Platform::Windows => Platform::Windows,
|
||||||
|
whoami::Platform::Linux => Platform::Linux,
|
||||||
|
whoami::Platform::MacOS => Platform::MacOs,
|
||||||
|
_ => unimplemented!(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -399,7 +468,7 @@ pub trait ProcessHandler: Send + 'static {
|
|||||||
args: Vec<String>,
|
args: Vec<String>,
|
||||||
game_version: &GameVersion,
|
game_version: &GameVersion,
|
||||||
current_dir: &str,
|
current_dir: &str,
|
||||||
) -> Result<String, ProcessError>;
|
) -> String;
|
||||||
|
|
||||||
fn valid_for_platform(&self, db: &Database, target: &Platform) -> bool;
|
fn valid_for_platform(&self, db: &Database, state: &AppState, target: &Platform) -> bool;
|
||||||
}
|
}
|
||||||
@ -1,8 +1,10 @@
|
|||||||
use std::{io, path::PathBuf, sync::Arc};
|
use std::{path::PathBuf, sync::Arc};
|
||||||
|
|
||||||
use download_manager::error::ApplicationDownloadError;
|
use futures_lite::io;
|
||||||
use sysinfo::{Disk, DiskRefreshKind, Disks};
|
use sysinfo::{Disk, DiskRefreshKind, Disks};
|
||||||
|
|
||||||
|
use crate::error::application_download_error::ApplicationDownloadError;
|
||||||
|
|
||||||
pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownloadError> {
|
pub fn get_disk_available(mount_point: PathBuf) -> Result<u64, ApplicationDownloadError> {
|
||||||
let disks = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::nothing().with_storage());
|
let disks = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::nothing().with_storage());
|
||||||
|
|
||||||
224
src-tauri/src/remote/auth.rs
Normal file
224
src-tauri/src/remote/auth.rs
Normal file
@ -0,0 +1,224 @@
|
|||||||
|
use std::{collections::HashMap, env, sync::Mutex};
|
||||||
|
|
||||||
|
use chrono::Utc;
|
||||||
|
use droplet_rs::ssl::sign_nonce;
|
||||||
|
use gethostname::gethostname;
|
||||||
|
use log::{debug, error, warn};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
database::{
|
||||||
|
db::{borrow_db_checked, borrow_db_mut_checked},
|
||||||
|
models::data::DatabaseAuth,
|
||||||
|
}, error::{drop_server_error::DropServerError, remote_access_error::RemoteAccessError}, remote::{cache::clear_cached_object, requests::make_authenticated_get, utils::{DROP_CLIENT_ASYNC, DROP_CLIENT_SYNC}}, AppState, AppStatus, User
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
cache::{cache_object, get_cached_object},
|
||||||
|
requests::generate_url,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct CapabilityConfiguration {}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct InitiateRequestBody {
|
||||||
|
name: String,
|
||||||
|
platform: String,
|
||||||
|
capabilities: HashMap<String, CapabilityConfiguration>,
|
||||||
|
mode: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct HandshakeRequestBody {
|
||||||
|
client_id: String,
|
||||||
|
token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct HandshakeResponse {
|
||||||
|
private: String,
|
||||||
|
certificate: String,
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_authorization_header() -> String {
|
||||||
|
let certs = {
|
||||||
|
let db = borrow_db_checked();
|
||||||
|
db.auth.clone().unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
let nonce = Utc::now().timestamp_millis().to_string();
|
||||||
|
|
||||||
|
let signature = sign_nonce(certs.private, nonce.clone()).unwrap();
|
||||||
|
|
||||||
|
format!("Nonce {} {} {}", certs.client_id, nonce, signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_user() -> Result<User, RemoteAccessError> {
|
||||||
|
let response = make_authenticated_get(generate_url(&["/api/v1/client/user"], &[])?).await?;
|
||||||
|
if response.status() != 200 {
|
||||||
|
let err: DropServerError = response.json().await?;
|
||||||
|
warn!("{err:?}");
|
||||||
|
|
||||||
|
if err.status_message == "Nonce expired" {
|
||||||
|
return Err(RemoteAccessError::OutOfSync);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Err(RemoteAccessError::InvalidResponse(err));
|
||||||
|
}
|
||||||
|
|
||||||
|
response
|
||||||
|
.json::<User>()
|
||||||
|
.await
|
||||||
|
.map_err(std::convert::Into::into)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), RemoteAccessError> {
|
||||||
|
let path_chunks: Vec<&str> = path.split('/').collect();
|
||||||
|
if path_chunks.len() != 3 {
|
||||||
|
app.emit("auth/failed", ()).unwrap();
|
||||||
|
return Err(RemoteAccessError::HandshakeFailed(
|
||||||
|
"failed to parse token".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let base_url = {
|
||||||
|
let handle = borrow_db_checked();
|
||||||
|
Url::parse(handle.base_url.as_str())?
|
||||||
|
};
|
||||||
|
|
||||||
|
let client_id = path_chunks.get(1).unwrap();
|
||||||
|
let token = path_chunks.get(2).unwrap();
|
||||||
|
let body = HandshakeRequestBody {
|
||||||
|
client_id: (*client_id).to_string(),
|
||||||
|
token: (*token).to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let endpoint = base_url.join("/api/v1/client/auth/handshake")?;
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
let response = client.post(endpoint).json(&body).send().await?;
|
||||||
|
debug!("handshake responsded with {}", response.status().as_u16());
|
||||||
|
if !response.status().is_success() {
|
||||||
|
return Err(RemoteAccessError::InvalidResponse(response.json().await?));
|
||||||
|
}
|
||||||
|
let response_struct: HandshakeResponse = response.json().await?;
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut handle = borrow_db_mut_checked();
|
||||||
|
handle.auth = Some(DatabaseAuth {
|
||||||
|
private: response_struct.private,
|
||||||
|
cert: response_struct.certificate,
|
||||||
|
client_id: response_struct.id,
|
||||||
|
web_token: None, // gets created later
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let web_token = {
|
||||||
|
let header = generate_authorization_header();
|
||||||
|
let token = client
|
||||||
|
.post(base_url.join("/api/v1/client/user/webtoken").unwrap())
|
||||||
|
.header("Authorization", header)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
token.text().await.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut handle = borrow_db_mut_checked();
|
||||||
|
let mut_auth = handle.auth.as_mut().unwrap();
|
||||||
|
mut_auth.web_token = Some(web_token);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recieve_handshake(app: AppHandle, path: String) {
|
||||||
|
// Tell the app we're processing
|
||||||
|
app.emit("auth/processing", ()).unwrap();
|
||||||
|
|
||||||
|
let handshake_result = recieve_handshake_logic(&app, path).await;
|
||||||
|
if let Err(e) = handshake_result {
|
||||||
|
warn!("error with authentication: {e}");
|
||||||
|
app.emit("auth/failed", e.to_string()).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let app_state = app.state::<Mutex<AppState>>();
|
||||||
|
|
||||||
|
let (app_status, user) = setup().await;
|
||||||
|
|
||||||
|
let mut state_lock = app_state.lock().unwrap();
|
||||||
|
|
||||||
|
state_lock.status = app_status;
|
||||||
|
state_lock.user = user;
|
||||||
|
|
||||||
|
let _ = clear_cached_object("collections");
|
||||||
|
let _ = clear_cached_object("library");
|
||||||
|
|
||||||
|
drop(state_lock);
|
||||||
|
|
||||||
|
app.emit("auth/finished", ()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 endpoint = base_url.join("/api/v1/client/auth/initiate")?;
|
||||||
|
let body = InitiateRequestBody {
|
||||||
|
name: format!("{} (Desktop)", hostname.into_string().unwrap()),
|
||||||
|
platform: env::consts::OS.to_string(),
|
||||||
|
capabilities: HashMap::from([
|
||||||
|
("peerAPI".to_owned(), CapabilityConfiguration {}),
|
||||||
|
("cloudSaves".to_owned(), CapabilityConfiguration {}),
|
||||||
|
]),
|
||||||
|
mode,
|
||||||
|
};
|
||||||
|
|
||||||
|
let client = DROP_CLIENT_SYNC.clone();
|
||||||
|
let response = client.post(endpoint.to_string()).json(&body).send()?;
|
||||||
|
|
||||||
|
if response.status() != 200 {
|
||||||
|
let data: DropServerError = response.json()?;
|
||||||
|
error!("could not start handshake: {}", data.status_message);
|
||||||
|
|
||||||
|
return Err(RemoteAccessError::HandshakeFailed(data.status_message));
|
||||||
|
}
|
||||||
|
|
||||||
|
let response = response.text()?;
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn setup() -> (AppStatus, Option<User>) {
|
||||||
|
let auth = {
|
||||||
|
let data = borrow_db_checked();
|
||||||
|
data.auth.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
if auth.is_some() {
|
||||||
|
let user_result = match fetch_user().await {
|
||||||
|
Ok(data) => data,
|
||||||
|
Err(RemoteAccessError::FetchError(_)) => {
|
||||||
|
let user = get_cached_object::<User>("user").unwrap();
|
||||||
|
return (AppStatus::Offline, Some(user));
|
||||||
|
}
|
||||||
|
Err(_) => return (AppStatus::SignedInNeedsReauth, None),
|
||||||
|
};
|
||||||
|
cache_object("user", &user_result).unwrap();
|
||||||
|
return (AppStatus::SignedIn, Some(user_result));
|
||||||
|
}
|
||||||
|
|
||||||
|
(AppStatus::SignedOut, None)
|
||||||
|
}
|
||||||
@ -5,19 +5,18 @@ use std::{
|
|||||||
time::SystemTime,
|
time::SystemTime,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
database::{db::borrow_db_checked, models::data::Database},
|
||||||
|
error::remote_access_error::RemoteAccessError,
|
||||||
|
};
|
||||||
use bitcode::{Decode, DecodeOwned, Encode};
|
use bitcode::{Decode, DecodeOwned, Encode};
|
||||||
use database::{Database, borrow_db_checked};
|
|
||||||
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
use http::{Response, header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
||||||
|
|
||||||
use crate::error::{CacheError, RemoteAccessError};
|
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! offline {
|
macro_rules! offline {
|
||||||
($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => {
|
($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => {
|
||||||
|
|
||||||
async move {
|
async move { if $crate::borrow_db_checked().settings.force_offline || $var.lock().unwrap().status == $crate::AppStatus::Offline {
|
||||||
if ::database::borrow_db_checked().settings.force_offline
|
|
||||||
|| ::utils::lock!($var).status == ::client::app_status::AppStatus::Offline {
|
|
||||||
$func2( $( $arg ), *).await
|
$func2( $( $arg ), *).await
|
||||||
} else {
|
} else {
|
||||||
$func1( $( $arg ), *).await
|
$func1( $( $arg ), *).await
|
||||||
@ -83,7 +82,10 @@ pub fn get_cached_object_db<D: DecodeOwned>(
|
|||||||
pub fn clear_cached_object(key: &str) -> Result<(), RemoteAccessError> {
|
pub fn clear_cached_object(key: &str) -> Result<(), RemoteAccessError> {
|
||||||
clear_cached_object_db(key, &borrow_db_checked())
|
clear_cached_object_db(key, &borrow_db_checked())
|
||||||
}
|
}
|
||||||
pub fn clear_cached_object_db(key: &str, db: &Database) -> Result<(), RemoteAccessError> {
|
pub fn clear_cached_object_db(
|
||||||
|
key: &str,
|
||||||
|
db: &Database,
|
||||||
|
) -> Result<(), RemoteAccessError> {
|
||||||
delete_sync(&db.cache_dir, key).map_err(RemoteAccessError::Cache)?;
|
delete_sync(&db.cache_dir, key).map_err(RemoteAccessError::Cache)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -102,39 +104,30 @@ impl ObjectCache {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<Response<Vec<u8>>> for ObjectCache {
|
impl From<Response<Vec<u8>>> for ObjectCache {
|
||||||
type Error = CacheError;
|
fn from(value: Response<Vec<u8>>) -> Self {
|
||||||
|
ObjectCache {
|
||||||
fn try_from(value: Response<Vec<u8>>) -> Result<Self, Self::Error> {
|
|
||||||
Ok(ObjectCache {
|
|
||||||
content_type: value
|
content_type: value
|
||||||
.headers()
|
.headers()
|
||||||
.get(CONTENT_TYPE)
|
.get(CONTENT_TYPE)
|
||||||
.ok_or(CacheError::HeaderNotFound(CONTENT_TYPE))?
|
.unwrap()
|
||||||
.to_str()
|
.to_str()
|
||||||
.map_err(CacheError::ParseError)?
|
.unwrap()
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
body: value.body().clone(),
|
body: value.body().clone(),
|
||||||
expiry: get_sys_time_in_secs() + 60 * 60 * 24,
|
expiry: get_sys_time_in_secs() + 60 * 60 * 24,
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl TryFrom<ObjectCache> for Response<Vec<u8>> {
|
impl From<ObjectCache> for Response<Vec<u8>> {
|
||||||
type Error = CacheError;
|
fn from(value: ObjectCache) -> Self {
|
||||||
fn try_from(value: ObjectCache) -> Result<Self, Self::Error> {
|
|
||||||
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type);
|
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type);
|
||||||
resp_builder
|
resp_builder.body(value.body).unwrap()
|
||||||
.body(value.body)
|
|
||||||
.map_err(CacheError::ConstructionError)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl TryFrom<&ObjectCache> for Response<Vec<u8>> {
|
impl From<&ObjectCache> for Response<Vec<u8>> {
|
||||||
type Error = CacheError;
|
fn from(value: &ObjectCache) -> Self {
|
||||||
|
|
||||||
fn try_from(value: &ObjectCache) -> Result<Self, Self::Error> {
|
|
||||||
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type.clone());
|
let resp_builder = ResponseBuilder::new().header(CONTENT_TYPE, value.content_type.clone());
|
||||||
resp_builder
|
resp_builder.body(value.body.clone()).unwrap()
|
||||||
.body(value.body.clone())
|
|
||||||
.map_err(CacheError::ConstructionError)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1,50 +1,35 @@
|
|||||||
use std::{sync::Mutex, time::Duration};
|
use std::sync::Mutex;
|
||||||
|
|
||||||
use client::app_status::AppStatus;
|
|
||||||
use database::{borrow_db_checked, borrow_db_mut_checked};
|
|
||||||
use futures_lite::StreamExt;
|
use futures_lite::StreamExt;
|
||||||
use log::{debug, warn};
|
use log::{debug, warn};
|
||||||
use remote::{auth::{auth_initiate_logic, generate_authorization_header}, cache::{cache_object, get_cached_object}, error::RemoteAccessError, requests::generate_url, setup, utils::{DropHealthcheck, DROP_CLIENT_ASYNC, DROP_CLIENT_WS_CLIENT}};
|
|
||||||
use reqwest_websocket::{Message, RequestBuilderExt};
|
use reqwest_websocket::{Message, RequestBuilderExt};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tauri::{AppHandle, Emitter, Manager};
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use utils::{app_emit, lock, webbrowser_open::webbrowser_open};
|
|
||||||
|
|
||||||
use crate::{recieve_handshake, AppState};
|
use crate::{
|
||||||
|
AppState, AppStatus,
|
||||||
|
database::db::{borrow_db_checked, borrow_db_mut_checked},
|
||||||
|
error::remote_access_error::RemoteAccessError,
|
||||||
|
remote::{
|
||||||
|
auth::generate_authorization_header,
|
||||||
|
requests::generate_url,
|
||||||
|
utils::{DROP_CLIENT_SYNC, DROP_CLIENT_WS_CLIENT},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
auth::{auth_initiate_logic, recieve_handshake, setup},
|
||||||
|
cache::{cache_object, get_cached_object},
|
||||||
|
utils::use_remote_logic,
|
||||||
|
};
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn use_remote(
|
pub async fn use_remote(
|
||||||
url: String,
|
url: String,
|
||||||
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
) -> Result<(), RemoteAccessError> {
|
) -> Result<(), RemoteAccessError> {
|
||||||
debug!("connecting to url {url}");
|
use_remote_logic(url, state).await
|
||||||
let base_url = Url::parse(&url)?;
|
|
||||||
|
|
||||||
// Test Drop url
|
|
||||||
let test_endpoint = base_url.join("/api/v1")?;
|
|
||||||
let client = DROP_CLIENT_ASYNC.clone();
|
|
||||||
let response = client
|
|
||||||
.get(test_endpoint.to_string())
|
|
||||||
.timeout(Duration::from_secs(3))
|
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let result: DropHealthcheck = response.json().await?;
|
|
||||||
|
|
||||||
if result.app_name() != "Drop" {
|
|
||||||
warn!("user entered drop endpoint that connected, but wasn't identified as Drop");
|
|
||||||
return Err(RemoteAccessError::InvalidEndpoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut app_state = lock!(state);
|
|
||||||
app_state.status = AppStatus::SignedOut;
|
|
||||||
drop(app_state);
|
|
||||||
|
|
||||||
let mut db_state = borrow_db_mut_checked();
|
|
||||||
db_state.base_url = base_url.to_string();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -55,7 +40,7 @@ pub fn gen_drop_url(path: String) -> Result<String, RemoteAccessError> {
|
|||||||
Url::parse(&handle.base_url).map_err(RemoteAccessError::ParsingError)?
|
Url::parse(&handle.base_url).map_err(RemoteAccessError::ParsingError)?
|
||||||
};
|
};
|
||||||
|
|
||||||
let url = base_url.join(&path)?;
|
let url = base_url.join(&path).unwrap();
|
||||||
|
|
||||||
Ok(url.to_string())
|
Ok(url.to_string())
|
||||||
}
|
}
|
||||||
@ -64,7 +49,7 @@ pub fn gen_drop_url(path: String) -> Result<String, RemoteAccessError> {
|
|||||||
pub fn fetch_drop_object(path: String) -> Result<Vec<u8>, RemoteAccessError> {
|
pub fn fetch_drop_object(path: String) -> Result<Vec<u8>, RemoteAccessError> {
|
||||||
let _drop_url = gen_drop_url(path.clone())?;
|
let _drop_url = gen_drop_url(path.clone())?;
|
||||||
let req = generate_url(&[&path], &[])?;
|
let req = generate_url(&[&path], &[])?;
|
||||||
let req = remote::utils::DROP_CLIENT_SYNC
|
let req = DROP_CLIENT_SYNC
|
||||||
.get(req)
|
.get(req)
|
||||||
.header("Authorization", generate_authorization_header())
|
.header("Authorization", generate_authorization_header())
|
||||||
.send();
|
.send();
|
||||||
@ -92,20 +77,20 @@ pub fn sign_out(app: AppHandle) {
|
|||||||
// Update app state
|
// Update app state
|
||||||
{
|
{
|
||||||
let app_state = app.state::<Mutex<AppState>>();
|
let app_state = app.state::<Mutex<AppState>>();
|
||||||
let mut app_state_handle = lock!(app_state);
|
let mut app_state_handle = app_state.lock().unwrap();
|
||||||
app_state_handle.status = AppStatus::SignedOut;
|
app_state_handle.status = AppStatus::SignedOut;
|
||||||
app_state_handle.user = None;
|
app_state_handle.user = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emit event for frontend
|
// Emit event for frontend
|
||||||
app_emit!(app, "auth/signedout", ());
|
app.emit("auth/signedout", ()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState<'_>>>) -> Result<(), ()> {
|
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState<'_>>>) -> Result<(), ()> {
|
||||||
let (app_status, user) = setup().await;
|
let (app_status, user) = setup().await;
|
||||||
|
|
||||||
let mut guard = lock!(state);
|
let mut guard = state.lock().unwrap();
|
||||||
guard.status = app_status;
|
guard.status = app_status;
|
||||||
guard.user = user;
|
guard.user = user;
|
||||||
drop(guard);
|
drop(guard);
|
||||||
@ -124,7 +109,7 @@ pub fn auth_initiate() -> Result<(), RemoteAccessError> {
|
|||||||
let complete_redir_url = base_url.join(&redir_url)?;
|
let complete_redir_url = base_url.join(&redir_url)?;
|
||||||
|
|
||||||
debug!("opening web browser to continue authentication");
|
debug!("opening web browser to continue authentication");
|
||||||
webbrowser_open(complete_redir_url.as_ref());
|
webbrowser::open(complete_redir_url.as_ref()).unwrap();
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -139,7 +124,7 @@ struct CodeWebsocketResponse {
|
|||||||
pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
||||||
let base_url = {
|
let base_url = {
|
||||||
let db_lock = borrow_db_checked();
|
let db_lock = borrow_db_checked();
|
||||||
Url::parse(&db_lock.base_url.clone())?.clone()
|
Url::parse(&db_lock.base_url.clone())?
|
||||||
};
|
};
|
||||||
|
|
||||||
let code = auth_initiate_logic("code".to_string())?;
|
let code = auth_initiate_logic("code".to_string())?;
|
||||||
@ -166,13 +151,14 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
|||||||
match response.response_type.as_str() {
|
match response.response_type.as_str() {
|
||||||
"token" => {
|
"token" => {
|
||||||
let recieve_app = app.clone();
|
let recieve_app = app.clone();
|
||||||
manual_recieve_handshake(recieve_app, response.value).await;
|
manual_recieve_handshake(recieve_app, response.value).await.unwrap();
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
_ => return Err(RemoteAccessError::HandshakeFailed(response.value)),
|
_ => return Err(RemoteAccessError::HandshakeFailed(response.value)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Err(RemoteAccessError::HandshakeFailed(
|
Err(RemoteAccessError::HandshakeFailed(
|
||||||
"Failed to connect to websocket".to_string(),
|
"Failed to connect to websocket".to_string(),
|
||||||
))
|
))
|
||||||
@ -181,7 +167,7 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
|||||||
let result = load().await;
|
let result = load().await;
|
||||||
if let Err(err) = result {
|
if let Err(err) = result {
|
||||||
warn!("{err}");
|
warn!("{err}");
|
||||||
app_emit!(app, "auth/failed", err.to_string());
|
app.emit("auth/failed", err.to_string()).unwrap();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -189,6 +175,8 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn manual_recieve_handshake(app: AppHandle, token: String) {
|
pub async fn manual_recieve_handshake(app: AppHandle, token: String) -> Result<(), ()> {
|
||||||
recieve_handshake(app, format!("handshake/{token}")).await;
|
recieve_handshake(app, format!("handshake/{token}")).await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
51
src-tauri/src/remote/fetch_object.rs
Normal file
51
src-tauri/src/remote/fetch_object.rs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
use http::{header::CONTENT_TYPE, response::Builder as ResponseBuilder};
|
||||||
|
use log::warn;
|
||||||
|
use tauri::UriSchemeResponder;
|
||||||
|
|
||||||
|
use crate::{database::db::DatabaseImpls, remote::utils::DROP_CLIENT_ASYNC, DB};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
auth::generate_authorization_header,
|
||||||
|
cache::{ObjectCache, cache_object, get_cached_object},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub async fn fetch_object(request: http::Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
|
// Drop leading /
|
||||||
|
let object_id = &request.uri().path()[1..];
|
||||||
|
|
||||||
|
let cache_result = get_cached_object::<ObjectCache>(object_id);
|
||||||
|
if let Ok(cache_result) = &cache_result
|
||||||
|
&& !cache_result.has_expired()
|
||||||
|
{
|
||||||
|
responder.respond(cache_result.into());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let header = generate_authorization_header();
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
let url = format!("{}api/v1/client/object/{object_id}", DB.fetch_base_url());
|
||||||
|
let response = client.get(url).header("Authorization", header).send().await;
|
||||||
|
|
||||||
|
if response.is_err() {
|
||||||
|
match cache_result {
|
||||||
|
Ok(cache_result) => responder.respond(cache_result.into()),
|
||||||
|
Err(e) => {
|
||||||
|
warn!("{e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let response = response.unwrap();
|
||||||
|
|
||||||
|
let resp_builder = ResponseBuilder::new().header(
|
||||||
|
CONTENT_TYPE,
|
||||||
|
response.headers().get("Content-Type").unwrap(),
|
||||||
|
);
|
||||||
|
let data = Vec::from(response.bytes().await.unwrap());
|
||||||
|
let resp = resp_builder.body(data).unwrap();
|
||||||
|
if cache_result.is_err() || cache_result.unwrap().has_expired() {
|
||||||
|
cache_object::<ObjectCache>(object_id, &resp.clone().into()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
responder.respond(resp);
|
||||||
|
}
|
||||||
@ -1,10 +1,8 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
pub mod cache;
|
pub mod cache;
|
||||||
|
pub mod commands;
|
||||||
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;
|
|
||||||
@ -1,8 +1,10 @@
|
|||||||
use database::{interface::DatabaseImpls, DB};
|
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
auth::generate_authorization_header, error::RemoteAccessError, utils::DROP_CLIENT_ASYNC,
|
DB,
|
||||||
|
database::db::DatabaseImpls,
|
||||||
|
error::remote_access_error::RemoteAccessError,
|
||||||
|
remote::{auth::generate_authorization_header, utils::DROP_CLIENT_ASYNC},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn generate_url<T: AsRef<str>>(
|
pub fn generate_url<T: AsRef<str>>(
|
||||||
57
src-tauri/src/remote/server_proto.rs
Normal file
57
src-tauri/src/remote/server_proto.rs
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
use http::{uri::PathAndQuery, Request, Response, StatusCode, Uri};
|
||||||
|
use tauri::UriSchemeResponder;
|
||||||
|
|
||||||
|
use crate::{database::db::borrow_db_checked, remote::utils::DROP_CLIENT_SYNC};
|
||||||
|
|
||||||
|
pub async fn handle_server_proto_offline(_request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
|
let four_oh_four = Response::builder()
|
||||||
|
.status(StatusCode::NOT_FOUND)
|
||||||
|
.body(Vec::new())
|
||||||
|
.unwrap();
|
||||||
|
responder.respond(four_oh_four);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn handle_server_proto(request: Request<Vec<u8>>, responder: UriSchemeResponder) {
|
||||||
|
let db_handle = borrow_db_checked();
|
||||||
|
let web_token = match &db_handle.auth.as_ref().unwrap().web_token {
|
||||||
|
Some(e) => e,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
let remote_uri = db_handle.base_url.parse::<Uri>().unwrap();
|
||||||
|
|
||||||
|
let path = request.uri().path();
|
||||||
|
|
||||||
|
let mut new_uri = request.uri().clone().into_parts();
|
||||||
|
new_uri.path_and_query =
|
||||||
|
Some(PathAndQuery::from_str(&format!("{path}?noWrapper=true")).unwrap());
|
||||||
|
new_uri.authority = remote_uri.authority().cloned();
|
||||||
|
new_uri.scheme = remote_uri.scheme().cloned();
|
||||||
|
let new_uri = Uri::from_parts(new_uri).unwrap();
|
||||||
|
|
||||||
|
let whitelist_prefix = ["/store", "/api", "/_", "/fonts"];
|
||||||
|
|
||||||
|
if whitelist_prefix.iter().all(|f| !path.starts_with(f)) {
|
||||||
|
webbrowser::open(&new_uri.to_string()).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = DROP_CLIENT_SYNC.clone();
|
||||||
|
let response = client
|
||||||
|
.request(request.method().clone(), new_uri.to_string())
|
||||||
|
.header("Authorization", format!("Bearer {web_token}"))
|
||||||
|
.headers(request.headers().clone())
|
||||||
|
.send()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let response_status = response.status();
|
||||||
|
let response_body = response.bytes().unwrap();
|
||||||
|
|
||||||
|
let http_response = Response::builder()
|
||||||
|
.status(response_status)
|
||||||
|
.body(response_body.to_vec())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
responder.respond(http_response);
|
||||||
|
}
|
||||||
133
src-tauri/src/remote/utils.rs
Normal file
133
src-tauri/src/remote/utils.rs
Normal file
@ -0,0 +1,133 @@
|
|||||||
|
use std::{
|
||||||
|
fs::{self, File},
|
||||||
|
io::{self, Read},
|
||||||
|
sync::{LazyLock, Mutex},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use log::{debug, info, warn};
|
||||||
|
use reqwest::Certificate;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
AppState, AppStatus,
|
||||||
|
database::db::{DATA_ROOT_DIR, borrow_db_mut_checked},
|
||||||
|
error::remote_access_error::RemoteAccessError,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DropHealthcheck {
|
||||||
|
app_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
static DROP_CERT_BUNDLE: LazyLock<Vec<Certificate>> = LazyLock::new(|| {
|
||||||
|
fetch_certificates().unwrap_or_else(|e| panic!("Failed to fetch certificates with error {}", e))
|
||||||
|
});
|
||||||
|
pub static DROP_CLIENT_SYNC: LazyLock<reqwest::blocking::Client> = LazyLock::new(get_client_sync);
|
||||||
|
pub static DROP_CLIENT_ASYNC: LazyLock<reqwest::Client> = LazyLock::new(get_client_async);
|
||||||
|
pub static DROP_CLIENT_WS_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(get_client_ws);
|
||||||
|
|
||||||
|
fn fetch_certificates() -> Result<Vec<Certificate>, io::Error> {
|
||||||
|
let certificate_dir = DATA_ROOT_DIR.join("certificates");
|
||||||
|
|
||||||
|
let mut certs = Vec::new();
|
||||||
|
match fs::read_dir(&certificate_dir) {
|
||||||
|
Ok(c) => {
|
||||||
|
for entry in c {
|
||||||
|
match entry {
|
||||||
|
Ok(c) => {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
File::open(c.path())?.read_to_end(&mut buf)?;
|
||||||
|
|
||||||
|
for cert in match Certificate::from_pem_bundle(&buf) {
|
||||||
|
Ok(certificates) => certificates,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Could not parse pem bundle with error {}. Skipping", e);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} {
|
||||||
|
certs.push(cert);
|
||||||
|
}
|
||||||
|
info!(
|
||||||
|
"added {} certificate(s) from {}",
|
||||||
|
certs.len(),
|
||||||
|
c.file_name().display().to_string()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!(
|
||||||
|
"Could not open directory entry {} in certificates with error {}",
|
||||||
|
certificate_dir.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
debug!("not loading certificates due to error: {e}");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(certs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_client_sync() -> reqwest::blocking::Client {
|
||||||
|
let mut client = reqwest::blocking::ClientBuilder::new();
|
||||||
|
|
||||||
|
for cert in DROP_CERT_BUNDLE.iter() {
|
||||||
|
client = client.add_root_certificate(cert.clone());
|
||||||
|
}
|
||||||
|
client.use_rustls_tls().build().unwrap()
|
||||||
|
}
|
||||||
|
pub fn get_client_async() -> reqwest::Client {
|
||||||
|
let mut client = reqwest::ClientBuilder::new();
|
||||||
|
|
||||||
|
for cert in DROP_CERT_BUNDLE.iter() {
|
||||||
|
client = client.add_root_certificate(cert.clone());
|
||||||
|
}
|
||||||
|
client.use_rustls_tls().build().unwrap()
|
||||||
|
}
|
||||||
|
pub fn get_client_ws() -> reqwest::Client {
|
||||||
|
let mut client = reqwest::ClientBuilder::new();
|
||||||
|
|
||||||
|
for cert in DROP_CERT_BUNDLE.iter() {
|
||||||
|
client = client.add_root_certificate(cert.clone());
|
||||||
|
}
|
||||||
|
client.use_rustls_tls().http1_only().build().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn use_remote_logic(
|
||||||
|
url: String,
|
||||||
|
state: tauri::State<'_, Mutex<AppState<'_>>>,
|
||||||
|
) -> Result<(), RemoteAccessError> {
|
||||||
|
debug!("connecting to url {url}");
|
||||||
|
let base_url = Url::parse(&url)?;
|
||||||
|
|
||||||
|
// Test Drop url
|
||||||
|
let test_endpoint = base_url.join("/api/v1")?;
|
||||||
|
let client = DROP_CLIENT_ASYNC.clone();
|
||||||
|
let response = client
|
||||||
|
.get(test_endpoint.to_string())
|
||||||
|
.timeout(Duration::from_secs(3))
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let result: DropHealthcheck = response.json().await?;
|
||||||
|
|
||||||
|
if result.app_name != "Drop" {
|
||||||
|
warn!("user entered drop endpoint that connected, but wasn't identified as Drop");
|
||||||
|
return Err(RemoteAccessError::InvalidEndpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut app_state = state.lock().unwrap();
|
||||||
|
app_state.status = AppStatus::SignedOut;
|
||||||
|
drop(app_state);
|
||||||
|
|
||||||
|
let mut db_state = borrow_db_mut_checked();
|
||||||
|
db_state.base_url = base_url.to_string();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user