1use std::{borrow::Cow, collections::BTreeMap};
6
7use js_int::UInt;
8use ruma_common::{OwnedDeviceId, OwnedEventId, serde::JsonObject};
9use ruma_macros::EventContent;
10use serde::{Deserialize, Serialize};
11
12use super::message;
13use crate::{
14 relation::{Annotation, CustomRelation, InReplyTo, Reference, RelationType, Thread},
15 room::message::RelationWithoutReplacement,
16};
17
18mod relation_serde;
19#[cfg(feature = "unstable-msc4362")]
20pub mod unstable_state;
21
22#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
24#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
25#[ruma_event(type = "m.room.encrypted", kind = MessageLike)]
26pub struct RoomEncryptedEventContent {
27 #[serde(flatten)]
29 pub scheme: EncryptedEventScheme,
30
31 #[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
33 pub relates_to: Option<Relation>,
34}
35
36impl RoomEncryptedEventContent {
37 pub fn new(scheme: EncryptedEventScheme, relates_to: Option<Relation>) -> Self {
39 Self { scheme, relates_to }
40 }
41}
42
43impl From<EncryptedEventScheme> for RoomEncryptedEventContent {
44 fn from(scheme: EncryptedEventScheme) -> Self {
45 Self { scheme, relates_to: None }
46 }
47}
48
49#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
51#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
52#[ruma_event(type = "m.room.encrypted", kind = ToDevice)]
53pub struct ToDeviceRoomEncryptedEventContent {
54 #[serde(flatten)]
56 pub scheme: EncryptedEventScheme,
57}
58
59impl ToDeviceRoomEncryptedEventContent {
60 pub fn new(scheme: EncryptedEventScheme) -> Self {
62 Self { scheme }
63 }
64}
65
66impl From<EncryptedEventScheme> for ToDeviceRoomEncryptedEventContent {
67 fn from(scheme: EncryptedEventScheme) -> Self {
68 Self { scheme }
69 }
70}
71
72#[derive(Clone, Debug, Deserialize, Serialize)]
74#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
75#[serde(tag = "algorithm")]
76pub enum EncryptedEventScheme {
77 #[serde(rename = "m.olm.v1.curve25519-aes-sha2")]
79 OlmV1Curve25519AesSha2(OlmV1Curve25519AesSha2Content),
80
81 #[serde(rename = "m.megolm.v1.aes-sha2")]
83 MegolmV1AesSha2(MegolmV1AesSha2Content),
84}
85
86#[derive(Clone, Debug)]
90#[allow(clippy::manual_non_exhaustive)]
91#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
92pub enum Relation {
93 Reply {
95 in_reply_to: InReplyTo,
97 },
98
99 Replacement(Replacement),
101
102 Reference(Reference),
104
105 Annotation(Annotation),
107
108 Thread(Thread),
110
111 #[doc(hidden)]
112 _Custom(CustomRelation),
113}
114
115impl Relation {
116 pub fn rel_type(&self) -> Option<RelationType> {
120 match self {
121 Relation::Reply { .. } => None,
122 Relation::Replacement(_) => Some(RelationType::Replacement),
123 Relation::Reference(_) => Some(RelationType::Reference),
124 Relation::Annotation(_) => Some(RelationType::Annotation),
125 Relation::Thread(_) => Some(RelationType::Thread),
126 Relation::_Custom(c) => c.rel_type(),
127 }
128 }
129
130 pub fn data(&self) -> Cow<'_, JsonObject> {
139 if let Relation::_Custom(CustomRelation(data)) = self {
140 Cow::Borrowed(data)
141 } else {
142 Cow::Owned(self.serialize_data())
143 }
144 }
145}
146
147impl<C> From<message::Relation<C>> for Relation {
148 fn from(rel: message::Relation<C>) -> Self {
149 match rel {
150 message::Relation::Reply { in_reply_to } => Self::Reply { in_reply_to },
151 message::Relation::Replacement(re) => {
152 Self::Replacement(Replacement { event_id: re.event_id })
153 }
154 message::Relation::Thread(t) => Self::Thread(Thread {
155 event_id: t.event_id,
156 in_reply_to: t.in_reply_to,
157 is_falling_back: t.is_falling_back,
158 }),
159 message::Relation::_Custom(c) => Self::_Custom(c),
160 }
161 }
162}
163
164impl From<RelationWithoutReplacement> for Relation {
165 fn from(value: RelationWithoutReplacement) -> Self {
166 match value {
167 RelationWithoutReplacement::Thread(t) => Self::Thread(t),
168 RelationWithoutReplacement::_Custom(c) => Self::_Custom(c),
169 RelationWithoutReplacement::Reply { in_reply_to } => Self::Reply { in_reply_to },
170 }
171 }
172}
173
174#[derive(Clone, Debug, Deserialize, Serialize)]
182#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
183#[serde(tag = "rel_type", rename = "m.replace")]
184pub struct Replacement {
185 pub event_id: OwnedEventId,
187}
188
189impl Replacement {
190 pub fn new(event_id: OwnedEventId) -> Self {
192 Self { event_id }
193 }
194}
195
196#[derive(Clone, Debug, Serialize, Deserialize)]
198#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
199pub struct OlmV1Curve25519AesSha2Content {
200 pub ciphertext: BTreeMap<String, CiphertextInfo>,
202
203 pub sender_key: String,
205}
206
207impl OlmV1Curve25519AesSha2Content {
208 pub fn new(ciphertext: BTreeMap<String, CiphertextInfo>, sender_key: String) -> Self {
210 Self { ciphertext, sender_key }
211 }
212}
213
214#[derive(Clone, Debug, Deserialize, Serialize)]
218#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
219pub struct CiphertextInfo {
220 pub body: String,
222
223 #[serde(rename = "type")]
225 pub message_type: UInt,
226}
227
228impl CiphertextInfo {
229 pub fn new(body: String, message_type: UInt) -> Self {
231 Self { body, message_type }
232 }
233}
234
235#[derive(Clone, Debug, Serialize, Deserialize)]
240#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
241pub struct MegolmV1AesSha2Content {
242 pub ciphertext: String,
244
245 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
247 #[serde(skip_serializing_if = "Option::is_none")]
248 pub sender_key: Option<String>,
249
250 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
252 #[serde(skip_serializing_if = "Option::is_none")]
253 pub device_id: Option<OwnedDeviceId>,
254
255 pub session_id: String,
257}
258
259#[derive(Debug)]
264#[allow(clippy::exhaustive_structs)]
265pub struct MegolmV1AesSha2ContentInit {
266 pub ciphertext: String,
268
269 pub sender_key: String,
271
272 pub device_id: OwnedDeviceId,
274
275 pub session_id: String,
277}
278
279impl From<MegolmV1AesSha2ContentInit> for MegolmV1AesSha2Content {
280 fn from(init: MegolmV1AesSha2ContentInit) -> Self {
282 let MegolmV1AesSha2ContentInit { ciphertext, sender_key, device_id, session_id } = init;
283 #[allow(deprecated)]
284 Self { ciphertext, sender_key: Some(sender_key), device_id: Some(device_id), session_id }
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use assert_matches2::assert_matches;
291 use js_int::uint;
292 use ruma_common::{
293 canonical_json::assert_to_canonical_json_eq, device_id, owned_event_id, serde::Raw,
294 };
295 use serde_json::{from_value as from_json_value, json};
296
297 use super::{
298 EncryptedEventScheme, InReplyTo, MegolmV1AesSha2ContentInit, Relation,
299 RoomEncryptedEventContent,
300 };
301
302 #[test]
303 fn serialization() {
304 let key_verification_start_content = RoomEncryptedEventContent {
305 scheme: EncryptedEventScheme::MegolmV1AesSha2(
306 MegolmV1AesSha2ContentInit {
307 ciphertext: "ciphertext".into(),
308 sender_key: "sender_key".into(),
309 device_id: "device_id".into(),
310 session_id: "session_id".into(),
311 }
312 .into(),
313 ),
314 relates_to: Some(Relation::Reply {
315 in_reply_to: InReplyTo { event_id: owned_event_id!("$h29iv0s8:example.com") },
316 }),
317 };
318
319 assert_to_canonical_json_eq!(
320 key_verification_start_content,
321 json!({
322 "algorithm": "m.megolm.v1.aes-sha2",
323 "ciphertext": "ciphertext",
324 "sender_key": "sender_key",
325 "device_id": "device_id",
326 "session_id": "session_id",
327 "m.relates_to": {
328 "m.in_reply_to": {
329 "event_id": "$h29iv0s8:example.com"
330 }
331 },
332 }),
333 );
334 }
335
336 #[test]
337 #[allow(deprecated)]
338 fn deserialization() {
339 let json_data = json!({
340 "algorithm": "m.megolm.v1.aes-sha2",
341 "ciphertext": "ciphertext",
342 "sender_key": "sender_key",
343 "device_id": "device_id",
344 "session_id": "session_id",
345 "m.relates_to": {
346 "m.in_reply_to": {
347 "event_id": "$h29iv0s8:example.com"
348 }
349 },
350 });
351
352 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
353
354 assert_matches!(content.scheme, EncryptedEventScheme::MegolmV1AesSha2(scheme));
355 assert_eq!(scheme.ciphertext, "ciphertext");
356 assert_eq!(scheme.sender_key.as_deref(), Some("sender_key"));
357 assert_eq!(scheme.device_id.as_deref(), Some(device_id!("device_id")));
358 assert_eq!(scheme.session_id, "session_id");
359
360 assert_matches!(content.relates_to, Some(Relation::Reply { in_reply_to }));
361 assert_eq!(in_reply_to.event_id, "$h29iv0s8:example.com");
362 }
363
364 #[test]
365 fn deserialization_olm() {
366 let json_data = json!({
367 "sender_key": "test_key",
368 "ciphertext": {
369 "test_curve_key": {
370 "body": "encrypted_body",
371 "type": 1
372 }
373 },
374 "algorithm": "m.olm.v1.curve25519-aes-sha2"
375 });
376 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
377
378 assert_matches!(content.scheme, EncryptedEventScheme::OlmV1Curve25519AesSha2(c));
379 assert_eq!(c.sender_key, "test_key");
380 assert_eq!(c.ciphertext.len(), 1);
381 assert_eq!(c.ciphertext["test_curve_key"].body, "encrypted_body");
382 assert_eq!(c.ciphertext["test_curve_key"].message_type, uint!(1));
383
384 assert_matches!(content.relates_to, None);
385 }
386
387 #[test]
388 fn deserialization_failure() {
389 from_json_value::<Raw<RoomEncryptedEventContent>>(
390 json!({ "algorithm": "m.megolm.v1.aes-sha2" }),
391 )
392 .unwrap()
393 .deserialize()
394 .unwrap_err();
395 }
396}