use crate::utils::random_hash;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Req {
pub subscription_id: String,
pub filters: Vec<ReqFilter>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReqFilter {
pub ids: Option<Vec<String>>,
pub authors: Option<Vec<String>>,
pub kinds: Option<Vec<u16>>,
#[serde(rename = "#e")]
pub e: Option<Vec<String>>,
#[serde(rename = "#p")]
pub p: Option<Vec<String>>,
pub since: Option<u64>,
pub until: Option<u64>,
pub limit: Option<u64>,
}
impl ReqFilter {
pub fn to_json(&self) -> serde_json::Value {
let mut json = json!({});
if let Some(ids) = &self.ids {
json["ids"] = json!(ids);
}
if let Some(authors) = &self.authors {
json["authors"] = json!(authors);
}
if let Some(kinds) = &self.kinds {
json["kinds"] = json!(kinds);
}
if let Some(e) = &self.e {
json["#e"] = json!(e);
}
if let Some(p) = &self.p {
json["#p"] = json!(p);
}
if let Some(since) = &self.since {
json["since"] = json!(since);
}
if let Some(until) = &self.until {
json["until"] = json!(until);
}
if let Some(limit) = &self.limit {
json["limit"] = json!(limit);
}
json
}
}
impl Req {
pub fn new(subscription_id: Option<&str>, filters: Vec<ReqFilter>) -> Self {
Self {
subscription_id: subscription_id.unwrap_or(&random_hash()).to_string(),
filters,
}
}
pub fn get_close_event(&self) -> String {
json!({
"subscription_id": self.subscription_id,
"close": true
})
.to_string()
}
}
impl fmt::Display for Req {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut req = json!(["REQ", self.subscription_id]);
for filter in &self.filters {
req.as_array_mut().unwrap().push(filter.to_json());
}
write!(f, "{}", serde_json::to_string(&req).unwrap())
}
}