Skip to content
Snippets Groups Projects
media.rs 8.82 KiB
Newer Older
  • Learn to ignore specific revisions
  • use std::time::Duration;
    
    
    Timo Kösters's avatar
    Timo Kösters committed
    use crate::{service::media::FileMeta, services, utils, Error, Result, Ruma};
    
    use ruma::api::client::{
        error::ErrorKind,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
        media::{
    
            create_content, get_content, get_content_as_filename, get_content_thumbnail,
            get_media_config,
        },
    
    /// generated MXC ID (`media-id`) length
    
    const MXC_LENGTH: usize = 32;
    
    /// # `GET /_matrix/media/v3/config`
    
    ///
    /// Returns max upload size.
    
    pub async fn get_media_config_route(
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
        _body: Ruma<get_media_config::v3::Request>,
    ) -> Result<get_media_config::v3::Response> {
        Ok(get_media_config::v3::Response {
    
            upload_size: services().globals.max_request_size().into(),
    
    /// # `POST /_matrix/media/v3/upload`
    
    ///
    /// Permanently save media in the server.
    ///
    /// - Some metadata will be saved in the database
    /// - Media will be saved in the media/ directory
    
    pub async fn create_content_route(
    
    Jonas Platte's avatar
    Jonas Platte committed
        body: Ruma<create_content::v3::Request>,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
    ) -> Result<create_content::v3::Response> {
    
        let mxc = format!(
            "mxc://{}/{}",
    
            services().globals.server_name(),
    
            utils::random_string(MXC_LENGTH)
        );
    
    Timo Kösters's avatar
    Timo Kösters committed
        services()
            .media
    
            .create(
                mxc.clone(),
    
    Timo Kösters's avatar
    Timo Kösters committed
                body.filename
    
                    .as_ref()
                    .map(|filename| "inline; filename=".to_owned() + filename)
                    .as_deref(),
    
    Timo Kösters's avatar
    Timo Kösters committed
                body.content_type.as_deref(),
    
                &body.file,
            )
            .await?;
    
        let content_uri = mxc.into();
    
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
        Ok(create_content::v3::Response {
    
            blurhash: None,
    
    /// helper method to fetch remote media from other servers over federation
    
    pub async fn get_remote_content(
        mxc: &str,
        server_name: &ruma::ServerName,
    
    Jonas Platte's avatar
    Jonas Platte committed
        media_id: String,
    
        allow_redirect: bool,
        timeout_ms: Duration,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
    ) -> Result<get_content::v3::Response, Error> {
    
        // we'll lie to the client and say the blocked server's media was not found and log.
        // the client has no way of telling anyways so this is a security bonus.
        if services()
            .globals
            .prevent_media_downloads_from()
            .contains(&server_name.to_owned())
        {
            info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc);
            return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
        }
    
    
        let content_response = services()
    
            .sending
            .send_federation_request(
                server_name,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
                get_content::v3::Request {
    
                    allow_remote: true,
    
    Jonas Platte's avatar
    Jonas Platte committed
                    server_name: server_name.to_owned(),
    
                    media_id,
    
                    timeout_ms,
                    allow_redirect,
    
    Timo Kösters's avatar
    Timo Kösters committed
        services()
            .media
    
    Nyaaori's avatar
    Nyaaori committed
                mxc.to_owned(),
    
    Timo Kösters's avatar
    Timo Kösters committed
                content_response.content_disposition.as_deref(),
                content_response.content_type.as_deref(),
    
    /// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}`
    
    ///
    /// Load media from our server or over federation.
    ///
    /// - Only allows federation if `allow_remote` is true
    
    /// - Only redirects if `allow_redirect` is true
    /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
    
    pub async fn get_content_route(
    
    Jonas Platte's avatar
    Jonas Platte committed
        body: Ruma<get_content::v3::Request>,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
    ) -> Result<get_content::v3::Response> {
    
        let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
    
        if let Some(FileMeta {
    
            content_type,
            file,
    
        }) = services().media.get(mxc.clone()).await?
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
            Ok(get_content::v3::Response {
    
                cross_origin_resource_policy: Some("cross-origin".to_owned()),
    
        } else if &*body.server_name != services().globals.server_name() && body.allow_remote {
    
            let remote_content_response = get_remote_content(
                &mxc,
                &body.server_name,
                body.media_id.clone(),
                body.allow_redirect,
                body.timeout_ms,
            )
            .await?;
    
            Ok(remote_content_response)
    
        } else {
            Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
        }
    }
    
    
    /// # `GET /_matrix/media/v3/download/{serverName}/{mediaId}/{fileName}`
    
    ///
    /// Load media from our server or over federation, permitting desired filename.
    ///
    /// - Only allows federation if `allow_remote` is true
    
    /// - Only redirects if `allow_redirect` is true
    /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
    
    pub async fn get_content_as_filename_route(
    
    Jonas Platte's avatar
    Jonas Platte committed
        body: Ruma<get_content_as_filename::v3::Request>,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
    ) -> Result<get_content_as_filename::v3::Response> {
    
        let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
    
        if let Some(FileMeta {
    
    🥺's avatar
    🥺 committed
            content_type, file, ..
    
        }) = services().media.get(mxc.clone()).await?
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
            Ok(get_content_as_filename::v3::Response {
    
                file,
                content_type,
                content_disposition: Some(format!("inline; filename={}", body.filename)),
    
                cross_origin_resource_policy: Some("cross-origin".to_owned()),
    
        } else if &*body.server_name != services().globals.server_name() && body.allow_remote {
    
            let remote_content_response = get_remote_content(
                &mxc,
                &body.server_name,
                body.media_id.clone(),
                body.allow_redirect,
                body.timeout_ms,
            )
            .await?;
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
            Ok(get_content_as_filename::v3::Response {
    
                content_disposition: Some(format!("inline: filename={}", body.filename)),
    
                content_type: remote_content_response.content_type,
    
                file: remote_content_response.file,
    
                cross_origin_resource_policy: Some("cross-origin".to_owned()),
    
        } else {
            Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
        }
    }
    
    
    /// # `GET /_matrix/media/v3/thumbnail/{serverName}/{mediaId}`
    
    ///
    /// Load media thumbnail from our server or over federation.
    ///
    /// - Only allows federation if `allow_remote` is true
    
    /// - Only redirects if `allow_redirect` is true
    /// - Uses client-provided `timeout_ms` if available, else defaults to 20 seconds
    
    pub async fn get_content_thumbnail_route(
    
    Jonas Platte's avatar
    Jonas Platte committed
        body: Ruma<get_content_thumbnail::v3::Request>,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
    ) -> Result<get_content_thumbnail::v3::Response> {
    
        let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);
    
    
        if let Some(FileMeta {
            content_type, file, ..
    
        }) = services()
    
            .media
            .get_thumbnail(
    
                mxc.clone(),
    
                body.width
                    .try_into()
                    .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
                body.height
                    .try_into()
    
    🥺's avatar
    🥺 committed
                    .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Height is invalid."))?,
    
            Ok(get_content_thumbnail::v3::Response {
                file,
                content_type,
                cross_origin_resource_policy: Some("cross-origin".to_owned()),
            })
    
        } else if &*body.server_name != services().globals.server_name() && body.allow_remote {
    
            // we'll lie to the client and say the blocked server's media was not found and log.
            // the client has no way of telling anyways so this is a security bonus.
            if services()
                .globals
                .prevent_media_downloads_from()
                .contains(&body.server_name.to_owned())
            {
                info!("Received request for remote media `{}` but server is in our media server blocklist. Returning 404.", mxc);
                return Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."));
            }
    
    
            let get_thumbnail_response = services()
    
                .sending
                .send_federation_request(
    
                    &body.server_name,
    
    Jonathan de Jong's avatar
    Jonathan de Jong committed
                    get_content_thumbnail::v3::Request {
    
                        allow_remote: body.allow_remote,
    
                        height: body.height,
                        width: body.width,
    
                        method: body.method.clone(),
    
    Jonas Platte's avatar
    Jonas Platte committed
                        server_name: body.server_name.clone(),
                        media_id: body.media_id.clone(),
    
                        timeout_ms: body.timeout_ms,
                        allow_redirect: body.allow_redirect,
    
    Timo Kösters's avatar
    Timo Kösters committed
            services()
                .media
    
                .upload_thumbnail(
                    mxc,
    
    Timo Kösters's avatar
    Timo Kösters committed
                    None,
                    get_thumbnail_response.content_type.as_deref(),
    
                    body.width.try_into().expect("all UInts are valid u32s"),
                    body.height.try_into().expect("all UInts are valid u32s"),
                    &get_thumbnail_response.file,
                )
                .await?;
    
            Ok(get_thumbnail_response)
    
        } else {
            Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
        }
    }