Skip to main content

ruma_events/
key_backup.rs

1//! Types for the [`m.key_backup`] account data event.
2//!
3//! [`m.key_backup`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4287
4
5use ruma_macros::EventContent;
6use serde::{Deserialize, Serialize};
7
8/// The content of an [`m.key_backup`] event.
9///
10/// [`m.key_backup`]: https://github.com/matrix-org/matrix-spec-proposals/pull/4287
11#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
12#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
13#[ruma_event(type = "m.key_backup", kind = GlobalAccountData)]
14pub struct KeyBackupEventContent {
15    /// Is key backup (key storage) explicitly enabled or disabled by the user?
16    pub enabled: bool,
17}
18
19impl KeyBackupEventContent {
20    /// Creates a new `KeyBackupEventContent`.
21    pub fn new(enabled: bool) -> Self {
22        Self { enabled }
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use assert_matches2::assert_matches;
29    use ruma_common::canonical_json::assert_to_canonical_json_eq;
30    use serde_json::{from_value as from_json_value, json};
31
32    use super::KeyBackupEventContent;
33    use crate::AnyGlobalAccountDataEvent;
34
35    #[test]
36    fn key_backup_serialization() {
37        let content_false = KeyBackupEventContent::new(false);
38
39        assert_to_canonical_json_eq!(
40            content_false,
41            json!({
42                "enabled": false,
43            }),
44        );
45
46        let content_true = KeyBackupEventContent::new(true);
47
48        assert_to_canonical_json_eq!(
49            content_true,
50            json!({
51                "enabled": true,
52            }),
53        );
54    }
55
56    #[test]
57    fn key_backup_deserialization() {
58        let json_false = json!({
59            "content": {
60                "enabled": false,
61            },
62            "type": "m.key_backup",
63        });
64
65        assert_matches!(
66            from_json_value::<AnyGlobalAccountDataEvent>(json_false),
67            Ok(AnyGlobalAccountDataEvent::KeyBackup(ev_false))
68        );
69
70        assert!(!ev_false.content.enabled);
71
72        let json_true = json!({
73            "content": {
74                "enabled": true,
75            },
76            "type": "m.key_backup",
77        });
78
79        assert_matches!(
80            from_json_value::<AnyGlobalAccountDataEvent>(json_true),
81            Ok(AnyGlobalAccountDataEvent::KeyBackup(ev_true))
82        );
83
84        assert!(ev_true.content.enabled);
85    }
86}