1use crate::utils::random_hash;
2use serde::{Deserialize, Serialize};
3use serde_json::json;
4use std::fmt;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct Req {
9 pub subscription_id: String,
11 pub filters: Vec<ReqFilter>,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ReqFilter {
18 pub ids: Option<Vec<String>>,
20 pub authors: Option<Vec<String>>,
22 pub kinds: Option<Vec<u16>>,
24 #[serde(rename = "#e")]
26 pub e: Option<Vec<String>>,
27 #[serde(rename = "#p")]
29 pub p: Option<Vec<String>>,
30 pub since: Option<u64>,
32 pub until: Option<u64>,
34 pub limit: Option<u64>,
36}
37
38impl ReqFilter {
39 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 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}