logo
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! Types for extensible file message events ([MSC3551]).
//!
//! [MSC3551]: https://github.com/matrix-org/matrix-spec-proposals/pull/3551

use std::collections::BTreeMap;

use js_int::UInt;
use ruma_macros::EventContent;
use serde::{Deserialize, Serialize};

use super::{
    message::MessageContent,
    room::{
        message::{
            FileInfo, FileMessageEventContent, MessageType, Relation, RoomMessageEventContent,
        },
        EncryptedFile, JsonWebKey, MediaSource,
    },
};
use crate::{serde::Base64, OwnedMxcUri};

/// The payload for an extensible file message.
///
/// This is the new primary type introduced in [MSC3551] and should not be sent before the end of
/// the transition period. See the documentation of the [`message`] module for more information.
///
/// `FileEventContent` can be converted to a [`RoomMessageEventContent`] with a
/// [`MessageType::File`]. You can convert it back with
/// [`FileEventContent::from_file_room_message()`].
///
/// [MSC3551]: https://github.com/matrix-org/matrix-spec-proposals/pull/3551
/// [`message`]: super::message
/// [`RoomMessageEventContent`]: super::room::message::RoomMessageEventContent
/// [`MessageType::File`]: super::room::message::MessageType::File
#[derive(Clone, Debug, Serialize, Deserialize, EventContent)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[ruma_event(type = "m.file", kind = MessageLike)]
pub struct FileEventContent {
    /// The text representation of the message.
    #[serde(flatten)]
    pub message: MessageContent,

    /// The file content of the message.
    #[serde(rename = "m.file")]
    pub file: FileContent,

    /// Information about related messages.
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub relates_to: Option<Relation>,
}

impl FileEventContent {
    /// Creates a new non-encrypted `FileEventContent` with the given plain text message, url and
    /// file info.
    pub fn plain(
        message: impl Into<String>,
        url: OwnedMxcUri,
        info: Option<Box<FileContentInfo>>,
    ) -> Self {
        Self {
            message: MessageContent::plain(message),
            file: FileContent::plain(url, info),
            relates_to: None,
        }
    }

    /// Creates a new non-encrypted `FileEventContent` with the given message, url and
    /// file info.
    pub fn plain_message(
        message: MessageContent,
        url: OwnedMxcUri,
        info: Option<Box<FileContentInfo>>,
    ) -> Self {
        Self { message, file: FileContent::plain(url, info), relates_to: None }
    }

    /// Creates a new encrypted `FileEventContent` with the given plain text message, url,
    /// encryption info and file info.
    pub fn encrypted(
        message: impl Into<String>,
        url: OwnedMxcUri,
        encryption_info: EncryptedContent,
        info: Option<Box<FileContentInfo>>,
    ) -> Self {
        Self {
            message: MessageContent::plain(message),
            file: FileContent::encrypted(url, encryption_info, info),
            relates_to: None,
        }
    }

    /// Creates a new encrypted `FileEventContent` with the given message, url,
    /// encryption info and file info.
    pub fn encrypted_message(
        message: MessageContent,
        url: OwnedMxcUri,
        encryption_info: EncryptedContent,
        info: Option<Box<FileContentInfo>>,
    ) -> Self {
        Self { message, file: FileContent::encrypted(url, encryption_info, info), relates_to: None }
    }

    /// Create a new `FileEventContent` from the given `FileMessageEventContent` and optional
    /// relation.
    pub fn from_file_room_message(
        content: FileMessageEventContent,
        relates_to: Option<Relation>,
    ) -> Self {
        let FileMessageEventContent { body, filename, source, info, message, file } = content;
        let FileInfo { mimetype, size, .. } = info.map(|info| *info).unwrap_or_default();

        let message = message.unwrap_or_else(|| MessageContent::plain(body));
        let file = file.unwrap_or_else(|| {
            FileContent::from_room_message_content(source, filename, mimetype, size)
        });

        Self { message, file, relates_to }
    }
}

impl From<FileEventContent> for RoomMessageEventContent {
    fn from(content: FileEventContent) -> Self {
        let FileEventContent { message, file, relates_to } = content;

        Self {
            msgtype: MessageType::File(FileMessageEventContent::from_extensible_content(
                message, file,
            )),
            relates_to,
        }
    }
}

/// File content.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct FileContent {
    /// The URL to the file.
    pub url: OwnedMxcUri,

    /// Information about the uploaded file.
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub info: Option<Box<FileContentInfo>>,

    /// Information on the encrypted file.
    ///
    /// Required if the file is encrypted.
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub encryption_info: Option<Box<EncryptedContent>>,
}

impl FileContent {
    /// Creates a new non-encrypted `FileContent` with the given url and file info.
    pub fn plain(url: OwnedMxcUri, info: Option<Box<FileContentInfo>>) -> Self {
        Self { url, info, encryption_info: None }
    }

    /// Creates a new encrypted `FileContent` with the given url, encryption info and file info.
    pub fn encrypted(
        url: OwnedMxcUri,
        encryption_info: EncryptedContent,
        info: Option<Box<FileContentInfo>>,
    ) -> Self {
        Self { url, info, encryption_info: Some(Box::new(encryption_info)) }
    }

    /// Create a new `FileContent` with the given media source, file info and filename.
    pub(crate) fn from_room_message_content(
        source: MediaSource,
        filename: Option<String>,
        mimetype: Option<String>,
        size: Option<UInt>,
    ) -> Self {
        let (url, encryption_info) = source.into_extensible_content();
        let info =
            FileContentInfo::from_room_message_content(filename, mimetype, size).map(Box::new);

        Self { url, encryption_info: encryption_info.map(Box::new), info }
    }

    /// Whether the file is encrypted.
    pub fn is_encrypted(&self) -> bool {
        self.encryption_info.is_some()
    }
}

/// Information about a file content.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct FileContentInfo {
    /// The original filename of the uploaded file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// The mimetype of the file, e.g. "application/msword".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mimetype: Option<String>,

    /// The size of the file in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<UInt>,
}

impl FileContentInfo {
    /// Creates an empty `FileContentInfo`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new `FileContentInfo` with the given filename, mimetype and size.
    ///
    /// Returns `None` if the `FileContentInfo` would be empty.
    pub(crate) fn from_room_message_content(
        filename: Option<String>,
        mimetype: Option<String>,
        size: Option<UInt>,
    ) -> Option<Self> {
        if filename.is_none() && mimetype.is_none() && size.is_none() {
            None
        } else {
            Some(Self { name: filename, mimetype, size })
        }
    }
}

/// The encryption info of a file sent to a room with end-to-end encryption enabled.
///
/// To create an instance of this type, first create a `EncryptedContentInit` and convert it via
/// `EncryptedContent::from` / `.into()`.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct EncryptedContent {
    /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
    pub key: JsonWebKey,

    /// The 128-bit unique counter block used by AES-CTR, encoded as unpadded base64.
    pub iv: Base64,

    /// A map from an algorithm name to a hash of the ciphertext, encoded as unpadded base64.
    ///
    /// Clients should support the SHA-256 hash, which uses the key sha256.
    pub hashes: BTreeMap<String, Base64>,

    /// Version of the encrypted attachments protocol.
    ///
    /// Must be `v2`.
    pub v: String,
}

/// Initial set of fields of `EncryptedContent`.
///
/// This struct will not be updated even if additional fields are added to `EncryptedContent` in a
/// new (non-breaking) release of the Matrix specification.
#[derive(Debug)]
#[allow(clippy::exhaustive_structs)]
pub struct EncryptedContentInit {
    /// A [JSON Web Key](https://tools.ietf.org/html/rfc7517#appendix-A.3) object.
    pub key: JsonWebKey,

    /// The 128-bit unique counter block used by AES-CTR, encoded as unpadded base64.
    pub iv: Base64,

    /// A map from an algorithm name to a hash of the ciphertext, encoded as unpadded base64.
    ///
    /// Clients should support the SHA-256 hash, which uses the key sha256.
    pub hashes: BTreeMap<String, Base64>,

    /// Version of the encrypted attachments protocol.
    ///
    /// Must be `v2`.
    pub v: String,
}

impl From<EncryptedContentInit> for EncryptedContent {
    fn from(init: EncryptedContentInit) -> Self {
        let EncryptedContentInit { key, iv, hashes, v } = init;
        Self { key, iv, hashes, v }
    }
}

impl From<&EncryptedFile> for EncryptedContent {
    fn from(encrypted: &EncryptedFile) -> Self {
        let EncryptedFile { key, iv, hashes, v, .. } = encrypted;
        Self { key: key.to_owned(), iv: iv.to_owned(), hashes: hashes.to_owned(), v: v.to_owned() }
    }
}