cosmic_applet_avestruz/nostr/
relay_info.rs1use nostr_sdk::prelude::RelayUrl;
11use serde_json::Value;
12
13use crate::http;
14
15const DOCUMENT_MAX_BYTES: usize = 256 * 1024;
17
18const NAME_MAX_CHARS: usize = 60;
21const DESCRIPTION_MAX_CHARS: usize = 200;
22
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub struct Limits {
27 pub auth_required: bool,
30 pub payment_required: bool,
32 pub restricted_writes: bool,
34}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct RelayInfo {
39 pub name: Option<String>,
41 pub description: Option<String>,
43 pub nips: Option<Vec<u16>>,
46 pub limits: Limits,
48}
49
50impl RelayInfo {
51 pub fn supports(&self, nip: u16) -> Option<bool> {
54 self.nips.as_ref().map(|nips| nips.contains(&nip))
55 }
56}
57
58pub fn document_url(relay: &RelayUrl) -> Option<String> {
62 relay.as_str().strip_prefix("wss://").map(|rest| format!("https://{rest}"))
63}
64
65pub fn parse(json: &str) -> Option<RelayInfo> {
68 let document: Value = serde_json::from_str(json).ok()?;
69 let document = document.as_object()?;
70 let said = |field: &str, max: usize| {
71 let words = document.get(field)?.as_str()?.lines().next()?.trim();
72 (!words.is_empty()).then(|| words.chars().take(max).collect::<String>())
73 };
74 let nips: Option<Vec<u16>> = document
75 .get("supported_nips")
76 .and_then(Value::as_array)
77 .map(|nips| nips.iter().filter_map(|nip| u16::try_from(nip.as_u64()?).ok()).collect())
78 .filter(|nips: &Vec<u16>| !nips.is_empty());
79 let asked =
80 |limit: &str| document.get("limitation").and_then(|limits| limits.get(limit)).and_then(Value::as_bool).unwrap_or(false);
81 let limits = Limits {
82 auth_required: asked("auth_required"),
83 payment_required: asked("payment_required"),
84 restricted_writes: asked("restricted_writes"),
85 };
86 Some(RelayInfo { name: said("name", NAME_MAX_CHARS), description: said("description", DESCRIPTION_MAX_CHARS), nips, limits })
87}
88
89pub async fn fetch(http: &reqwest::Client, relay: &RelayUrl) -> Option<RelayInfo> {
91 let url = document_url(relay)?;
92 match http::get_as(http, &url, "application/nostr+json", DOCUMENT_MAX_BYTES).await {
93 Ok(answer) => parse(&String::from_utf8_lossy(&answer)),
94 Err(e) => {
95 tracing::debug!("{relay} did not say what it is: {e}");
96 None
97 }
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::{Limits, RelayInfo, document_url, parse};
104 use nostr_sdk::prelude::RelayUrl;
105
106 #[test]
107 fn a_relay_is_asked_what_it_is_at_its_own_address() {
108 let url = |relay: &str| document_url(&RelayUrl::parse(relay).unwrap());
109 assert_eq!(url("wss://relay.example.com").as_deref(), Some("https://relay.example.com"));
110 assert_eq!(url("wss://relay.example.com/inbox").as_deref(), Some("https://relay.example.com/inbox"));
111 assert_eq!(url("ws://127.0.0.1:7777"), None);
112 }
113
114 #[test]
115 fn what_a_relay_says_of_itself_is_its_name_a_line_about_it_and_what_it_supports() {
116 let document =
117 r#"{"name":" Example relay ","description":"A relay.\nWith rules.","supported_nips":[1,11,50],"software":"x"}"#;
118 let info = parse(document).unwrap();
119 assert_eq!(info.name.as_deref(), Some("Example relay"));
120 assert_eq!(info.description.as_deref(), Some("A relay."));
121 assert_eq!(info.nips, Some(vec![1, 11, 50]));
122 assert_eq!((info.supports(50), info.supports(42)), (Some(true), Some(false)));
123
124 assert_eq!(info.limits, Limits::default());
125
126 let limited = r#"{"limitation":{"auth_required":true,"payment_required":false,"restricted_writes":true,"max_limit":5}}"#;
128 let limits = Limits { auth_required: true, payment_required: false, restricted_writes: true };
129 assert_eq!(parse(limited), Some(RelayInfo { limits, ..RelayInfo::default() }));
130 let paid = Limits { payment_required: true, ..Limits::default() };
131 assert_eq!(parse(r#"{"supported_nips":[],"limitation":{"payment_required":true}}"#).unwrap().limits, paid);
132 assert_eq!(parse(r#"{"limitation":{"payment_required":"yes"}}"#).unwrap().limits, Limits::default());
133 assert_eq!(parse(r#"{"limitation":[true]}"#).unwrap().limits, Limits::default());
134
135 assert_eq!(parse(r#"{"supported_nips":[1],"name":""}"#), Some(RelayInfo { nips: Some(vec![1]), ..RelayInfo::default() }));
138 for unsaid in [r#"{"supported_nips":"50","name":7}"#, r#"{"supported_nips":[]}"#, r#"{"supported_nips":["50",-1]}"#, "{}"]
140 {
141 assert_eq!(parse(unsaid), Some(RelayInfo::default()), "{unsaid}");
142 assert_eq!(parse(unsaid).unwrap().supports(50), None);
143 }
144 let long = format!(r#"{{"name":"{}"}}"#, "n".repeat(500));
145 assert_eq!(parse(&long).unwrap().name.unwrap().chars().count(), 60);
146 assert_eq!(parse("<html></html>"), None);
147 assert_eq!(parse("[]"), None);
148 }
149}