Files
STARTLINER/rust/src/download_handler.rs
2025-02-23 20:54:47 +01:00

60 lines
2.0 KiB
Rust

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()) {
// Todo when there is a clear cache button, it should clear the set
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?;
log::debug!("Downloaded to {}", zip_path.to_string_lossy());
app.emit("download-end", pkg_key)?;
Ok(())
}
}