1use std::{borrow::Cow, collections::BTreeMap};
6
7use js_int::UInt;
8use ruma_common::{serde::JsonObject, OwnedDeviceId, OwnedEventId};
9use ruma_macros::EventContent;
10use serde::{Deserialize, Serialize};
11
12use super::message;
13use crate::relation::{Annotation, CustomRelation, InReplyTo, Reference, RelationType, Thread};
14
15mod relation_serde;
16#[cfg(feature = "unstable-msc3414")]
17pub mod unstable_state;
18
19#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
21#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
22#[ruma_event(type = "m.room.encrypted", kind = MessageLike)]
23pub struct RoomEncryptedEventContent {
24 #[serde(flatten)]
26 pub scheme: EncryptedEventScheme,
27
28 #[serde(rename = "m.relates_to", skip_serializing_if = "Option::is_none")]
30 pub relates_to: Option<Relation>,
31}
32
33impl RoomEncryptedEventContent {
34 pub fn new(scheme: EncryptedEventScheme, relates_to: Option<Relation>) -> Self {
36 Self { scheme, relates_to }
37 }
38}
39
40impl From<EncryptedEventScheme> for RoomEncryptedEventContent {
41 fn from(scheme: EncryptedEventScheme) -> Self {
42 Self { scheme, relates_to: None }
43 }
44}
45
46#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
48#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
49#[ruma_event(type = "m.room.encrypted", kind = ToDevice)]
50pub struct ToDeviceRoomEncryptedEventContent {
51 #[serde(flatten)]
53 pub scheme: EncryptedEventScheme,
54}
55
56impl ToDeviceRoomEncryptedEventContent {
57 pub fn new(scheme: EncryptedEventScheme) -> Self {
59 Self { scheme }
60 }
61}
62
63impl From<EncryptedEventScheme> for ToDeviceRoomEncryptedEventContent {
64 fn from(scheme: EncryptedEventScheme) -> Self {
65 Self { scheme }
66 }
67}
68
69#[derive(Clone, Debug, Deserialize, Serialize)]
71#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
72#[serde(tag = "algorithm")]
73pub enum EncryptedEventScheme {
74 #[serde(rename = "m.olm.v1.curve25519-aes-sha2")]
76 OlmV1Curve25519AesSha2(OlmV1Curve25519AesSha2Content),
77
78 #[serde(rename = "m.megolm.v1.aes-sha2")]
80 MegolmV1AesSha2(MegolmV1AesSha2Content),
81}
82
83#[derive(Clone, Debug)]
87#[allow(clippy::manual_non_exhaustive)]
88#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
89pub enum Relation {
90 Reply {
92 in_reply_to: InReplyTo,
94 },
95
96 Replacement(Replacement),
98
99 Reference(Reference),
101
102 Annotation(Annotation),
104
105 Thread(Thread),
107
108 #[doc(hidden)]
109 _Custom(CustomRelation),
110}
111
112impl Relation {
113 pub fn rel_type(&self) -> Option<RelationType> {
117 match self {
118 Relation::Reply { .. } => None,
119 Relation::Replacement(_) => Some(RelationType::Replacement),
120 Relation::Reference(_) => Some(RelationType::Reference),
121 Relation::Annotation(_) => Some(RelationType::Annotation),
122 Relation::Thread(_) => Some(RelationType::Thread),
123 Relation::_Custom(c) => c.rel_type(),
124 }
125 }
126
127 pub fn data(&self) -> Cow<'_, JsonObject> {
136 if let Relation::_Custom(CustomRelation(data)) = self {
137 Cow::Borrowed(data)
138 } else {
139 Cow::Owned(self.serialize_data())
140 }
141 }
142}
143
144impl<C> From<message::Relation<C>> for Relation {
145 fn from(rel: message::Relation<C>) -> Self {
146 match rel {
147 message::Relation::Reply { in_reply_to } => Self::Reply { in_reply_to },
148 message::Relation::Replacement(re) => {
149 Self::Replacement(Replacement { event_id: re.event_id })
150 }
151 message::Relation::Thread(t) => Self::Thread(Thread {
152 event_id: t.event_id,
153 in_reply_to: t.in_reply_to,
154 is_falling_back: t.is_falling_back,
155 }),
156 message::Relation::_Custom(c) => Self::_Custom(c),
157 }
158 }
159}
160
161#[derive(Clone, Debug, Deserialize, Serialize)]
169#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
170#[serde(tag = "rel_type", rename = "m.replace")]
171pub struct Replacement {
172 pub event_id: OwnedEventId,
174}
175
176impl Replacement {
177 pub fn new(event_id: OwnedEventId) -> Self {
179 Self { event_id }
180 }
181}
182
183#[derive(Clone, Debug, Serialize, Deserialize)]
185#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
186pub struct OlmV1Curve25519AesSha2Content {
187 pub ciphertext: BTreeMap<String, CiphertextInfo>,
189
190 pub sender_key: String,
192}
193
194impl OlmV1Curve25519AesSha2Content {
195 pub fn new(ciphertext: BTreeMap<String, CiphertextInfo>, sender_key: String) -> Self {
197 Self { ciphertext, sender_key }
198 }
199}
200
201#[derive(Clone, Debug, Deserialize, Serialize)]
205#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
206pub struct CiphertextInfo {
207 pub body: String,
209
210 #[serde(rename = "type")]
212 pub message_type: UInt,
213}
214
215impl CiphertextInfo {
216 pub fn new(body: String, message_type: UInt) -> Self {
218 Self { body, message_type }
219 }
220}
221
222#[derive(Clone, Debug, Serialize, Deserialize)]
227#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
228pub struct MegolmV1AesSha2Content {
229 pub ciphertext: String,
231
232 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
234 #[serde(skip_serializing_if = "Option::is_none")]
235 pub sender_key: Option<String>,
236
237 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
239 #[serde(skip_serializing_if = "Option::is_none")]
240 pub device_id: Option<OwnedDeviceId>,
241
242 pub session_id: String,
244}
245
246#[derive(Debug)]
251#[allow(clippy::exhaustive_structs)]
252pub struct MegolmV1AesSha2ContentInit {
253 pub ciphertext: String,
255
256 pub sender_key: String,
258
259 pub device_id: OwnedDeviceId,
261
262 pub session_id: String,
264}
265
266impl From<MegolmV1AesSha2ContentInit> for MegolmV1AesSha2Content {
267 fn from(init: MegolmV1AesSha2ContentInit) -> Self {
269 let MegolmV1AesSha2ContentInit { ciphertext, sender_key, device_id, session_id } = init;
270 #[allow(deprecated)]
271 Self { ciphertext, sender_key: Some(sender_key), device_id: Some(device_id), session_id }
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use assert_matches2::assert_matches;
278 use js_int::uint;
279 use ruma_common::{device_id, owned_event_id, serde::Raw};
280 use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
281
282 use super::{
283 EncryptedEventScheme, InReplyTo, MegolmV1AesSha2ContentInit, Relation,
284 RoomEncryptedEventContent,
285 };
286
287 #[test]
288 fn serialization() {
289 let key_verification_start_content = RoomEncryptedEventContent {
290 scheme: EncryptedEventScheme::MegolmV1AesSha2(
291 MegolmV1AesSha2ContentInit {
292 ciphertext: "ciphertext".into(),
293 sender_key: "sender_key".into(),
294 device_id: "device_id".into(),
295 session_id: "session_id".into(),
296 }
297 .into(),
298 ),
299 relates_to: Some(Relation::Reply {
300 in_reply_to: InReplyTo { event_id: owned_event_id!("$h29iv0s8:example.com") },
301 }),
302 };
303
304 let json_data = json!({
305 "algorithm": "m.megolm.v1.aes-sha2",
306 "ciphertext": "ciphertext",
307 "sender_key": "sender_key",
308 "device_id": "device_id",
309 "session_id": "session_id",
310 "m.relates_to": {
311 "m.in_reply_to": {
312 "event_id": "$h29iv0s8:example.com"
313 }
314 },
315 });
316
317 assert_eq!(to_json_value(&key_verification_start_content).unwrap(), json_data);
318 }
319
320 #[test]
321 #[allow(deprecated)]
322 fn deserialization() {
323 let json_data = json!({
324 "algorithm": "m.megolm.v1.aes-sha2",
325 "ciphertext": "ciphertext",
326 "sender_key": "sender_key",
327 "device_id": "device_id",
328 "session_id": "session_id",
329 "m.relates_to": {
330 "m.in_reply_to": {
331 "event_id": "$h29iv0s8:example.com"
332 }
333 },
334 });
335
336 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
337
338 assert_matches!(content.scheme, EncryptedEventScheme::MegolmV1AesSha2(scheme));
339 assert_eq!(scheme.ciphertext, "ciphertext");
340 assert_eq!(scheme.sender_key.as_deref(), Some("sender_key"));
341 assert_eq!(scheme.device_id.as_deref(), Some(device_id!("device_id")));
342 assert_eq!(scheme.session_id, "session_id");
343
344 assert_matches!(content.relates_to, Some(Relation::Reply { in_reply_to }));
345 assert_eq!(in_reply_to.event_id, "$h29iv0s8:example.com");
346 }
347
348 #[test]
349 fn deserialization_olm() {
350 let json_data = json!({
351 "sender_key": "test_key",
352 "ciphertext": {
353 "test_curve_key": {
354 "body": "encrypted_body",
355 "type": 1
356 }
357 },
358 "algorithm": "m.olm.v1.curve25519-aes-sha2"
359 });
360 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
361
362 assert_matches!(content.scheme, EncryptedEventScheme::OlmV1Curve25519AesSha2(c));
363 assert_eq!(c.sender_key, "test_key");
364 assert_eq!(c.ciphertext.len(), 1);
365 assert_eq!(c.ciphertext["test_curve_key"].body, "encrypted_body");
366 assert_eq!(c.ciphertext["test_curve_key"].message_type, uint!(1));
367
368 assert_matches!(content.relates_to, None);
369 }
370
371 #[test]
372 fn deserialization_failure() {
373 from_json_value::<Raw<RoomEncryptedEventContent>>(
374 json!({ "algorithm": "m.megolm.v1.aes-sha2" }),
375 )
376 .unwrap()
377 .deserialize()
378 .unwrap_err();
379 }
380}