feat: add upload progress bar

This commit is contained in:
uku 2025-05-12 22:54:13 +02:00
parent ca96431208
commit 3b75134572
Signed by: uku
SSH key fingerprint: SHA256:4P0aN6M8ajKukNi6aPOaX0LacanGYtlfjmN+m/sHY/o
4 changed files with 125 additions and 27 deletions

View file

@ -1,9 +1,16 @@
use std::{path::Path, sync::LazyLock};
use color_eyre::eyre::{Result, bail};
use reqwest::{Client, StatusCode, header::AUTHORIZATION, multipart::Form};
use futures::StreamExt;
use relm4::{Sender, tokio::fs::File};
use reqwest::{
Body, Client, StatusCode,
header::AUTHORIZATION,
multipart::{Form, Part},
};
use tokio_util::io::ReaderStream;
use crate::Config;
use crate::{Config, ProgressMessage};
static CLIENT: LazyLock<Client> = LazyLock::new(Client::new);
@ -42,6 +49,31 @@ impl ZiplineFileInfo {
}
}
async fn wrap_file(path: &Path, sender: Sender<ProgressMessage>) -> Result<Part> {
let file_name = path
.file_name()
.map(|filename| filename.to_string_lossy().into_owned());
let file = File::open(path).await?;
let len = file.metadata().await?.len();
sender.emit(ProgressMessage::SetTotal(len as usize));
let stream = ReaderStream::new(file).map(move |b| {
if let Ok(ref bytes) = b {
sender.emit(ProgressMessage::Progress(bytes.len()));
}
b
});
let field = Part::stream_with_length(Body::wrap_stream(stream), len).mime_str("video/webm")?;
Ok(if let Some(file_name) = file_name {
field.file_name(file_name)
} else {
field
})
}
pub async fn get_folders(config: &Config) -> Result<Vec<ZiplineFolder>> {
let url = format!("{}api/user/folders?noincl=true", config.fixed_url());
@ -64,14 +96,14 @@ pub async fn get_folders(config: &Config) -> Result<Vec<ZiplineFolder>> {
pub async fn upload_file(
config: &Config,
sender: &Sender<ProgressMessage>,
folder: Option<&ZiplineFolder>,
file_path: &Path,
) -> Result<ZiplineUploadResponse> {
let url = format!("{}api/upload", config.fixed_url());
// TODO use Part::stream to provide a wrapped file with a custom stream impl to send progress
// (i hope it works)
let form = Form::new().file("file", file_path).await?;
let wrapped_file = wrap_file(file_path, sender.clone()).await?;
let form = Form::new().part("file", wrapped_file);
let mut req = CLIENT
.post(url)