2025-02-11 00:56:14 +01:00
|
|
|
use iced::futures::StreamExt;
|
2025-02-21 01:28:47 +01:00
|
|
|
use iced::task::{Straw, sipper};
|
2022-01-15 11:45:19 +07:00
|
|
|
|
2024-09-10 19:24:30 +02:00
|
|
|
use std::sync::Arc;
|
2020-03-23 15:54:23 +01:00
|
|
|
|
2025-02-11 00:56:14 +01:00
|
|
|
pub fn download(url: impl AsRef<str>) -> impl Straw<(), Progress, Error> {
|
2025-02-21 02:01:42 +01:00
|
|
|
sipper(async move |mut progress| {
|
2024-11-22 02:14:33 +01:00
|
|
|
let response = reqwest::get(url.as_ref()).await?;
|
2024-09-10 19:24:30 +02:00
|
|
|
let total = response.content_length().ok_or(Error::NoContentLength)?;
|
2022-01-15 11:45:19 +07:00
|
|
|
|
2025-02-11 00:56:14 +01:00
|
|
|
let _ = progress.send(Progress { percent: 0.0 }).await;
|
2024-09-10 19:24:30 +02:00
|
|
|
|
|
|
|
|
let mut byte_stream = response.bytes_stream();
|
|
|
|
|
let mut downloaded = 0;
|
2022-01-17 15:29:41 +07:00
|
|
|
|
2024-09-10 19:24:30 +02:00
|
|
|
while let Some(next_bytes) = byte_stream.next().await {
|
|
|
|
|
let bytes = next_bytes?;
|
|
|
|
|
downloaded += bytes.len();
|
2022-01-17 15:29:41 +07:00
|
|
|
|
2025-02-11 00:56:14 +01:00
|
|
|
let _ = progress
|
|
|
|
|
.send(Progress {
|
2024-09-10 19:24:30 +02:00
|
|
|
percent: 100.0 * downloaded as f32 / total as f32,
|
|
|
|
|
})
|
|
|
|
|
.await;
|
2022-01-17 15:29:41 +07:00
|
|
|
}
|
2024-09-10 19:24:30 +02:00
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
})
|
2020-03-23 15:54:23 +01:00
|
|
|
}
|
|
|
|
|
|
2020-03-23 20:34:16 +01:00
|
|
|
#[derive(Debug, Clone)]
|
2025-02-11 00:56:14 +01:00
|
|
|
pub struct Progress {
|
|
|
|
|
pub percent: f32,
|
2020-03-23 15:54:23 +01:00
|
|
|
}
|
|
|
|
|
|
2024-09-10 19:24:30 +02:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
|
pub enum Error {
|
|
|
|
|
RequestFailed(Arc<reqwest::Error>),
|
|
|
|
|
NoContentLength,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl From<reqwest::Error> for Error {
|
|
|
|
|
fn from(error: reqwest::Error) -> Self {
|
|
|
|
|
Error::RequestFailed(Arc::new(error))
|
|
|
|
|
}
|
2020-03-23 15:54:23 +01:00
|
|
|
}
|