matrix_sdk/media.rs
1// Copyright 2021 Kévin Commaille
2// Copyright 2022 The Matrix.org Foundation C.I.C.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! High-level media API.
17
18#[cfg(feature = "e2e-encryption")]
19use std::io::Read;
20use std::{fmt, time::Duration};
21#[cfg(not(target_family = "wasm"))]
22use std::{fs::File, path::Path};
23
24use eyeball::SharedObservable;
25use futures_util::future::try_join;
26use matrix_sdk_base::media::store::IgnoreMediaRetentionPolicy;
27pub use matrix_sdk_base::media::{store::MediaRetentionPolicy, *};
28use matrix_sdk_common::{BoxFuture, SendOutsideWasm, SyncOutsideWasm};
29use mime::Mime;
30use ruma::{
31 MilliSecondsSinceUnixEpoch, MxcUri, OwnedMxcUri, TransactionId, UInt,
32 api::{
33 Metadata,
34 client::{authenticated_media, media},
35 error::ErrorKind,
36 },
37 assign,
38 events::room::{MediaSource, ThumbnailInfo},
39};
40#[cfg(not(target_family = "wasm"))]
41use tempfile::{Builder as TempFileBuilder, NamedTempFile, TempDir};
42#[cfg(not(target_family = "wasm"))]
43use tokio::{fs::File as TokioFile, io::AsyncWriteExt};
44
45use crate::{
46 Client, Error, Result, TransmissionProgress, attachment::Thumbnail,
47 client::futures::SendMediaUploadRequest, config::RequestConfig,
48};
49
50/// A conservative upload speed of 1Mbps
51const DEFAULT_UPLOAD_SPEED: u64 = 125_000;
52/// 5 min minimal upload request timeout, used to clamp the request timeout.
53const MIN_UPLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(60 * 5);
54/// The server name used to generate local MXC URIs.
55// This mustn't represent a potentially valid media server, otherwise it'd be
56// possible for an attacker to return malicious content under some
57// preconditions (e.g. the cache store has been cleared before the upload
58// took place). To mitigate against this, we use the .localhost TLD,
59// which is guaranteed to be on the local machine. As a result, the only attack
60// possible would be coming from the user themselves, which we consider a
61// non-threat.
62const LOCAL_MXC_SERVER_NAME: &str = "send-queue.localhost";
63
64/// A high-level API to interact with the media API.
65#[derive(Debug, Clone)]
66pub struct Media {
67 /// The underlying HTTP client.
68 client: Client,
69}
70
71/// A file handle that takes ownership of a media file on disk. When the handle
72/// is dropped, the file will be removed from the disk.
73#[derive(Debug)]
74#[cfg(not(target_family = "wasm"))]
75pub struct MediaFileHandle {
76 /// The temporary file that contains the media.
77 file: NamedTempFile,
78 /// An intermediary temporary directory used in certain cases.
79 ///
80 /// Only stored for its `Drop` semantics.
81 _directory: Option<TempDir>,
82}
83
84#[cfg(not(target_family = "wasm"))]
85impl MediaFileHandle {
86 /// Get the media file's path.
87 pub fn path(&self) -> &Path {
88 self.file.path()
89 }
90
91 /// Persist the media file to the given path.
92 pub fn persist(self, path: &Path) -> Result<File, PersistError> {
93 self.file.persist(path).map_err(|e| PersistError {
94 error: e.error,
95 file: Self { file: e.file, _directory: self._directory },
96 })
97 }
98}
99
100/// Error returned when [`MediaFileHandle::persist`] fails.
101#[cfg(not(target_family = "wasm"))]
102pub struct PersistError {
103 /// The underlying IO error.
104 pub error: std::io::Error,
105 /// The temporary file that couldn't be persisted.
106 pub file: MediaFileHandle,
107}
108
109#[cfg(not(any(target_family = "wasm", tarpaulin_include)))]
110impl fmt::Debug for PersistError {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(f, "PersistError({:?})", self.error)
113 }
114}
115
116#[cfg(not(any(target_family = "wasm", tarpaulin_include)))]
117impl fmt::Display for PersistError {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 write!(f, "failed to persist temporary file: {}", self.error)
120 }
121}
122
123/// A preallocated MXC URI created by [`Media::create_content_uri()`], and
124/// to be used with [`Media::upload_preallocated()`].
125#[derive(Debug)]
126pub struct PreallocatedMxcUri {
127 /// The URI for the media URI.
128 pub uri: OwnedMxcUri,
129 /// The expiration date for the media URI.
130 expire_date: Option<MilliSecondsSinceUnixEpoch>,
131}
132
133/// An error that happened in the realm of media.
134#[derive(Debug, thiserror::Error)]
135pub enum MediaError {
136 /// A preallocated MXC URI has expired.
137 #[error("a preallocated MXC URI has expired")]
138 ExpiredPreallocatedMxcUri,
139
140 /// Preallocated media already had content, cannot overwrite.
141 #[error("preallocated media already had content, cannot overwrite")]
142 CannotOverwriteMedia,
143
144 /// Local-only media content was not found.
145 #[error("local-only media content was not found")]
146 LocalMediaNotFound,
147
148 /// The provided media is too large to upload.
149 #[error(
150 "The provided media is too large to upload. \
151 Maximum upload length is {max} bytes, tried to upload {current} bytes"
152 )]
153 MediaTooLargeToUpload {
154 /// The `max_upload_size` value for this homeserver.
155 max: UInt,
156 /// The size of the current media to upload.
157 current: UInt,
158 },
159
160 /// Fetching the `max_upload_size` value from the homeserver failed.
161 #[error("Fetching the `max_upload_size` value from the homeserver failed: {0}")]
162 FetchMaxUploadSizeFailed(String),
163}
164
165/// A generic trait for fetching media content.
166pub trait MediaFetcher: SendOutsideWasm + SyncOutsideWasm + fmt::Debug {
167 /// Fetches the media content for the given [`MediaRequestParameters`].
168 /// Returns either a byte array or an [`crate::Error`].
169 fn fetch_media_content<'a>(
170 &'a self,
171 client: &'a Client,
172 request: &'a MediaRequestParameters,
173 ) -> BoxFuture<'a, Result<Vec<u8>, Error>>;
174}
175
176impl Media {
177 pub(crate) fn new(client: Client) -> Self {
178 Self { client }
179 }
180
181 /// Upload some media to the server.
182 ///
183 /// # Arguments
184 ///
185 /// * `content_type` - The type of the media, this will be used as the
186 /// content-type header.
187 ///
188 /// * `data` - Vector of bytes to be uploaded to the server.
189 ///
190 /// * `request_config` - Optional request configuration for the HTTP client,
191 /// overriding the default. If not provided, a reasonable timeout value is
192 /// inferred.
193 ///
194 /// # Examples
195 ///
196 /// ```no_run
197 /// # use std::fs;
198 /// # use matrix_sdk::{Client, ruma::room_id};
199 /// # use url::Url;
200 /// # use mime;
201 /// # async {
202 /// # let homeserver = Url::parse("http://localhost:8080")?;
203 /// # let mut client = Client::new(homeserver).await?;
204 /// let image = fs::read("/home/example/my-cat.jpg")?;
205 ///
206 /// let response =
207 /// client.media().upload(&mime::IMAGE_JPEG, image, None).await?;
208 ///
209 /// println!("Cat URI: {}", response.content_uri);
210 /// # anyhow::Ok(()) };
211 /// ```
212 pub fn upload(
213 &self,
214 content_type: &Mime,
215 data: Vec<u8>,
216 request_config: Option<RequestConfig>,
217 ) -> SendMediaUploadRequest {
218 let request_config = request_config.unwrap_or_else(|| {
219 self.client.request_config().timeout(Self::reasonable_upload_timeout(&data))
220 });
221
222 let request = assign!(media::create_content::v3::Request::new(data), {
223 content_type: Some(content_type.essence_str().to_owned()),
224 });
225
226 let request = self.client.send(request).with_request_config(request_config);
227 SendMediaUploadRequest::new(request)
228 }
229
230 /// Returns a reasonable upload timeout for an upload, based on the size of
231 /// the data to be uploaded.
232 pub(crate) fn reasonable_upload_timeout(data: &[u8]) -> Duration {
233 std::cmp::max(
234 Duration::from_secs(data.len() as u64 / DEFAULT_UPLOAD_SPEED),
235 MIN_UPLOAD_REQUEST_TIMEOUT,
236 )
237 }
238
239 /// Preallocates an MXC URI for a media that will be uploaded soon.
240 ///
241 /// This preallocates an URI *before* any content is uploaded to the server.
242 /// The resulting preallocated MXC URI can then be consumed with
243 /// [`Media::upload_preallocated`].
244 ///
245 /// # Examples
246 ///
247 /// ```no_run
248 /// # use std::fs;
249 /// # use matrix_sdk::{Client, ruma::room_id};
250 /// # use url::Url;
251 /// # use mime;
252 /// # async {
253 /// # let homeserver = Url::parse("http://localhost:8080")?;
254 /// # let mut client = Client::new(homeserver).await?;
255 ///
256 /// let preallocated = client.media().create_content_uri().await?;
257 /// println!("Cat URI: {}", preallocated.uri);
258 ///
259 /// let image = fs::read("/home/example/my-cat.jpg")?;
260 /// client
261 /// .media()
262 /// .upload_preallocated(preallocated, &mime::IMAGE_JPEG, image)
263 /// .await?;
264 ///
265 /// # anyhow::Ok(()) };
266 /// ```
267 pub async fn create_content_uri(&self) -> Result<PreallocatedMxcUri> {
268 // Note: this request doesn't have any parameters.
269 let request = media::create_mxc_uri::v1::Request::default();
270
271 let response = self.client.send(request).await?;
272
273 Ok(PreallocatedMxcUri {
274 uri: response.content_uri,
275 expire_date: response.unused_expires_at,
276 })
277 }
278
279 /// Fills the content of a preallocated MXC URI with the given content type
280 /// and data.
281 ///
282 /// The URI must have been preallocated with [`Self::create_content_uri`].
283 /// See this method's documentation for a full example.
284 pub async fn upload_preallocated(
285 &self,
286 uri: PreallocatedMxcUri,
287 content_type: &Mime,
288 data: Vec<u8>,
289 ) -> Result<()> {
290 // Do a best-effort at reporting an expired MXC URI here; otherwise the server
291 // may complain about it later.
292 if let Some(expire_date) = uri.expire_date
293 && MilliSecondsSinceUnixEpoch::now() >= expire_date
294 {
295 return Err(Error::Media(MediaError::ExpiredPreallocatedMxcUri));
296 }
297
298 let timeout = std::cmp::max(
299 Duration::from_secs(data.len() as u64 / DEFAULT_UPLOAD_SPEED),
300 MIN_UPLOAD_REQUEST_TIMEOUT,
301 );
302
303 let request = assign!(media::create_content_async::v3::Request::from_url(&uri.uri, data)?, {
304 content_type: Some(content_type.as_ref().to_owned()),
305 });
306
307 let request_config = self.client.request_config().timeout(timeout);
308
309 if let Err(err) = self.client.send(request).with_request_config(request_config).await {
310 match err.client_api_error_kind() {
311 Some(ErrorKind::CannotOverwriteMedia) => {
312 Err(Error::Media(MediaError::CannotOverwriteMedia))
313 }
314
315 // Unfortunately, the spec says a server will return 404 for either an expired MXC
316 // ID or a non-existing MXC ID. Do a best-effort guess to recognize an expired MXC
317 // ID based on the error string, which will work with Synapse (as of 2024-10-23).
318 Some(ErrorKind::Unknown) if err.to_string().contains("expired") => {
319 Err(Error::Media(MediaError::ExpiredPreallocatedMxcUri))
320 }
321
322 _ => Err(err.into()),
323 }
324 } else {
325 Ok(())
326 }
327 }
328
329 /// Gets a media file by copying it to a temporary location on disk.
330 ///
331 /// The file won't be encrypted even if it is encrypted on the server.
332 ///
333 /// Returns a `MediaFileHandle` which takes ownership of the file. When the
334 /// handle is dropped, the file will be deleted from the temporary location.
335 ///
336 /// # Arguments
337 ///
338 /// * `request` - The `MediaRequest` of the content.
339 ///
340 /// * `filename` - The filename specified in the event. It is suggested to
341 /// use the `filename()` method on the event's content instead of using
342 /// the `filename` field directly. If not provided, a random name will be
343 /// generated.
344 ///
345 /// * `content_type` - The type of the media, this will be used to set the
346 /// temporary file's extension when one isn't included in the filename.
347 ///
348 /// * `use_cache` - If we should use the media cache for this request.
349 ///
350 /// * `temp_dir` - Path to a directory where temporary directories can be
351 /// created. If not provided, a default, global temporary directory will
352 /// be used; this may not work properly on Android, where the default
353 /// location may require root access on some older Android versions.
354 #[cfg(not(target_family = "wasm"))]
355 pub async fn get_media_file(
356 &self,
357 request: &MediaRequestParameters,
358 filename: Option<String>,
359 content_type: &Mime,
360 use_cache: bool,
361 temp_dir: Option<String>,
362 ) -> Result<MediaFileHandle> {
363 let data = self.get_media_content(request, use_cache).await?;
364
365 let inferred_extension = mime2ext::mime2ext(content_type);
366
367 let filename_as_path = filename.as_ref().map(Path::new);
368
369 let (sanitized_filename, filename_has_extension) = if let Some(path) = filename_as_path {
370 let sanitized_filename = path.file_name().and_then(|f| f.to_str());
371 let filename_has_extension = path.extension().is_some();
372 (sanitized_filename, filename_has_extension)
373 } else {
374 (None, false)
375 };
376
377 let (temp_file, temp_dir) =
378 match (sanitized_filename, filename_has_extension, inferred_extension) {
379 // If the file name has an extension use that
380 (Some(filename_with_extension), true, _) => {
381 // Use an intermediary directory to avoid conflicts
382 let temp_dir = temp_dir.map(TempDir::new_in).unwrap_or_else(TempDir::new)?;
383 let temp_file = TempFileBuilder::new()
384 .prefix(filename_with_extension)
385 .rand_bytes(0)
386 .tempfile_in(&temp_dir)?;
387 (temp_file, Some(temp_dir))
388 }
389 // If the file name doesn't have an extension try inferring one for it
390 (Some(filename), false, Some(inferred_extension)) => {
391 // Use an intermediary directory to avoid conflicts
392 let temp_dir = temp_dir.map(TempDir::new_in).unwrap_or_else(TempDir::new)?;
393 let temp_file = TempFileBuilder::new()
394 .prefix(filename)
395 .suffix(&(".".to_owned() + inferred_extension))
396 .rand_bytes(0)
397 .tempfile_in(&temp_dir)?;
398 (temp_file, Some(temp_dir))
399 }
400 // If the only thing we have is an inferred extension then use that together with a
401 // randomly generated file name
402 (None, _, Some(inferred_extension)) => (
403 TempFileBuilder::new()
404 .suffix(&&(".".to_owned() + inferred_extension))
405 .tempfile()?,
406 None,
407 ),
408 // Otherwise just use a completely random file name
409 _ => (TempFileBuilder::new().tempfile()?, None),
410 };
411
412 let mut file = TokioFile::from_std(temp_file.reopen()?);
413 file.write_all(&data).await?;
414 // Make sure the file metadata is flushed to disk.
415 file.sync_all().await?;
416
417 Ok(MediaFileHandle { file: temp_file, _directory: temp_dir })
418 }
419
420 /// Get a media file's content.
421 ///
422 /// If the content is encrypted and encryption is enabled, the content will
423 /// be decrypted.
424 ///
425 /// # Arguments
426 ///
427 /// * `request` - The `MediaRequest` of the content.
428 ///
429 /// * `use_cache` - If we should use the media cache for this request.
430 pub async fn get_media_content(
431 &self,
432 request: &MediaRequestParameters,
433 use_cache: bool,
434 ) -> Result<Vec<u8>> {
435 // Ignore request parameters for local medias, notably those pending in the send
436 // queue.
437 if let Some(uri) = Self::as_local_uri(&request.source) {
438 return self.get_local_media_content(uri).await;
439 }
440
441 // Read from the cache.
442 if use_cache
443 && let Some(content) =
444 self.client.media_store().lock().await?.get_media_content(request).await?
445 {
446 return Ok(content);
447 }
448
449 let content = self
450 .client
451 .inner
452 .media_fetcher
453 .read()
454 .await
455 .fetch_media_content(&self.client, request)
456 .await?;
457
458 if use_cache {
459 self.client
460 .media_store()
461 .lock()
462 .await?
463 .add_media_content(request, content.clone(), IgnoreMediaRetentionPolicy::No)
464 .await?;
465 }
466
467 Ok(content)
468 }
469
470 /// Get a media file's content that is only available in the media cache.
471 ///
472 /// # Arguments
473 ///
474 /// * `uri` - The local MXC URI of the media content.
475 async fn get_local_media_content(&self, uri: &MxcUri) -> Result<Vec<u8>> {
476 // Read from the cache.
477 self.client
478 .media_store()
479 .lock()
480 .await?
481 .get_media_content_for_uri(uri)
482 .await?
483 .ok_or_else(|| MediaError::LocalMediaNotFound.into())
484 }
485
486 /// Remove a media file's content from the store.
487 ///
488 /// # Arguments
489 ///
490 /// * `request` - The `MediaRequest` of the content.
491 pub async fn remove_media_content(&self, request: &MediaRequestParameters) -> Result<()> {
492 Ok(self.client.media_store().lock().await?.remove_media_content(request).await?)
493 }
494
495 /// Delete all the media content corresponding to the given
496 /// uri from the store.
497 ///
498 /// # Arguments
499 ///
500 /// * `uri` - The `MxcUri` of the files.
501 pub async fn remove_media_content_for_uri(&self, uri: &MxcUri) -> Result<()> {
502 Ok(self.client.media_store().lock().await?.remove_media_content_for_uri(uri).await?)
503 }
504
505 /// Get the file of the given media event content.
506 ///
507 /// If the content is encrypted and encryption is enabled, the content will
508 /// be decrypted.
509 ///
510 /// Returns `Ok(None)` if the event content has no file.
511 ///
512 /// This is a convenience method that calls the
513 /// [`get_media_content`](#method.get_media_content) method.
514 ///
515 /// # Arguments
516 ///
517 /// * `event_content` - The media event content.
518 ///
519 /// * `use_cache` - If we should use the media cache for this file.
520 pub async fn get_file(
521 &self,
522 event_content: &impl MediaEventContent,
523 use_cache: bool,
524 ) -> Result<Option<Vec<u8>>> {
525 let Some(source) = event_content.source() else { return Ok(None) };
526 let file = self
527 .get_media_content(
528 &MediaRequestParameters { source, format: MediaFormat::File },
529 use_cache,
530 )
531 .await?;
532 Ok(Some(file))
533 }
534
535 /// Remove the file of the given media event content from the cache.
536 ///
537 /// This is a convenience method that calls the
538 /// [`remove_media_content`](#method.remove_media_content) method.
539 ///
540 /// # Arguments
541 ///
542 /// * `event_content` - The media event content.
543 pub async fn remove_file(&self, event_content: &impl MediaEventContent) -> Result<()> {
544 if let Some(source) = event_content.source() {
545 self.remove_media_content(&MediaRequestParameters {
546 source,
547 format: MediaFormat::File,
548 })
549 .await?;
550 }
551
552 Ok(())
553 }
554
555 /// Get a thumbnail of the given media event content.
556 ///
557 /// If the content is encrypted and encryption is enabled, the content will
558 /// be decrypted.
559 ///
560 /// Returns `Ok(None)` if the event content has no thumbnail.
561 ///
562 /// This is a convenience method that calls the
563 /// [`get_media_content`](#method.get_media_content) method.
564 ///
565 /// # Arguments
566 ///
567 /// * `event_content` - The media event content.
568 ///
569 /// * `settings` - The _desired_ settings of the thumbnail. The actual
570 /// thumbnail may not match the settings specified.
571 ///
572 /// * `use_cache` - If we should use the media cache for this thumbnail.
573 pub async fn get_thumbnail(
574 &self,
575 event_content: &impl MediaEventContent,
576 settings: MediaThumbnailSettings,
577 use_cache: bool,
578 ) -> Result<Option<Vec<u8>>> {
579 let Some(source) = event_content.thumbnail_source() else { return Ok(None) };
580 let thumbnail = self
581 .get_media_content(
582 &MediaRequestParameters { source, format: MediaFormat::Thumbnail(settings) },
583 use_cache,
584 )
585 .await?;
586 Ok(Some(thumbnail))
587 }
588
589 /// Remove the thumbnail of the given media event content from the cache.
590 ///
591 /// This is a convenience method that calls the
592 /// [`remove_media_content`](#method.remove_media_content) method.
593 ///
594 /// # Arguments
595 ///
596 /// * `event_content` - The media event content.
597 ///
598 /// * `size` - The _desired_ settings of the thumbnail. Must match the
599 /// settings requested with [`get_thumbnail`](#method.get_thumbnail).
600 pub async fn remove_thumbnail(
601 &self,
602 event_content: &impl MediaEventContent,
603 settings: MediaThumbnailSettings,
604 ) -> Result<()> {
605 if let Some(source) = event_content.source() {
606 self.remove_media_content(&MediaRequestParameters {
607 source,
608 format: MediaFormat::Thumbnail(settings),
609 })
610 .await?
611 }
612
613 Ok(())
614 }
615
616 /// Set the [`MediaRetentionPolicy`] to use for deciding whether to store or
617 /// keep media content.
618 ///
619 /// It is used:
620 ///
621 /// * When a media needs to be cached, to check that it does not exceed the
622 /// max file size.
623 ///
624 /// * When [`Media::clean()`], to check that all media content in the store
625 /// fits those criteria.
626 ///
627 /// To apply the new policy to the media cache right away,
628 /// [`Media::clean()`] should be called after this.
629 ///
630 /// By default, an empty `MediaRetentionPolicy` is used, which means that no
631 /// criteria are applied.
632 ///
633 /// # Arguments
634 ///
635 /// * `policy` - The `MediaRetentionPolicy` to use.
636 pub async fn set_media_retention_policy(&self, policy: MediaRetentionPolicy) -> Result<()> {
637 self.client.media_store().lock().await?.set_media_retention_policy(policy).await?;
638 Ok(())
639 }
640
641 /// Get the current `MediaRetentionPolicy`.
642 pub async fn media_retention_policy(&self) -> Result<MediaRetentionPolicy> {
643 Ok(self.client.media_store().lock().await?.media_retention_policy())
644 }
645
646 /// Clean up the media cache with the current [`MediaRetentionPolicy`].
647 ///
648 /// If there is already an ongoing cleanup, this is a noop.
649 pub async fn clean(&self) -> Result<()> {
650 self.client.media_store().lock().await?.clean().await?;
651 Ok(())
652 }
653
654 /// Upload the file bytes in `data` and return the source information.
655 pub(crate) async fn upload_plain_media_and_thumbnail(
656 &self,
657 content_type: &Mime,
658 data: Vec<u8>,
659 thumbnail: Option<Thumbnail>,
660 send_progress: SharedObservable<TransmissionProgress>,
661 ) -> Result<(MediaSource, Option<(MediaSource, Box<ThumbnailInfo>)>)> {
662 let upload_thumbnail = self.upload_thumbnail(thumbnail, send_progress.clone());
663
664 let upload_attachment = async move {
665 self.upload(content_type, data, None).with_send_progress_observable(send_progress).await
666 };
667
668 let (thumbnail, response) = try_join(upload_thumbnail, upload_attachment).await?;
669
670 Ok((MediaSource::Plain(response.content_uri), thumbnail))
671 }
672
673 /// Uploads an unencrypted thumbnail to the media repository, and returns
674 /// its source and extra information.
675 async fn upload_thumbnail(
676 &self,
677 thumbnail: Option<Thumbnail>,
678 send_progress: SharedObservable<TransmissionProgress>,
679 ) -> Result<Option<(MediaSource, Box<ThumbnailInfo>)>> {
680 let Some(thumbnail) = thumbnail else {
681 return Ok(None);
682 };
683
684 let (data, content_type, thumbnail_info) = thumbnail.into_parts();
685
686 let response = self
687 .upload(&content_type, data, None)
688 .with_send_progress_observable(send_progress)
689 .await?;
690 let url = response.content_uri;
691
692 Ok(Some((MediaSource::Plain(url), thumbnail_info)))
693 }
694
695 /// Create an [`OwnedMxcUri`] for a file or thumbnail we want to store
696 /// locally before sending it.
697 ///
698 /// This uses a MXC ID that is only locally valid.
699 pub(crate) fn make_local_uri(txn_id: &TransactionId) -> OwnedMxcUri {
700 OwnedMxcUri::from(format!("mxc://{LOCAL_MXC_SERVER_NAME}/{txn_id}"))
701 }
702
703 /// Create a [`MediaRequest`] for a file we want to store locally before
704 /// sending it.
705 ///
706 /// This uses a MXC ID that is only locally valid.
707 pub(crate) fn make_local_file_media_request(txn_id: &TransactionId) -> MediaRequestParameters {
708 MediaRequestParameters {
709 source: MediaSource::Plain(Self::make_local_uri(txn_id)),
710 format: MediaFormat::File,
711 }
712 }
713
714 /// Returns the local MXC URI contained by the given source, if any.
715 ///
716 /// A local MXC URI is a URI that was generated with `make_local_uri`.
717 fn as_local_uri(source: &MediaSource) -> Option<&MxcUri> {
718 let uri = match source {
719 MediaSource::Plain(uri) => uri,
720 MediaSource::Encrypted(file) => &file.url,
721 };
722
723 uri.server_name()
724 .is_ok_and(|server_name| server_name == LOCAL_MXC_SERVER_NAME)
725 .then_some(uri)
726 }
727}
728
729/// A [`MediaFetcher`] that uses the default media/authenticated media endpoints
730/// to fetch new media.
731#[derive(Debug, Clone)]
732pub struct DefaultMediaFetcher;
733
734impl MediaFetcher for DefaultMediaFetcher {
735 fn fetch_media_content<'a>(
736 &'a self,
737 client: &'a Client,
738 request: &'a MediaRequestParameters,
739 ) -> BoxFuture<'a, Result<Vec<u8>, Error>> {
740 Box::pin(async move {
741 let request_config = client
742 .request_config()
743 // Downloading a file should have no timeout as we don't know the network
744 // connectivity available for the user or the file size
745 .timeout(Some(Duration::MAX));
746
747 // Use the authenticated endpoints when the server supports it.
748 let supported_versions = client.supported_versions().await?;
749
750 let use_auth = authenticated_media::get_content::v1::Request::PATH_BUILDER
751 .is_supported(&supported_versions);
752
753 match &request.source {
754 MediaSource::Encrypted(file) => {
755 let content = if use_auth {
756 let request =
757 authenticated_media::get_content::v1::Request::from_uri(&file.url)?;
758 client.send(request).with_request_config(request_config).await?.file
759 } else {
760 #[allow(deprecated)]
761 let request = media::get_content::v3::Request::from_url(&file.url)?;
762 client.send(request).with_request_config(request_config).await?.file
763 };
764
765 #[cfg(feature = "e2e-encryption")]
766 let content = {
767 let content_len = content.len();
768 let mut cursor = std::io::Cursor::new(content);
769 let mut reader = matrix_sdk_base::crypto::AttachmentDecryptor::new(
770 &mut cursor,
771 file.as_ref().clone().into(),
772 )?;
773
774 // Encrypted size should be the same as the decrypted size,
775 // rounded up to a cipher block.
776 let mut decrypted = Vec::with_capacity(content_len);
777
778 reader.read_to_end(&mut decrypted)?;
779
780 decrypted
781 };
782
783 Ok(content)
784 }
785
786 MediaSource::Plain(uri) => {
787 if let MediaFormat::Thumbnail(settings) = &request.format {
788 if use_auth {
789 let mut request =
790 authenticated_media::get_content_thumbnail::v1::Request::from_uri(
791 uri,
792 settings.width,
793 settings.height,
794 )?;
795 request.method = Some(settings.method.clone());
796 request.animated = Some(settings.animated);
797
798 Ok(client.send(request).with_request_config(request_config).await?.file)
799 } else {
800 #[allow(deprecated)]
801 let request = {
802 let mut request =
803 media::get_content_thumbnail::v3::Request::from_url(
804 uri,
805 settings.width,
806 settings.height,
807 )?;
808 request.method = Some(settings.method.clone());
809 request.animated = Some(settings.animated);
810 request
811 };
812
813 Ok(client.send(request).with_request_config(request_config).await?.file)
814 }
815 } else if use_auth {
816 let request = authenticated_media::get_content::v1::Request::from_uri(uri)?;
817 Ok(client.send(request).with_request_config(request_config).await?.file)
818 } else {
819 #[allow(deprecated)]
820 let request = media::get_content::v3::Request::from_url(uri)?;
821 Ok(client.send(request).with_request_config(request_config).await?.file)
822 }
823 }
824 }
825 })
826 }
827}
828
829#[cfg(test)]
830mod tests {
831 use assert_matches2::assert_matches;
832 use ruma::{
833 MxcUri,
834 events::room::{EncryptedFile, MediaSource},
835 mxc_uri, owned_mxc_uri,
836 };
837 use serde_json::json;
838
839 use super::Media;
840
841 /// Create an `EncryptedFile` with the given MXC URI.
842 fn encrypted_file(mxc_uri: &MxcUri) -> Box<EncryptedFile> {
843 Box::new(
844 serde_json::from_value(json!({
845 "url": mxc_uri,
846 "key": {
847 "kty": "oct",
848 "key_ops": ["encrypt", "decrypt"],
849 "alg": "A256CTR",
850 "k": "b50ACIv6LMn9AfMCFD1POJI_UAFWIclxAN1kWrEO2X8",
851 "ext": true,
852 },
853 "iv": "AK1wyzigZtQAAAABAAAAKK",
854 "hashes": {
855 "sha256": "/NogKqW5bz/m8xHgFiH5haFGjCNVmUIPLzfvOhHdrxY",
856 },
857 "v": "v2",
858 }))
859 .unwrap(),
860 )
861 }
862
863 #[test]
864 fn test_as_local_uri() {
865 let txn_id = "abcdef";
866
867 // Request generated with `make_local_file_media_request`.
868 let request = Media::make_local_file_media_request(txn_id.into());
869 assert_matches!(Media::as_local_uri(&request.source), Some(uri));
870 assert_eq!(uri.media_id(), Ok(txn_id));
871
872 // Local plain source.
873 let source = MediaSource::Plain(Media::make_local_uri(txn_id.into()));
874 assert_matches!(Media::as_local_uri(&source), Some(uri));
875 assert_eq!(uri.media_id(), Ok(txn_id));
876
877 // Local encrypted source.
878 let source = MediaSource::Encrypted(encrypted_file(&Media::make_local_uri(txn_id.into())));
879 assert_matches!(Media::as_local_uri(&source), Some(uri));
880 assert_eq!(uri.media_id(), Ok(txn_id));
881
882 // Test non-local plain source.
883 let source = MediaSource::Plain(owned_mxc_uri!("mxc://server.local/poiuyt"));
884 assert_matches!(Media::as_local_uri(&source), None);
885
886 // Test non-local encrypted source.
887 let source = MediaSource::Encrypted(encrypted_file(mxc_uri!("mxc://server.local/mlkjhg")));
888 assert_matches!(Media::as_local_uri(&source), None);
889
890 // Test invalid MXC URI.
891 let source = MediaSource::Plain("https://server.local/nbvcxw".into());
892 assert_matches!(Media::as_local_uri(&source), None);
893 }
894}