Implement better error system and segregate errors and commands (#23)
* chore: Progress on amend_settings command Signed-off-by: quexeky <git@quexeky.dev> * chore(errors): Progress on better error handling with segragation of files * chore: Progress on amend_settings command Signed-off-by: quexeky <git@quexeky.dev> * chore(commands): Separated commands under each subdirectory into respective commands.rs files Signed-off-by: quexeky <git@quexeky.dev> * chore(errors): Almost all errors and commands have been segregated * chore(errors): Added drop server error Signed-off-by: quexeky <git@quexeky.dev> * feat(core): Update to using nightly compiler Signed-off-by: quexeky <git@quexeky.dev> * chore(errors): More progress on error handling Signed-off-by: quexeky <git@quexeky.dev> * chore(errors): Implementing Try and FromResidual for UserValue Signed-off-by: quexeky <git@quexeky.dev> * refactor(errors): Segregated errors and commands from code, and made commands return UserValue struct Signed-off-by: quexeky <git@quexeky.dev> * fix(errors): Added missing files * chore(errors): Convert match statement to map_err * feat(settings): Implemented settings editing from UI * feat(errors): Clarified return values from retry_connect command * chore(errors): Moved autostart commands to autostart.rs * chore(process manager): Converted launch_process function for games to use game_id --------- Signed-off-by: quexeky <git@quexeky.dev>
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
use std::{
|
||||
fs::create_dir_all,
|
||||
io::{Error, ErrorKind},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{database::settings::Settings, error::user_error::UserValue, DB};
|
||||
|
||||
use super::{db::DATA_ROOT_DIR, debug::SystemData};
|
||||
|
||||
// Will, in future, return disk/remaining size
|
||||
// Just returns the directories that have been set up
|
||||
#[tauri::command]
|
||||
pub fn fetch_download_dir_stats() -> Vec<PathBuf> {
|
||||
let lock = DB.borrow_data().unwrap();
|
||||
lock.applications.install_dirs.clone()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_download_dir(index: usize) {
|
||||
let mut lock = DB.borrow_data_mut().unwrap();
|
||||
lock.applications.install_dirs.remove(index);
|
||||
drop(lock);
|
||||
DB.save().unwrap();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn add_download_dir(new_dir: PathBuf) -> UserValue<(), Error> {
|
||||
// Check the new directory is all good
|
||||
let new_dir_path = Path::new(&new_dir);
|
||||
if new_dir_path.exists() {
|
||||
let dir_contents = new_dir_path.read_dir()?;
|
||||
if dir_contents.count() != 0 {
|
||||
return UserValue::Err(Error::new(
|
||||
ErrorKind::DirectoryNotEmpty,
|
||||
"Selected directory cannot contain any existing files",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
create_dir_all(new_dir_path)?;
|
||||
}
|
||||
|
||||
// Add it to the dictionary
|
||||
let mut lock = DB.borrow_data_mut().unwrap();
|
||||
if lock.applications.install_dirs.contains(&new_dir) {
|
||||
return UserValue::Err(Error::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
"Selected directory already exists in database",
|
||||
));
|
||||
}
|
||||
lock.applications.install_dirs.push(new_dir);
|
||||
drop(lock);
|
||||
DB.save().unwrap();
|
||||
|
||||
UserValue::Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn update_settings(new_settings: Value) {
|
||||
println!("{}", new_settings);
|
||||
let mut db_lock = DB.borrow_data_mut().unwrap();
|
||||
let mut current_settings = serde_json::to_value(db_lock.settings.clone()).unwrap();
|
||||
for (key, value) in new_settings.as_object().unwrap() {
|
||||
current_settings[key] = value.clone();
|
||||
}
|
||||
println!("New settings unset: {}", ¤t_settings);
|
||||
let new_settings: Settings = serde_json::from_value(current_settings).unwrap();
|
||||
db_lock.settings = new_settings;
|
||||
println!("New Settings: {:?}", db_lock.settings);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn fetch_system_data() -> SystemData {
|
||||
let db_handle = DB.borrow_data().unwrap();
|
||||
SystemData::new(
|
||||
db_handle.auth.as_ref().unwrap().client_id.clone(),
|
||||
db_handle.base_url.clone(),
|
||||
DATA_ROOT_DIR.lock().unwrap().to_string_lossy().to_string(),
|
||||
std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, create_dir_all},
|
||||
path::{Path, PathBuf},
|
||||
sync::{LazyLock, Mutex, RwLockWriteGuard},
|
||||
};
|
||||
|
||||
use chrono::Utc;
|
||||
use directories::BaseDirs;
|
||||
use log::{debug, info};
|
||||
use rustbreak::{DeSerError, DeSerializer, PathDatabase, RustbreakError};
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
use serde_with::serde_as;
|
||||
use tauri::AppHandle;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
database::settings::Settings,
|
||||
download_manager::downloadable_metadata::DownloadableMetadata,
|
||||
games::{library::push_game_update, state::GameStatusManager},
|
||||
process::process_manager::Platform,
|
||||
DB,
|
||||
};
|
||||
|
||||
#[derive(serde::Serialize, Clone, Deserialize)]
|
||||
pub struct DatabaseAuth {
|
||||
pub private: String,
|
||||
pub cert: String,
|
||||
pub client_id: String,
|
||||
}
|
||||
|
||||
// Strings are version names for a particular game
|
||||
#[derive(Serialize, Clone, Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum GameDownloadStatus {
|
||||
Remote {},
|
||||
SetupRequired {
|
||||
version_name: String,
|
||||
install_dir: String,
|
||||
},
|
||||
Installed {
|
||||
version_name: String,
|
||||
install_dir: String,
|
||||
},
|
||||
}
|
||||
|
||||
// Stuff that shouldn't be synced to disk
|
||||
#[derive(Clone, Serialize)]
|
||||
pub enum ApplicationTransientStatus {
|
||||
Downloading { version_name: String },
|
||||
Uninstalling {},
|
||||
Updating { version_name: String },
|
||||
Running {},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GameVersion {
|
||||
pub version_index: usize,
|
||||
pub version_name: String,
|
||||
pub launch_command: String,
|
||||
pub setup_command: String,
|
||||
pub platform: Platform,
|
||||
}
|
||||
|
||||
#[serde_as]
|
||||
#[derive(Serialize, Clone, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DatabaseApplications {
|
||||
pub install_dirs: Vec<PathBuf>,
|
||||
// Guaranteed to exist if the game also exists in the app state map
|
||||
pub game_statuses: HashMap<String, GameDownloadStatus>,
|
||||
pub game_versions: HashMap<String, HashMap<String, GameVersion>>,
|
||||
pub installed_game_version: HashMap<String, DownloadableMetadata>,
|
||||
|
||||
#[serde(skip)]
|
||||
pub transient_statuses: HashMap<DownloadableMetadata, ApplicationTransientStatus>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
pub struct Database {
|
||||
#[serde(default)]
|
||||
pub settings: Settings,
|
||||
pub auth: Option<DatabaseAuth>,
|
||||
pub base_url: String,
|
||||
pub applications: DatabaseApplications,
|
||||
pub prev_database: Option<PathBuf>,
|
||||
}
|
||||
impl Database {
|
||||
fn new<T: Into<PathBuf>>(games_base_dir: T, prev_database: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
applications: DatabaseApplications {
|
||||
install_dirs: vec![games_base_dir.into()],
|
||||
..Default::default()
|
||||
},
|
||||
prev_database,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
pub static DATA_ROOT_DIR: LazyLock<Mutex<PathBuf>> =
|
||||
LazyLock::new(|| Mutex::new(BaseDirs::new().unwrap().data_dir().join("drop")));
|
||||
|
||||
// Custom JSON serializer to support everything we need
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DropDatabaseSerializer;
|
||||
|
||||
impl<T: Serialize + DeserializeOwned> DeSerializer<T> for DropDatabaseSerializer {
|
||||
fn serialize(&self, val: &T) -> rustbreak::error::DeSerResult<Vec<u8>> {
|
||||
serde_json::to_vec(val).map_err(|e| DeSerError::Internal(e.to_string()))
|
||||
}
|
||||
|
||||
fn deserialize<R: std::io::Read>(&self, s: R) -> rustbreak::error::DeSerResult<T> {
|
||||
serde_json::from_reader(s).map_err(|e| DeSerError::Internal(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub type DatabaseInterface =
|
||||
rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer>;
|
||||
|
||||
pub trait DatabaseImpls {
|
||||
fn set_up_database() -> DatabaseInterface;
|
||||
fn database_is_set_up(&self) -> bool;
|
||||
fn fetch_base_url(&self) -> Url;
|
||||
}
|
||||
impl DatabaseImpls for DatabaseInterface {
|
||||
fn set_up_database() -> DatabaseInterface {
|
||||
let data_root_dir = DATA_ROOT_DIR.lock().unwrap();
|
||||
let db_path = data_root_dir.join("drop.db");
|
||||
let games_base_dir = data_root_dir.join("games");
|
||||
let logs_root_dir = data_root_dir.join("logs");
|
||||
|
||||
debug!("Creating data directory at {:?}", data_root_dir);
|
||||
create_dir_all(data_root_dir.clone()).unwrap();
|
||||
create_dir_all(games_base_dir.clone()).unwrap();
|
||||
create_dir_all(logs_root_dir.clone()).unwrap();
|
||||
|
||||
let exists = fs::exists(db_path.clone()).unwrap();
|
||||
|
||||
match exists {
|
||||
true => match PathDatabase::load_from_path(db_path.clone()) {
|
||||
Ok(db) => db,
|
||||
Err(e) => handle_invalid_database(e, db_path, games_base_dir),
|
||||
},
|
||||
false => {
|
||||
let default = Database::new(games_base_dir, None);
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn database_is_set_up(&self) -> bool {
|
||||
!self.borrow_data().unwrap().base_url.is_empty()
|
||||
}
|
||||
|
||||
fn fetch_base_url(&self) -> Url {
|
||||
let handle = self.borrow_data().unwrap();
|
||||
Url::parse(&handle.base_url).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_game_status<F: FnOnce(&mut RwLockWriteGuard<'_, Database>, &DownloadableMetadata)>(
|
||||
app_handle: &AppHandle,
|
||||
meta: DownloadableMetadata,
|
||||
setter: F,
|
||||
) {
|
||||
let mut db_handle = DB.borrow_data_mut().unwrap();
|
||||
setter(&mut db_handle, &meta);
|
||||
drop(db_handle);
|
||||
DB.save().unwrap();
|
||||
|
||||
let status = GameStatusManager::fetch_state(&meta.id);
|
||||
|
||||
push_game_update(app_handle, &meta.id, status);
|
||||
}
|
||||
// TODO: Make the error relelvant rather than just assume that it's a Deserialize error
|
||||
fn handle_invalid_database(
|
||||
_e: RustbreakError,
|
||||
db_path: PathBuf,
|
||||
games_base_dir: PathBuf,
|
||||
) -> rustbreak::Database<Database, rustbreak::backend::PathBackend, DropDatabaseSerializer> {
|
||||
let new_path = {
|
||||
let time = Utc::now().timestamp();
|
||||
let mut base = db_path.clone();
|
||||
base.set_file_name(format!("drop.db.backup-{}", time.to_string()));
|
||||
base
|
||||
};
|
||||
info!("{:?}", new_path);
|
||||
fs::rename(&db_path, &new_path).unwrap();
|
||||
|
||||
let db = Database::new(
|
||||
games_base_dir.into_os_string().into_string().unwrap(),
|
||||
Some(new_path.into()),
|
||||
);
|
||||
|
||||
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::{DATA_ROOT_DIR, DB};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SystemData {
|
||||
client_id: String,
|
||||
base_url: String,
|
||||
data_dir: String,
|
||||
log_level: String,
|
||||
}
|
||||
|
||||
impl SystemData {
|
||||
pub fn new(client_id: String, base_url: String, data_dir: String, log_level: String) -> Self {
|
||||
Self {
|
||||
client_id,
|
||||
base_url,
|
||||
data_dir,
|
||||
log_level,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod commands;
|
||||
pub mod db;
|
||||
pub mod debug;
|
||||
pub mod settings;
|
||||
@@ -0,0 +1,24 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Settings {
|
||||
pub autostart: bool,
|
||||
pub max_download_threads: usize,
|
||||
// ... other settings ...
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
autostart: false,
|
||||
max_download_threads: 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ideally use pointers instead of a macro to assign the settings
|
||||
// fn deserialize_into<T>(v: serde_json::Value, t: &mut T) -> Result<(), serde_json::Error>
|
||||
// where T: for<'a> Deserialize<'a>
|
||||
// {
|
||||
// *t = serde_json::from_value(v)?;
|
||||
// Ok(())
|
||||
// }
|
||||
Reference in New Issue
Block a user