teloxide_core/bot/
download.rs1use std::path::Path;
2
3use bytes::Bytes;
4use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt, TryStreamExt};
5
6use tokio::{
7 fs::File,
8 io::{AsyncReadExt, AsyncWrite, AsyncWriteExt},
9};
10
11use crate::{
12 bot::Bot,
13 net::{self, Download},
14 DownloadError,
15};
16
17impl Download for Bot {
18 type Err<'dst> = DownloadError;
19
20 type Fut<'dst> = BoxFuture<'dst, Result<(), Self::Err<'dst>>>;
23
24 fn download_file<'dst>(
25 &self,
26 path: &'dst str,
27 destination: &'dst mut (dyn AsyncWrite + Unpin + Send),
28 ) -> Self::Fut<'dst> {
29 if self.is_local_file(path) {
30 return copy_file(path, destination).boxed();
31 }
32
33 net::download_file(
34 &self.client,
35 reqwest::Url::clone(&*self.api_url),
36 &self.token,
37 path,
38 destination,
39 )
40 .boxed()
41 }
42
43 type StreamErr = DownloadError;
44
45 type Stream = BoxStream<'static, Result<Bytes, Self::StreamErr>>;
46
47 fn download_file_stream(&self, path: &str) -> Self::Stream {
48 if self.is_local_file(path) {
49 let path = path.to_owned();
50 return futures::stream::once(async move {
51 let file = File::open(path).await?;
52 Ok::<_, DownloadError>(
53 tokio_util::io::ReaderStream::new(file).map_err(DownloadError::from),
54 )
55 })
56 .try_flatten()
57 .boxed();
58 }
59
60 net::download_file_stream(
61 &self.client,
62 reqwest::Url::clone(&*self.api_url),
63 &self.token,
64 path,
65 )
66 .boxed()
67 }
68}
69
70impl Bot {
71 fn is_local_file(&self, path: &str) -> bool {
72 Path::new(path).is_absolute()
73 && matches!(self.api_url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
74 }
75}
76
77async fn copy_file<'o, D>(path: &'o str, dst: &'o mut D) -> Result<(), DownloadError>
78where
79 D: ?Sized + AsyncWrite + Unpin,
80{
81 let mut src_file = File::open(path).await?;
82
83 let mut buffer = [0; 128 * 1024];
84 loop {
85 let n = src_file.read(&mut buffer).await?;
86 if n == 0 {
87 break;
88 }
89
90 dst.write_all(&buffer[..n]).await?;
91 }
92
93 dst.flush().await?;
94 Ok(())
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[tokio::test]
102 async fn download_stream_and_writer_share_local_source_selection() {
103 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
104 let path = dir.join("schema.ron");
105 let path = path.to_str().unwrap();
106 let bot = Bot::new("not-used").set_api_url("http://[::1]:80".parse().unwrap());
107 let mut via_writer = Vec::new();
108 bot.download_file(path, &mut via_writer).await.unwrap();
109 let via_stream = bot
110 .download_file_stream(path)
111 .try_fold(Vec::new(), |mut data, chunk| async move {
112 data.extend_from_slice(&chunk);
113 Ok(data)
114 })
115 .await
116 .unwrap();
117 assert_eq!(via_stream, via_writer);
118 assert_eq!(via_stream, include_bytes!("../../schema.ron"));
119 }
120}