message.rs (1973B)
1 use crate::Error; 2 use nostrdb::{Filter, Note}; 3 use serde_json::json; 4 5 #[derive(Debug, Clone)] 6 pub struct EventClientMessage { 7 pub note_json: String, 8 } 9 10 impl EventClientMessage { 11 pub fn to_json(&self) -> String { 12 format!("[\"EVENT\", {}]", self.note_json) 13 } 14 } 15 16 /// Messages sent by clients, received by relays 17 #[derive(Debug, Clone)] 18 pub enum ClientMessage { 19 Event(EventClientMessage), 20 Req { 21 sub_id: String, 22 filters: Vec<Filter>, 23 }, 24 Close { 25 sub_id: String, 26 }, 27 Raw(String), 28 } 29 30 impl ClientMessage { 31 pub fn event(note: Note) -> Result<Self, Error> { 32 Ok(ClientMessage::Event(EventClientMessage { 33 note_json: note.json()?, 34 })) 35 } 36 37 pub fn raw(raw: String) -> Self { 38 ClientMessage::Raw(raw) 39 } 40 41 pub fn req(sub_id: String, filters: Vec<Filter>) -> Self { 42 ClientMessage::Req { sub_id, filters } 43 } 44 45 pub fn close(sub_id: String) -> Self { 46 ClientMessage::Close { sub_id } 47 } 48 49 pub fn to_json(&self) -> Result<String, Error> { 50 Ok(match self { 51 Self::Event(ecm) => ecm.to_json(), 52 Self::Raw(raw) => raw.clone(), 53 Self::Req { sub_id, filters } => { 54 if filters.is_empty() { 55 format!("[\"REQ\",\"{}\",{{ }}]", sub_id) 56 } else if filters.len() == 1 { 57 let filters_json_str = filters[0].json()?; 58 format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str) 59 } else { 60 let filters_json_str: Result<Vec<String>, Error> = filters 61 .iter() 62 .map(|f| f.json().map_err(Into::<Error>::into)) 63 .collect(); 64 format!("[\"REQ\",\"{}\",{}]", sub_id, filters_json_str?.join(",")) 65 } 66 } 67 Self::Close { sub_id } => json!(["CLOSE", sub_id]).to_string(), 68 }) 69 } 70 }