feat: phase 2
Newfound motivation
This commit is contained in:
57
rust/src/download_handler.rs
Normal file
57
rust/src/download_handler.rs
Normal file
@ -0,0 +1,57 @@
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tokio::fs::File;
|
||||
use anyhow::{anyhow, Result};
|
||||
|
||||
use crate::pkg::{Package, PkgKey, Remote};
|
||||
|
||||
pub struct DownloadHandler {
|
||||
set: HashSet<String>,
|
||||
app: AppHandle
|
||||
}
|
||||
|
||||
impl DownloadHandler {
|
||||
pub fn new(app: AppHandle) -> DownloadHandler {
|
||||
DownloadHandler {
|
||||
set: HashSet::new(),
|
||||
app
|
||||
}
|
||||
}
|
||||
|
||||
pub fn download_zip(&mut self, zip_path: &PathBuf, pkg: &Package) -> Result<()> {
|
||||
let rmt = pkg.rmt.as_ref()
|
||||
.ok_or_else(|| anyhow!("Attempted to download a package without remote data"))?
|
||||
.clone();
|
||||
if self.set.contains(zip_path.to_string_lossy().as_ref()) {
|
||||
Err(anyhow!("Already downloading"))
|
||||
} else {
|
||||
self.set.insert(zip_path.to_string_lossy().to_string());
|
||||
tauri::async_runtime::spawn(Self::download_zip_proc(self.app.clone(), zip_path.clone(), pkg.key(), rmt));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_zip_proc(app: AppHandle, zip_path: PathBuf, pkg_key: PkgKey, rmt: Remote) -> Result<()> {
|
||||
use futures::StreamExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
// let zip_path_part = zip_path.add_extension("part");
|
||||
let mut zip_path_part = zip_path.to_owned();
|
||||
zip_path_part.set_extension("zip.part");
|
||||
|
||||
let mut cache_file_w = File::create(&zip_path_part).await?;
|
||||
let mut byte_stream = reqwest::get(&rmt.download_url).await?.bytes_stream();
|
||||
|
||||
log::info!("Downloading: {}", rmt.download_url);
|
||||
while let Some(item) = byte_stream.next().await {
|
||||
let i = item?;
|
||||
cache_file_w.write_all(&mut i.as_ref()).await?;
|
||||
}
|
||||
cache_file_w.sync_all().await?;
|
||||
tokio::fs::rename(&zip_path_part, &zip_path).await?;
|
||||
|
||||
app.emit("download-end", pkg_key)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user