summaryrefslogtreecommitdiff
path: root/src/api/client_server/media.rs
blob: 75f8e15664a7c67489c3e34b186c8f5410578254 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use std::time::Duration;

use crate::{service::media::FileMeta, services, utils, Error, Result, Ruma};
use ruma::api::client::{
    error::ErrorKind,
    media::{
        create_content, get_content, get_content_as_filename, get_content_thumbnail,
        get_media_config,
    },
};

const MXC_LENGTH: usize = 32;

/// # `GET /_matrix/media/r0/config`
///
/// Returns max upload size.
pub async fn get_media_config_route(
    _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/r0/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(
    body: Ruma<create_content::v3::Request>,
) -> Result<create_content::v3::Response> {
    let mxc = format!(
        "mxc://{}/{}",
        services().globals.server_name(),
        utils::random_string(MXC_LENGTH)
    );

    services()
        .media
        .create(
            mxc.clone(),
            body.filename
                .as_ref()
                .map(|filename| "inline; filename=".to_owned() + filename)
                .as_deref(),
            body.content_type.as_deref(),
            &body.file,
        )
        .await?;

    Ok(create_content::v3::Response {
        content_uri: mxc.try_into().expect("Invalid mxc:// URI"),
        blurhash: None,
    })
}

pub async fn get_remote_content(
    mxc: &str,
    server_name: &ruma::ServerName,
    media_id: String,
) -> Result<get_content::v3::Response, Error> {
    let content_response = services()
        .sending
        .send_federation_request(
            server_name,
            get_content::v3::Request {
                allow_remote: false,
                server_name: server_name.to_owned(),
                media_id,
                timeout_ms: Duration::from_secs(20),
                allow_redirect: false,
            },
        )
        .await?;

    services()
        .media
        .create(
            mxc.to_owned(),
            content_response.content_disposition.as_deref(),
            content_response.content_type.as_deref(),
            &content_response.file,
        )
        .await?;

    Ok(content_response)
}

/// # `GET /_matrix/media/r0/download/{serverName}/{mediaId}`
///
/// Load media from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
pub async fn get_content_route(
    body: Ruma<get_content::v3::Request>,
) -> Result<get_content::v3::Response> {
    let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);

    if let Some(FileMeta {
        content_disposition,
        content_type,
        file,
    }) = services().media.get(mxc.clone()).await?
    {
        Ok(get_content::v3::Response {
            file,
            content_type,
            content_disposition,
            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()).await?;
        Ok(remote_content_response)
    } else {
        Err(Error::BadRequest(ErrorKind::NotFound, "Media not found."))
    }
}

/// # `GET /_matrix/media/r0/download/{serverName}/{mediaId}/{fileName}`
///
/// Load media from our server or over federation, permitting desired filename.
///
/// - Only allows federation if `allow_remote` is true
pub async fn get_content_as_filename_route(
    body: Ruma<get_content_as_filename::v3::Request>,
) -> Result<get_content_as_filename::v3::Response> {
    let mxc = format!("mxc://{}/{}", body.server_name, body.media_id);

    if let Some(FileMeta {
        content_disposition: _,
        content_type,
        file,
    }) = services().media.get(mxc.clone()).await?
    {
        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()).await?;

        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/r0/thumbnail/{serverName}/{mediaId}`
///
/// Load media thumbnail from our server or over federation.
///
/// - Only allows federation if `allow_remote` is true
pub async fn get_content_thumbnail_route(
    body: Ruma<get_content_thumbnail::v3::Request>,
) -> 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()
                .map_err(|_| Error::BadRequest(ErrorKind::InvalidParam, "Width is invalid."))?,
        )
        .await?
    {
        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 {
        let get_thumbnail_response = services()
            .sending
            .send_federation_request(
                &body.server_name,
                get_content_thumbnail::v3::Request {
                    allow_remote: false,
                    height: body.height,
                    width: body.width,
                    method: body.method.clone(),
                    server_name: body.server_name.clone(),
                    media_id: body.media_id.clone(),
                    timeout_ms: Duration::from_secs(20),
                    allow_redirect: false,
                },
            )
            .await?;

        services()
            .media
            .upload_thumbnail(
                mxc,
                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."))
    }
}