1use std::sync::atomic::{AtomicU64, Ordering};
10use std::collections::HashSet;
11
12use nostr_sdk::prelude::*;
13use serde::{Deserialize, Serialize};
14
15use crate::state::nostr_client;
16
17pub const DEFAULT_BLOSSOM_SERVERS: &[&str] = &[
20 "https://blossom.ditto.pub",
21 "https://blossom.primal.net",
22 "https://blossom.data.haus",
23];
24
25#[derive(Serialize, Deserialize, Clone, Debug)]
26pub struct CustomBlossomServer {
27 pub url: String,
28 pub enabled: bool,
29}
30
31pub fn validate_url(url: &str) -> Result<String, String> {
34 let trimmed = url.trim();
35 if trimmed.is_empty() {
36 return Err("URL cannot be empty".to_string());
37 }
38 let with_scheme = if trimmed.contains("://") {
39 trimmed.to_string()
40 } else {
41 format!("https://{}", trimmed)
42 };
43 let parsed = ::url::Url::parse(&with_scheme)
44 .map_err(|e| format!("Invalid URL: {}", e))?;
45 let scheme = parsed.scheme();
46 if scheme != "https" && scheme != "http" {
47 return Err("URL must use https:// or http://".to_string());
48 }
49 if parsed.host_str().map_or(true, str::is_empty) {
50 return Err("URL must include a host".to_string());
51 }
52 Ok(with_scheme.trim_end_matches('/').to_string())
53}
54
55#[derive(Serialize, Clone, Debug)]
57pub struct BlossomServerInfo {
58 pub url: String,
59 pub is_default: bool,
60 pub is_custom: bool,
61 pub enabled: bool,
62}
63
64pub fn load_custom_blossom_servers() -> Result<Vec<CustomBlossomServer>, String> {
69 match crate::db::get_sql_setting("custom_blossom_servers".to_string())
70 .ok().flatten()
71 {
72 Some(json) => serde_json::from_str(&json)
73 .map_err(|e| format!("Failed to parse custom_blossom_servers: {}", e)),
74 None => Ok(Vec::new()),
75 }
76}
77
78pub fn save_custom_blossom_servers(servers: &[CustomBlossomServer]) -> Result<(), String> {
79 let json = serde_json::to_string(servers)
80 .map_err(|e| format!("Failed to serialize custom blossom servers: {}", e))?;
81 crate::db::set_sql_setting("custom_blossom_servers".to_string(), json)
82}
83
84pub fn load_disabled_default_blossom_servers() -> Result<Vec<String>, String> {
85 match crate::db::get_sql_setting("disabled_default_blossom_servers".to_string())
86 .ok().flatten()
87 {
88 Some(json) => serde_json::from_str(&json)
89 .map_err(|e| format!("Failed to parse disabled_default_blossom_servers: {}", e)),
90 None => Ok(Vec::new()),
91 }
92}
93
94pub fn save_disabled_default_blossom_servers(urls: &[String]) -> Result<(), String> {
95 let json = serde_json::to_string(urls)
96 .map_err(|e| format!("Failed to serialize disabled default blossom servers: {}", e))?;
97 crate::db::set_sql_setting("disabled_default_blossom_servers".to_string(), json)
98}
99
100pub fn is_default_server(url: &str) -> bool {
105 let norm = url.trim().trim_end_matches('/').to_lowercase();
106 DEFAULT_BLOSSOM_SERVERS.iter()
107 .any(|d| d.trim_end_matches('/').to_lowercase() == norm)
108}
109
110pub fn is_enabled_server(url: &str) -> bool {
113 let target = url.trim().trim_end_matches('/').to_lowercase();
114 compute_enabled_servers().iter()
115 .any(|s| s.trim_end_matches('/').to_lowercase() == target)
116}
117
118pub fn compute_enabled_servers() -> Vec<String> {
119 let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
120 let disabled_lower: HashSet<String> = disabled.iter()
121 .map(|s| s.trim().trim_end_matches('/').to_lowercase())
122 .collect();
123
124 let mut out: Vec<String> = Vec::new();
130 let customs = load_custom_blossom_servers().unwrap_or_default();
131 for c in customs {
132 if c.enabled {
133 out.push(c.url);
134 }
135 }
136 for d in DEFAULT_BLOSSOM_SERVERS {
137 let key = d.trim_end_matches('/').to_lowercase();
138 if !disabled_lower.contains(&key) {
139 out.push((*d).to_string());
140 }
141 }
142 out
143}
144
145pub fn list_all_servers() -> Vec<BlossomServerInfo> {
147 let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
148 let disabled_lower: HashSet<String> = disabled.iter()
149 .map(|s| s.trim().trim_end_matches('/').to_lowercase())
150 .collect();
151
152 let mut out: Vec<BlossomServerInfo> = Vec::new();
153 for d in DEFAULT_BLOSSOM_SERVERS {
154 let key = d.trim_end_matches('/').to_lowercase();
155 out.push(BlossomServerInfo {
156 url: (*d).to_string(),
157 is_default: true,
158 is_custom: false,
159 enabled: !disabled_lower.contains(&key),
160 });
161 }
162 for c in load_custom_blossom_servers().unwrap_or_default() {
163 out.push(BlossomServerInfo {
164 url: c.url,
165 is_default: false,
166 is_custom: true,
167 enabled: c.enabled,
168 });
169 }
170 out
171}
172
173pub fn refresh_cache() {
175 crate::state::set_blossom_servers(compute_enabled_servers());
176}
177
178pub async fn publish_blossom_servers(client: &Client) -> Result<(), String> {
186 let servers = compute_enabled_servers();
187 let mut builder = EventBuilder::new(Kind::Custom(10063), "");
188 for url in &servers {
189 builder = builder.tag(Tag::custom("server", vec![url.clone()]));
190 }
191 crate::sign_and_send(client, builder).await
192 .map_err(|e| format!("Failed to publish blossom servers: {}", e))?;
193 crate::log_info!("[BlossomServers] Published kind 10063 with {} server(s)", servers.len());
194 Ok(())
195}
196
197static REPUBLISH_GEN: AtomicU64 = AtomicU64::new(0);
198
199pub fn republish_blossom_servers_debounced() {
204 let gen = REPUBLISH_GEN.fetch_add(1, Ordering::SeqCst) + 1;
205 crate::db::spawn_bound(async move {
206 tokio::time::sleep(std::time::Duration::from_millis(800)).await;
207 if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
208 let client = match nostr_client() {
209 Some(c) => c,
210 None => return,
211 };
212 if let Err(e) = publish_blossom_servers(&client).await {
213 crate::log_warn!("[BlossomServers] Republish failed: {} (retrying in 5s)", e);
214 tokio::time::sleep(std::time::Duration::from_secs(5)).await;
215 if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
216 if let Err(e2) = publish_blossom_servers(&client).await {
217 crate::log_warn!("[BlossomServers] Republish retry failed: {}", e2);
218 }
219 }
220 });
221}
222
223pub fn merge_urls_into_customs(
230 incoming: &[String],
231 mut customs: Vec<CustomBlossomServer>,
232) -> (Vec<CustomBlossomServer>, usize) {
233 let mut known_lower: HashSet<String> = customs.iter()
234 .map(|c| c.url.trim_end_matches('/').to_lowercase())
235 .collect();
236 for d in DEFAULT_BLOSSOM_SERVERS {
237 known_lower.insert(d.trim_end_matches('/').to_lowercase());
238 }
239
240 let mut added = 0usize;
241 for raw in incoming {
242 let normalized = match validate_url(raw) {
243 Ok(u) => u,
244 Err(_) => continue,
245 };
246 let key = normalized.to_lowercase();
247 if known_lower.contains(&key) { continue; }
248 customs.push(CustomBlossomServer { url: normalized, enabled: true });
249 known_lower.insert(key);
250 added += 1;
251 }
252 (customs, added)
253}
254
255pub async fn fetch_and_merge_own_list(
259 client: &Client,
260 my_pubkey: PublicKey,
261) -> Result<usize, String> {
262 let filter = Filter::new()
263 .author(my_pubkey)
264 .kind(Kind::Custom(10063))
265 .limit(1);
266 let events = client
267 .fetch_events(filter).timeout(std::time::Duration::from_secs(8))
268 .await
269 .map_err(|e| format!("Failed to fetch kind 10063: {}", e))?;
270
271
272 let event = match events.into_iter().max_by_key(|e| e.created_at) {
273 Some(e) => e,
274 None => {
275 crate::log_debug!("[BlossomServers] No kind 10063 found for own pubkey");
276 return Ok(0);
277 }
278 };
279
280 let urls_from_event: Vec<String> = event.tags.iter()
281 .filter_map(|t| {
282 if t.kind() == "server" {
283 t.content().map(|s| s.to_string())
284 } else {
285 None
286 }
287 })
288 .collect();
289
290 let urls_lower: HashSet<String> = urls_from_event.iter()
294 .map(|u| u.trim().trim_end_matches('/').to_lowercase())
295 .collect();
296 let mut disabled = load_disabled_default_blossom_servers().unwrap_or_default();
297 let mut defaults_changed = false;
298 for d in DEFAULT_BLOSSOM_SERVERS {
299 let key = d.trim_end_matches('/').to_lowercase();
300 let in_event = urls_lower.contains(&key);
301 let currently_disabled = disabled.iter()
302 .any(|s| s.trim_end_matches('/').to_lowercase() == key);
303 if in_event && currently_disabled {
304 disabled.retain(|s| s.trim_end_matches('/').to_lowercase() != key);
305 defaults_changed = true;
306 } else if !in_event && !currently_disabled {
307 disabled.push(d.to_string());
308 defaults_changed = true;
309 }
310 }
311
312 let customs = load_custom_blossom_servers().unwrap_or_default();
313 let (new_customs, customs_added) = merge_urls_into_customs(&urls_from_event, customs);
314
315 let any_changes = customs_added > 0 || defaults_changed;
316 if any_changes {
317 if defaults_changed {
318 save_disabled_default_blossom_servers(&disabled)?;
319 }
320 if customs_added > 0 {
321 save_custom_blossom_servers(&new_customs)?;
322 }
323 refresh_cache();
324 crate::traits::emit_event("blossom_servers_updated", &());
325 crate::log_info!(
326 "[BlossomServers] Merged kind 10063: {} custom server(s) added, defaults reconciled (disabled now {})",
327 customs_added, disabled.len(),
328 );
329 }
330 Ok(customs_added)
331}
332
333static USER_SERVER_LIST_CACHE: std::sync::LazyLock<
341 std::sync::Mutex<std::collections::HashMap<String, (Vec<String>, std::time::Instant)>>,
342> = std::sync::LazyLock::new(Default::default);
343const USER_SERVER_LIST_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);
344const USER_SERVER_LIST_MAX: usize = 8;
345
346pub async fn fetch_user_server_list(client: &Client, author: PublicKey) -> Vec<String> {
351 let key = author.to_hex();
352 if let Ok(cache) = USER_SERVER_LIST_CACHE.lock() {
353 if let Some((servers, at)) = cache.get(&key) {
354 if at.elapsed() < USER_SERVER_LIST_TTL {
355 return servers.clone();
356 }
357 }
358 }
359
360 let filter = Filter::new()
361 .author(author)
362 .kind(Kind::Custom(10063))
363 .limit(1);
364 let events = match client
365 .fetch_events(filter)
366 .timeout(std::time::Duration::from_secs(8))
367 .await
368 {
369 Ok(e) => e,
370 Err(e) => {
371 crate::log_debug!("[BlossomServers] foreign 10063 fetch failed for {}: {}", key, e);
372 return Vec::new();
373 }
374 };
375
376 let servers: Vec<String> = events
377 .into_iter()
378 .max_by_key(|e| e.created_at)
379 .map(|event| {
380 event
381 .tags
382 .iter()
383 .filter_map(|t| {
384 if t.kind() == "server" {
385 t.content()
386 .and_then(|s| validate_url(s).ok())
387 .filter(|u| u.starts_with("https://"))
390 } else {
391 None
392 }
393 })
394 .take(USER_SERVER_LIST_MAX)
395 .collect()
396 })
397 .unwrap_or_default();
398
399 if servers.is_empty() {
400 let any_connected = client
403 .relays()
404 .await
405 .values()
406 .any(|r| r.status() == RelayStatus::Connected);
407 if !any_connected {
408 return servers;
409 }
410 }
411
412 if let Ok(mut cache) = USER_SERVER_LIST_CACHE.lock() {
413 if cache.len() > 512 {
416 cache.clear();
417 }
418 cache.insert(key, (servers.clone(), std::time::Instant::now()));
419 }
420 servers
421}
422
423pub async fn author_swap_servers(author_npub: Option<&str>, is_own_blob: bool) -> Vec<String> {
427 let me = crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok());
428 if is_own_blob || (author_npub.is_some() && author_npub == me.as_deref()) {
429 return compute_enabled_servers();
430 }
431 let Some(author) = author_npub else {
432 return Vec::new();
433 };
434 match (crate::state::nostr_client(), PublicKey::parse(author)) {
435 (Some(client), Ok(pk)) => fetch_user_server_list(&client, pk).await,
436 _ => Vec::new(),
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 fn custom(url: &str, enabled: bool) -> CustomBlossomServer {
445 CustomBlossomServer { url: url.to_string(), enabled }
446 }
447
448 #[test]
449 fn validate_url_strips_trailing_slash_and_whitespace() {
450 assert_eq!(validate_url(" https://example.com/ ").unwrap(), "https://example.com");
451 assert_eq!(validate_url("https://example.com").unwrap(), "https://example.com");
452 }
453
454 #[test]
455 fn validate_url_auto_prefixes_bare_domain_with_https() {
456 assert_eq!(validate_url("blossom.band").unwrap(), "https://blossom.band");
457 assert_eq!(validate_url(" blossom.primal.net/ ").unwrap(), "https://blossom.primal.net");
458 }
459
460 #[test]
461 fn validate_url_keeps_explicit_http_scheme() {
462 assert_eq!(validate_url("http://localhost:8080").unwrap(), "http://localhost:8080");
463 }
464
465 #[test]
466 fn validate_url_rejects_non_http_schemes() {
467 assert!(validate_url("ftp://example.com").is_err());
468 assert!(validate_url("wss://example.com").is_err());
469 assert!(validate_url("javascript:alert(1)").is_err());
470 }
471
472 #[test]
473 fn validate_url_rejects_empty_or_hostless() {
474 assert!(validate_url("").is_err());
475 assert!(validate_url("https://").is_err());
476 assert!(validate_url("not a url").is_err());
477 }
478
479 #[test]
480 fn is_default_server_normalizes() {
481 assert!(is_default_server("https://blossom.primal.net"));
482 assert!(is_default_server("https://blossom.primal.net/"));
483 assert!(is_default_server("HTTPS://BLOSSOM.PRIMAL.NET"));
484 assert!(!is_default_server("https://other.example.com"));
485 }
486
487 #[test]
488 fn merge_appends_new_urls_normalized() {
489 let incoming = vec![
490 "https://new.example.com/".to_string(),
491 "https://another.example.com".to_string(),
492 ];
493 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
494 assert_eq!(added, 2);
495 assert_eq!(out.len(), 2);
496 assert_eq!(out[0].url, "https://new.example.com");
497 assert!(out[0].enabled);
498 }
499
500 #[test]
501 fn merge_skips_urls_already_in_customs_regardless_of_slash_or_case() {
502 let existing = vec![custom("https://Existing.example.com", true)];
503 let incoming = vec![
504 "https://existing.example.com/".to_string(),
505 "HTTPS://EXISTING.EXAMPLE.COM".to_string(),
506 ];
507 let (out, added) = merge_urls_into_customs(&incoming, existing);
508 assert_eq!(added, 0);
509 assert_eq!(out.len(), 1);
510 }
511
512 #[test]
513 fn merge_skips_default_servers() {
514 let incoming = vec!["https://blossom.primal.net/".to_string()];
515 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
516 assert_eq!(added, 0);
517 assert!(out.is_empty());
518 }
519
520 #[test]
521 fn merge_drops_malformed_urls() {
522 let incoming = vec![
523 "".to_string(),
524 "not a url".to_string(),
525 "ftp://example.com".to_string(),
526 "https://".to_string(),
527 "https://valid.example.com".to_string(),
528 ];
529 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
530 assert_eq!(added, 1);
531 assert_eq!(out[0].url, "https://valid.example.com");
532 }
533
534 #[test]
535 fn merge_preserves_existing_order_and_appends() {
536 let existing = vec![
537 custom("https://a.example.com", true),
538 custom("https://b.example.com", false),
539 ];
540 let incoming = vec!["https://c.example.com".to_string()];
541 let (out, _) = merge_urls_into_customs(&incoming, existing);
542 assert_eq!(out.len(), 3);
543 assert_eq!(out[0].url, "https://a.example.com");
544 assert_eq!(out[1].url, "https://b.example.com");
545 assert!(!out[1].enabled, "merge must not flip enabled state of existing rows");
546 assert_eq!(out[2].url, "https://c.example.com");
547 }
548}