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

@ -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,