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
//! Types for the *m.key.verification.cancel* event.

use std::{
    borrow::Cow,
    fmt::{Display, Formatter, Result as FmtResult},
};

use ruma_events_macros::ruma_event;
use serde::{Deserialize, Serialize};

ruma_event! {
    /// Cancels a key verification process/request.
    ///
    /// Typically sent as a to-device event.
    CancelEvent {
        kind: Event,
        event_type: "m.key.verification.cancel",
        content: {
            /// The opaque identifier for the verification process/request.
            pub transaction_id: String,

            /// A human readable description of the `code`.
            ///
            /// The client should only rely on this string if it does not understand the `code`.
            pub reason: String,

            /// The error code for why the process/request was cancelled by the user.
            pub code: CancelCode,
        },
    }
}

/// An error code for why the process/request was cancelled by the user.
///
/// Custom error codes should use the Java package naming convention.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
// Cow<str> because deserialization sometimes needs to copy to unescape things
#[serde(from = "Cow<'_, str>", into = "String")]
pub enum CancelCode {
    /// The user cancelled the verification.
    User,

    /// The verification process timed out. Verification processes can define their own timeout
    /// parameters.
    Timeout,

    /// The device does not know about the given transaction ID.
    UnknownTransaction,

    /// The device does not know how to handle the requested method.
    ///
    /// This should be sent for *m.key.verification.start* messages and messages defined by
    /// individual verification processes.
    UnknownMethod,

    /// The device received an unexpected message.
    ///
    /// Typically raised when one of the parties is handling the verification out of order.
    UnexpectedMessage,

    /// The key was not verified.
    KeyMismatch,

    /// The expected user did not match the user verified.
    UserMismatch,

    /// The message received was invalid.
    InvalidMessage,

    /// An *m.key.verification.request* was accepted by a different device.
    ///
    /// The device receiving this error can ignore the verification request.
    Accepted,

    /// Any code that is not part of the specification.
    Custom(String),

    /// Additional variants may be added in the future and will not be considered breaking changes
    /// to ruma-events.
    #[doc(hidden)]
    __Nonexhaustive,
}

impl Display for CancelCode {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let cancel_code_str = match *self {
            CancelCode::User => "m.user",
            CancelCode::Timeout => "m.timeout",
            CancelCode::UnknownTransaction => "m.unknown_transaction",
            CancelCode::UnknownMethod => "m.unknown_method",
            CancelCode::UnexpectedMessage => "m.unexpected_message",
            CancelCode::KeyMismatch => "m.key_mismatch",
            CancelCode::UserMismatch => "m.user_mismatch",
            CancelCode::InvalidMessage => "m.invalid_message",
            CancelCode::Accepted => "m.accepted",
            CancelCode::Custom(ref cancel_code) => cancel_code,
            CancelCode::__Nonexhaustive => {
                panic!("__Nonexhaustive enum variant is not intended for use.")
            }
        };

        write!(f, "{}", cancel_code_str)
    }
}

impl From<Cow<'_, str>> for CancelCode {
    fn from(s: Cow<'_, str>) -> CancelCode {
        match &s as &str {
            "m.user" => CancelCode::User,
            "m.timeout" => CancelCode::Timeout,
            "m.unknown_transaction" => CancelCode::UnknownTransaction,
            "m.unknown_method" => CancelCode::UnknownMethod,
            "m.unexpected_message" => CancelCode::UnexpectedMessage,
            "m.key_mismatch" => CancelCode::KeyMismatch,
            "m.user_mismatch" => CancelCode::UserMismatch,
            "m.invalid_message" => CancelCode::InvalidMessage,
            "m.accepted" => CancelCode::Accepted,
            _ => CancelCode::Custom(s.into_owned()),
        }
    }
}

impl From<&str> for CancelCode {
    fn from(s: &str) -> CancelCode {
        CancelCode::from(Cow::Borrowed(s))
    }
}

impl From<CancelCode> for String {
    fn from(cancel_code: CancelCode) -> String {
        cancel_code.to_string()
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{from_str, to_string};

    use super::CancelCode;

    #[test]
    fn cancel_codes_serialize_to_display_form() {
        assert_eq!(to_string(&CancelCode::User).unwrap(), r#""m.user""#);
    }

    #[test]
    fn custom_cancel_codes_serialize_to_display_form() {
        assert_eq!(
            to_string(&CancelCode::Custom("io.ruma.test".to_string())).unwrap(),
            r#""io.ruma.test""#
        );
    }

    #[test]
    fn cancel_codes_deserialize_from_display_form() {
        assert_eq!(
            from_str::<CancelCode>(r#""m.user""#).unwrap(),
            CancelCode::User
        );
    }

    #[test]
    fn custom_cancel_codes_deserialize_from_display_form() {
        assert_eq!(
            from_str::<CancelCode>(r#""io.ruma.test""#).unwrap(),
            CancelCode::Custom("io.ruma.test".to_string())
        )
    }
}