notedeck

One damus client to rule them all
git clone git://jb55.com/notedeck
Log | Files | Refs | README | LICENSE

message.rs (1710B)


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