refactor: Cleaning up downloads playing and pausing

Signed-off-by: quexeky <git@quexeky.dev>
This commit is contained in:
quexeky
2024-11-09 19:57:53 +11:00
parent 55b7921ee6
commit 2c7b5fb47d
9 changed files with 60 additions and 61 deletions

View File

@ -94,7 +94,7 @@ fn recieve_handshake_logic(app: &AppHandle, path: String) -> Result<(), RemoteAc
if path_chunks.len() != 3 { if path_chunks.len() != 3 {
app.emit("auth/failed", ()).unwrap(); app.emit("auth/failed", ()).unwrap();
return Err(RemoteAccessError::GenericErrror( 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()?); app_state_handle.user = Some(fetch_user()?);
} }
return Ok(()); Ok(())
} }
pub fn recieve_handshake(app: AppHandle, path: String) { 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"); info!("opening web browser to continue authentication");
webbrowser::open(complete_redir_url.as_ref()).unwrap(); webbrowser::open(complete_redir_url.as_ref()).unwrap();
return Ok(()); Ok(())
} }
#[tauri::command] #[tauri::command]

View File

@ -5,7 +5,6 @@ use crate::downloads::manifest::{DropDownloadContext, DropManifest};
use crate::downloads::progress::ProgressChecker; use crate::downloads::progress::ProgressChecker;
use crate::DB; use crate::DB;
use atomic_counter::RelaxedCounter; use atomic_counter::RelaxedCounter;
use http::status;
use log::info; use log::info;
use rustix::fs::{fallocate, FallocateFlags}; use rustix::fs::{fallocate, FallocateFlags};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

View File

@ -1,5 +1,5 @@
use std::{ use std::{
sync::{atomic::Ordering, Arc, Mutex}, sync::{Arc, Mutex},
thread, thread,
}; };
@ -95,7 +95,7 @@ pub async fn cancel_specific_game_download(
game_id: String, game_id: String,
) -> Result<(), String> { ) -> Result<(), String> {
info!("called stop_specific_game_download"); 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 //TODO: Drop the game download instance
@ -109,7 +109,9 @@ pub async fn get_game_download_progress(
state: tauri::State<'_, Mutex<AppState>>, state: tauri::State<'_, Mutex<AppState>>,
game_id: String, game_id: String,
) -> Result<f64, String> { ) -> Result<f64, String> {
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); info!("{}", progress);
Ok(progress) Ok(progress)
} }

View File

@ -6,17 +6,13 @@ use atomic_counter::{AtomicCounter, RelaxedCounter};
use log::{error, info}; use log::{error, info};
use md5::{Context, Digest}; use md5::{Context, Digest};
#[cfg(windows)]
use tokio::signal::windows::Signal;
use tokio::sync::{broadcast::Receiver, mpsc};
use std::{ use std::{
fs::{File, OpenOptions}, fs::{File, OpenOptions},
io::{self, BufWriter, Error, ErrorKind, Seek, SeekFrom, Write}, io::{self, BufWriter, Error, ErrorKind, Seek, SeekFrom, Write},
path::PathBuf, path::PathBuf,
sync::{ sync::{Arc, RwLock},
atomic::{AtomicBool, Ordering}, thread::sleep,
Arc, RwLock, time::Duration,
}, thread::sleep, time::Duration,
}; };
use urlencoding::encode; use urlencoding::encode;
@ -29,12 +25,16 @@ pub struct DropFileWriter {
status: Arc<RwLock<GameDownloadState>>, status: Arc<RwLock<GameDownloadState>>,
} }
impl DropFileWriter { impl DropFileWriter {
fn new(path: PathBuf, status: Arc<RwLock<GameDownloadState>>, progress: Arc<RelaxedCounter>) -> Self { fn new(
path: PathBuf,
status: Arc<RwLock<GameDownloadState>>,
progress: Arc<RelaxedCounter>,
) -> Self {
Self { Self {
file: OpenOptions::new().write(true).open(path).unwrap(), file: OpenOptions::new().write(true).open(path).unwrap(),
hasher: Context::new(), hasher: Context::new(),
progress, progress,
status status,
} }
} }
fn finish(mut self) -> io::Result<Digest> { fn finish(mut self) -> io::Result<Digest> {
@ -43,46 +43,43 @@ impl DropFileWriter {
} }
fn manage_state(&mut self) -> Option<Result<usize, Error>> { fn manage_state(&mut self) -> Option<Result<usize, Error>> {
match {self.status.read().unwrap().clone()} { match self.status.read().unwrap().clone() {
GameDownloadState::Uninitialised => todo!(), GameDownloadState::Uninitialised => todo!(),
GameDownloadState::Queued => { GameDownloadState::Queued => {
return Some(Err(Error::new( return Some(Err(Error::new(
ErrorKind::NotConnected, ErrorKind::NotConnected,
"Download has not yet been started" "Download has not yet been started",
))) )))
}, }
GameDownloadState::Manifest => { GameDownloadState::Manifest => {
return Some(Err(Error::new( return Some(Err(Error::new(
ErrorKind::NotFound, ErrorKind::NotFound,
"Manifest still not finished downloading" "Manifest still not finished downloading",
))) )))
}, }
GameDownloadState::Downloading => {}, GameDownloadState::Downloading => {}
GameDownloadState::Finished => { GameDownloadState::Finished => {
return Some(Err(Error::new( return Some(Err(Error::new(
ErrorKind::AlreadyExists, "Download already finished"))) ErrorKind::AlreadyExists,
}, "Download already finished",
)))
}
GameDownloadState::Stalled => { GameDownloadState::Stalled => {
return Some(Err(Error::new( return Some(Err(Error::new(ErrorKind::Interrupted, "Download Stalled")))
ErrorKind::Interrupted, "Download Stalled" }
)))
},
GameDownloadState::Failed => { GameDownloadState::Failed => {
return Some(Err(Error::new( return Some(Err(Error::new(ErrorKind::BrokenPipe, "Download Failed")))
ErrorKind::BrokenPipe, }
"Download Failed"
)))
},
GameDownloadState::Cancelled => { GameDownloadState::Cancelled => {
return Some(Err(Error::new( return Some(Err(Error::new(
ErrorKind::ConnectionAborted, ErrorKind::ConnectionAborted,
"Interrupt command recieved", "Interrupt command recieved",
))); )));
}, }
GameDownloadState::Paused => { GameDownloadState::Paused => {
info!("Game download paused"); info!("Game download paused");
sleep(Duration::from_secs(1)); sleep(Duration::from_secs(1));
}, }
}; };
None None
} }
@ -137,15 +134,14 @@ pub fn download_game_chunk(
let header = generate_authorization_header(); let header = generate_authorization_header();
let mut response = match client let mut response = match client.get(chunk_url).header("Authorization", header).send() {
.get(chunk_url)
.header("Authorization", header)
.send() {
Ok(response) => response, Ok(response) => response,
Err(e) => { info!("{}", e); return; }, Err(e) => {
info!("{}", e);
return;
}
}; };
let mut file: DropFileWriter = DropFileWriter::new(ctx.path, status, progress); let mut file: DropFileWriter = DropFileWriter::new(ctx.path, status, progress);
if ctx.offset != 0 { if ctx.offset != 0 {
@ -181,5 +177,4 @@ pub fn download_game_chunk(
ctx.checksum, res, ctx.file_name ctx.checksum, res, ctx.file_name
); );
} }
} }

View File

@ -1,7 +1,6 @@
use atomic_counter::{AtomicCounter, RelaxedCounter}; use atomic_counter::{AtomicCounter, RelaxedCounter};
use log::info; use log::info;
use rayon::ThreadPoolBuilder; use rayon::ThreadPoolBuilder;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex, RwLock}; use std::sync::{Arc, Mutex, RwLock};
use super::download_agent::GameDownloadState; use super::download_agent::GameDownloadState;
@ -11,7 +10,9 @@ where
T: 'static + Send + Sync, T: 'static + Send + Sync,
{ {
counter: Arc<RelaxedCounter>, counter: Arc<RelaxedCounter>,
f: Arc<Box<dyn Fn(T, Arc<RwLock<GameDownloadState>>, Arc<RelaxedCounter>) + Send + Sync + 'static>>, f: Arc<
Box<dyn Fn(T, Arc<RwLock<GameDownloadState>>, Arc<RelaxedCounter>) + Send + Sync + 'static>,
>,
status: Arc<RwLock<GameDownloadState>>, status: Arc<RwLock<GameDownloadState>>,
capacity: Mutex<usize>, capacity: Mutex<usize>,
} }
@ -21,7 +22,9 @@ where
T: Send + Sync, T: Send + Sync,
{ {
pub fn new( pub fn new(
f: Box<dyn Fn(T, Arc<RwLock<GameDownloadState>>, Arc<RelaxedCounter>) + Send + Sync + 'static>, f: Box<
dyn Fn(T, Arc<RwLock<GameDownloadState>>, Arc<RelaxedCounter>) + Send + Sync + 'static,
>,
counter: Arc<RelaxedCounter>, counter: Arc<RelaxedCounter>,
status: Arc<RwLock<GameDownloadState>>, status: Arc<RwLock<GameDownloadState>>,
capacity: usize, capacity: usize,

View File

@ -2,8 +2,8 @@ mod auth;
mod db; mod db;
mod downloads; mod downloads;
mod library; mod library;
mod remote;
mod p2p; mod p2p;
mod remote;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
@ -79,7 +79,7 @@ fn setup() -> AppState {
let (app_status, user) = auth::setup().unwrap(); let (app_status, user) = auth::setup().unwrap();
AppState { AppState {
status: app_status, status: app_status,
user: user, user,
games: HashMap::new(), games: HashMap::new(),
game_downloads: HashMap::new(), game_downloads: HashMap::new(),
} }

View File

@ -76,7 +76,7 @@ pub fn fetch_library(app: AppHandle) -> Result<String, String> {
return Err(result.err().unwrap().to_string()); return Err(result.err().unwrap().to_string());
} }
return Ok(result.unwrap()); Ok(result.unwrap())
} }
fn fetch_game_logic(id: String, app: tauri::AppHandle) -> Result<String, RemoteAccessError> { fn fetch_game_logic(id: String, app: tauri::AppHandle) -> Result<String, RemoteAccessError> {

View File

@ -3,7 +3,7 @@ use url::Url;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct P2PManager { pub struct P2PManager {
peers: Vec<Peer> peers: Vec<Peer>,
} }
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
@ -15,9 +15,9 @@ pub struct Peer {
impl Peer { impl Peer {
pub fn get_current_endpoint(&self) -> Url { 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!() todo!()
} }
pub fn disconnect(&mut self) { pub fn disconnect(&mut self) {