Skip to main content

tauri_plugin_upload/
lib.rs

1// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5//! Upload files from disk to a remote server over HTTP.
6//!
7//! Download files from a remote HTTP server to disk.
8//!
9//! ## Cargo features
10//!
11//! - **rustls-tls** *(enabled by default)*: Enables TLS functionality provided by `rustls`.
12//! - **native-tls**: Enables TLS functionality provided by `native-tls`.
13//! - **native-tls-vendored**: Enables the `vendored` feature of `native-tls`.
14
15#![doc(
16    html_logo_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png",
17    html_favicon_url = "https://github.com/tauri-apps/tauri/raw/dev/app-icon.png"
18)]
19
20mod transfer_stats;
21use transfer_stats::TransferStats;
22
23use futures_util::TryStreamExt;
24use serde::{ser::Serializer, Deserialize, Serialize};
25use tauri::{
26    command,
27    ipc::Channel,
28    plugin::{Builder as PluginBuilder, TauriPlugin},
29    Runtime,
30};
31use tokio::{
32    fs::File,
33    io::{AsyncWriteExt, BufWriter},
34};
35use tokio_util::codec::{BytesCodec, FramedRead};
36
37use read_progress_stream::ReadProgressStream;
38
39use std::collections::HashMap;
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42#[serde(rename_all = "UPPERCASE")]
43pub enum HttpMethod {
44    Post,
45    Put,
46    Patch,
47}
48
49type Result<T> = std::result::Result<T, Error>;
50
51#[derive(Debug, thiserror::Error)]
52pub enum Error {
53    #[error(transparent)]
54    Io(#[from] std::io::Error),
55    #[error(transparent)]
56    Request(#[from] reqwest::Error),
57    #[error("{0}")]
58    ContentLength(String),
59    #[error("request failed with status code {0}: {1}")]
60    HttpErrorCode(u16, String),
61}
62
63impl Serialize for Error {
64    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
65    where
66        S: Serializer,
67    {
68        serializer.serialize_str(self.to_string().as_ref())
69    }
70}
71
72#[derive(Clone, Serialize)]
73#[serde(rename_all = "camelCase")]
74struct ProgressPayload {
75    progress: u64,
76    progress_total: u64,
77    total: u64,
78    transfer_speed: u64,
79}
80
81#[command]
82async fn download(
83    url: String,
84    file_path: String,
85    headers: HashMap<String, String>,
86    body: Option<String>,
87    on_progress: Channel<ProgressPayload>,
88) -> Result<()> {
89    tokio::spawn(async move {
90        let client = reqwest::Client::new();
91        let mut request = if let Some(body) = body {
92            client.post(&url).body(body)
93        } else {
94            client.get(&url)
95        };
96        // Loop trought the headers keys and values
97        // and add them to the request object.
98        for (key, value) in headers {
99            request = request.header(&key, value);
100        }
101
102        let response = request.send().await?;
103        if !response.status().is_success() {
104            return Err(Error::HttpErrorCode(
105                response.status().as_u16(),
106                response.text().await.unwrap_or_default(),
107            ));
108        }
109        let total = response.content_length().unwrap_or(0);
110
111        let mut file = BufWriter::new(File::create(&file_path).await?);
112        let mut stream = response.bytes_stream();
113
114        let mut stats = TransferStats::default();
115        while let Some(chunk) = stream.try_next().await? {
116            file.write_all(&chunk).await?;
117            stats.record_chunk_transfer(chunk.len());
118            let _ = on_progress.send(ProgressPayload {
119                progress: chunk.len() as u64,
120                progress_total: stats.total_transferred,
121                total,
122                transfer_speed: stats.transfer_speed,
123            });
124        }
125        file.flush().await?;
126        Ok(())
127    })
128    .await
129    .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?
130}
131
132#[command]
133async fn upload(
134    url: String,
135    file_path: String,
136    headers: HashMap<String, String>,
137    method: Option<HttpMethod>,
138    on_progress: Channel<ProgressPayload>,
139) -> Result<String> {
140    tokio::spawn(async move {
141        // Read the file
142        let file = File::open(&file_path).await?;
143        let file_len = file.metadata().await.unwrap().len();
144
145        // Get HTTP method (defaults to POST)
146        let http_method = method.unwrap_or(HttpMethod::Post);
147
148        // Create the request and attach the file to the body
149        let client = reqwest::Client::new();
150        let mut request = match http_method {
151            HttpMethod::Put => client.put(&url),
152            HttpMethod::Patch => client.patch(&url),
153            HttpMethod::Post => client.post(&url),
154        }
155        .header(reqwest::header::CONTENT_LENGTH, file_len)
156        .body(file_to_body(on_progress, file, file_len));
157
158        // Loop through the headers keys and values
159        // and add them to the request object.
160        for (key, value) in headers {
161            request = request.header(&key, value);
162        }
163
164        let response = request.send().await?;
165        if response.status().is_success() {
166            response.text().await.map_err(Into::into)
167        } else {
168            Err(Error::HttpErrorCode(
169                response.status().as_u16(),
170                response.text().await.unwrap_or_default(),
171            ))
172        }
173    })
174    .await
175    .map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?
176}
177
178fn file_to_body(channel: Channel<ProgressPayload>, file: File, file_len: u64) -> reqwest::Body {
179    let stream = FramedRead::new(file, BytesCodec::new()).map_ok(|r| r.freeze());
180
181    let mut stats = TransferStats::default();
182    reqwest::Body::wrap_stream(ReadProgressStream::new(
183        stream,
184        Box::new(move |progress, _total| {
185            stats.record_chunk_transfer(progress as usize);
186            let _ = channel.send(ProgressPayload {
187                progress,
188                progress_total: stats.total_transferred,
189                total: file_len,
190                transfer_speed: stats.transfer_speed,
191            });
192        }),
193    ))
194}
195
196pub fn init<R: Runtime>() -> TauriPlugin<R> {
197    PluginBuilder::new("upload")
198        .invoke_handler(tauri::generate_handler![download, upload])
199        .build()
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use mockito::{self, Mock, Server, ServerGuard};
206    use tauri::ipc::InvokeResponseBody;
207    struct MockedServer {
208        _server: ServerGuard,
209        url: String,
210        mocked_endpoint: Mock,
211    }
212
213    #[tokio::test]
214    async fn should_error_on_download_if_status_not_success() {
215        let mocked_server = spawn_server_mocked(400).await;
216        let result = download_file(mocked_server.url).await;
217        mocked_server.mocked_endpoint.assert();
218        assert!(result.is_err());
219    }
220
221    #[tokio::test]
222    async fn should_download_file_successfully() {
223        let mocked_server = spawn_server_mocked(200).await;
224        let result = download_file(mocked_server.url).await;
225        mocked_server.mocked_endpoint.assert();
226        assert!(
227            result.is_ok(),
228            "failed to download file: {}",
229            result.unwrap_err()
230        );
231    }
232
233    #[tokio::test]
234    async fn should_error_on_upload_if_status_not_success() {
235        let mocked_server = spawn_upload_server_mocked(500, "POST").await;
236        let result = upload_file(mocked_server.url, None).await;
237        mocked_server.mocked_endpoint.assert();
238        assert!(result.is_err());
239        match result.unwrap_err() {
240            Error::HttpErrorCode(status, _) => assert_eq!(status, 500),
241            _ => panic!("Expected HttpErrorCode error"),
242        }
243    }
244
245    #[tokio::test]
246    async fn should_error_on_upload_if_file_not_found() {
247        let mocked_server = spawn_upload_server_mocked(200, "POST").await;
248        let file_path = "/nonexistent/file.txt".to_string();
249        let headers = HashMap::new();
250        let sender: Channel<ProgressPayload> =
251            Channel::new(|msg: InvokeResponseBody| -> tauri::Result<()> {
252                let _ = msg;
253                Ok(())
254            });
255
256        let result = upload(mocked_server.url, file_path, headers, None, sender).await;
257        assert!(result.is_err());
258        match result.unwrap_err() {
259            Error::Io(_) => {}
260            _ => panic!("Expected IO error for missing file"),
261        }
262    }
263
264    #[tokio::test]
265    async fn should_upload_file_with_post_method() {
266        let mocked_server = spawn_upload_server_mocked(200, "POST").await;
267        let result = upload_file(mocked_server.url, Some(HttpMethod::Post)).await;
268        mocked_server.mocked_endpoint.assert();
269        assert!(
270            result.is_ok(),
271            "failed to upload file: {}",
272            result.unwrap_err()
273        );
274        let response_body = result.unwrap();
275        assert_eq!(response_body, "upload successful");
276    }
277
278    #[tokio::test]
279    async fn should_upload_file_with_put_method() {
280        let mocked_server = spawn_upload_server_mocked(200, "PUT").await;
281        let result = upload_file(mocked_server.url, Some(HttpMethod::Put)).await;
282        mocked_server.mocked_endpoint.assert();
283        assert!(
284            result.is_ok(),
285            "failed to upload file with PUT: {}",
286            result.unwrap_err()
287        );
288        let response_body = result.unwrap();
289        assert_eq!(response_body, "upload successful");
290    }
291
292    #[tokio::test]
293    async fn should_upload_file_with_patch_method() {
294        let mocked_server = spawn_upload_server_mocked(200, "PATCH").await;
295        let result = upload_file(mocked_server.url, Some(HttpMethod::Patch)).await;
296        mocked_server.mocked_endpoint.assert();
297        assert!(
298            result.is_ok(),
299            "failed to upload file with PATCH: {}",
300            result.unwrap_err()
301        );
302        let response_body = result.unwrap();
303        assert_eq!(response_body, "upload successful");
304    }
305
306    async fn download_file(url: String) -> Result<()> {
307        let file_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/download.txt").to_string();
308        let headers = HashMap::new();
309        let sender: Channel<ProgressPayload> =
310            Channel::new(|msg: InvokeResponseBody| -> tauri::Result<()> {
311                let _ = msg;
312                Ok(())
313            });
314        download(url, file_path, headers, None, sender).await
315    }
316
317    async fn upload_file(url: String, method: Option<HttpMethod>) -> Result<String> {
318        let file_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test/upload.txt").to_string();
319        let headers = HashMap::new();
320        let sender: Channel<ProgressPayload> =
321            Channel::new(|msg: InvokeResponseBody| -> tauri::Result<()> {
322                let _ = msg;
323                Ok(())
324            });
325        upload(url, file_path, headers, method, sender).await
326    }
327
328    async fn spawn_server_mocked(return_status: usize) -> MockedServer {
329        let mut _server = Server::new_async().await;
330        let path = "/mock_test";
331        let mock = _server
332            .mock("GET", path)
333            .with_status(return_status)
334            .with_body("mocked response body")
335            .create_async()
336            .await;
337
338        let url = _server.url() + path;
339        MockedServer {
340            _server,
341            url,
342            mocked_endpoint: mock,
343        }
344    }
345
346    async fn spawn_upload_server_mocked(return_status: usize, method: &str) -> MockedServer {
347        let mut _server = Server::new_async().await;
348        let path = "/upload_test";
349        let mock = _server
350            .mock(method, path)
351            .with_status(return_status)
352            .with_body("upload successful")
353            .match_header("content-length", "20")
354            .create_async()
355            .await;
356
357        let url = _server.url() + path;
358        MockedServer {
359            _server,
360            url,
361            mocked_endpoint: mock,
362        }
363    }
364}