matrix_sdk/encryption/
futures.rs1#![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#[allow(missing_debug_implementations)]
30pub struct UploadEncryptedFile<'a, R: ?Sized> {
31 client: 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: &Client, reader: &'a mut R) -> Self {
39 Self {
40 client: client.clone(),
41 reader,
42 send_progress: Default::default(),
43 request_config: None,
44 }
45 }
46
47 pub fn with_send_progress_observable(
54 mut self,
55 send_progress: SharedObservable<TransmissionProgress>,
56 ) -> Self {
57 self.send_progress = send_progress;
58 self
59 }
60
61 pub fn with_request_config(mut self, request_config: RequestConfig) -> Self {
66 self.request_config = Some(request_config);
67 self
68 }
69
70 pub fn subscribe_to_send_progress(&self) -> Subscriber<TransmissionProgress> {
73 self.send_progress.subscribe()
74 }
75}
76
77impl<'a, R> IntoFuture for UploadEncryptedFile<'a, R>
78where
79 R: Read + Send + ?Sized + 'a,
80{
81 type Output = Result<EncryptedFile>;
82 boxed_into_future!(extra_bounds: 'a);
83
84 fn into_future(self) -> Self::IntoFuture {
85 let Self { client, reader, send_progress, request_config } = self;
86 Box::pin(async move {
87 let mut encryptor = matrix_sdk_base::crypto::AttachmentEncryptor::new(reader);
88
89 let mut buf = Vec::new();
90 encryptor.read_to_end(&mut buf)?;
91
92 let request_config =
95 request_config.map(|config| config.timeout(Media::reasonable_upload_timeout(&buf)));
96
97 let response = client
98 .media()
99 .upload(&mime::APPLICATION_OCTET_STREAM, buf, request_config)
100 .with_send_progress_observable(send_progress)
101 .await?;
102
103 let file: EncryptedFile = {
104 let keys = encryptor.finish();
105 EncryptedFileInit {
106 url: response.content_uri,
107 key: keys.key,
108 iv: keys.iv,
109 hashes: keys.hashes,
110 v: keys.version,
111 }
112 .into()
113 };
114
115 Ok(file)
116 })
117 }
118}