mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-07-04 15:47:50 +02:00
feat(upload): Add transfer_speed for downloading and uploading files (#1797)
Co-authored-by: Victor Aremu <me@victorare.mu> Co-authored-by: Fabian-Lars <github@fabianlars.de>
This commit is contained in:
@@ -13,6 +13,9 @@
|
||||
html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
|
||||
)]
|
||||
|
||||
mod transfer_stats;
|
||||
use transfer_stats::TransferStats;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use serde::{ser::Serializer, Serialize};
|
||||
use tauri::{
|
||||
@@ -55,9 +58,11 @@ impl Serialize for Error {
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ProgressPayload {
|
||||
progress: u64,
|
||||
total: u64,
|
||||
transfer_speed: u64,
|
||||
}
|
||||
|
||||
#[command]
|
||||
@@ -88,11 +93,14 @@ async fn download(
|
||||
let mut file = BufWriter::new(File::create(file_path).await?);
|
||||
let mut stream = response.bytes_stream();
|
||||
|
||||
let mut stats = TransferStats::default();
|
||||
while let Some(chunk) = stream.try_next().await? {
|
||||
file.write_all(&chunk).await?;
|
||||
stats.record_chunk_transfer(chunk.len());
|
||||
let _ = on_progress.send(ProgressPayload {
|
||||
progress: chunk.len() as u64,
|
||||
total,
|
||||
transfer_speed: stats.transfer_speed,
|
||||
});
|
||||
}
|
||||
file.flush().await?;
|
||||
@@ -138,10 +146,16 @@ async fn upload(
|
||||
fn file_to_body(channel: Channel<ProgressPayload>, file: File) -> reqwest::Body {
|
||||
let stream = FramedRead::new(file, BytesCodec::new()).map_ok(|r| r.freeze());
|
||||
|
||||
let mut stats = TransferStats::default();
|
||||
reqwest::Body::wrap_stream(ReadProgressStream::new(
|
||||
stream,
|
||||
Box::new(move |progress, total| {
|
||||
let _ = channel.send(ProgressPayload { progress, total });
|
||||
stats.record_chunk_transfer(progress as usize);
|
||||
let _ = channel.send(ProgressPayload {
|
||||
progress,
|
||||
total,
|
||||
transfer_speed: stats.transfer_speed,
|
||||
});
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user