nostr_rust/
req.rs

1use crate::utils::random_hash;
2use serde::{Deserialize, Serialize};
3use serde_json::json;
4use std::fmt;
5
6/// Req struct is used to request events and subscribe to new updates.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct Req {
9    /// `<subscription_id>` is a random string that should be used to represent a subscription.
10    pub subscription_id: String,
11    /// `<filters>` is a JSON object that determines what events will be sent in that subscription, it can have the following attributes:
12    pub filters: Vec<ReqFilter>,
13}
14
15/// ReqFilter is a JSON object that determines what events will be sent in that subscription.
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ReqFilter {
18    /// a list of event ids or prefixes
19    pub ids: Option<Vec<String>>,
20    /// a list of pubkeys or prefixes, the pubkey of an event must be one of these
21    pub authors: Option<Vec<String>>,
22    /// a list of a kind numbers
23    pub kinds: Option<Vec<u16>>,
24    /// a list of event ids that are referenced in an "e" tag
25    #[serde(rename = "#e")]
26    pub e: Option<Vec<String>>,
27    /// a list of pubkeys that are referenced in a "p" tag
28    #[serde(rename = "#p")]
29    pub p: Option<Vec<String>>,
30    /// a timestamp, events must be newer than this to pass
31    pub since: Option<u64>,
32    /// a timestamp, events must be older than this to pass
33    pub until: Option<u64>,
34    /// maximum number of events to be returned in the initial query
35    pub limit: Option<u64>,
36}
37
38impl ReqFilter {
39    /// Return a clean json object (Value)
40    pub fn to_json(&self) -> serde_json::Value {
41        let mut json = json!({});
42
43        if let Some(ids) = &self.ids {
44            json["ids"] = json!(ids);
45        }
46
47        if let Some(authors) = &self.authors {
48            json["authors"] = json!(authors);
49        }
50
51        if let Some(kinds) = &self.kinds {
52            json["kinds"] = json!(kinds);
53        }
54
55        if let Some(e) = &self.e {
56            json["#e"] = json!(e);
57        }
58
59        if let Some(p) = &self.p {
60            json["#p"] = json!(p);
61        }
62
63        if let Some(since) = &self.since {
64            json["since"] = json!(since);
65        }
66
67        if let Some(until) = &self.until {
68            json["until"] = json!(until);
69        }
70
71        if let Some(limit) = &self.limit {
72            json["limit"] = json!(limit);
73        }
74
75        json
76    }
77}
78
79impl Req {
80    pub fn new(subscription_id: Option<&str>, filters: Vec<ReqFilter>) -> Self {
81        Self {
82            subscription_id: subscription_id.unwrap_or(&random_hash()).to_string(),
83            filters,
84        }
85    }
86
87    pub fn get_close_event(&self) -> String {
88        json!({
89            "subscription_id": self.subscription_id,
90            "close": true
91        })
92        .to_string()
93    }
94}
95
96impl fmt::Display for Req {
97    /// Return the serialized event
98    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
99        let mut req = json!(["REQ", self.subscription_id]);
100        for filter in &self.filters {
101            req.as_array_mut().unwrap().push(filter.to_json());
102        }
103
104        write!(f, "{}", serde_json::to_string(&req).unwrap())
105    }
106}