Skip to main content

privchat_protocol/
lib.rs

1// Copyright 2025 Shanghai Boyu Information Technology Co., Ltd.
2// https://privchat.dev
3//
4// Author: zoujiaqing <zoujiaqing@gmail.com>
5//
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10//     http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18pub mod error_code;
19pub mod message;
20pub mod notification;
21pub mod presence;
22/// PrivChat 协议库
23///
24/// PrivChat 协议消息定义和编解码工具
25///
26/// 使用示例:
27/// ```
28/// use privchat_protocol::protocol::*;
29///
30/// fn main() {
31///     let mut connect_req = AuthorizationRequest::new();
32///     connect_req.auth_token = "test_token".to_string();
33///     let packet = connect_req.create_packet();
34///     println!("消息类型: {:?}", packet.message_type);
35/// }
36/// ```
37// 导出主要模块
38pub mod protocol;
39pub mod rpc;
40pub mod version;
41
42pub use error_code::ErrorCode;
43pub use message::*;
44pub use notification::*;
45pub use presence::*;
46pub use protocol::*;
47pub use version::{PROTOCOL_VERSION, VERSION};
48
49/// 解码消息的通用函数
50pub fn decode_message<T>(payload: &[u8]) -> Result<T, Box<dyn std::error::Error>>
51where
52    T: serde::de::DeserializeOwned,
53{
54    let json_str = String::from_utf8(payload.to_vec())?;
55    let message: T = serde_json::from_str(&json_str)?;
56    Ok(message)
57}
58
59/// 编码消息的通用函数
60pub fn encode_message<T>(message: &T) -> Result<Vec<u8>, Box<dyn std::error::Error>>
61where
62    T: serde::Serialize,
63{
64    let json_str = serde_json::to_string(message)?;
65    Ok(json_str.into_bytes())
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn test_basic_message_creation() {
74        // 测试连接消息
75        let mut connect_req = AuthorizationRequest::new();
76        connect_req.auth_token = "test_token".to_string();
77
78        let packet = connect_req.create_packet();
79        assert_eq!(packet.message_type, MessageType::AuthorizationRequest);
80    }
81
82    #[test]
83    fn test_message_types() {
84        // 确保所有消息类型都有正确的值
85        assert_eq!(MessageType::AuthorizationRequest as u8, 1);
86        assert_eq!(MessageType::AuthorizationResponse as u8, 2);
87        assert_eq!(MessageType::DisconnectRequest as u8, 3);
88        assert_eq!(MessageType::DisconnectResponse as u8, 4);
89        assert_eq!(MessageType::SendMessageRequest as u8, 5);
90        assert_eq!(MessageType::SendMessageResponse as u8, 6);
91        assert_eq!(MessageType::PushMessageRequest as u8, 7);
92        assert_eq!(MessageType::PushMessageResponse as u8, 8);
93        assert_eq!(MessageType::PushBatchRequest as u8, 9); // 批量接收消息
94        assert_eq!(MessageType::PushBatchResponse as u8, 10); // 批量接收确认
95        assert_eq!(MessageType::PingRequest as u8, 11);
96        assert_eq!(MessageType::PongResponse as u8, 12);
97        assert_eq!(MessageType::SubscribeRequest as u8, 13);
98        assert_eq!(MessageType::SubscribeResponse as u8, 14);
99        assert_eq!(MessageType::PublishRequest as u8, 15); // 推送消息
100        assert_eq!(MessageType::PublishResponse as u8, 16); // 推送确认
101    }
102
103    #[test]
104    fn test_send_message() {
105        let mut send_req = SendMessageRequest::new();
106        send_req.from_uid = 123;
107        send_req.channel_id = 456;
108        send_req.payload = "Hello World".as_bytes().to_vec();
109
110        let packet = send_req.create_packet();
111        assert_eq!(packet.message_type, MessageType::SendMessageRequest);
112    }
113
114    #[test]
115    fn test_recv_message() {
116        let mut recv_req = PushMessageRequest::new();
117        recv_req.from_uid = 456;
118        recv_req.channel_id = 789;
119        recv_req.server_message_id = 100;
120        recv_req.payload = "Hello Back".as_bytes().to_vec();
121
122        let packet = recv_req.create_packet();
123        assert_eq!(packet.message_type, MessageType::PushMessageRequest);
124    }
125}