refactor: Builds, but some logic still left to move back

Signed-off-by: quexeky <git@quexeky.dev>
This commit is contained in:
quexeky
2025-10-12 18:33:43 +11:00
parent 5d22b883d5
commit 9e1bf9852f
24 changed files with 254 additions and 185 deletions

5
Cargo.lock generated
View File

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

View File

@ -358,6 +358,15 @@ pub mod data {
compat_info: None,
}
}
}
impl DatabaseAuth {
pub fn new(private: String, cert: String, client_id: String, web_token: Option<String>) -> Self {
Self {
private,
cert,
client_id,
web_token,
}
}
}
}

View File

@ -370,7 +370,7 @@ impl DownloadManagerBuilder {
fn push_ui_stats_update(&self, kbs: usize, time: usize) {
let event_data = StatsUpdateEvent { speed: kbs, time };
app_emit!(self.app_handle, "update_stats", event_data);
app_emit!(&self.app_handle, "update_stats", event_data);
}
fn push_ui_queue_update(&self) {
let queue = &self.download_queue.read();
@ -389,6 +389,6 @@ impl DownloadManagerBuilder {
.collect();
let event_data = QueueUpdateEvent { queue: queue_objs };
app_emit!(self.app_handle, "update_queue", event_data);
app_emit!(&self.app_handle, "update_queue", event_data);
}
}

View File

@ -80,6 +80,7 @@ pub enum DownloadStatus {
/// The actual download queue may be accessed through the .`edit()` function,
/// which provides raw access to the underlying queue.
/// THIS EDITING IS BLOCKING!!!
#[derive(Debug)]
pub struct DownloadManager {
terminator: Mutex<Option<JoinHandle<Result<(), ()>>>>,
download_queue: Queue,

View File

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

View File

@ -15,7 +15,7 @@ use crate::download_manager_frontend::DownloadManagerSignal;
use super::rolling_progress_updates::RollingProgressWindow;
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct ProgressObject {
max: Arc<Mutex<usize>>,
progress_instances: Arc<Mutex<Vec<Arc<AtomicUsize>>>>,

View File

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

View File

@ -3,7 +3,7 @@ use std::sync::{
atomic::{AtomicUsize, Ordering},
};
#[derive(Clone)]
#[derive(Clone, Debug)]
pub struct RollingProgressWindow<const S: usize> {
window: Arc<[AtomicUsize; S]>,
current: Arc<AtomicUsize>,

View File

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

View File

@ -168,7 +168,7 @@ pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle)
);
debug!("uninstalled game id {}", &meta.id);
app_emit!(app_handle, "update_library", ());
app_emit!(&app_handle, "update_library", ());
}
});
} else {
@ -284,41 +284,8 @@ pub struct FrontendGameOptions {
launch_string: String,
}
#[tauri::command]
pub fn update_game_configuration(
game_id: String,
options: FrontendGameOptions,
) -> Result<(), LibraryError> {
let mut handle = borrow_db_mut_checked();
let installed_version = handle
.applications
.installed_game_version
.get(&game_id)
.ok_or(LibraryError::MetaNotFound(game_id))?;
let id = installed_version.id.clone();
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
let mut existing_configuration = handle
.applications
.game_versions
.get(&id)
.unwrap()
.get(&version)
.unwrap()
.clone();
// Add more options in here
existing_configuration.launch_command_template = options.launch_string;
// Add no more options past here
handle
.applications
.game_versions
.get_mut(&id)
.unwrap()
.insert(version.to_string(), existing_configuration);
Ok(())
impl FrontendGameOptions {
pub fn launch_string(&self) -> &String {
&self.launch_string
}
}

View File

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

View File

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

View File

@ -17,7 +17,7 @@ macro_rules! offline {
async move {
if ::database::borrow_db_checked().settings.force_offline
|| ::utils::lock!($var).status == ::client::app_status::AppStatus::Offline {
|| $var.lock().status == ::client::app_status::AppStatus::Offline {
$func2( $( $arg ), *).await
} else {
$func1( $( $arg ), *).await

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
use std::sync::Mutex;
use std::sync::nonpoison::Mutex;
use database::{borrow_db_checked, borrow_db_mut_checked, GameDownloadStatus, GameVersion};
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, Game}, state::{GameStatusManager, GameStatusWithTransient}};
use games::{downloads::error::LibraryError, library::{get_current_meta, uninstall_game_logic, FetchGameStruct, FrontendGameOptions, 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};
@ -13,7 +13,7 @@ use crate::AppState;
#[tauri::command]
pub async fn fetch_library(
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
hard_refresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
offline!(
@ -27,7 +27,7 @@ pub async fn fetch_library(
pub async fn fetch_library_logic(
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
hard_fresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
let do_hard_refresh = hard_fresh.unwrap_or(false);
@ -54,7 +54,7 @@ pub async fn fetch_library_logic(
let mut games: Vec<Game> = response.json().await?;
let mut handle = lock!(state);
let mut handle = state.lock();
let mut db_handle = borrow_db_mut_checked();
@ -95,7 +95,7 @@ pub async fn fetch_library_logic(
Ok(games)
}
pub async fn fetch_library_logic_offline(
_state: tauri::State<'_, Mutex<AppState<'_>>>,
_state: tauri::State<'_, Mutex<AppState>>,
_hard_refresh: Option<bool>,
) -> Result<Vec<Game>, RemoteAccessError> {
let mut games: Vec<Game> = get_cached_object("library")?;
@ -117,10 +117,10 @@ pub async fn fetch_library_logic_offline(
}
pub async fn fetch_game_logic(
id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
let version = {
let state_handle = lock!(state);
let state_handle = state.lock();
let db_lock = borrow_db_checked();
@ -173,7 +173,7 @@ pub async fn fetch_game_logic(
let game: Game = response.json().await?;
let mut state_handle = lock!(state);
let mut state_handle = state.lock();
state_handle.games.insert(id.clone(), game.clone());
let mut db_handle = borrow_db_mut_checked();
@ -197,7 +197,7 @@ pub async fn fetch_game_logic(
pub async fn fetch_game_version_options_logic(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<Vec<GameVersion>, RemoteAccessError> {
let client = DROP_CLIENT_ASYNC.clone();
@ -216,7 +216,7 @@ pub async fn fetch_game_version_options_logic(
let data: Vec<GameVersion> = response.json().await?;
let state_lock = lock!(state);
let state_lock = state.lock();
let process_manager_lock = PROCESS_MANAGER.lock();
let data: Vec<GameVersion> = data
.into_iter()
@ -231,7 +231,7 @@ pub async fn fetch_game_version_options_logic(
pub async fn fetch_game_logic_offline(
id: String,
_state: tauri::State<'_, Mutex<AppState<'_>>>,
_state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
let db_handle = borrow_db_checked();
let metadata_option = db_handle.applications.installed_game_version.get(&id);
@ -256,7 +256,7 @@ pub async fn fetch_game_logic_offline(
#[tauri::command]
pub async fn fetch_game(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<FetchGameStruct, RemoteAccessError> {
offline!(
state,
@ -287,7 +287,46 @@ pub fn uninstall_game(game_id: String, app_handle: AppHandle) -> Result<(), Libr
#[tauri::command]
pub async fn fetch_game_version_options(
game_id: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<Vec<GameVersion>, RemoteAccessError> {
fetch_game_version_options_logic(game_id, state).await
}
#[tauri::command]
pub fn update_game_configuration(
game_id: String,
options: FrontendGameOptions,
) -> Result<(), LibraryError> {
let mut handle = borrow_db_mut_checked();
let installed_version = handle
.applications
.installed_game_version
.get(&game_id)
.ok_or(LibraryError::MetaNotFound(game_id))?;
let id = installed_version.id.clone();
let version = installed_version.version.clone().ok_or(LibraryError::VersionNotFound(id.clone()))?;
let mut existing_configuration = handle
.applications
.game_versions
.get(&id)
.unwrap()
.get(&version)
.unwrap()
.clone();
// Add more options in here
existing_configuration.launch_command_template = options.launch_string().clone();
// Add no more options past here
handle
.applications
.game_versions
.get_mut(&id)
.unwrap()
.insert(version.to_string(), existing_configuration);
Ok(())
}

View File

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

View File

@ -12,15 +12,15 @@ pub fn launch_game(
id: String,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), ProcessError> {
let state_lock = lock!(state);
let process_manager_lock = PROCESS_MANAGER.lock();
let state_lock = state.lock();
let mut process_manager_lock = PROCESS_MANAGER.lock();
//let meta = DownloadableMetadata {
// id,
// version: Some(version),
// download_type: DownloadType::Game,
//};
match process_manager_lock.launch_process(id, &state_lock) {
match process_manager_lock.launch_process(id) {
Ok(()) => {}
Err(e) => return Err(e),
}

View File

@ -1,4 +1,4 @@
use std::{sync::Mutex, time::Duration};
use std::{sync::nonpoison::Mutex, time::Duration};
use client::app_status::AppStatus;
use database::{borrow_db_checked, borrow_db_mut_checked};
@ -16,7 +16,7 @@ use crate::{recieve_handshake, AppState};
#[tauri::command]
pub async fn use_remote(
url: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<(), RemoteAccessError> {
debug!("connecting to url {url}");
let base_url = Url::parse(&url)?;
@ -37,7 +37,7 @@ pub async fn use_remote(
return Err(RemoteAccessError::InvalidEndpoint);
}
let mut app_state = lock!(state);
let mut app_state = state.lock();
app_state.status = AppStatus::SignedOut;
drop(app_state);
@ -91,21 +91,21 @@ pub fn sign_out(app: AppHandle) {
// Update app state
{
let app_state = app.state::<Mutex<AppState>>();
let mut app_state_handle = lock!(app_state);
let state = app.state::<Mutex<AppState>>();
let mut app_state_handle = state.lock();
app_state_handle.status = AppStatus::SignedOut;
app_state_handle.user = None;
}
// Emit event for frontend
app_emit!(app, "auth/signedout", ());
app_emit!(&app, "auth/signedout", ());
}
#[tauri::command]
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState<'_>>>) -> Result<(), ()> {
pub async fn retry_connect(state: tauri::State<'_, Mutex<AppState>>) -> Result<(), ()> {
let (app_status, user) = setup().await;
let mut guard = lock!(state);
let mut guard = state.lock();
guard.status = app_status;
guard.user = user;
drop(guard);
@ -181,7 +181,7 @@ pub fn auth_initiate_code(app: AppHandle) -> Result<String, RemoteAccessError> {
let result = load().await;
if let Err(err) = result {
warn!("{err}");
app_emit!(app, "auth/failed", err.to_string());
app_emit!(&app, "auth/failed", err.to_string());
}
});

View File

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

View File

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