jmap_client/blob/
download.rs

1/*
2 * Copyright Stalwart Labs Ltd. See the COPYING
3 * file at the top-level directory of this distribution.
4 *
5 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8 * option. This file may not be copied, modified, or distributed
9 * except according to those terms.
10 */
11
12use reqwest::header::CONTENT_TYPE;
13
14use crate::{client::Client, core::session::URLPart};
15
16#[cfg(feature = "blocking")]
17use reqwest::blocking::Client as HttpClient;
18#[cfg(feature = "async")]
19use reqwest::Client as HttpClient;
20
21impl Client {
22    #[maybe_async::maybe_async]
23    pub async fn download(&self, blob_id: &str) -> crate::Result<Vec<u8>> {
24        let account_id = self.default_account_id();
25        let mut download_url = String::with_capacity(
26            self.session().download_url().len() + account_id.len() + blob_id.len(),
27        );
28
29        for part in self.download_url() {
30            match part {
31                URLPart::Value(value) => {
32                    download_url.push_str(value);
33                }
34                URLPart::Parameter(param) => match param {
35                    super::URLParameter::AccountId => {
36                        download_url.push_str(account_id);
37                    }
38                    super::URLParameter::BlobId => {
39                        download_url.push_str(blob_id);
40                    }
41                    super::URLParameter::Name => {
42                        download_url.push_str("none");
43                    }
44                    super::URLParameter::Type => {
45                        download_url.push_str("application/octet-stream");
46                    }
47                },
48            }
49        }
50
51        let mut headers = self.headers().clone();
52        headers.remove(CONTENT_TYPE);
53
54        Client::handle_error(
55            HttpClient::builder()
56                .timeout(self.timeout())
57                .danger_accept_invalid_certs(self.accept_invalid_certs)
58                .redirect(self.redirect_policy())
59                .default_headers(headers)
60                .build()?
61                .get(download_url)
62                .send()
63                .await?,
64        )
65        .await?
66        .bytes()
67        .await
68        .map(|bytes| bytes.to_vec())
69        .map_err(|err| err.into())
70    }
71}