chore: Ran cargo clippy & cargo fmt

This commit is contained in:
quexeky
2025-01-20 08:55:19 +11:00
parent 7d4651db69
commit 92729701c3
26 changed files with 144 additions and 126 deletions

View File

@ -12,11 +12,9 @@ pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mut
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"),
}
Ok(res) => match res {
Ok(_) => debug!("download manager terminated correctly"),
Err(_) => error!("download manager failed to terminate correctly"),
},
Err(e) => panic!("{:?}", e),
}

View File

@ -1,9 +1,4 @@
use tauri::AppHandle;
use crate::{
autostart::{get_autostart_enabled_logic, toggle_autostart_logic},
AppState,
};
use crate::AppState;
#[tauri::command]
pub fn fetch_state(

View File

@ -6,9 +6,15 @@ use std::{
use serde_json::Value;
use crate::{database::{db::borrow_db_mut_checked, settings::Settings}, download_manager::{download_manager::DownloadManagerSignal, internal_error::InternalError}, DB};
use crate::{
database::{db::borrow_db_mut_checked, settings::Settings},
download_manager::internal_error::InternalError,
};
use super::{db::{borrow_db_checked, save_db, DATA_ROOT_DIR}, debug::SystemData};
use super::{
db::{borrow_db_checked, save_db, DATA_ROOT_DIR},
debug::SystemData,
};
// Will, in future, return disk/remaining size
// Just returns the directories that have been set up
@ -36,7 +42,8 @@ pub fn add_download_dir(new_dir: PathBuf) -> Result<(), InternalError<()>> {
return Err(Error::new(
ErrorKind::DirectoryNotEmpty,
"Selected directory cannot contain any existing files",
).into());
)
.into());
}
} else {
create_dir_all(new_dir_path)?;
@ -48,7 +55,8 @@ pub fn add_download_dir(new_dir: PathBuf) -> Result<(), InternalError<()>> {
return Err(Error::new(
ErrorKind::AlreadyExists,
"Selected directory already exists in database",
).into());
)
.into());
}
lock.applications.install_dirs.push(new_dir);
drop(lock);

View File

@ -1,7 +1,7 @@
use std::{
collections::HashMap,
fs::{self, create_dir_all},
path::{Path, PathBuf},
path::PathBuf,
sync::{LazyLock, Mutex, RwLockReadGuard, RwLockWriteGuard},
};
@ -187,28 +187,30 @@ fn handle_invalid_database(
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.set_file_name(format!("drop.db.backup-{}", time));
base
};
info!("old database stored at: {}", new_path.to_string_lossy().to_string());
info!(
"old database stored at: {}",
new_path.to_string_lossy().to_string()
);
fs::rename(&db_path, &new_path).unwrap();
let db = Database::new(
games_base_dir.into_os_string().into_string().unwrap(),
Some(new_path.into()),
Some(new_path),
);
PathDatabase::create_at_path(db_path, db).expect("Database could not be created")
}
pub fn borrow_db_checked<'a>() -> RwLockReadGuard<'a, Database> {
match DB.borrow_data() {
Ok(data) => data,
Err(e) => {
error!("database borrow failed with error {}", e);
panic!("database borrow failed with error {}", e);
},
}
}
}
@ -224,10 +226,10 @@ pub fn borrow_db_mut_checked<'a>() -> RwLockWriteGuard<'a, Database> {
pub fn save_db() {
match DB.save() {
Ok(_) => {},
Ok(_) => {}
Err(e) => {
error!("database failed to save with error {}", e);
panic!("database failed to save with error {}", e)
},
}
}
}
}

View File

@ -1,4 +1,3 @@
use crate::{DATA_ROOT_DIR, DB};
use serde::Serialize;
#[derive(Serialize)]

View File

@ -1,4 +1,4 @@
use std::sync::{mpsc::SendError, Arc, Mutex};
use std::sync::Mutex;
use crate::{download_manager::downloadable_metadata::DownloadableMetadata, AppState};

View File

@ -3,7 +3,8 @@ use std::{
collections::VecDeque,
fmt::Debug,
sync::{
mpsc::{SendError, Sender}, Mutex, MutexGuard
mpsc::{SendError, Sender},
Mutex, MutexGuard,
},
thread::JoinHandle,
};
@ -150,7 +151,10 @@ impl DownloadManager {
.unwrap();
}
debug!("moving download at index {} to index {}", current_index, new_index);
debug!(
"moving download at index {} to index {}",
current_index, new_index
);
let mut queue = self.edit();
let to_move = queue.remove(current_index).unwrap();

View File

@ -5,13 +5,13 @@ use serde_with::SerializeDisplay;
#[derive(SerializeDisplay)]
pub enum InternalError<T> {
IOError(io::Error),
SignalError(SendError<T>)
SignalError(SendError<T>),
}
impl<T> Display for InternalError<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InternalError::IOError(error) => write!(f, "{}", error.to_string()),
InternalError::SignalError(send_error) => write!(f, "{}", send_error.to_string()),
InternalError::IOError(error) => write!(f, "{}", error),
InternalError::SignalError(send_error) => write!(f, "{}", send_error),
}
}
}
@ -24,4 +24,4 @@ impl<T> From<io::Error> for InternalError<T> {
fn from(value: io::Error) -> Self {
InternalError::IOError(value)
}
}
}

View File

@ -4,7 +4,7 @@ pub mod download_manager_builder;
pub mod download_thread_control_flag;
pub mod downloadable;
pub mod downloadable_metadata;
pub mod internal_error;
pub mod progress_object;
pub mod queue;
pub mod rolling_progress_updates;
pub mod internal_error;

View File

@ -2,16 +2,17 @@ use std::{
sync::{
atomic::{AtomicUsize, Ordering},
mpsc::Sender,
Arc, Mutex, RwLock,
Arc, Mutex,
},
time::{Duration, Instant},
};
use atomic_instant_full::AtomicInstant;
use log::info;
use throttle_my_fn::throttle;
use super::{download_manager::DownloadManagerSignal, rolling_progress_updates::RollingProgressWindow};
use super::{
download_manager::DownloadManagerSignal, rolling_progress_updates::RollingProgressWindow,
};
#[derive(Clone)]
pub struct ProgressObject {
@ -22,7 +23,7 @@ pub struct ProgressObject {
//last_update: Arc<RwLock<Instant>>,
last_update_time: Arc<AtomicInstant>,
bytes_last_update: Arc<AtomicUsize>,
rolling: RollingProgressWindow<1024>
rolling: RollingProgressWindow<256>,
}
pub struct ProgressHandle {
@ -43,7 +44,7 @@ impl ProgressHandle {
pub fn add(&self, amount: usize) {
self.progress
.fetch_add(amount, std::sync::atomic::Ordering::Relaxed);
calculate_update(&self.progress_object, amount);
calculate_update(&self.progress_object);
}
}
@ -63,8 +64,6 @@ impl ProgressObject {
}
}
pub fn set_time_now(&self) {
*self.start.lock().unwrap() = Instant::now();
}
@ -97,25 +96,27 @@ impl ProgressObject {
}
}
#[throttle(1, Duration::from_millis(20))]
pub fn calculate_update(progress: &ProgressObject, amount_added: usize) {
let last_update_time = progress.last_update_time.swap(Instant::now(), Ordering::SeqCst);
pub fn calculate_update(progress_object: &ProgressObject) {
let last_update_time = progress_object
.last_update_time
.swap(Instant::now(), Ordering::SeqCst);
let time_since_last_update = Instant::now().duration_since(last_update_time).as_millis();
let current_bytes_downloaded = progress.sum();
let max = progress.get_max();
let bytes_at_last_update = progress.bytes_last_update.swap(current_bytes_downloaded, Ordering::Relaxed);
let current_bytes_downloaded = progress_object.sum();
let max = progress_object.get_max();
let bytes_at_last_update = progress_object
.bytes_last_update
.swap(current_bytes_downloaded, Ordering::Relaxed);
let bytes_since_last_update = current_bytes_downloaded - bytes_at_last_update;
let kilobytes_per_second =
bytes_since_last_update / (time_since_last_update as usize).max(1);
let kilobytes_per_second = bytes_since_last_update / (time_since_last_update as usize).max(1);
let bytes_remaining = max - current_bytes_downloaded; // bytes
progress.update_window(kilobytes_per_second);
push_update(progress, bytes_remaining);
progress_object.update_window(kilobytes_per_second);
push_update(progress_object, bytes_remaining);
}
#[throttle(1, Duration::from_millis(500))]
@ -123,7 +124,6 @@ pub fn push_update(progress: &ProgressObject, bytes_remaining: usize) {
let average_speed = progress.rolling.get_average();
let time_remaining = (bytes_remaining / 1000) / average_speed.max(1);
update_ui(progress, average_speed, time_remaining);
update_queue(progress);
}
@ -143,4 +143,4 @@ fn update_queue(progress: &ProgressObject) {
.sender
.send(DownloadManagerSignal::UpdateUIQueue)
.unwrap();
}
}

View File

@ -32,7 +32,7 @@ impl Queue {
pub fn pop_front(&self) -> Option<DownloadableMetadata> {
self.edit().pop_front()
}
pub fn empty(&self) -> bool {
pub fn is_empty(&self) -> bool {
self.inner.lock().unwrap().len() == 0
}
pub fn exists(&self, meta: DownloadableMetadata) -> bool {
@ -52,10 +52,7 @@ impl Queue {
}
pub fn pop_front_if_equal(&self, meta: &DownloadableMetadata) -> Option<DownloadableMetadata> {
let mut queue = self.edit();
let front = match queue.front() {
Some(front) => front,
None => return None,
};
let front = queue.front()?;
if front == meta {
return queue.pop_front();
}

View File

@ -12,7 +12,7 @@ impl<const S: usize> RollingProgressWindow<S> {
pub fn new() -> Self {
Self {
window: Arc::new([(); S].map(|_| AtomicUsize::new(0))),
current: Arc::new(AtomicUsize::new(0))
current: Arc::new(AtomicUsize::new(0)),
}
}
pub fn update(&self, kilobytes_per_second: usize) {
@ -22,6 +22,12 @@ impl<const S: usize> RollingProgressWindow<S> {
}
pub fn get_average(&self) -> usize {
let current = self.current.load(Ordering::SeqCst);
self.window.iter().enumerate().filter(|(i, _)| i < &current).map(|(_, x)| x.load(Ordering::Relaxed)).sum::<usize>() / S
self.window
.iter()
.enumerate()
.filter(|(i, _)| i < &current)
.map(|(_, x)| x.load(Ordering::Relaxed))
.sum::<usize>()
/ S
}
}

View File

@ -3,9 +3,7 @@ use std::sync::Mutex;
use tauri::AppHandle;
use crate::{
error::{
library_error::LibraryError, remote_access_error::RemoteAccessError,
},
error::{library_error::LibraryError, remote_access_error::RemoteAccessError},
games::library::{get_current_meta, uninstall_game_logic},
AppState,
};

View File

@ -1,7 +1,10 @@
use std::sync::{mpsc::SendError, Arc, Mutex};
use std::sync::{Arc, Mutex};
use crate::{
download_manager::{download_manager::DownloadManagerSignal, downloadable::Downloadable, internal_error::InternalError},
download_manager::{
download_manager::DownloadManagerSignal, downloadable::Downloadable,
internal_error::InternalError,
},
AppState,
};

View File

@ -1,6 +1,7 @@
use crate::auth::generate_authorization_header;
use crate::database::db::{
borrow_db_checked, set_game_status, ApplicationTransientStatus, DatabaseImpls, GameDownloadStatus
borrow_db_checked, set_game_status, ApplicationTransientStatus, DatabaseImpls,
GameDownloadStatus,
};
use crate::download_manager::download_manager::{DownloadManagerSignal, DownloadStatus};
use crate::download_manager::download_thread_control_flag::{
@ -18,7 +19,6 @@ use crate::DB;
use log::{debug, error, info};
use rayon::ThreadPoolBuilder;
use slice_deque::SliceDeque;
use std::collections::HashMap;
use std::fs::{create_dir_all, File};
use std::path::Path;
use std::sync::mpsc::Sender;
@ -275,17 +275,18 @@ impl GameDownloadAgent {
let sender = self.sender.clone();
// TODO: Error handling
let request = make_request(&client, &[
"/api/v1/client/chunk"
], &[
("id", &context.game_id),
("version", &context.version),
("name", &context.file_name),
("chunk", &context.index.to_string()),
],
|r| {
r.header("Authorization", generate_authorization_header())
}).unwrap();
let request = make_request(
&client,
&["/api/v1/client/chunk"],
&[
("id", &context.game_id),
("version", &context.version),
("name", &context.file_name),
("chunk", &context.index.to_string()),
],
|r| r.header("Authorization", generate_authorization_header()),
)
.unwrap();
scope.spawn(move |_| {
match download_game_chunk(context, &self.control_flag, progress_handle, request)
@ -315,10 +316,12 @@ impl GameDownloadAgent {
completed_contexts_lock.len()
};
// If we're not out of contexts, we're not done, so we don't fire completed
if completed_lock_len != contexts.len() {
info!("download agent for {} exited without completing", self.id.clone());
info!(
"download agent for {} exited without completing",
self.id.clone()
);
self.stored_manifest
.set_completed_contexts(self.completed_contexts.lock().unwrap().as_slice());
self.stored_manifest.write();

View File

@ -5,7 +5,7 @@ use crate::download_manager::progress_object::ProgressHandle;
use crate::error::application_download_error::ApplicationDownloadError;
use crate::error::remote_access_error::RemoteAccessError;
use crate::games::downloads::manifest::DropDownloadContext;
use log::{error, warn};
use log::warn;
use md5::{Context, Digest};
use reqwest::blocking::{RequestBuilder, Response};
@ -177,7 +177,6 @@ pub fn download_game_chunk(
set_permissions(ctx.path.clone(), permissions).unwrap();
}
let checksum = pipeline
.finish()
.map_err(|e| ApplicationDownloadError::IoError(e.kind()))?;

View File

@ -2,7 +2,7 @@ use std::fs::remove_dir_all;
use std::sync::Mutex;
use std::thread::spawn;
use log::{debug, error, info, warn};
use log::{debug, error, warn};
use serde::{Deserialize, Serialize};
use tauri::Emitter;
use tauri::{AppHandle, Manager};
@ -139,9 +139,10 @@ pub fn fetch_game_logic(
return Ok(data);
}
let client = reqwest::blocking::Client::new();
let response = make_request(&client, &["/api/v1/game/", &id],&[], |r| {
let response = make_request(&client, &["/api/v1/game/", &id], &[], |r| {
r.header("Authorization", generate_authorization_header())
})?.send()?;
})?
.send()?;
if response.status() == 404 {
return Err(RemoteAccessError::GameNotFound);
@ -179,10 +180,14 @@ pub fn fetch_game_verion_options_logic(
state: tauri::State<'_, Mutex<AppState>>,
) -> Result<Vec<GameVersionOption>, RemoteAccessError> {
let client = reqwest::blocking::Client::new();
let response = make_request(&client, &["/api/v1/client/game/versions"], &[("id", &game_id)], |r| {
r.header("Authorization", generate_authorization_header())
})?.send()?;
let response = make_request(
&client,
&["/api/v1/client/game/versions"],
&[("id", &game_id)],
|r| r.header("Authorization", generate_authorization_header()),
)?
.send()?;
if response.status() != 200 {
let err = response.json().unwrap();

View File

@ -1,7 +1,4 @@
use crate::{
database::db::{borrow_db_checked, ApplicationTransientStatus, GameDownloadStatus},
DB,
};
use crate::database::db::{borrow_db_checked, ApplicationTransientStatus, GameDownloadStatus};
pub type GameStatusWithTransient = (
Option<GameDownloadStatus>,

View File

@ -16,9 +16,12 @@ use autostart::{get_autostart_enabled, toggle_autostart};
use cleanup::{cleanup_and_exit, quit};
use commands::fetch_state;
use database::commands::{
add_download_dir, delete_download_dir, fetch_download_dir_stats, fetch_system_data, fetch_settings, update_settings
add_download_dir, delete_download_dir, fetch_download_dir_stats, fetch_settings,
fetch_system_data, update_settings,
};
use database::db::{
borrow_db_checked, borrow_db_mut_checked, DatabaseInterface, GameDownloadStatus, DATA_ROOT_DIR,
};
use database::db::{borrow_db_checked, borrow_db_mut_checked, DatabaseInterface, GameDownloadStatus, DATA_ROOT_DIR};
use download_manager::commands::{
cancel_game, move_download_in_queue, pause_downloads, resume_downloads,
};
@ -44,13 +47,13 @@ use remote::commands::{
auth_initiate, gen_drop_url, manual_recieve_handshake, retry_connect, sign_out, use_remote,
};
use serde::{Deserialize, Serialize};
use tauri::ipc::IpcResponse;
use std::path::Path;
use std::sync::Arc;
use std::{
collections::HashMap,
sync::{LazyLock, Mutex},
};
use tauri::ipc::IpcResponse;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
use tauri::tray::TrayIconBuilder;
use tauri::{AppHandle, Manager, RunEvent, WindowEvent};
@ -100,7 +103,9 @@ fn setup(handle: AppHandle) -> AppState<'static> {
.unwrap();
let console = ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new("{d} | {l} | {f}:{L} - {m}{n}")))
.encoder(Box::new(PatternEncoder::new(
"{d} | {l} | {f}:{L} - {m}{n}",
)))
.build();
let config = Config::builder()

View File

@ -1,9 +1,6 @@
use std::sync::Mutex;
use crate::{
error::process_error::ProcessError,
AppState,
};
use crate::{error::process_error::ProcessError, AppState};
#[tauri::command]
pub fn launch_game(

View File

@ -15,7 +15,9 @@ use tauri::{AppHandle, Manager};
use umu_wrapper_lib::command_builder::UmuCommandBuilder;
use crate::{
database::db::{borrow_db_mut_checked, ApplicationTransientStatus, GameDownloadStatus, DATA_ROOT_DIR},
database::db::{
borrow_db_mut_checked, ApplicationTransientStatus, GameDownloadStatus, DATA_ROOT_DIR,
},
download_manager::downloadable_metadata::{DownloadType, DownloadableMetadata},
error::process_error::ProcessError,
games::{library::push_game_update, state::GameStatusManager},
@ -83,7 +85,7 @@ impl ProcessManager<'_> {
(absolute_exe, Vec::new())
}
pub fn kill_game(&mut self, game_id: String) -> Result<(), io::Error> {
return match self.processes.get(&game_id) {
match self.processes.get(&game_id) {
Some(child) => {
child.kill()?;
child.wait()?;
@ -93,7 +95,7 @@ impl ProcessManager<'_> {
io::ErrorKind::NotFound,
"Game ID not running",
)),
};
}
}
fn on_process_finish(&mut self, game_id: String, result: Result<ExitStatus, std::io::Error>) {
@ -166,9 +168,9 @@ impl ProcessManager<'_> {
{
Some(GameDownloadStatus::Installed { version_name, .. }) => version_name,
Some(GameDownloadStatus::SetupRequired { .. }) => {
return Err(ProcessError::SetupRequired).into()
return Err(ProcessError::SetupRequired)
}
_ => return Err(ProcessError::NotInstalled).into(),
_ => return Err(ProcessError::NotInstalled),
};
let meta = DownloadableMetadata {
id: game_id.clone(),
@ -192,7 +194,7 @@ impl ProcessManager<'_> {
GameDownloadStatus::Installed {
version_name,
install_dir,
} => Some((&version_name, &install_dir)),
} => Some((version_name, install_dir)),
GameDownloadStatus::SetupRequired {
version_name,
install_dir,

View File

@ -1,14 +1,16 @@
use std::{env, sync::Mutex};
use chrono::Utc;
use log::{debug, error, info, warn};
use log::{debug, error, warn};
use openssl::{ec::EcKey, hash::MessageDigest, pkey::PKey, sign::Signer};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager};
use url::Url;
use crate::{
database::db::{borrow_db_checked, borrow_db_mut_checked, save_db, DatabaseAuth, DatabaseImpls},
database::db::{
borrow_db_checked, borrow_db_mut_checked, save_db, DatabaseAuth, DatabaseImpls,
},
error::{drop_server_error::DropServerError, remote_access_error::RemoteAccessError},
AppState, AppStatus, User, DB,
};

View File

@ -4,7 +4,9 @@ use tauri::{AppHandle, Emitter, Manager};
use url::Url;
use crate::{
database::db::{borrow_db_checked, borrow_db_mut_checked, save_db}, error::remote_access_error::RemoteAccessError, AppState, AppStatus, DB
database::db::{borrow_db_checked, borrow_db_mut_checked, save_db},
error::remote_access_error::RemoteAccessError,
AppState, AppStatus,
};
use super::{
@ -17,7 +19,7 @@ pub fn use_remote(
url: String,
state: tauri::State<'_, Mutex<AppState<'_>>>,
) -> Result<(), RemoteAccessError> {
Ok(use_remote_logic(url, state)?)
use_remote_logic(url, state)
}
#[tauri::command]
@ -67,7 +69,7 @@ pub fn retry_connect(state: tauri::State<'_, Mutex<AppState>>) {
#[tauri::command]
pub fn auth_initiate() -> Result<(), RemoteAccessError> {
auth_initiate_logic().into()
auth_initiate_logic()
}
#[tauri::command]

View File

@ -1,4 +1,4 @@
pub mod auth;
pub mod commands;
pub mod remote;
pub mod requests;
pub mod requests;

View File

@ -1,15 +1,14 @@
use std::{
error::Error,
fmt::{Display, Formatter},
sync::{Arc, Mutex},
};
use std::sync::Mutex;
use http::StatusCode;
use log::{debug, info, warn};
use log::{debug, warn};
use serde::Deserialize;
use url::{ParseError, Url};
use url::Url;
use crate::{database::db::{borrow_db_mut_checked, save_db}, error::remote_access_error::RemoteAccessError, AppState, AppStatus, DB};
use crate::{
database::db::{borrow_db_mut_checked, save_db},
error::remote_access_error::RemoteAccessError,
AppState, AppStatus,
};
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]

View File

@ -1,11 +1,8 @@
use std::ops::Deref;
use reqwest::blocking::{Client, RequestBuilder, Response};
use url::{ParseError, Url};
use reqwest::blocking::{Client, RequestBuilder};
use crate::{database::db::DatabaseImpls, error::remote_access_error::RemoteAccessError, DB};
pub fn make_request<'a, T: AsRef<str>, F: FnOnce(RequestBuilder) -> RequestBuilder>(
pub fn make_request<T: AsRef<str>, F: FnOnce(RequestBuilder) -> RequestBuilder>(
client: &Client,
endpoints: &[T],
params: &[(T, T)],