Skip to main content

xmtp_content_types/
leave_request.rs

1use std::collections::HashMap;
2
3use prost::Message;
4
5use super::{CodecError, ContentCodec};
6use xmtp_proto::xmtp::mls::message_contents::content_types::LeaveRequest;
7use xmtp_proto::xmtp::mls::message_contents::{ContentTypeId, EncodedContent};
8
9pub struct LeaveRequestCodec {
10    #[allow(dead_code)]
11    authenticated_note: Option<Vec<u8>>,
12}
13
14impl LeaveRequestCodec {
15    const AUTHORITY_ID: &'static str = "xmtp.org";
16    pub const TYPE_ID: &'static str = "leave_request";
17    pub const MAJOR_VERSION: u32 = 1;
18    pub const MINOR_VERSION: u32 = 0;
19}
20
21impl ContentCodec<LeaveRequest> for LeaveRequestCodec {
22    fn content_type() -> ContentTypeId {
23        ContentTypeId {
24            authority_id: LeaveRequestCodec::AUTHORITY_ID.to_string(),
25            type_id: LeaveRequestCodec::TYPE_ID.to_string(),
26            version_major: LeaveRequestCodec::MAJOR_VERSION,
27            version_minor: LeaveRequestCodec::MINOR_VERSION,
28        }
29    }
30
31    fn encode(mut data: LeaveRequest) -> Result<EncodedContent, CodecError> {
32        data.authenticated_note = data.authenticated_note.filter(|note| !note.is_empty());
33        let mut buf = Vec::new();
34        data.encode(&mut buf)
35            .map_err(|e| CodecError::Encode(e.to_string()))?;
36
37        Ok(EncodedContent {
38            r#type: Some(LeaveRequestCodec::content_type()),
39            parameters: HashMap::new(),
40            fallback: Some("A member has requested leaving the group".to_string()),
41            compression: None,
42            content: buf,
43        })
44    }
45
46    fn decode(content: EncodedContent) -> Result<LeaveRequest, CodecError> {
47        let mut decoded = LeaveRequest::decode(content.content.as_slice())
48            .map_err(|e| CodecError::Decode(e.to_string()))?;
49
50        decoded.authenticated_note = decoded.authenticated_note.filter(|note| !note.is_empty());
51        Ok(decoded)
52    }
53
54    fn should_push() -> bool {
55        false
56    }
57}
58
59#[cfg(test)]
60pub(crate) mod tests {
61    use super::*;
62
63    #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
64    #[cfg_attr(not(target_arch = "wasm32"), test)]
65    fn test_encode_decode() {
66        let data = LeaveRequest {
67            authenticated_note: None,
68        };
69
70        let encoded = LeaveRequestCodec::encode(data).unwrap();
71        assert_eq!(encoded.clone().r#type.unwrap().type_id, "leave_request");
72
73        let _ = LeaveRequestCodec::decode(encoded).unwrap();
74    }
75}