Can retrieve room media

This commit is contained in:
2025-11-25 14:54:02 +01:00
parent 2adbf146d0
commit b7378aa4dc
8 changed files with 156 additions and 24 deletions

View File

@@ -4,19 +4,35 @@ use crate::utils::crypt_utils::sha512;
use actix_web::dev::Payload;
use actix_web::http::header;
use actix_web::{FromRequest, HttpRequest, HttpResponse, web};
use matrix_sdk::crypto::{AttachmentDecryptor, MediaEncryptionInfo};
use matrix_sdk::media::{MediaFormat, MediaRequestParameters, MediaThumbnailSettings};
use matrix_sdk::ruma::events::room::MediaSource;
use matrix_sdk::ruma::{OwnedMxcUri, UInt};
use std::io::{Cursor, Read};
#[derive(serde::Deserialize)]
struct MediaQuery {
pub struct MediaMXCInPath {
mxc: OwnedMxcUri,
}
/// Serve media resource handler
pub async fn serve_mxc_handler(req: HttpRequest, media: web::Path<MediaMXCInPath>) -> HttpResult {
serve_mxc_file(req, media.into_inner().mxc).await
}
#[derive(serde::Deserialize)]
pub struct MediaQuery {
#[serde(default)]
thumbnail: bool,
pub thumbnail: bool,
}
pub async fn serve_mxc_file(req: HttpRequest, media: OwnedMxcUri) -> HttpResult {
let query = web::Query::<MediaQuery>::from_request(&req, &mut Payload::None).await?;
serve_media(req, MediaSource::Plain(media), query.thumbnail).await
}
/// Serve a media file
pub async fn serve_media(req: HttpRequest, media: OwnedMxcUri) -> HttpResult {
let query = web::Query::<MediaQuery>::from_request(&req, &mut Payload::None).await?;
pub async fn serve_media(req: HttpRequest, source: MediaSource, thumbnail: bool) -> HttpResult {
let client = MatrixClientExtractor::from_request(&req, &mut Payload::None).await?;
let media = client
@@ -25,8 +41,8 @@ pub async fn serve_media(req: HttpRequest, media: OwnedMxcUri) -> HttpResult {
.media()
.get_media_content(
&MediaRequestParameters {
source: MediaSource::Plain(media),
format: match query.thumbnail {
source: source.clone(),
format: match thumbnail {
true => MediaFormat::Thumbnail(MediaThumbnailSettings::new(
UInt::new(100).unwrap(),
UInt::new(100).unwrap(),
@@ -38,6 +54,21 @@ pub async fn serve_media(req: HttpRequest, media: OwnedMxcUri) -> HttpResult {
)
.await?;
// Decrypt file if needed
let media = if let MediaSource::Encrypted(file) = source {
let mut cursor = Cursor::new(media);
let mut decryptor =
AttachmentDecryptor::new(&mut cursor, MediaEncryptionInfo::from(*file))?;
let mut decrypted_data = Vec::new();
decryptor.read_to_end(&mut decrypted_data)?;
decrypted_data
} else {
media
};
let digest = sha512(&media);
let mime_type = infer::get(&media).map(|x| x.mime_type());
@@ -55,13 +86,3 @@ pub async fn serve_media(req: HttpRequest, media: OwnedMxcUri) -> HttpResult {
.insert_header(("cache-control", "max-age=360000"))
.body(media))
}
#[derive(serde::Deserialize)]
pub struct MediaMXCInPath {
mxc: OwnedMxcUri,
}
/// Save media resource handler
pub async fn serve_media_res(req: HttpRequest, media: web::Path<MediaMXCInPath>) -> HttpResult {
serve_media(req, media.into_inner().mxc).await
}