use std::future::Future;
use bytes::Bytes;
use futures::{stream::once, Stream, StreamExt, TryStreamExt};
use reqwest::{Client, Url};
use tokio::io::{AsyncWrite, AsyncWriteExt};
use crate::{errors::DownloadError, net::file_url};
pub trait Download {
type Err<'dst>;
type Fut<'dst>: Future<Output = Result<(), Self::Err<'dst>>> + Send;
fn download_file<'dst>(
&self,
path: &'dst str,
destination: &'dst mut (dyn AsyncWrite + Unpin + Send),
) -> Self::Fut<'dst>;
type StreamErr;
type Stream: Stream<Item = Result<Bytes, Self::StreamErr>> + Send;
fn download_file_stream(&self, path: &str) -> Self::Stream;
}
pub fn download_file<'o, D>(
client: &Client,
api_url: Url,
token: &str,
path: &str,
dst: &'o mut D,
) -> impl Future<Output = Result<(), DownloadError>> + 'o
where
D: ?Sized + AsyncWrite + Unpin,
{
let chunks = download_file_stream(client, api_url, token, path);
async move {
futures::pin_mut!(chunks);
while let Some(chunk) = chunks.next().await {
dst.write_all(&chunk?).await?;
}
Ok(())
}
}
pub fn download_file_stream(
client: &Client,
api_url: Url,
token: &str,
path: &str,
) -> impl Stream<Item = Result<Bytes, DownloadError>> + Send + 'static {
let request = file_url(api_url, token, path).map(|url| client.get(url).send());
once(async move {
let response = request?.await?.error_for_status()?;
Ok::<_, DownloadError>(response.bytes_stream().map_err(DownloadError::from))
})
.try_flatten()
}