AppFlowy/shared-lib/lib-ws/src/msg.rs

51 lines
1.3 KiB
Rust
Raw Normal View History

2021-09-18 14:32:00 +00:00
use bytes::Bytes;
2021-09-23 09:50:28 +00:00
use flowy_derive::{ProtoBuf, ProtoBuf_Enum};
2021-09-30 09:24:02 +00:00
use std::convert::TryInto;
use tokio_tungstenite::tungstenite::Message as TokioMessage;
2021-09-18 14:32:00 +00:00
#[derive(ProtoBuf, Debug, Clone, Default)]
2021-12-26 11:10:37 +00:00
pub struct WebSocketRawMessage {
2021-09-18 14:32:00 +00:00
#[pb(index = 1)]
2022-01-22 10:48:43 +00:00
pub channel: WSChannel,
2021-09-18 14:32:00 +00:00
#[pb(index = 2)]
pub data: Vec<u8>,
}
2022-03-04 14:09:16 +00:00
// The lib-ws crate should not contain business logic.So WSChannel should be removed into another place.
2021-09-23 09:50:28 +00:00
#[derive(ProtoBuf_Enum, Debug, Clone, Eq, PartialEq, Hash)]
2022-01-22 10:48:43 +00:00
pub enum WSChannel {
Document = 0,
2022-01-24 09:35:58 +00:00
Folder = 1,
2022-03-04 14:09:16 +00:00
Grid = 2,
2021-09-23 09:50:28 +00:00
}
2022-01-22 10:48:43 +00:00
impl std::default::Default for WSChannel {
2022-01-24 09:35:58 +00:00
fn default() -> Self {
WSChannel::Document
}
2021-09-23 09:50:28 +00:00
}
2022-01-22 10:48:43 +00:00
impl ToString for WSChannel {
2021-09-23 09:50:28 +00:00
fn to_string(&self) -> String {
match self {
2022-01-22 10:48:43 +00:00
WSChannel::Document => "0".to_string(),
WSChannel::Folder => "1".to_string(),
2022-03-04 14:09:16 +00:00
WSChannel::Grid => "2".to_string(),
2021-09-23 09:50:28 +00:00
}
}
}
2021-12-26 11:10:37 +00:00
impl std::convert::From<WebSocketRawMessage> for TokioMessage {
fn from(msg: WebSocketRawMessage) -> Self {
2021-11-27 11:19:41 +00:00
let result: Result<Bytes, ::protobuf::ProtobufError> = msg.try_into();
2021-09-18 14:32:00 +00:00
match result {
2021-09-23 09:50:28 +00:00
Ok(bytes) => TokioMessage::Binary(bytes.to_vec()),
2021-09-18 14:32:00 +00:00
Err(e) => {
log::error!("WsMessage serialize error: {:?}", e);
2021-09-23 09:50:28 +00:00
TokioMessage::Binary(vec![])
2022-01-24 09:35:58 +00:00
}
2021-09-18 14:32:00 +00:00
}
}
}