diff --git a/desktop/.github/workflows/clippy.yml b/desktop/.github/workflows/clippy.yml new file mode 100644 index 00000000..0db08a07 --- /dev/null +++ b/desktop/.github/workflows/clippy.yml @@ -0,0 +1,23 @@ +on: push +name: Clippy check +jobs: + clippy_check: + runs-on: ubuntu-24.04 + permissions: + checks: write + steps: + - uses: actions/checkout@v1 + - name: install dependencies (ubuntu only) + run: | + sudo apt-get update + sudo apt-get install -y libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.1-dev + + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + components: clippy + override: true + - uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + args: --manifest-path ./src-tauri/Cargo.toml \ No newline at end of file diff --git a/desktop/.github/workflows/release.yml b/desktop/.github/workflows/release.yml index 5fdbc90b..3ea73f9a 100644 --- a/desktop/.github/workflows/release.yml +++ b/desktop/.github/workflows/release.yml @@ -48,10 +48,10 @@ jobs: targets: ${{ matrix.platform == 'macos-latest' && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }} - name: install dependencies (ubuntu only) - if: matrix.platform == 'ubuntu-22.04' # This must match the platform value defined above. + if: matrix.platform == 'ubuntu-24.04' # This must match the platform value defined above. run: | sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.0-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libgtk2.0-dev libsoup3.0-dev + sudo apt-get install -y libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.1-dev # webkitgtk 4.0 is for Tauri v1 - webkitgtk 4.1 is for Tauri v2. # You can remove the one that doesn't apply to your app to speed up the workflow a bit. diff --git a/desktop/src-tauri/src/client/cleanup.rs b/desktop/src-tauri/src/client/cleanup.rs index de0e4e6f..f847b09f 100644 --- a/desktop/src-tauri/src/client/cleanup.rs +++ b/desktop/src-tauri/src/client/cleanup.rs @@ -16,7 +16,7 @@ pub fn cleanup_and_exit(app: &AppHandle, state: &tauri::State<'_, std::sync::Mut Ok(_) => debug!("download manager terminated correctly"), Err(_) => error!("download manager failed to terminate correctly"), }, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } app.exit(0); diff --git a/desktop/src-tauri/src/database/db.rs b/desktop/src-tauri/src/database/db.rs index 5ffbffd5..b4c51619 100644 --- a/desktop/src-tauri/src/database/db.rs +++ b/desktop/src-tauri/src/database/db.rs @@ -1,5 +1,9 @@ use std::{ - fs::{self, create_dir_all}, mem::ManuallyDrop, ops::{Deref, DerefMut}, path::PathBuf, rc::Rc, sync::{Arc, LazyLock, Mutex, RwLockReadGuard, RwLockWriteGuard} + fs::{self, create_dir_all}, + mem::ManuallyDrop, + ops::{Deref, DerefMut}, + path::PathBuf, + sync::{Arc, LazyLock, RwLockReadGuard, RwLockWriteGuard}, }; use chrono::Utc; @@ -54,7 +58,7 @@ impl DatabaseImpls for DatabaseInterface { let cache_dir = DATA_ROOT_DIR.join("cache"); 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(); create_dir_all(&games_base_dir).unwrap(); create_dir_all(&logs_root_dir).unwrap(); @@ -97,17 +101,14 @@ fn handle_invalid_database( games_base_dir: PathBuf, cache_dir: PathBuf, ) -> rustbreak::Database { - warn!("{}", _e); + warn!("{_e}"); let new_path = { let time = Utc::now().timestamp(); let mut base = db_path.clone(); - base.set_file_name(format!("drop.db.backup-{}", time)); + 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()); fs::rename(&db_path, &new_path).unwrap(); let db = Database::new( @@ -150,8 +151,8 @@ impl<'a> Drop for DBWrite<'a> { match DB.save() { Ok(_) => {} Err(e) => { - error!("database failed to save with error {}", e); - panic!("database failed to save with error {}", e) + error!("database failed to save with error {e}"); + panic!("database failed to save with error {e}") } } } @@ -160,8 +161,8 @@ pub fn borrow_db_checked<'a>() -> DBRead<'a> { match DB.borrow_data() { Ok(data) => DBRead(data), Err(e) => { - error!("database borrow failed with error {}", e); - panic!("database borrow failed with error {}", e); + error!("database borrow failed with error {e}"); + panic!("database borrow failed with error {e}"); } } } @@ -170,8 +171,8 @@ pub fn borrow_db_mut_checked<'a>() -> DBWrite<'a> { match DB.borrow_data_mut() { Ok(data) => DBWrite(ManuallyDrop::new(data)), Err(e) => { - error!("database borrow mut failed with error {}", e); - panic!("database borrow mut failed with error {}", e); + error!("database borrow mut failed with error {e}"); + panic!("database borrow mut failed with error {e}"); } } } diff --git a/desktop/src-tauri/src/database/models.rs b/desktop/src-tauri/src/database/models.rs index a0e88a80..179f8417 100644 --- a/desktop/src-tauri/src/database/models.rs +++ b/desktop/src-tauri/src/database/models.rs @@ -3,7 +3,7 @@ use crate::database::models::data::Database; pub mod data { use std::path::PathBuf; - use native_model::{native_model, Model}; + use native_model::native_model; use serde::{Deserialize, Serialize}; pub type GameVersion = v1::GameVersion; @@ -134,7 +134,7 @@ pub mod data { pub enum DownloadType { Game, Tool, - DLC, + Dlc, Mod, } diff --git a/desktop/src-tauri/src/download_manager/download_manager_builder.rs b/desktop/src-tauri/src/download_manager/download_manager_builder.rs index 7d3a39d8..4d037121 100644 --- a/desktop/src-tauri/src/download_manager/download_manager_builder.rs +++ b/desktop/src-tauri/src/download_manager/download_manager_builder.rs @@ -17,7 +17,7 @@ use crate::{ }; use super::{ - download_manager::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus}, + download_manager_frontend::{DownloadManager, DownloadManagerSignal, DownloadManagerStatus}, downloadable::Downloadable, util::{ download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, @@ -176,7 +176,6 @@ impl DownloadManagerBuilder { DownloadManagerSignal::Cancel(meta) => { self.manage_cancel_signal(&meta); } - _ => {} }; } } @@ -184,7 +183,7 @@ impl DownloadManagerBuilder { debug!("got signal Queue"); let meta = download_agent.metadata(); - debug!("queue metadata: {:?}", meta); + debug!("queue metadata: {meta:?}"); if self.download_queue.exists(meta.clone()) { warn!("download with same ID already exists"); @@ -210,8 +209,8 @@ impl DownloadManagerBuilder { return; } - if self.current_download_agent.is_some() { - if self.download_queue.read().front().unwrap() + if self.current_download_agent.is_some() + && self.download_queue.read().front().unwrap() == &self.current_download_agent.as_ref().unwrap().metadata() { debug!( @@ -220,14 +219,13 @@ impl DownloadManagerBuilder { ); return; } - } debug!("current download queue: {:?}", self.download_queue.read()); // Should always be Some if the above two statements keep going let agent_data = self.download_queue.read().front().unwrap().clone(); - info!("starting download for {:?}", agent_data); + info!("starting download for {agent_data:?}"); let download_agent = self .download_agent_registry @@ -313,7 +311,7 @@ impl DownloadManagerBuilder { self.stop_and_wait_current_download(); self.remove_and_cleanup_front_download(¤t_agent.metadata()); } - self.set_status(DownloadManagerStatus::Error(error)); + self.set_status(DownloadManagerStatus::Error); } fn manage_cancel_signal(&mut self, meta: &DownloadableMetadata) { debug!("got signal Cancel"); diff --git a/desktop/src-tauri/src/download_manager/download_manager.rs b/desktop/src-tauri/src/download_manager/download_manager_frontend.rs similarity index 91% rename from desktop/src-tauri/src/download_manager/download_manager.rs rename to desktop/src-tauri/src/download_manager/download_manager_frontend.rs index 7227a716..21892b9f 100644 --- a/desktop/src-tauri/src/download_manager/download_manager.rs +++ b/desktop/src-tauri/src/download_manager/download_manager_frontend.rs @@ -38,16 +38,11 @@ pub enum DownloadManagerSignal { Finish, /// Stops, removes, and tells a download to cleanup Cancel(DownloadableMetadata), - /// Removes a given application - Remove(DownloadableMetadata), /// Any error which occurs in the agent Error(ApplicationDownloadError), /// Pushes UI update UpdateUIQueue, UpdateUIStats(usize, usize), //kb/s and seconds - /// Uninstall download - /// Takes download ID - Uninstall(DownloadableMetadata), } #[derive(Debug)] @@ -55,8 +50,7 @@ pub enum DownloadManagerStatus { Downloading, Paused, Empty, - Error(ApplicationDownloadError), - Finished, + Error, } impl Serialize for DownloadManagerStatus { @@ -64,7 +58,7 @@ impl Serialize for DownloadManagerStatus { where S: serde::Serializer, { - serializer.serialize_str(&format!["{:?}", self]) + serializer.serialize_str(&format!["{self:?}"]) } } @@ -155,8 +149,7 @@ impl DownloadManager { } debug!( - "moving download at index {} to index {}", - current_index, new_index + "moving download at index {current_index} to index {new_index}" ); let mut queue = self.edit(); @@ -187,11 +180,6 @@ impl DownloadManager { let terminator = self.terminator.lock().unwrap().take(); terminator.unwrap().join() } - pub fn uninstall_application(&self, meta: DownloadableMetadata) { - self.command_sender - .send(DownloadManagerSignal::Uninstall(meta)) - .unwrap(); - } pub fn get_sender(&self) -> Sender { self.command_sender.clone() } diff --git a/desktop/src-tauri/src/download_manager/downloadable.rs b/desktop/src-tauri/src/download_manager/downloadable.rs index 4a666697..fff8011c 100644 --- a/desktop/src-tauri/src/download_manager/downloadable.rs +++ b/desktop/src-tauri/src/download_manager/downloadable.rs @@ -8,7 +8,7 @@ use crate::{ }; use super::{ - download_manager::DownloadStatus, + download_manager_frontend::DownloadStatus, util::{download_thread_control_flag::DownloadThreadControl, progress_object::ProgressObject}, }; diff --git a/desktop/src-tauri/src/download_manager/mod.rs b/desktop/src-tauri/src/download_manager/mod.rs index 1895798b..b21961f3 100644 --- a/desktop/src-tauri/src/download_manager/mod.rs +++ b/desktop/src-tauri/src/download_manager/mod.rs @@ -1,5 +1,5 @@ pub mod commands; -pub mod download_manager; +pub mod download_manager_frontend; pub mod download_manager_builder; pub mod downloadable; pub mod util; diff --git a/desktop/src-tauri/src/download_manager/util/progress_object.rs b/desktop/src-tauri/src/download_manager/util/progress_object.rs index a945aa06..49537046 100644 --- a/desktop/src-tauri/src/download_manager/util/progress_object.rs +++ b/desktop/src-tauri/src/download_manager/util/progress_object.rs @@ -10,7 +10,7 @@ use std::{ use atomic_instant_full::AtomicInstant; use throttle_my_fn::throttle; -use crate::download_manager::download_manager::DownloadManagerSignal; +use crate::download_manager::download_manager_frontend::DownloadManagerSignal; use super::rolling_progress_updates::RollingProgressWindow; @@ -133,11 +133,7 @@ pub fn calculate_update(progress: &ProgressObject) { let kilobytes_per_second = bytes_since_last_update / (time_since_last_update as usize).max(1); - let bytes_remaining = if (max < current_bytes_downloaded) { - 0 - } else { - max - current_bytes_downloaded - }; // bytes + let bytes_remaining = max.saturating_sub(current_bytes_downloaded); // bytes progress.update_window(kilobytes_per_second); push_update(progress, bytes_remaining); diff --git a/desktop/src-tauri/src/download_manager/util/queue.rs b/desktop/src-tauri/src/download_manager/util/queue.rs index 1406737d..c4fda823 100644 --- a/desktop/src-tauri/src/download_manager/util/queue.rs +++ b/desktop/src-tauri/src/download_manager/util/queue.rs @@ -32,49 +32,13 @@ impl Queue { pub fn pop_front(&self) -> Option { self.edit().pop_front() } - pub fn is_empty(&self) -> bool { - self.inner.lock().unwrap().len() == 0 - } pub fn exists(&self, meta: DownloadableMetadata) -> bool { self.read().contains(&meta) } - /// Either inserts `interface` at the specified index, or appends to - /// the back of the deque if index is greater than the length of the deque - pub fn insert(&self, interface: DownloadableMetadata, index: usize) { - if self.read().len() > index { - self.append(interface); - } else { - self.edit().insert(index, interface); - } - } pub fn append(&self, interface: DownloadableMetadata) { self.edit().push_back(interface); } - pub fn pop_front_if_equal(&self, meta: &DownloadableMetadata) -> Option { - let mut queue = self.edit(); - let front = queue.front()?; - if front == meta { - return queue.pop_front(); - } - None - } pub fn get_by_meta(&self, meta: &DownloadableMetadata) -> Option { self.read().iter().position(|data| data == meta) } - pub fn move_to_index_by_meta( - &self, - meta: &DownloadableMetadata, - new_index: usize, - ) -> Result<(), ()> { - let index = match self.get_by_meta(meta) { - Some(index) => index, - None => return Err(()), - }; - let existing = match self.edit().remove(index) { - Some(existing) => existing, - None => return Err(()), - }; - self.edit().insert(new_index, existing); - Ok(()) - } } diff --git a/desktop/src-tauri/src/error/application_download_error.rs b/desktop/src-tauri/src/error/application_download_error.rs index 64968af3..7ea8bf49 100644 --- a/desktop/src-tauri/src/error/application_download_error.rs +++ b/desktop/src-tauri/src/error/application_download_error.rs @@ -5,14 +5,13 @@ use std::{ use serde_with::SerializeDisplay; -use super::{remote_access_error::RemoteAccessError, setup_error::SetupError}; +use super::{remote_access_error::RemoteAccessError}; // TODO: Rename / separate from downloads #[derive(Debug, SerializeDisplay)] pub enum ApplicationDownloadError { Communication(RemoteAccessError), Checksum, - Setup(SetupError), Lock, IoError(io::ErrorKind), DownloadError, @@ -21,11 +20,10 @@ pub enum ApplicationDownloadError { impl Display for ApplicationDownloadError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - ApplicationDownloadError::Communication(error) => write!(f, "{}", error), - ApplicationDownloadError::Setup(error) => write!(f, "an error occurred while setting up the download: {}", error), + ApplicationDownloadError::Communication(error) => write!(f, "{error}"), ApplicationDownloadError::Lock => write!(f, "failed to acquire lock. Something has gone very wrong internally. Please restart the application"), ApplicationDownloadError::Checksum => 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 => write!(f, "download failed. See Download Manager status for specific error"), } } diff --git a/desktop/src-tauri/src/error/backup_error.rs b/desktop/src-tauri/src/error/backup_error.rs deleted file mode 100644 index 1adfafe4..00000000 --- a/desktop/src-tauri/src/error/backup_error.rs +++ /dev/null @@ -1,21 +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) - } -} diff --git a/desktop/src-tauri/src/error/download_manager_error.rs b/desktop/src-tauri/src/error/download_manager_error.rs index 29c1fea9..b2ca365b 100644 --- a/desktop/src-tauri/src/error/download_manager_error.rs +++ b/desktop/src-tauri/src/error/download_manager_error.rs @@ -10,8 +10,8 @@ pub enum DownloadManagerError { impl Display for DownloadManagerError { 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), + DownloadManagerError::IOError(error) => write!(f, "{error}"), + DownloadManagerError::SignalError(send_error) => write!(f, "{send_error}"), } } } diff --git a/desktop/src-tauri/src/error/drop_server_error.rs b/desktop/src-tauri/src/error/drop_server_error.rs index ab422632..26f371b7 100644 --- a/desktop/src-tauri/src/error/drop_server_error.rs +++ b/desktop/src-tauri/src/error/drop_server_error.rs @@ -5,6 +5,6 @@ use serde::Deserialize; pub struct DropServerError { pub status_code: usize, pub status_message: String, - pub message: String, - pub url: String, + // pub message: String, + // pub url: String, } diff --git a/desktop/src-tauri/src/error/library_error.rs b/desktop/src-tauri/src/error/library_error.rs index c13dd231..cad5ada0 100644 --- a/desktop/src-tauri/src/error/library_error.rs +++ b/desktop/src-tauri/src/error/library_error.rs @@ -11,8 +11,7 @@ impl Display for LibraryError { match self { LibraryError::MetaNotFound(id) => write!( f, - "Could not locate any installed version of game ID {} in the database", - id + "Could not locate any installed version of game ID {id} in the database" ), } } diff --git a/desktop/src-tauri/src/error/mod.rs b/desktop/src-tauri/src/error/mod.rs index 4053efdc..80bc5857 100644 --- a/desktop/src-tauri/src/error/mod.rs +++ b/desktop/src-tauri/src/error/mod.rs @@ -1,8 +1,6 @@ pub mod application_download_error; -pub mod backup_error; pub mod download_manager_error; pub mod drop_server_error; pub mod library_error; pub mod process_error; pub mod remote_access_error; -pub mod setup_error; diff --git a/desktop/src-tauri/src/error/process_error.rs b/desktop/src-tauri/src/error/process_error.rs index fefa2c33..99bf9baa 100644 --- a/desktop/src-tauri/src/error/process_error.rs +++ b/desktop/src-tauri/src/error/process_error.rs @@ -26,8 +26,8 @@ impl Display for ProcessError { ProcessError::InvalidVersion => "Invalid Game version", ProcessError::IOError(error) => &error.to_string(), ProcessError::InvalidPlatform => "This Game cannot be played on the current platform", - ProcessError::FormatError(e) => &format!("Failed to format template: {}", e), + ProcessError::FormatError(e) => &format!("Failed to format template: {e}"), }; - write!(f, "{}", s) + write!(f, "{s}") } } diff --git a/desktop/src-tauri/src/error/remote_access_error.rs b/desktop/src-tauri/src/error/remote_access_error.rs index 9f2407f1..6717c6e3 100644 --- a/desktop/src-tauri/src/error/remote_access_error.rs +++ b/desktop/src-tauri/src/error/remote_access_error.rs @@ -18,7 +18,6 @@ pub enum RemoteAccessError { HandshakeFailed(String), GameNotFound(String), InvalidResponse(DropServerError), - InvalidRedirect, ManifestDownloadFailed(StatusCode, String), OutOfSync, Cache(cacache::Error), @@ -44,20 +43,18 @@ impl Display for RemoteAccessError { ) }, RemoteAccessError::ParsingError(parse_error) => { - write!(f, "{}", parse_error) + write!(f, "{parse_error}") } RemoteAccessError::InvalidEndpoint => write!(f, "invalid drop endpoint"), - RemoteAccessError::HandshakeFailed(message) => write!(f, "failed to complete handshake: {}", message), - RemoteAccessError::GameNotFound(id) => write!(f, "could not find game on server: {}", id), + RemoteAccessError::HandshakeFailed(message) => write!(f, "failed to complete handshake: {message}"), + RemoteAccessError::GameNotFound(id) => write!(f, "could not find game on server: {id}"), RemoteAccessError::InvalidResponse(error) => write!(f, "server returned an invalid response: {} {}", error.status_code, error.status_message), - RemoteAccessError::InvalidRedirect => write!(f, "server redirect was invalid"), RemoteAccessError::ManifestDownloadFailed(status, response) => write!( f, - "failed to download game manifest: {} {}", - status, response + "failed to download game manifest: {status} {response}" ), RemoteAccessError::OutOfSync => write!(f, "server's and client's time are out of sync. Please ensure they are within at least 30 seconds of each other"), - RemoteAccessError::Cache(error) => write!(f, "Cache Error: {}", error), + RemoteAccessError::Cache(error) => write!(f, "Cache Error: {error}"), } } } diff --git a/desktop/src-tauri/src/error/setup_error.rs b/desktop/src-tauri/src/error/setup_error.rs deleted file mode 100644 index bd76ce50..00000000 --- a/desktop/src-tauri/src/error/setup_error.rs +++ /dev/null @@ -1,14 +0,0 @@ -use std::fmt::{Display, Formatter}; - -#[derive(Debug, Clone)] -pub enum SetupError { - Context, -} - -impl Display for SetupError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - match self { - SetupError::Context => write!(f, "failed to generate contexts for download"), - } - } -} diff --git a/desktop/src-tauri/src/games/collections/commands.rs b/desktop/src-tauri/src/games/collections/commands.rs index 6688d1be..7f815287 100644 --- a/desktop/src-tauri/src/games/collections/commands.rs +++ b/desktop/src-tauri/src/games/collections/commands.rs @@ -41,7 +41,7 @@ pub fn create_collection(name: String) -> Result let client = Client::new(); let base_url = DB.fetch_base_url(); - let base_url = Url::parse(&format!("{}api/v1/client/collection/", base_url))?; + let base_url = Url::parse(&format!("{base_url}api/v1/client/collection/"))?; let response = client .post(base_url) diff --git a/desktop/src-tauri/src/games/downloads/commands.rs b/desktop/src-tauri/src/games/downloads/commands.rs index 7d1118c4..1bead284 100644 --- a/desktop/src-tauri/src/games/downloads/commands.rs +++ b/desktop/src-tauri/src/games/downloads/commands.rs @@ -5,7 +5,7 @@ use std::{ use crate::{ database::{db::borrow_db_checked, models::data::GameDownloadStatus}, - download_manager::{download_manager::DownloadManagerSignal, downloadable::Downloadable}, + download_manager::{download_manager_frontend::DownloadManagerSignal, downloadable::Downloadable}, error::download_manager_error::DownloadManagerError, AppState, }; diff --git a/desktop/src-tauri/src/games/downloads/download_agent.rs b/desktop/src-tauri/src/games/downloads/download_agent.rs index eb9bf2a8..1bbd85ac 100644 --- a/desktop/src-tauri/src/games/downloads/download_agent.rs +++ b/desktop/src-tauri/src/games/downloads/download_agent.rs @@ -3,7 +3,7 @@ use crate::database::db::{borrow_db_checked, borrow_db_mut_checked}; use crate::database::models::data::{ ApplicationTransientStatus, DownloadType, DownloadableMetadata, }; -use crate::download_manager::download_manager::{DownloadManagerSignal, DownloadStatus}; +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, @@ -212,6 +212,7 @@ impl GameDownloadAgent { let file = OpenOptions::new() .read(true) .write(true) + .truncate(true) .create(true) .open(path.clone()) .unwrap(); @@ -267,7 +268,7 @@ impl GameDownloadAgent { let completed_indexes_loop_arc = completed_contexts.clone(); let contexts = self.contexts.lock().unwrap(); - debug!("{:#?}", contexts); + debug!("{contexts:#?}"); pool.scope(|scope| { let client = &reqwest::blocking::Client::new(); let context_map = self.context_map.lock().unwrap(); @@ -325,7 +326,7 @@ impl GameDownloadAgent { ); } Err(e) => { - error!("{}", e); + error!("{e}"); sender.send(DownloadManagerSignal::Error(e)).unwrap(); } } @@ -352,8 +353,7 @@ impl GameDownloadAgent { context_map_lock .get(&x.checksum) .cloned() - .or(Some(false)) - .unwrap(), + .unwrap_or(false), ) }) .collect::>(); @@ -409,7 +409,7 @@ impl Downloadable for GameDownloadAgent { .emit("download_error", error.to_string()) .unwrap(); - error!("error while managing download: {}", error); + error!("error while managing download: {error}"); let mut handle = borrow_db_mut_checked(); handle diff --git a/desktop/src-tauri/src/games/downloads/download_logic.rs b/desktop/src-tauri/src/games/downloads/download_logic.rs index 3e08a49f..69473e03 100644 --- a/desktop/src-tauri/src/games/downloads/download_logic.rs +++ b/desktop/src-tauri/src/games/downloads/download_logic.rs @@ -6,12 +6,12 @@ use crate::error::application_download_error::ApplicationDownloadError; use crate::error::remote_access_error::RemoteAccessError; use crate::games::downloads::manifest::DropDownloadContext; use crate::remote::auth::generate_authorization_header; -use log::{debug, info, warn}; +use log::{debug, warn}; use md5::{Context, Digest}; use reqwest::blocking::{RequestBuilder, Response}; use std::fs::{set_permissions, Permissions}; -use std::io::{ErrorKind, Read}; +use std::io::Read; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::{ @@ -41,9 +41,8 @@ impl DropWriter { impl Write for DropWriter { fn write(&mut self, buf: &[u8]) -> io::Result { self.hasher.write_all(buf).map_err(|e| { - io::Error::new( - ErrorKind::Other, - format!("Unable to write to hasher: {}", e), + io::Error::other( + format!("Unable to write to hasher: {e}"), ) })?; self.destination.write(buf) @@ -102,7 +101,7 @@ impl<'a> DropDownloadPipeline<'a, Response, File> { if current_size > self.size { let over = current_size - self.size; - warn!("server sent too many bytes... {} over", over); + warn!("server sent too many bytes... {over} over"); bytes_read -= over; current_size = self.size; } diff --git a/desktop/src-tauri/src/games/downloads/drop_data.rs b/desktop/src-tauri/src/games/downloads/drop_data.rs index 4ec61a93..0408b373 100644 --- a/desktop/src-tauri/src/games/downloads/drop_data.rs +++ b/desktop/src-tauri/src/games/downloads/drop_data.rs @@ -43,7 +43,7 @@ impl DropData { let mut file = match File::open(base_path.join(DROP_DATA_PATH)) { Ok(file) => file, Err(_) => { - debug!("Generating new dropdata for game {}", game_id); + debug!("Generating new dropdata for game {game_id}"); return DropData::new(game_id, game_version, base_path); } }; @@ -52,7 +52,7 @@ impl DropData { match file.read_to_end(&mut s) { Ok(_) => {} Err(e) => { - error!("{}", e); + error!("{e}"); return DropData::new(game_id, game_version, base_path); } }; @@ -60,7 +60,7 @@ impl DropData { match native_model::rmp_serde_1_3::RmpSerde::decode(s) { Ok(manifest) => manifest, Err(e) => { - warn!("{}", e); + warn!("{e}"); DropData::new(game_id, game_version, base_path) } } @@ -74,14 +74,14 @@ impl DropData { let mut file = match File::create(self.base_path.join(DROP_DATA_PATH)) { Ok(file) => file, Err(e) => { - error!("{}", e); + error!("{e}"); return; } }; match file.write_all(&manifest_raw) { Ok(_) => {} - Err(e) => error!("{}", e), + Err(e) => error!("{e}"), }; } pub fn set_contexts(&self, completed_contexts: &[(String, bool)]) { diff --git a/desktop/src-tauri/src/games/downloads/validate.rs b/desktop/src-tauri/src/games/downloads/validate.rs index 42ddcb73..c92a106d 100644 --- a/desktop/src-tauri/src/games/downloads/validate.rs +++ b/desktop/src-tauri/src/games/downloads/validate.rs @@ -11,7 +11,7 @@ use rayon::ThreadPoolBuilder; use crate::{ database::db::borrow_db_checked, download_manager::{ - download_manager::DownloadManagerSignal, + download_manager_frontend::DownloadManagerSignal, util::{ download_thread_control_flag::{DownloadThreadControl, DownloadThreadControlFlag}, progress_object::{ProgressHandle, ProgressObject}, @@ -19,7 +19,6 @@ use crate::{ }, error::application_download_error::ApplicationDownloadError, games::downloads::{drop_data::DropData, manifest::DropDownloadContext}, - remote::{auth::generate_authorization_header, requests::make_request}, }; pub fn game_validate_logic( @@ -41,40 +40,15 @@ pub fn game_validate_logic( .build() .unwrap(); - debug!("{:#?}", contexts); + debug!("{contexts:#?}"); let invalid_chunks = Arc::new(boxcar::Vec::new()); pool.scope(|scope| { - let client = &reqwest::blocking::Client::new(); for (index, context) in contexts.iter().enumerate() { - let client = client.clone(); - let current_progress = progress.get(index); let progress_handle = ProgressHandle::new(current_progress, progress.clone()); let invalid_chunks_scoped = invalid_chunks.clone(); let sender = sender.clone(); - let request = match 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()), - ) { - Ok(request) => request, - Err(e) => { - sender - .send(DownloadManagerSignal::Error( - ApplicationDownloadError::Communication(e), - )) - .unwrap(); - continue; - } - }; - scope.spawn(move |_| { match validate_game_chunk(context, control_flag, progress_handle) { Ok(true) => { @@ -91,7 +65,7 @@ pub fn game_validate_logic( invalid_chunks_scoped.push(context.checksum.clone()); } Err(e) => { - error!("{}", e); + error!("{e}"); sender.send(DownloadManagerSignal::Error(e)).unwrap(); } } diff --git a/desktop/src-tauri/src/games/library.rs b/desktop/src-tauri/src/games/library.rs index 710fa37d..968dc497 100644 --- a/desktop/src-tauri/src/games/library.rs +++ b/desktop/src-tauri/src/games/library.rs @@ -11,7 +11,7 @@ use crate::database::db::{borrow_db_checked, borrow_db_mut_checked}; use crate::database::models::data::{ ApplicationTransientStatus, DownloadableMetadata, GameDownloadStatus, GameVersion, }; -use crate::download_manager::download_manager::DownloadStatus; +use crate::download_manager::download_manager_frontend::DownloadStatus; use crate::error::library_error::LibraryError; use crate::error::remote_access_error::RemoteAccessError; use crate::games::state::{GameStatusManager, GameStatusWithTransient}; @@ -85,7 +85,7 @@ pub fn fetch_library_logic( if response.status() != 200 { let err = response.json().unwrap(); - warn!("{:?}", err); + warn!("{err:?}"); return Err(RemoteAccessError::InvalidResponse(err)); } @@ -106,8 +106,8 @@ pub fn fetch_library_logic( } // Add games that are installed but no longer in library - for (_, meta) in &db_handle.applications.installed_game_version { - if games.iter().find(|e| e.id == meta.id).is_some() { + 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 @@ -187,7 +187,7 @@ pub fn fetch_game_logic( } if response.status() != 200 { let err = response.json().unwrap(); - warn!("{:?}", err); + warn!("{err:?}"); return Err(RemoteAccessError::InvalidResponse(err)); } @@ -263,7 +263,7 @@ pub fn fetch_game_verion_options_logic( if response.status() != 200 { let err = response.json().unwrap(); - warn!("{:?}", err); + warn!("{err:?}"); return Err(RemoteAccessError::InvalidResponse(err)); } @@ -330,7 +330,7 @@ pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle) let app_handle = app_handle.clone(); spawn(move || match remove_dir_all(install_dir) { Err(e) => { - error!("{}", e); + error!("{e}"); } Ok(_) => { let mut db_handle = borrow_db_mut_checked(); @@ -347,7 +347,7 @@ pub fn uninstall_game_logic(meta: DownloadableMetadata, app_handle: &AppHandle) drop(db_handle); debug!("uninstalled game id {}", &meta.id); - app_handle.emit("update_library", {}).unwrap(); + app_handle.emit("update_library", ()).unwrap(); push_game_update( &app_handle, @@ -510,7 +510,7 @@ pub fn push_game_update( ) { app_handle .emit( - &format!("update_game/{}", game_id), + &format!("update_game/{game_id}"), GameUpdateEvent { game_id: game_id.clone(), status, diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index d00b0801..a4d0fabd 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ #![feature(fn_traits)] +#![deny(clippy::all)] mod database; mod games; @@ -24,7 +25,7 @@ use database::models::data::GameDownloadStatus; use download_manager::commands::{ cancel_game, move_download_in_queue, pause_downloads, resume_downloads, }; -use download_manager::download_manager::DownloadManager; +use download_manager::download_manager_frontend::DownloadManager; use download_manager::download_manager_builder::DownloadManagerBuilder; use games::collections::commands::{ add_game_to_collection, create_collection, delete_collection, delete_game_in_collection, @@ -184,7 +185,7 @@ fn setup(handle: AppHandle) -> AppState<'static> { } } - info!("detected games missing: {:?}", missing_games); + info!("detected games missing: {missing_games:?}"); let mut db_handle = borrow_db_mut_checked(); for game_id in missing_games { @@ -201,7 +202,7 @@ fn setup(handle: AppHandle) -> AppState<'static> { // Sync autostart state if let Err(e) = sync_autostart_on_startup(&handle) { - warn!("failed to sync autostart state: {}", e); + warn!("failed to sync autostart state: {e}"); } AppState { @@ -224,7 +225,7 @@ pub fn custom_panic_handler(e: &PanicHookInfo) -> Option<()> { .as_secs() )); let mut file = File::create_new(crash_file).ok()?; - file.write_all(format!("Drop crashed with the following panic:\n{}", e).as_bytes()).ok()?; + file.write_all(format!("Drop crashed with the following panic:\n{e}").as_bytes()).ok()?; drop(file); Some(()) @@ -381,11 +382,7 @@ pub fn run() { if let Some(original) = db_handle.prev_database.take() { warn!( "Database corrupted. Original file at {}", - original - .canonicalize() - .unwrap() - .to_string_lossy() - .to_string() + original.canonicalize().unwrap().to_string_lossy() ); app.dialog() .message( @@ -441,7 +438,7 @@ pub fn run() { }); } -fn run_on_tray ()>(f: T) { +fn run_on_tray(f: T) { if match std::env::var("NO_TRAY_ICON") { Ok(s) => s.to_lowercase() != "true", Err(_) => true, diff --git a/desktop/src-tauri/src/process/process_manager.rs b/desktop/src-tauri/src/process/process_manager.rs index b977777f..be822738 100644 --- a/desktop/src-tauri/src/process/process_manager.rs +++ b/desktop/src-tauri/src/process/process_manager.rs @@ -92,7 +92,7 @@ impl ProcessManager<'_> { fn on_process_finish(&mut self, game_id: String, result: Result) { if !self.processes.contains_key(&game_id) { - warn!("process on_finish was called, but game_id is no longer valid. finished with result: {:?}", result); + warn!("process on_finish was called, but game_id is no longer valid. finished with result: {result:?}"); return; } @@ -110,22 +110,20 @@ impl ProcessManager<'_> { db_handle.applications.transient_statuses.remove(&meta); let current_state = db_handle.applications.game_statuses.get(&game_id).cloned(); - if let Some(saved_state) = current_state { - if let GameDownloadStatus::SetupRequired { - version_name, - install_dir, - } = saved_state - { - if let Ok(exit_code) = result { - if exit_code.success() { - db_handle.applications.game_statuses.insert( - game_id.clone(), - GameDownloadStatus::Installed { - version_name: version_name.to_string(), - install_dir: install_dir.to_string(), - }, - ); - } + if let Some(GameDownloadStatus::SetupRequired { + version_name, + install_dir, + }) = current_state + { + if let Ok(exit_code) = result { + if exit_code.success() { + db_handle.applications.game_statuses.insert( + game_id.clone(), + GameDownloadStatus::Installed { + version_name: version_name.to_string(), + install_dir: install_dir.to_string(), + }, + ); } } } @@ -140,9 +138,7 @@ impl ProcessManager<'_> { pub fn valid_platform(&self, platform: &Platform) -> Result { let current = &self.current_platform; - Ok(self - .game_launchers - .contains_key(&(current.clone(), platform.clone()))) + Ok(self.game_launchers.contains_key(&(*current, *platform))) } pub fn launch_process(&mut self, game_id: String) -> Result<(), ProcessError> { @@ -233,8 +229,8 @@ impl ProcessManager<'_> { ))) .map_err(ProcessError::IOError)?; - let current_platform = self.current_platform.clone(); - let target_platform = game_version.platform.clone(); + let current_platform = self.current_platform; + let target_platform = game_version.platform; let game_launcher = self .game_launchers @@ -251,13 +247,13 @@ impl ProcessManager<'_> { install_dir: _, } => (&game_version.setup_command, &game_version.setup_args), GameDownloadStatus::PartiallyInstalled { - version_name, - install_dir, + version_name: _, + install_dir: _, } => unreachable!("Game registered as 'Partially Installed'"), GameDownloadStatus::Remote {} => unreachable!("Game registered as 'Remote'"), }; - let launch = PathBuf::from_str(&install_dir).unwrap().join(launch); + let launch = PathBuf::from_str(install_dir).unwrap().join(launch); let launch = launch.to_str().unwrap(); let launch_string = game_launcher.create_launch_process( @@ -281,7 +277,7 @@ impl ProcessManager<'_> { #[cfg(target_os = "windows")] command.raw_arg(format!("/C \"{}\"", &launch_string)); - info!("launching (in {}): {}", install_dir, launch_string,); + info!("launching (in {install_dir}): {launch_string}",); #[cfg(unix)] let mut command: Command = Command::new("sh"); @@ -342,9 +338,6 @@ pub enum Platform { } impl Platform { - const WINDOWS: bool = cfg!(target_os = "windows"); - const MAC: bool = cfg!(target_os = "macos"); - const LINUX: bool = cfg!(target_os = "linux"); #[cfg(target_os = "windows")] pub const HOST: Platform = Self::Windows; #[cfg(target_os = "macos")] @@ -420,10 +413,13 @@ impl ProcessHandler for UMULauncher { ) -> String { debug!("Game override: \"{:?}\"", &game_version.umu_id_override); let game_id = match &game_version.umu_id_override { - Some(game_override) => game_override - .is_empty() - .then_some(game_version.game_id.clone()) - .unwrap_or(game_override.clone()), + Some(game_override) => { + if game_override.is_empty() { + game_version.game_id.clone() + } else { + game_override.clone() + } + } None => game_version.game_id.clone(), }; format!( diff --git a/desktop/src-tauri/src/remote/auth.rs b/desktop/src-tauri/src/remote/auth.rs index a94f8117..cb643504 100644 --- a/desktop/src-tauri/src/remote/auth.rs +++ b/desktop/src-tauri/src/remote/auth.rs @@ -72,7 +72,7 @@ pub fn fetch_user() -> Result { .send()?; if response.status() != 200 { let err: DropServerError = response.json()?; - warn!("{:?}", err); + warn!("{err:?}"); if err.status_message == "Nonce expired" { return Err(RemoteAccessError::OutOfSync); @@ -148,7 +148,7 @@ pub fn recieve_handshake(app: AppHandle, path: String) { let handshake_result = recieve_handshake_logic(&app, path); if let Err(e) = handshake_result { - warn!("error with authentication: {}", e); + warn!("error with authentication: {e}"); app.emit("auth/failed", e.to_string()).unwrap(); return; } @@ -212,7 +212,7 @@ pub fn setup() -> (AppStatus, Option) { let user_result = match fetch_user() { Ok(data) => data, Err(RemoteAccessError::FetchError(_)) => { - let user = get_cached_object::("user".to_owned()).unwrap(); + let user = get_cached_object::<_, User>("user").unwrap(); return (AppStatus::Offline, Some(user)); } Err(_) => return (AppStatus::SignedInNeedsReauth, None), diff --git a/desktop/src-tauri/src/remote/cache.rs b/desktop/src-tauri/src/remote/cache.rs index 062fe75d..892ce27a 100644 --- a/desktop/src-tauri/src/remote/cache.rs +++ b/desktop/src-tauri/src/remote/cache.rs @@ -11,7 +11,7 @@ use serde_binary::binary_stream::Endian; macro_rules! offline { ($var:expr, $func1:expr, $func2:expr, $( $arg:expr ),* ) => { - if crate::borrow_db_checked().settings.force_offline || $var.lock().unwrap().status == crate::AppStatus::Offline { + if $crate::borrow_db_checked().settings.force_offline || $var.lock().unwrap().status == $crate::AppStatus::Offline { $func2( $( $arg ), *) } else { $func1( $( $arg ), *) @@ -19,24 +19,24 @@ macro_rules! offline { } } -pub fn cache_object<'a, K: AsRef, D: Serialize + DeserializeOwned>( +pub fn cache_object, D: Serialize + DeserializeOwned>( key: K, data: &D, ) -> Result { let bytes = serde_binary::to_vec(data, Endian::Little).unwrap(); cacache::write_sync(&borrow_db_checked().cache_dir, key, bytes) - .map_err(|e| RemoteAccessError::Cache(e)) + .map_err(RemoteAccessError::Cache) } -pub fn get_cached_object<'a, K: AsRef, D: Serialize + DeserializeOwned>( +pub fn get_cached_object, D: Serialize + DeserializeOwned>( key: K, ) -> Result { get_cached_object_db::(key, &borrow_db_checked()) } -pub fn get_cached_object_db<'a, K: AsRef, D: Serialize + DeserializeOwned>( +pub fn get_cached_object_db, D: Serialize + DeserializeOwned>( key: K, db: &Database, ) -> Result { - let bytes = cacache::read_sync(&db.cache_dir, key).map_err(|e| RemoteAccessError::Cache(e))?; + let bytes = cacache::read_sync(&db.cache_dir, key).map_err(RemoteAccessError::Cache)?; let data = serde_binary::from_slice::(&bytes, Endian::Little).unwrap(); Ok(data) } diff --git a/desktop/src-tauri/src/remote/commands.rs b/desktop/src-tauri/src/remote/commands.rs index 613e2a3c..2ba36f8a 100644 --- a/desktop/src-tauri/src/remote/commands.rs +++ b/desktop/src-tauri/src/remote/commands.rs @@ -15,7 +15,7 @@ use crate::{ use super::{ auth::{auth_initiate_logic, recieve_handshake, setup}, cache::{cache_object, get_cached_object}, - remote::use_remote_logic, + utils::use_remote_logic, }; #[tauri::command] @@ -54,7 +54,7 @@ pub fn fetch_drop_object(path: String) -> Result, RemoteAccessError> { Ok(data) } Err(e) => { - debug!("{}", e); + debug!("{e}"); get_cached_object::<&str, Vec>(&path) } } @@ -96,5 +96,5 @@ pub fn auth_initiate() -> Result<(), RemoteAccessError> { #[tauri::command] pub fn manual_recieve_handshake(app: AppHandle, token: String) { - recieve_handshake(app, format!("handshake/{}", token)); + recieve_handshake(app, format!("handshake/{token}")); } diff --git a/desktop/src-tauri/src/remote/fetch_object.rs b/desktop/src-tauri/src/remote/fetch_object.rs index 4900b6da..bd3a5814 100644 --- a/desktop/src-tauri/src/remote/fetch_object.rs +++ b/desktop/src-tauri/src/remote/fetch_object.rs @@ -25,7 +25,7 @@ pub fn fetch_object(request: http::Request>, responder: UriSchemeRespond match data { Ok(data) => responder.respond(data.into()), Err(e) => { - warn!("{}", e) + warn!("{e}") } } return; @@ -48,6 +48,6 @@ pub fn fetch_object_offline(request: http::Request>, responder: UriSchem match data { Ok(data) => responder.respond(data.into()), - Err(e) => warn!("{}", e), + Err(e) => warn!("{e}"), } } diff --git a/desktop/src-tauri/src/remote/mod.rs b/desktop/src-tauri/src/remote/mod.rs index 3352f0e2..59893eb9 100644 --- a/desktop/src-tauri/src/remote/mod.rs +++ b/desktop/src-tauri/src/remote/mod.rs @@ -3,6 +3,6 @@ pub mod auth; pub mod cache; pub mod commands; pub mod fetch_object; -pub mod remote; +pub mod utils; pub mod requests; pub mod server_proto; diff --git a/desktop/src-tauri/src/remote/server_proto.rs b/desktop/src-tauri/src/remote/server_proto.rs index 4bd7a5d3..4c5b8899 100644 --- a/desktop/src-tauri/src/remote/server_proto.rs +++ b/desktop/src-tauri/src/remote/server_proto.rs @@ -26,17 +26,16 @@ pub fn handle_server_proto(request: Request>, responder: UriSchemeRespon let mut new_uri = request.uri().clone().into_parts(); new_uri.path_and_query = - Some(PathAndQuery::from_str(&format!("{}?noWrapper=true", path)).unwrap()); + 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 = vec!["/store", "/api", "/_", "/fonts"]; + let whitelist_prefix = ["/store", "/api", "/_", "/fonts"]; if whitelist_prefix .iter() - .map(|f| !path.starts_with(f)) - .all(|f| f) + .all(|f| !path.starts_with(f)) { webbrowser::open(&new_uri.to_string()).unwrap(); return; @@ -45,7 +44,7 @@ pub fn handle_server_proto(request: Request>, responder: UriSchemeRespon let client = Client::new(); let response = client .request(request.method().clone(), new_uri.to_string()) - .header("Authorization", format!("Bearer {}", web_token)) + .header("Authorization", format!("Bearer {web_token}")) .headers(request.headers().clone()) .send() .unwrap(); diff --git a/desktop/src-tauri/src/remote/remote.rs b/desktop/src-tauri/src/remote/utils.rs similarity index 96% rename from desktop/src-tauri/src/remote/remote.rs rename to desktop/src-tauri/src/remote/utils.rs index 888ec447..baf8dada 100644 --- a/desktop/src-tauri/src/remote/remote.rs +++ b/desktop/src-tauri/src/remote/utils.rs @@ -19,7 +19,7 @@ pub fn use_remote_logic( url: String, state: tauri::State<'_, Mutex>>, ) -> Result<(), RemoteAccessError> { - debug!("connecting to url {}", url); + debug!("connecting to url {url}"); let base_url = Url::parse(&url)?; // Test Drop url