From 2c7b5fb47d7b04522167fb1bce9ab3f2a791aae7 Mon Sep 17 00:00:00 2001 From: quexeky Date: Sat, 9 Nov 2024 19:57:53 +1100 Subject: [PATCH] refactor: Cleaning up downloads playing and pausing Signed-off-by: quexeky --- src-tauri/src/auth.rs | 6 +- src-tauri/src/downloads/download_agent.rs | 1 - src-tauri/src/downloads/download_commands.rs | 14 ++-- src-tauri/src/downloads/download_logic.rs | 75 +++++++++----------- src-tauri/src/downloads/progress.rs | 9 ++- src-tauri/src/lib.rs | 4 +- src-tauri/src/library.rs | 2 +- src-tauri/src/p2p/discovery.rs | 8 +-- src-tauri/src/tests/progress_tests.rs | 2 +- 9 files changed, 60 insertions(+), 61 deletions(-) diff --git a/src-tauri/src/auth.rs b/src-tauri/src/auth.rs index 311f4a6..0c57c49 100644 --- a/src-tauri/src/auth.rs +++ b/src-tauri/src/auth.rs @@ -94,7 +94,7 @@ fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), RemoteAc if path_chunks.len() != 3 { app.emit("auth/failed", ()).unwrap(); return Err(RemoteAccessError::GenericErrror( - "Invalid number of handshake chunks".to_string().into(), + "Invalid number of handshake chunks".to_string(), )); } @@ -134,7 +134,7 @@ fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), RemoteAc app_state_handle.user = Some(fetch_user()?); } - return Ok(()); + Ok(()) } pub fn recieve_handshake(app: AppHandle, path: String) { @@ -177,7 +177,7 @@ async fn auth_initiate_wrapper() -> Result<(), RemoteAccessError> { info!("opening web browser to continue authentication"); webbrowser::open(complete_redir_url.as_ref()).unwrap(); - return Ok(()); + Ok(()) } #[tauri::command] diff --git a/src-tauri/src/downloads/download_agent.rs b/src-tauri/src/downloads/download_agent.rs index dd20dc2..59cf04b 100644 --- a/src-tauri/src/downloads/download_agent.rs +++ b/src-tauri/src/downloads/download_agent.rs @@ -5,7 +5,6 @@ use crate::downloads::manifest::{DropDownloadContext, DropManifest}; use crate::downloads::progress::ProgressChecker; use crate::DB; use atomic_counter::RelaxedCounter; -use http::status; use log::info; use rustix::fs::{fallocate, FallocateFlags}; use serde::{Deserialize, Serialize}; diff --git a/src-tauri/src/downloads/download_commands.rs b/src-tauri/src/downloads/download_commands.rs index 231838c..5a1f0cd 100644 --- a/src-tauri/src/downloads/download_commands.rs +++ b/src-tauri/src/downloads/download_commands.rs @@ -1,5 +1,5 @@ use std::{ - sync::{atomic::Ordering, Arc, Mutex}, + sync::{Arc, Mutex}, thread, }; @@ -95,7 +95,7 @@ pub async fn cancel_specific_game_download( game_id: String, ) -> Result<(), String> { info!("called stop_specific_game_download"); - let status = get_game_download(state, game_id).change_state(GameDownloadState::Cancelled); + get_game_download(state, game_id).change_state(GameDownloadState::Cancelled); //TODO: Drop the game download instance @@ -109,7 +109,9 @@ pub async fn get_game_download_progress( state: tauri::State<'_, Mutex>, game_id: String, ) -> Result { - let progress = get_game_download(state, game_id).progress.get_progress_percentage(); + let progress = get_game_download(state, game_id) + .progress + .get_progress_percentage(); info!("{}", progress); Ok(progress) } @@ -120,7 +122,7 @@ pub async fn pause_game_download( game_id: String, ) -> Result<(), String> { get_game_download(state, game_id).change_state(GameDownloadState::Paused); - + Ok(()) } @@ -130,7 +132,7 @@ pub async fn resume_game_download( game_id: String, ) -> Result<(), String> { get_game_download(state, game_id).change_state(GameDownloadState::Downloading); - + Ok(()) } @@ -141,4 +143,4 @@ fn get_game_download( let lock = state.lock().unwrap(); let download_agent = lock.game_downloads.get(&game_id).unwrap(); download_agent.clone() -} \ No newline at end of file +} diff --git a/src-tauri/src/downloads/download_logic.rs b/src-tauri/src/downloads/download_logic.rs index a5e202c..3e36189 100644 --- a/src-tauri/src/downloads/download_logic.rs +++ b/src-tauri/src/downloads/download_logic.rs @@ -6,17 +6,13 @@ use atomic_counter::{AtomicCounter, RelaxedCounter}; use log::{error, info}; use md5::{Context, Digest}; -#[cfg(windows)] -use tokio::signal::windows::Signal; -use tokio::sync::{broadcast::Receiver, mpsc}; use std::{ fs::{File, OpenOptions}, io::{self, BufWriter, Error, ErrorKind, Seek, SeekFrom, Write}, path::PathBuf, - sync::{ - atomic::{AtomicBool, Ordering}, - Arc, RwLock, - }, thread::sleep, time::Duration, + sync::{Arc, RwLock}, + thread::sleep, + time::Duration, }; use urlencoding::encode; @@ -29,60 +25,61 @@ pub struct DropFileWriter { status: Arc>, } impl DropFileWriter { - fn new(path: PathBuf, status: Arc>, progress: Arc) -> Self { + fn new( + path: PathBuf, + status: Arc>, + progress: Arc, + ) -> Self { Self { file: OpenOptions::new().write(true).open(path).unwrap(), hasher: Context::new(), progress, - status + status, } } fn finish(mut self) -> io::Result { self.flush().unwrap(); Ok(self.hasher.compute()) } - + fn manage_state(&mut self) -> Option> { - match {self.status.read().unwrap().clone()} { + match self.status.read().unwrap().clone() { GameDownloadState::Uninitialised => todo!(), GameDownloadState::Queued => { return Some(Err(Error::new( ErrorKind::NotConnected, - "Download has not yet been started" + "Download has not yet been started", ))) - }, + } GameDownloadState::Manifest => { return Some(Err(Error::new( - ErrorKind::NotFound, - "Manifest still not finished downloading" + ErrorKind::NotFound, + "Manifest still not finished downloading", ))) - }, - GameDownloadState::Downloading => {}, + } + GameDownloadState::Downloading => {} GameDownloadState::Finished => { return Some(Err(Error::new( - ErrorKind::AlreadyExists, "Download already finished"))) - }, + ErrorKind::AlreadyExists, + "Download already finished", + ))) + } GameDownloadState::Stalled => { - return Some(Err(Error::new( - ErrorKind::Interrupted, "Download Stalled" - ))) - }, + return Some(Err(Error::new(ErrorKind::Interrupted, "Download Stalled"))) + } GameDownloadState::Failed => { - return Some(Err(Error::new( - ErrorKind::BrokenPipe, - "Download Failed" - ))) - }, + return Some(Err(Error::new(ErrorKind::BrokenPipe, "Download Failed"))) + } GameDownloadState::Cancelled => { return Some(Err(Error::new( ErrorKind::ConnectionAborted, "Interrupt command recieved", ))); - }, + } GameDownloadState::Paused => { info!("Game download paused"); sleep(Duration::from_secs(1)); - }, + } }; None } @@ -137,14 +134,13 @@ pub fn download_game_chunk( let header = generate_authorization_header(); - let mut response = match client - .get(chunk_url) - .header("Authorization", header) - .send() { - Ok(response) => response, - Err(e) => { info!("{}", e); return; }, - }; - + let mut response = match client.get(chunk_url).header("Authorization", header).send() { + Ok(response) => response, + Err(e) => { + info!("{}", e); + return; + } + }; let mut file: DropFileWriter = DropFileWriter::new(ctx.path, status, progress); @@ -154,7 +150,7 @@ pub fn download_game_chunk( } // Writing everything to disk directly is probably slightly faster in terms of disk - // speed because it balances out the writes, but this is better than the performance + // speed because it balances out the writes, but this is better than the performance // loss from constantly reading the callbacks let mut writer = BufWriter::with_capacity(1024 * 1024, file); @@ -181,5 +177,4 @@ pub fn download_game_chunk( ctx.checksum, res, ctx.file_name ); } - } diff --git a/src-tauri/src/downloads/progress.rs b/src-tauri/src/downloads/progress.rs index 00a196f..850dba8 100644 --- a/src-tauri/src/downloads/progress.rs +++ b/src-tauri/src/downloads/progress.rs @@ -1,7 +1,6 @@ use atomic_counter::{AtomicCounter, RelaxedCounter}; use log::info; use rayon::ThreadPoolBuilder; -use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex, RwLock}; use super::download_agent::GameDownloadState; @@ -11,7 +10,9 @@ where T: 'static + Send + Sync, { counter: Arc, - f: Arc>, Arc) + Send + Sync + 'static>>, + f: Arc< + Box>, Arc) + Send + Sync + 'static>, + >, status: Arc>, capacity: Mutex, } @@ -21,7 +22,9 @@ where T: Send + Sync, { pub fn new( - f: Box>, Arc) + Send + Sync + 'static>, + f: Box< + dyn Fn(T, Arc>, Arc) + Send + Sync + 'static, + >, counter: Arc, status: Arc>, capacity: usize, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9c52cae..cf68d83 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,8 +2,8 @@ mod auth; mod db; mod downloads; mod library; -mod remote; mod p2p; +mod remote; #[cfg(test)] mod tests; @@ -79,7 +79,7 @@ fn setup() -> AppState { let (app_status, user) = auth::setup().unwrap(); AppState { status: app_status, - user: user, + user, games: HashMap::new(), game_downloads: HashMap::new(), } diff --git a/src-tauri/src/library.rs b/src-tauri/src/library.rs index 80e4134..65f9ec1 100644 --- a/src-tauri/src/library.rs +++ b/src-tauri/src/library.rs @@ -76,7 +76,7 @@ pub fn fetch_library(app: AppHandle) -> Result { return Err(result.err().unwrap().to_string()); } - return Ok(result.unwrap()); + Ok(result.unwrap()) } fn fetch_game_logic(id: String, app: tauri::AppHandle) -> Result { diff --git a/src-tauri/src/p2p/discovery.rs b/src-tauri/src/p2p/discovery.rs index a177538..0b2ec70 100644 --- a/src-tauri/src/p2p/discovery.rs +++ b/src-tauri/src/p2p/discovery.rs @@ -3,7 +3,7 @@ use url::Url; #[derive(Serialize, Deserialize, Debug)] pub struct P2PManager { - peers: Vec + peers: Vec, } #[derive(Serialize, Deserialize, Debug)] @@ -15,12 +15,12 @@ pub struct Peer { impl Peer { pub fn get_current_endpoint(&self) -> Url { - return self.endpoints[self.current_endpoint].clone(); + self.endpoints[self.current_endpoint].clone() } - pub fn connect(&mut self, ) { + pub fn connect(&mut self) { todo!() } pub fn disconnect(&mut self) { todo!() } -} \ No newline at end of file +} diff --git a/src-tauri/src/tests/progress_tests.rs b/src-tauri/src/tests/progress_tests.rs index e7a7ca0..228b22b 100644 --- a/src-tauri/src/tests/progress_tests.rs +++ b/src-tauri/src/tests/progress_tests.rs @@ -26,4 +26,4 @@ fn test_fn(int: usize, _callback: Arc, _counter: Arc println!("{}", int); } -*/ \ No newline at end of file +*/