matrix_sdk/encryption/
futures.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Named futures returned from methods on types in
16//! [the `encryption` module][super].
17
18#![deny(unreachable_pub)]
19
20use std::{future::IntoFuture, io::Read};
21
22use eyeball::{SharedObservable, Subscriber};
23use matrix_sdk_common::boxed_into_future;
24use ruma::events::room::{EncryptedFile, EncryptedFileInit};
25
26use crate::{config::RequestConfig, Client, Media, Result, TransmissionProgress};
27
28/// Future returned by [`Client::upload_encrypted_file`].
29#[allow(missing_debug_implementations)]
30pub struct UploadEncryptedFile<'a, R: ?Sized> {
31    client: &'a Client,
32    reader: &'a mut R,
33    send_progress: SharedObservable<TransmissionProgress>,
34    request_config: Option<RequestConfig>,
35}
36
37impl<'a, R: ?Sized> UploadEncryptedFile<'a, R> {
38    pub(crate) fn new(client: &'a Client, reader: &'a mut R) -> Self {
39        Self { client, reader, send_progress: Default::default(), request_config: None }
40    }
41
42    /// Replace the default `SharedObservable` used for tracking upload
43    /// progress.
44    ///
45    /// Note that any subscribers obtained from
46    /// [`subscribe_to_send_progress`][Self::subscribe_to_send_progress]
47    /// will be invalidated by this.
48    pub fn with_send_progress_observable(
49        mut self,
50        send_progress: SharedObservable<TransmissionProgress>,
51    ) -> Self {
52        self.send_progress = send_progress;
53        self
54    }
55
56    /// Replace the default request config used for the upload request.
57    ///
58    /// The timeout value will be overridden with a reasonable default, based on
59    /// the size of the encrypted payload.
60    pub fn with_request_config(mut self, request_config: RequestConfig) -> Self {
61        self.request_config = Some(request_config);
62        self
63    }
64
65    /// Get a subscriber to observe the progress of sending the request
66    /// body.
67    pub fn subscribe_to_send_progress(&self) -> Subscriber<TransmissionProgress> {
68        self.send_progress.subscribe()
69    }
70}
71
72impl<'a, R> IntoFuture for UploadEncryptedFile<'a, R>
73where
74    R: Read + Send + ?Sized + 'a,
75{
76    type Output = Result<EncryptedFile>;
77    boxed_into_future!(extra_bounds: 'a);
78
79    fn into_future(self) -> Self::IntoFuture {
80        let Self { client, reader, send_progress, request_config } = self;
81        Box::pin(async move {
82            let mut encryptor = matrix_sdk_base::crypto::AttachmentEncryptor::new(reader);
83
84            let mut buf = Vec::new();
85            encryptor.read_to_end(&mut buf)?;
86
87            // Override the reasonable upload timeout value, based on the size of the
88            // encrypted payload.
89            let request_config =
90                request_config.map(|config| config.timeout(Media::reasonable_upload_timeout(&buf)));
91
92            let response = client
93                .media()
94                .upload(&mime::APPLICATION_OCTET_STREAM, buf, request_config)
95                .with_send_progress_observable(send_progress)
96                .await?;
97
98            let file: EncryptedFile = {
99                let keys = encryptor.finish();
100                EncryptedFileInit {
101                    url: response.content_uri,
102                    key: keys.key,
103                    iv: keys.iv,
104                    hashes: keys.hashes,
105                    v: keys.version,
106                }
107                .into()
108            };
109
110            Ok(file)
111        })
112    }
113}