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 {
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]

View File

@ -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};

View File

@ -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<AppState>>,
game_id: 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);
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()
}
}

View File

@ -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<RwLock<GameDownloadState>>,
}
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 {
file: OpenOptions::new().write(true).open(path).unwrap(),
hasher: Context::new(),
progress,
status
status,
}
}
fn finish(mut self) -> io::Result<Digest> {
self.flush().unwrap();
Ok(self.hasher.compute())
}
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::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
);
}
}

View File

@ -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<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>>,
capacity: Mutex<usize>,
}
@ -21,7 +22,9 @@ where
T: Send + Sync,
{
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>,
status: Arc<RwLock<GameDownloadState>>,
capacity: usize,

View File

@ -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(),
}

View File

@ -76,7 +76,7 @@ pub fn fetch_library(app: AppHandle) -> Result<String, 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> {

View File

@ -3,7 +3,7 @@ use url::Url;
#[derive(Serialize, Deserialize, Debug)]
pub struct P2PManager {
peers: Vec<Peer>
peers: Vec<Peer>,
}
#[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!()
}
}
}

View File

@ -26,4 +26,4 @@ fn test_fn(int: usize, _callback: Arc<AtomicBool>, _counter: Arc<RelaxedCounter>
println!("{}", int);
}
*/
*/