teloxide-fork-core 0.16.0

Core part of the `teloxide` library - telegram bot API client
Documentation
use std::path::Path;

use bytes::Bytes;
use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryStreamExt};

use tokio::{
    fs::File,
    io::{AsyncReadExt, AsyncWrite, AsyncWriteExt},
};

use crate::{
    bot::Bot,
    net::{self, Download},
    DownloadError,
};

impl Download for Bot {
    type Err<'dst> = DownloadError;

    // I would like to unbox this, but my coworkers will kill me if they'll see yet
    // another hand written `Future`. (waffle)
    type Fut<'dst> = BoxFuture<'dst, Result<(), Self::Err<'dst>>>;

    fn download_file<'dst>(
        &self,
        path: &'dst str,
        destination: &'dst mut (dyn AsyncWrite + Unpin + Send),
    ) -> Self::Fut<'dst> {
        if self.is_local_file(path) {
            return copy_file(path, destination).boxed();
        }

        net::download_file(
            &self.client,
            reqwest::Url::clone(&*self.api_url),
            &self.token,
            path,
            destination,
        )
        .boxed()
    }

    type StreamErr = DownloadError;

    type Stream = BoxStream<'static, Result<Bytes, Self::StreamErr>>;

    fn download_file_stream(&self, path: &str) -> Self::Stream {
        if self.is_local_file(path) {
            let path = path.to_owned();
            return futures::stream::once(async move {
                let file = File::open(path).await?;
                Ok::<_, DownloadError>(
                    tokio_util::io::ReaderStream::new(file).map_err(DownloadError::from),
                )
            })
            .try_flatten()
            .boxed();
        }

        net::download_file_stream(
            &self.client,
            reqwest::Url::clone(&*self.api_url),
            &self.token,
            path,
        )
        .boxed()
    }
}

impl Bot {
    fn is_local_file(&self, path: &str) -> bool {
        Path::new(path).is_absolute()
            && matches!(self.api_url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
    }
}

async fn copy_file<'o, D>(path: &'o str, dst: &'o mut D) -> Result<(), DownloadError>
where
    D: ?Sized + AsyncWrite + Unpin,
{
    let mut src_file = File::open(path).await?;

    let mut buffer = [0; 128 * 1024];
    loop {
        let n = src_file.read(&mut buffer).await?;
        if n == 0 {
            break;
        }

        dst.write_all(&buffer[..n]).await?;
    }

    dst.flush().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn download_stream_and_writer_share_local_source_selection() {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let path = dir.join("schema.ron");
        let path = path.to_str().unwrap();
        let bot = Bot::new("not-used").set_api_url("http://[::1]:80".parse().unwrap());
        let mut via_writer = Vec::new();
        bot.download_file(path, &mut via_writer).await.unwrap();
        let via_stream = bot
            .download_file_stream(path)
            .try_fold(Vec::new(), |mut data, chunk| async move {
                data.extend_from_slice(&chunk);
                Ok(data)
            })
            .await
            .unwrap();
        assert_eq!(via_stream, via_writer);
        assert_eq!(via_stream, include_bytes!("../../schema.ron"));
    }
}