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, Reply, 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, Serialize)]
90#[allow(clippy::manual_non_exhaustive)]
91#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
92#[serde(untagged)]
93pub enum Relation {
94 Reply(Reply),
96
97 Replacement(Replacement),
99
100 Reference(Reference),
102
103 Annotation(Annotation),
105
106 Thread(Thread),
108
109 #[doc(hidden)]
110 _Custom(CustomRelation),
111}
112
113impl Relation {
114 pub fn rel_type(&self) -> Option<RelationType> {
118 match self {
119 Relation::Reply(_) => None,
120 Relation::Replacement(_) => Some(RelationType::Replacement),
121 Relation::Reference(_) => Some(RelationType::Reference),
122 Relation::Annotation(_) => Some(RelationType::Annotation),
123 Relation::Thread(_) => Some(RelationType::Thread),
124 Relation::_Custom(c) => c.rel_type(),
125 }
126 }
127
128 pub fn data(&self) -> Cow<'_, JsonObject> {
137 if let Relation::_Custom(CustomRelation(data)) = self {
138 Cow::Borrowed(data)
139 } else {
140 Cow::Owned(self.serialize_data())
141 }
142 }
143}
144
145impl<C> From<message::Relation<C>> for Relation {
146 fn from(rel: message::Relation<C>) -> Self {
147 match rel {
148 message::Relation::Reply(r) => Self::Reply(r),
149 message::Relation::Replacement(re) => {
150 Self::Replacement(Replacement { event_id: re.event_id })
151 }
152 message::Relation::Thread(t) => Self::Thread(Thread {
153 event_id: t.event_id,
154 in_reply_to: t.in_reply_to,
155 is_falling_back: t.is_falling_back,
156 }),
157 message::Relation::_Custom(c) => Self::_Custom(c),
158 }
159 }
160}
161
162impl From<RelationWithoutReplacement> for Relation {
163 fn from(value: RelationWithoutReplacement) -> Self {
164 match value {
165 RelationWithoutReplacement::Reply(r) => Self::Reply(r),
166 RelationWithoutReplacement::Thread(t) => Self::Thread(t),
167 RelationWithoutReplacement::_Custom(c) => Self::_Custom(c),
168 }
169 }
170}
171
172#[derive(Clone, Debug, Deserialize, Serialize)]
180#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
181#[serde(tag = "rel_type", rename = "m.replace")]
182pub struct Replacement {
183 pub event_id: OwnedEventId,
185}
186
187impl Replacement {
188 pub fn new(event_id: OwnedEventId) -> Self {
190 Self { event_id }
191 }
192}
193
194#[derive(Clone, Debug, Serialize, Deserialize)]
196#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
197pub struct OlmV1Curve25519AesSha2Content {
198 pub ciphertext: BTreeMap<String, CiphertextInfo>,
200
201 pub sender_key: String,
203}
204
205impl OlmV1Curve25519AesSha2Content {
206 pub fn new(ciphertext: BTreeMap<String, CiphertextInfo>, sender_key: String) -> Self {
208 Self { ciphertext, sender_key }
209 }
210}
211
212#[derive(Clone, Debug, Deserialize, Serialize)]
216#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
217pub struct CiphertextInfo {
218 pub body: String,
220
221 #[serde(rename = "type")]
223 pub message_type: UInt,
224}
225
226impl CiphertextInfo {
227 pub fn new(body: String, message_type: UInt) -> Self {
229 Self { body, message_type }
230 }
231}
232
233#[derive(Clone, Debug, Serialize, Deserialize)]
238#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
239pub struct MegolmV1AesSha2Content {
240 pub ciphertext: String,
242
243 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
245 #[serde(skip_serializing_if = "Option::is_none")]
246 pub sender_key: Option<String>,
247
248 #[deprecated = "Since Matrix 1.3, this field should still be sent but should not be used when received"]
250 #[serde(skip_serializing_if = "Option::is_none")]
251 pub device_id: Option<OwnedDeviceId>,
252
253 pub session_id: String,
255}
256
257#[derive(Debug)]
262#[allow(clippy::exhaustive_structs)]
263pub struct MegolmV1AesSha2ContentInit {
264 pub ciphertext: String,
266
267 pub sender_key: String,
269
270 pub device_id: OwnedDeviceId,
272
273 pub session_id: String,
275}
276
277impl From<MegolmV1AesSha2ContentInit> for MegolmV1AesSha2Content {
278 fn from(init: MegolmV1AesSha2ContentInit) -> Self {
280 let MegolmV1AesSha2ContentInit { ciphertext, sender_key, device_id, session_id } = init;
281 #[allow(deprecated)]
282 Self { ciphertext, sender_key: Some(sender_key), device_id: Some(device_id), session_id }
283 }
284}
285
286#[cfg(test)]
287mod tests {
288 use assert_matches2::assert_matches;
289 use js_int::uint;
290 use ruma_common::{
291 canonical_json::assert_to_canonical_json_eq, device_id, owned_event_id, serde::Raw,
292 };
293 use serde_json::{from_value as from_json_value, json};
294
295 use super::{
296 EncryptedEventScheme, MegolmV1AesSha2ContentInit, Relation, Reply,
297 RoomEncryptedEventContent,
298 };
299
300 #[test]
301 fn serialization() {
302 let key_verification_start_content = RoomEncryptedEventContent {
303 scheme: EncryptedEventScheme::MegolmV1AesSha2(
304 MegolmV1AesSha2ContentInit {
305 ciphertext: "ciphertext".into(),
306 sender_key: "sender_key".into(),
307 device_id: "device_id".into(),
308 session_id: "session_id".into(),
309 }
310 .into(),
311 ),
312 relates_to: Some(Relation::Reply(Reply::with_event_id(owned_event_id!(
313 "$h29iv0s8:example.com"
314 )))),
315 };
316
317 assert_to_canonical_json_eq!(
318 key_verification_start_content,
319 json!({
320 "algorithm": "m.megolm.v1.aes-sha2",
321 "ciphertext": "ciphertext",
322 "sender_key": "sender_key",
323 "device_id": "device_id",
324 "session_id": "session_id",
325 "m.relates_to": {
326 "m.in_reply_to": {
327 "event_id": "$h29iv0s8:example.com"
328 }
329 },
330 }),
331 );
332 }
333
334 #[test]
335 #[allow(deprecated)]
336 fn deserialization() {
337 let json_data = json!({
338 "algorithm": "m.megolm.v1.aes-sha2",
339 "ciphertext": "ciphertext",
340 "sender_key": "sender_key",
341 "device_id": "device_id",
342 "session_id": "session_id",
343 "m.relates_to": {
344 "m.in_reply_to": {
345 "event_id": "$h29iv0s8:example.com"
346 }
347 },
348 });
349
350 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
351
352 assert_matches!(content.scheme, EncryptedEventScheme::MegolmV1AesSha2(scheme));
353 assert_eq!(scheme.ciphertext, "ciphertext");
354 assert_eq!(scheme.sender_key.as_deref(), Some("sender_key"));
355 assert_eq!(scheme.device_id.as_deref(), Some(device_id!("device_id")));
356 assert_eq!(scheme.session_id, "session_id");
357
358 assert_matches!(content.relates_to, Some(Relation::Reply(reply)));
359 assert_eq!(reply.in_reply_to.event_id, "$h29iv0s8:example.com");
360 }
361
362 #[test]
363 fn deserialization_olm() {
364 let json_data = json!({
365 "sender_key": "test_key",
366 "ciphertext": {
367 "test_curve_key": {
368 "body": "encrypted_body",
369 "type": 1
370 }
371 },
372 "algorithm": "m.olm.v1.curve25519-aes-sha2"
373 });
374 let content: RoomEncryptedEventContent = from_json_value(json_data).unwrap();
375
376 assert_matches!(content.scheme, EncryptedEventScheme::OlmV1Curve25519AesSha2(c));
377 assert_eq!(c.sender_key, "test_key");
378 assert_eq!(c.ciphertext.len(), 1);
379 assert_eq!(c.ciphertext["test_curve_key"].body, "encrypted_body");
380 assert_eq!(c.ciphertext["test_curve_key"].message_type, uint!(1));
381
382 assert_matches!(content.relates_to, None);
383 }
384
385 #[test]
386 fn deserialization_failure() {
387 from_json_value::<Raw<RoomEncryptedEventContent>>(
388 json!({ "algorithm": "m.megolm.v1.aes-sha2" }),
389 )
390 .unwrap()
391 .deserialize()
392 .unwrap_err();
393 }
394}