refactor: Ran cargo clippy & cargo fmt

This commit is contained in:
Louis van Liefland
2024-12-09 20:32:42 +11:00
parent 01260f0732
commit 653717ebcf
14 changed files with 52 additions and 57 deletions

View File

@ -1,5 +1,7 @@
use std::{
borrow::BorrowMut, env, sync::Mutex, time::{SystemTime, UNIX_EPOCH}
env,
sync::Mutex,
time::{SystemTime, UNIX_EPOCH},
};
use log::{info, warn};
@ -9,7 +11,7 @@ use tauri::{AppHandle, Emitter, Manager};
use url::Url;
use crate::{
db::{self, DatabaseAuth, DatabaseImpls},
db::{DatabaseAuth, DatabaseImpls},
remote::RemoteAccessError,
AppState, AppStatus, User, DB,
};

View File

@ -10,7 +10,6 @@ use log::debug;
use rustbreak::{DeSerError, DeSerializer, PathDatabase};
use rustix::path::Arg;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
use url::Url;
use crate::DB;
@ -100,7 +99,8 @@ impl DatabaseImpls for DatabaseInterface {
#[allow(clippy::let_and_return)]
let exists = fs::exists(db_path.clone()).unwrap();
let db = match exists {
match exists {
true => PathDatabase::load_from_path(db_path).expect("Database loading failed"),
false => {
let default = Database {
@ -116,9 +116,7 @@ impl DatabaseImpls for DatabaseInterface {
PathDatabase::create_at_path(db_path, default)
.expect("Database could not be created")
}
};
db
}
}
fn database_is_set_up(&self) -> bool {

View File

@ -179,7 +179,7 @@ impl GameDownloadAgent {
drop(context_lock);
self.generate_contexts()?;
return Ok(());
Ok(())
}
pub fn generate_contexts(&self) -> Result<(), GameDownloadError> {
@ -208,7 +208,7 @@ impl GameDownloadAgent {
for (i, length) in chunk.lengths.iter().enumerate() {
contexts.push(DropDownloadContext {
file_name: raw_path.to_string(),
version: chunk.versionName.to_string(),
version: chunk.version_name.to_string(),
offset: running_offset,
index: i,
game_id: game_id.to_string(),
@ -257,13 +257,12 @@ impl GameDownloadAgent {
scope.spawn(move |_| {
match download_game_chunk(context.clone(), control_flag, progress_handle) {
Ok(res) => match res {
true => {
Ok(res) => {
if res {
let mut lock = completed_indexes_ref.lock().unwrap();
lock.push(index);
}
false => {}
},
}
Err(e) => {
error!("GameDownloadError: {}", e);
self.sender.send(DownloadManagerSignal::Error(e)).unwrap();

View File

@ -1,7 +1,5 @@
use std::sync::Mutex;
use log::info;
use crate::AppState;
#[tauri::command]
@ -42,8 +40,10 @@ pub fn move_game_in_queue(
.rearrange(old_index, new_index)
}
/*
#[tauri::command]
pub fn get_current_write_speed(state: tauri::State<'_, Mutex<AppState>>) {}
*/
/*
fn use_download_agent(

View File

@ -3,23 +3,21 @@ use crate::db::DatabaseImpls;
use crate::downloads::manifest::DropDownloadContext;
use crate::remote::RemoteAccessError;
use crate::DB;
use log::{info, warn};
use log::warn;
use md5::{Context, Digest};
use reqwest::blocking::Response;
use std::io::Read;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{
fs::{File, OpenOptions},
io::{self, BufWriter, ErrorKind, Seek, SeekFrom, Write},
io::{self, BufWriter, Seek, SeekFrom, Write},
path::PathBuf,
sync::Arc,
};
use urlencoding::encode;
use super::download_agent::GameDownloadError;
use super::download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag};
use super::progress_object::{ProgressHandle, ProgressObject};
use super::progress_object::ProgressHandle;
pub struct DropWriter<W: Write> {
hasher: Context,
@ -182,7 +180,7 @@ pub fn download_game_chunk(
content_length.unwrap().try_into().unwrap(),
);
let completed = pipeline.copy().map_err(|e| GameDownloadError::IoError(e))?;
let completed = pipeline.copy().map_err(GameDownloadError::IoError)?;
if !completed {
return Ok(false);
};

View File

@ -91,6 +91,7 @@ impl Debug for GameDownloadAgentQueueStandin {
}
}
#[allow(dead_code)]
impl DownloadManager {
pub fn new(
terminator: JoinHandle<Result<(), ()>>,

View File

@ -120,7 +120,7 @@ impl DownloadManagerBuilder {
&format!("update_game/{}", id),
GameUpdateEvent {
game_id: id,
status: status,
status,
},
)
.unwrap();
@ -145,7 +145,7 @@ impl DownloadManagerBuilder {
self.download_queue.pop_front();
let download_agent = self.download_agent_registry.remove(game_id).unwrap();
self.cleanup_current_download();
return download_agent;
download_agent
}
// CAREFUL WITH THIS FUNCTION

View File

@ -4,12 +4,13 @@ use std::path::PathBuf;
pub type DropManifest = HashMap<String, DropChunk>;
#[derive(Serialize, Deserialize, Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DropChunk {
pub permissions: usize,
pub ids: Vec<String>,
pub checksums: Vec<String>,
pub lengths: Vec<usize>,
pub versionName: String,
pub version_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@ -21,5 +22,5 @@ pub struct DropDownloadContext {
pub game_id: String,
pub path: PathBuf,
pub checksum: String,
pub length: usize
pub length: usize,
}

View File

@ -1,9 +1,9 @@
pub mod download_agent;
pub mod download_commands;
mod download_logic;
pub mod download_manager_builder;
pub mod download_manager;
pub mod download_manager_builder;
mod download_thread_control_flag;
mod manifest;
mod progress_object;
pub mod queue;
pub mod queue;

View File

@ -68,7 +68,7 @@ impl ProgressObject {
.fetch_add(amount_added, Ordering::Relaxed);
let to_update_handle = self.points_to_push_update.lock().unwrap();
let to_update = to_update_handle.clone();
let to_update = *to_update_handle;
drop(to_update_handle);
if current_amount < to_update {

View File

@ -10,6 +10,7 @@ pub struct Queue {
inner: Arc<Mutex<VecDeque<Arc<GameDownloadAgentQueueStandin>>>>,
}
#[allow(dead_code)]
impl Queue {
pub fn new() -> Self {
Self {
@ -40,7 +41,10 @@ impl Queue {
pub fn append(&self, interface: GameDownloadAgentQueueStandin) {
self.edit().push_back(Arc::new(interface));
}
pub fn pop_front_if_equal(&self, game_id: String) -> Option<Arc<GameDownloadAgentQueueStandin>> {
pub fn pop_front_if_equal(
&self,
game_id: String,
) -> Option<Arc<GameDownloadAgentQueueStandin>> {
let mut queue = self.edit();
let front = match queue.front() {
Some(front) => front,
@ -49,7 +53,7 @@ impl Queue {
if front.id == game_id {
return queue.pop_front();
}
return None;
None
}
pub fn get_by_id(&self, game_id: String) -> Option<usize> {
self.read().iter().position(|data| data.id == game_id)

View File

@ -2,7 +2,7 @@ mod auth;
mod db;
mod downloads;
mod library;
mod p2p;
// mod p2p;
mod remote;
mod settings;
#[cfg(test)]
@ -21,7 +21,7 @@ use env_logger::Env;
use http::{header::*, response::Builder as ResponseBuilder};
use library::{fetch_game, fetch_game_status, fetch_game_verion_options, fetch_library, Game};
use log::{debug, info};
use remote::{gen_drop_url, use_remote, RemoteAccessError};
use remote::{gen_drop_url, use_remote};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::{

View File

@ -1,17 +1,13 @@
use std::collections::{HashMap, VecDeque};
use std::fmt::format;
use std::sync::Mutex;
use log::info;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tauri::Emitter;
use tauri::{AppHandle, Manager};
use urlencoding::encode;
use crate::db::DatabaseGameStatus;
use crate::db::DatabaseImpls;
use crate::db::{self, GameVersion};
use crate::db::GameVersion;
use crate::downloads::download_manager::GameDownloadStatus;
use crate::remote::RemoteAccessError;
use crate::{auth::generate_authorization_header, AppState, DB};
@ -159,12 +155,11 @@ fn fetch_game_logic(
let mut db_handle = DB.borrow_data_mut().unwrap();
if !db_handle.games.games_statuses.contains_key(&id) {
db_handle
.games
.games_statuses
.insert(id, DatabaseGameStatus::Remote {});
}
db_handle
.games
.games_statuses
.entry(id)
.or_insert(DatabaseGameStatus::Remote {});
let data = FetchGameStruct {
game: game.clone(),
@ -176,7 +171,7 @@ fn fetch_game_logic(
.clone(),
};
return Ok(data);
Ok(data)
}
#[tauri::command]
@ -201,7 +196,7 @@ pub fn fetch_game_status(id: String) -> Result<DatabaseGameStatus, String> {
.clone();
drop(db_handle);
return Ok(status);
Ok(status)
}
fn fetch_game_verion_options_logic(
@ -227,7 +222,7 @@ fn fetch_game_verion_options_logic(
let data = response.json::<Vec<GameVersionOption>>()?;
return Ok(data);
Ok(data)
}
#[tauri::command]
@ -266,7 +261,7 @@ pub fn on_game_complete(
.games
.game_versions
.entry(game_id.clone())
.or_insert(HashMap::new())
.or_default()
.insert(version_name.clone(), data.clone());
drop(handle);
DB.save().unwrap();
@ -287,10 +282,7 @@ pub fn on_game_complete(
app_handle
.emit(
&format!("update_game/{}", game_id),
GameUpdateEvent {
game_id: game_id,
status: status,
},
GameUpdateEvent { game_id, status },
)
.unwrap();

View File

@ -5,7 +5,7 @@ use std::{
use http::StatusCode;
use log::{info, warn};
use serde::{Deserialize, Serialize};
use serde::Deserialize;
use url::{ParseError, Url};
use crate::{AppState, AppStatus, DB};
@ -20,7 +20,7 @@ pub enum RemoteAccessError {
GameNotFound,
InvalidResponse,
InvalidRedirect,
ManifestDownloadFailed(StatusCode, String)
ManifestDownloadFailed(StatusCode, String),
}
impl Display for RemoteAccessError {
@ -36,10 +36,10 @@ impl Display for RemoteAccessError {
RemoteAccessError::GameNotFound => write!(f, "Could not find game on server"),
RemoteAccessError::InvalidResponse => write!(f, "Server returned an invalid response"),
RemoteAccessError::InvalidRedirect => write!(f, "Server redirect was invalid"),
RemoteAccessError::ManifestDownloadFailed(status, response) =>
write!(f, "Failed to download game manifest: {} {}",
status,
response
RemoteAccessError::ManifestDownloadFailed(status, response) => write!(
f,
"Failed to download game manifest: {} {}",
status, response
),
}
}