Files
continuwuity/src/api/client/media.rs
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

328 lines
8.9 KiB
Rust
Raw Normal View History

2024-08-27 11:19:57 +00:00
use std::time::Duration;
2024-07-16 08:05:25 +00:00
use axum::extract::State;
2026-04-23 20:02:48 +01:00
use axum_client_ip::ClientIp;
2024-12-14 21:58:01 -05:00
use conduwuit::{
Err, Result, err,
2024-08-27 11:19:57 +00:00
utils::{self, content_disposition::make_content_disposition, math::ruma_from_usize},
};
2026-02-16 17:28:56 -05:00
use conduwuit_core::error;
2024-12-14 21:58:01 -05:00
use conduwuit_service::{
2024-08-27 11:19:57 +00:00
Services,
2026-04-10 22:27:55 -04:00
media::{Dim, FileMeta, MXC_LENGTH},
2024-08-27 11:19:57 +00:00
};
use reqwest::Url;
2024-08-27 11:19:57 +00:00
use ruma::{
UserId,
2024-08-27 11:19:57 +00:00
api::client::{
authenticated_media::{
get_content, get_content_as_filename, get_content_thumbnail, get_media_config,
get_media_preview,
2024-08-27 11:19:57 +00:00
},
media::create_content,
},
2026-04-10 22:27:55 -04:00
assign,
2020-07-30 18:14:47 +02:00
};
2026-04-10 22:27:55 -04:00
use service::media::mxc::Mxc;
2024-02-09 23:16:06 -05:00
use crate::Ruma;
2024-08-27 11:19:57 +00:00
/// # `GET /_matrix/client/v1/media/config`
pub(crate) async fn get_media_config_route(
State(services): State<crate::State>,
_body: Ruma<get_media_config::v1::Request>,
2024-08-27 11:19:57 +00:00
) -> Result<get_media_config::v1::Response> {
2026-04-10 22:27:55 -04:00
Ok(get_media_config::v1::Response::new(ruma_from_usize(
services.server.config.max_request_size,
)))
2024-08-27 11:19:57 +00:00
}
2024-01-16 20:44:20 -05:00
/// # `POST /_matrix/media/v3/upload`
2021-08-31 19:14:37 +02:00
///
/// Permanently save media in the server.
///
/// - Some metadata will be saved in the database
/// - Media will be saved in the media/ directory
2024-12-08 20:31:16 +00:00
#[tracing::instrument(
name = "media_upload",
level = "debug",
skip_all,
fields(%client),
)]
2024-04-22 23:48:57 -04:00
pub(crate) async fn create_content_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2024-07-16 08:05:25 +00:00
body: Ruma<create_content::v3::Request>,
2024-04-22 23:48:57 -04:00
) -> Result<create_content::v3::Response> {
let user = body.sender_user();
if services.users.is_suspended(user).await? {
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
2024-08-27 11:19:57 +00:00
let filename = body.filename.as_deref();
let content_type = body.content_type.as_deref();
let content_disposition = make_content_disposition(None, content_type, filename);
2025-02-04 02:24:50 +00:00
let ref mxc = Mxc {
2024-08-16 01:13:20 +00:00
server_name: services.globals.server_name(),
media_id: &utils::random_string(MXC_LENGTH),
};
if let Err(e) = services
2022-10-05 20:34:31 +02:00
.media
2025-02-04 02:24:50 +00:00
.create(mxc, Some(user), Some(&content_disposition), content_type, &body.file)
.await
{
err!("Failed to save uploaded media: {e}");
return Err!(Request(Unknown("Failed to save uploaded media")));
}
2025-02-04 02:24:50 +00:00
let blurhash = body.generate_blurhash.then(|| {
services
.media
.create_blurhash(&body.file, content_type, filename)
.ok()
.flatten()
});
2026-04-10 22:27:55 -04:00
Ok(assign!(create_content::v3::Response::new(mxc.to_string().into()), {
2025-02-04 02:24:50 +00:00
blurhash: blurhash.flatten(),
2026-04-10 22:27:55 -04:00
}))
2024-08-27 11:19:57 +00:00
}
/// # `GET /_matrix/client/v1/media/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
2024-12-08 20:31:16 +00:00
#[tracing::instrument(
name = "media_thumbnail_get",
level = "debug",
skip_all,
fields(%client),
)]
2024-08-27 11:19:57 +00:00
pub(crate) async fn get_content_thumbnail_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2024-08-27 11:19:57 +00:00
body: Ruma<get_content_thumbnail::v1::Request>,
) -> Result<get_content_thumbnail::v1::Response> {
let user = body.sender_user();
2024-08-27 11:19:57 +00:00
let dim = Dim::from_ruma(body.width, body.height, body.method.clone())?;
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
let FileMeta {
content,
content_type,
content_disposition,
2026-04-10 22:27:55 -04:00
} = match fetch_thumbnail_meta(&services, &mxc, user, body.timeout_ms, &dim).await {
2026-03-24 19:21:18 +00:00
| Ok(meta) => meta,
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound =>
return Err!(Request(NotFound("Thumbnail not found."))),
| std::io::ErrorKind::PermissionDenied => {
error!("Permission denied when trying to read file: {e:?}");
return Err!(Request(Unknown("Unknown error when fetching thumbnail.")));
},
| _ => return Err!(Request(Unknown("Unknown error when fetching thumbnail."))),
},
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching thumbnail."))),
};
2024-08-27 11:19:57 +00:00
2026-04-10 22:27:55 -04:00
let content_disposition =
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
Ok(get_content_thumbnail::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
2024-08-27 11:19:57 +00:00
content_disposition,
2026-04-10 22:27:55 -04:00
))
2020-07-30 18:14:47 +02:00
}
2024-08-27 11:19:57 +00:00
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
2024-12-08 20:31:16 +00:00
#[tracing::instrument(
name = "media_get",
level = "debug",
skip_all,
fields(%client),
)]
2024-08-27 11:19:57 +00:00
pub(crate) async fn get_content_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2024-08-27 11:19:57 +00:00
body: Ruma<get_content::v1::Request>,
) -> Result<get_content::v1::Response> {
let user = body.sender_user();
2024-08-27 11:19:57 +00:00
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
let FileMeta {
2024-08-27 11:19:57 +00:00
content,
content_type,
content_disposition,
2026-04-10 22:27:55 -04:00
} = match fetch_file_meta(&services, &mxc, user, body.timeout_ms).await {
| Ok(meta) => meta,
2026-02-16 17:28:56 -05:00
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound => return Err!(Request(NotFound("Media not found."))),
| std::io::ErrorKind::PermissionDenied => {
error!("Permission denied when trying to read file: {e:?}");
return Err!(Request(Unknown("Unknown error when fetching file.")));
},
| _ => return Err!(Request(Unknown("Unknown error when fetching file."))),
},
2026-02-16 13:35:37 -05:00
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching file."))),
};
2024-08-27 11:19:57 +00:00
2026-04-10 22:27:55 -04:00
let content_disposition =
make_content_disposition(content_disposition.as_ref(), content_type.as_deref(), None);
Ok(get_content::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
2024-08-27 11:19:57 +00:00
content_disposition,
2026-04-10 22:27:55 -04:00
))
2024-08-27 11:19:57 +00:00
}
/// # `GET /_matrix/client/v1/media/download/{serverName}/{mediaId}/{fileName}`
///
/// Load media from our server or over federation as fileName.
2024-12-08 20:31:16 +00:00
#[tracing::instrument(
name = "media_get_af",
level = "debug",
skip_all,
fields(%client),
)]
2024-08-27 11:19:57 +00:00
pub(crate) async fn get_content_as_filename_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2024-08-27 11:19:57 +00:00
body: Ruma<get_content_as_filename::v1::Request>,
) -> Result<get_content_as_filename::v1::Response> {
let user = body.sender_user();
2024-08-27 11:19:57 +00:00
let mxc = Mxc {
server_name: &body.server_name,
media_id: &body.media_id,
};
2026-02-15 11:24:40 -05:00
let FileMeta {
2024-08-27 11:19:57 +00:00
content,
content_type,
content_disposition,
2026-04-10 22:27:55 -04:00
} = match fetch_file_meta(&services, &mxc, user, body.timeout_ms).await {
2026-02-15 11:27:03 -05:00
| Ok(meta) => meta,
2026-02-16 17:28:56 -05:00
| Err(conduwuit::Error::Io(e)) => match e.kind() {
| std::io::ErrorKind::NotFound => return Err!(Request(NotFound("Media not found."))),
| std::io::ErrorKind::PermissionDenied => {
error!("Permission denied when trying to read file: {e:?}");
return Err!(Request(Unknown("Unknown error when fetching file.")));
},
| _ => return Err!(Request(Unknown("Unknown error when fetching file."))),
2026-02-15 11:27:03 -05:00
},
2026-02-16 13:35:37 -05:00
| Err(_) => return Err!(Request(Unknown("Unknown error when fetching file."))),
};
2024-08-27 11:19:57 +00:00
2026-04-10 22:27:55 -04:00
let content_disposition = make_content_disposition(
content_disposition.as_ref(),
content_type.as_deref(),
Some(&body.filename),
);
Ok(get_content_as_filename::v1::Response::new(
content.expect("entire file contents"),
content_type.unwrap_or_default(),
2024-08-27 11:19:57 +00:00
content_disposition,
2026-04-10 22:27:55 -04:00
))
2024-08-27 11:19:57 +00:00
}
/// # `GET /_matrix/client/v1/media/preview_url`
///
/// Returns URL preview.
2024-12-08 20:31:16 +00:00
#[tracing::instrument(
name = "url_preview",
level = "debug",
skip_all,
fields(%client),
)]
2024-08-27 11:19:57 +00:00
pub(crate) async fn get_media_preview_route(
State(services): State<crate::State>,
2026-04-23 20:02:48 +01:00
ClientIp(client): ClientIp,
2024-08-27 11:19:57 +00:00
body: Ruma<get_media_preview::v1::Request>,
) -> Result<get_media_preview::v1::Response> {
let sender_user = body.sender_user();
2024-08-27 11:19:57 +00:00
let url = &body.url;
let url = Url::parse(&body.url).map_err(|e| {
err!(Request(InvalidParam(
debug_warn!(%sender_user, %url, "Requested URL is not valid: {e}")
)))
})?;
if !services.media.url_preview_allowed(&url) {
2024-08-27 11:19:57 +00:00
return Err!(Request(Forbidden(
debug_warn!(%sender_user, %url, "URL is not allowed to be previewed")
)));
}
let preview = services
.media
.get_url_preview(&url)
.await
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to fetch URL preview: {error}")
)))
})?;
2024-08-27 11:19:57 +00:00
serde_json::value::to_raw_value(&preview)
.map(get_media_preview::v1::Response::from_raw_value)
.map_err(|error| {
err!(Request(Unknown(
debug_error!(%sender_user, %url, "Failed to parse URL preview: {error}")
2024-08-27 11:19:57 +00:00
)))
})
}
async fn fetch_thumbnail_meta(
services: &Services,
mxc: &Mxc<'_>,
user: &UserId,
timeout_ms: Duration,
dim: &Dim,
2024-08-27 11:19:57 +00:00
) -> Result<FileMeta> {
if let Some(filemeta) = services.media.get_thumbnail(mxc, dim).await? {
return Ok(filemeta);
}
if services.globals.server_is_ours(mxc.server_name) {
return Err!(Request(NotFound("Local thumbnail not found.")));
}
services
.media
.fetch_remote_thumbnail(mxc, Some(user), None, timeout_ms, dim)
.await
}
async fn fetch_file_meta(
services: &Services,
mxc: &Mxc<'_>,
user: &UserId,
timeout_ms: Duration,
) -> Result<FileMeta> {
2024-08-27 11:19:57 +00:00
if let Some(filemeta) = services.media.get(mxc).await? {
return Ok(filemeta);
}
if services.globals.server_is_ours(mxc.server_name) {
return Err!(Request(NotFound("Local media not found.")));
}
services
.media
.fetch_remote_content(mxc, Some(user), None, timeout_ms)
.await
}