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://magnitude.vectorapp.io",
21 "https://blossom.ditto.pub",
22 "https://blossom.primal.net",
23 "https://blossom.data.haus",
24];
25
26const DEFAULT_ADDED_AT: &[(&str, u64)] = &[("https://magnitude.vectorapp.io", 1_791_658_800)];
29
30fn default_added_at(url: &str) -> u64 {
31 DEFAULT_ADDED_AT.iter().find(|(u, _)| *u == url).map_or(0, |(_, at)| *at)
32}
33
34fn reconcile_defaults(listed: &HashSet<String>, published_at: u64, mut disabled: Vec<String>) -> (Vec<String>, bool) {
37 let mut changed = false;
38 for d in DEFAULT_BLOSSOM_SERVERS {
39 let key = d.trim_end_matches('/').to_lowercase();
40 let in_event = listed.contains(&key);
41 let currently_disabled = disabled.iter().any(|s| s.trim_end_matches('/').to_lowercase() == key);
42 if in_event && currently_disabled {
43 disabled.retain(|s| s.trim_end_matches('/').to_lowercase() != key);
44 changed = true;
45 } else if !in_event && !currently_disabled && published_at >= default_added_at(d) {
46 disabled.push(d.to_string());
47 changed = true;
48 }
49 }
50 (disabled, changed)
51}
52
53#[derive(Serialize, Deserialize, Clone, Debug)]
54pub struct CustomBlossomServer {
55 pub url: String,
56 pub enabled: bool,
57}
58
59pub fn validate_url(url: &str) -> Result<String, String> {
64 let trimmed = url.trim();
65 if trimmed.is_empty() {
66 return Err("URL cannot be empty".to_string());
67 }
68 let with_scheme = if trimmed.contains("://") {
69 trimmed.to_string()
70 } else {
71 let host = trimmed.split(['/', ':', '?', '#']).next().unwrap_or_default().to_ascii_lowercase();
72 let scheme = if host.ends_with(".i2p") { "http" } else { "https" };
73 format!("{scheme}://{trimmed}")
74 };
75 let parsed = ::url::Url::parse(&with_scheme)
76 .map_err(|e| format!("Invalid URL: {}", e))?;
77 let scheme = parsed.scheme();
78 if scheme != "https" && scheme != "http" {
79 return Err("URL must use https:// or http://".to_string());
80 }
81 if parsed.host_str().is_none_or(str::is_empty) {
82 return Err("URL must include a host".to_string());
83 }
84 Ok(with_scheme.trim_end_matches('/').to_string())
85}
86
87#[derive(Serialize, Clone, Debug)]
89pub struct BlossomServerInfo {
90 pub url: String,
91 pub is_default: bool,
92 pub is_custom: bool,
93 pub enabled: bool,
94 pub status: crate::blossom_stats::ServerStatus,
95}
96
97pub fn load_custom_blossom_servers() -> Result<Vec<CustomBlossomServer>, String> {
102 match crate::db::get_sql_setting("custom_blossom_servers".to_string())
103 .ok().flatten()
104 {
105 Some(json) => serde_json::from_str(&json)
106 .map_err(|e| format!("Failed to parse custom_blossom_servers: {}", e)),
107 None => Ok(Vec::new()),
108 }
109}
110
111pub fn save_custom_blossom_servers(servers: &[CustomBlossomServer]) -> Result<(), String> {
112 let json = serde_json::to_string(servers)
113 .map_err(|e| format!("Failed to serialize custom blossom servers: {}", e))?;
114 crate::db::set_sql_setting("custom_blossom_servers".to_string(), json)
115}
116
117pub fn load_disabled_default_blossom_servers() -> Result<Vec<String>, String> {
118 match crate::db::get_sql_setting("disabled_default_blossom_servers".to_string())
119 .ok().flatten()
120 {
121 Some(json) => serde_json::from_str(&json)
122 .map_err(|e| format!("Failed to parse disabled_default_blossom_servers: {}", e)),
123 None => Ok(Vec::new()),
124 }
125}
126
127pub fn save_disabled_default_blossom_servers(urls: &[String]) -> Result<(), String> {
128 let json = serde_json::to_string(urls)
129 .map_err(|e| format!("Failed to serialize disabled default blossom servers: {}", e))?;
130 crate::db::set_sql_setting("disabled_default_blossom_servers".to_string(), json)
131}
132
133pub fn is_default_server(url: &str) -> bool {
138 let norm = url.trim().trim_end_matches('/').to_lowercase();
139 DEFAULT_BLOSSOM_SERVERS.iter()
140 .any(|d| d.trim_end_matches('/').to_lowercase() == norm)
141}
142
143pub fn is_enabled_server(url: &str) -> bool {
146 let target = url.trim().trim_end_matches('/').to_lowercase();
147 compute_enabled_servers().iter()
148 .any(|s| s.trim_end_matches('/').to_lowercase() == target)
149}
150
151fn customs_beside_defaults() -> Vec<CustomBlossomServer> {
154 let mut customs = load_custom_blossom_servers().unwrap_or_default();
155 customs.retain(|c| !is_default_server(&c.url));
156 customs
157}
158
159pub fn compute_enabled_servers() -> Vec<String> {
160 let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
161 let disabled_lower: HashSet<String> = disabled.iter()
162 .map(|s| s.trim().trim_end_matches('/').to_lowercase())
163 .collect();
164
165 let mut out: Vec<String> = Vec::new();
171 for c in customs_beside_defaults() {
172 if c.enabled {
173 out.push(c.url);
174 }
175 }
176 for d in DEFAULT_BLOSSOM_SERVERS {
177 let key = d.trim_end_matches('/').to_lowercase();
178 if !disabled_lower.contains(&key) {
179 out.push((*d).to_string());
180 }
181 }
182 out
183}
184
185pub fn list_all_servers() -> Vec<BlossomServerInfo> {
187 let disabled = load_disabled_default_blossom_servers().unwrap_or_default();
188 let disabled_lower: HashSet<String> = disabled.iter()
189 .map(|s| s.trim().trim_end_matches('/').to_lowercase())
190 .collect();
191
192 let mut out: Vec<BlossomServerInfo> = Vec::new();
193 for d in DEFAULT_BLOSSOM_SERVERS {
194 let key = d.trim_end_matches('/').to_lowercase();
195 let enabled = !disabled_lower.contains(&key);
196 out.push(BlossomServerInfo {
197 url: (*d).to_string(),
198 is_default: true,
199 is_custom: false,
200 enabled,
201 status: crate::blossom_stats::status_for(d, enabled),
202 });
203 }
204 for c in customs_beside_defaults() {
205 let status = crate::blossom_stats::status_for(&c.url, c.enabled);
206 out.push(BlossomServerInfo {
207 url: c.url,
208 is_default: false,
209 is_custom: true,
210 enabled: c.enabled,
211 status,
212 });
213 }
214 out
215}
216
217pub fn resolve_if_open() -> Option<Vec<String>> {
219 crate::db::get_sql_setting("custom_blossom_servers".to_string()).ok()?;
220 Some(compute_enabled_servers())
221}
222
223pub fn refresh_cache() {
225 crate::state::set_blossom_servers(compute_enabled_servers());
226 crate::proxy::forget_picks();
228}
229
230pub async fn publish_blossom_servers(client: &Client) -> Result<(), String> {
238 let servers = compute_enabled_servers();
239 let mut builder = EventBuilder::new(Kind::Custom(10063), "");
240 for url in &servers {
241 builder = builder.tag(Tag::custom("server", vec![url.clone()]));
242 }
243 crate::sign_and_send(client, builder).await
244 .map_err(|e| format!("Failed to publish blossom servers: {}", e))?;
245 crate::log_info!("[BlossomServers] Published kind 10063 with {} server(s)", servers.len());
246 Ok(())
247}
248
249static REPUBLISH_GEN: AtomicU64 = AtomicU64::new(0);
250
251pub fn republish_blossom_servers_debounced() {
256 let gen = REPUBLISH_GEN.fetch_add(1, Ordering::SeqCst) + 1;
257 crate::db::spawn_bound(async move {
258 crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
259 if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
260 let client = match nostr_client() {
261 Some(c) => c,
262 None => return,
263 };
264 if let Err(e) = publish_blossom_servers(&client).await {
265 crate::log_warn!("[BlossomServers] Republish failed: {} (retrying in 5s)", e);
266 crate::rt::time::sleep(std::time::Duration::from_secs(5)).await;
267 if REPUBLISH_GEN.load(Ordering::SeqCst) != gen { return; }
268 if let Err(e2) = publish_blossom_servers(&client).await {
269 crate::log_warn!("[BlossomServers] Republish retry failed: {}", e2);
270 }
271 }
272 });
273}
274
275pub fn merge_urls_into_customs(
282 incoming: &[String],
283 mut customs: Vec<CustomBlossomServer>,
284) -> (Vec<CustomBlossomServer>, usize) {
285 let mut known_lower: HashSet<String> = customs.iter()
286 .map(|c| c.url.trim_end_matches('/').to_lowercase())
287 .collect();
288 for d in DEFAULT_BLOSSOM_SERVERS {
289 known_lower.insert(d.trim_end_matches('/').to_lowercase());
290 }
291
292 let mut added = 0usize;
293 for raw in incoming {
294 let normalized = match validate_url(raw) {
295 Ok(u) => u,
296 Err(_) => continue,
297 };
298 let key = normalized.to_lowercase();
299 if known_lower.contains(&key) { continue; }
300 customs.push(CustomBlossomServer { url: normalized, enabled: true });
301 known_lower.insert(key);
302 added += 1;
303 }
304 (customs, added)
305}
306
307pub async fn fetch_and_merge_own_list(
311 client: &Client,
312 my_pubkey: PublicKey,
313) -> Result<usize, String> {
314 let filter = Filter::new()
315 .author(my_pubkey)
316 .kind(Kind::Custom(10063))
317 .limit(1);
318 let events = client
319 .fetch_events(filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(8)))
320 .await
321 .map_err(|e| format!("Failed to fetch kind 10063: {}", e))?;
322
323
324 let event = match events.into_iter().max_by_key(|e| e.created_at) {
325 Some(e) => e,
326 None => {
327 crate::log_debug!("[BlossomServers] No kind 10063 found for own pubkey");
328 return Ok(0);
329 }
330 };
331
332 let urls_from_event: Vec<String> = event.tags.iter()
333 .filter_map(|t| {
334 if t.kind() == "server" {
335 t.content().map(|s| s.to_string())
336 } else {
337 None
338 }
339 })
340 .collect();
341
342 let urls_lower: HashSet<String> = urls_from_event.iter()
346 .map(|u| u.trim().trim_end_matches('/').to_lowercase())
347 .collect();
348 let (disabled, defaults_changed) = reconcile_defaults(
349 &urls_lower,
350 event.created_at.as_secs(),
351 load_disabled_default_blossom_servers().unwrap_or_default(),
352 );
353
354 let customs = load_custom_blossom_servers().unwrap_or_default();
355 let (new_customs, customs_added) = merge_urls_into_customs(&urls_from_event, customs);
356
357 let any_changes = customs_added > 0 || defaults_changed;
358 if any_changes {
359 if defaults_changed {
360 save_disabled_default_blossom_servers(&disabled)?;
361 }
362 if customs_added > 0 {
363 save_custom_blossom_servers(&new_customs)?;
364 }
365 refresh_cache();
366 crate::traits::emit_event("blossom_servers_updated", &());
367 crate::log_info!(
368 "[BlossomServers] Merged kind 10063: {} custom server(s) added, defaults reconciled (disabled now {})",
369 customs_added, disabled.len(),
370 );
371 }
372 Ok(customs_added)
373}
374
375type UserServerLists = std::collections::HashMap<String, (Vec<String>, web_time::Instant)>;
383
384static USER_SERVER_LIST_CACHE: std::sync::LazyLock<std::sync::Mutex<UserServerLists>> =
385 std::sync::LazyLock::new(Default::default);
386const USER_SERVER_LIST_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);
387const USER_SERVER_LIST_MAX: usize = 8;
388
389pub async fn fetch_user_server_list(client: &Client, author: PublicKey) -> Vec<String> {
394 let key = author.to_hex();
395 if let Ok(cache) = USER_SERVER_LIST_CACHE.lock() {
396 if let Some((servers, at)) = cache.get(&key) {
397 if at.elapsed() < USER_SERVER_LIST_TTL {
398 return servers.clone();
399 }
400 }
401 }
402
403 let filter = Filter::new()
404 .author(author)
405 .kind(Kind::Custom(10063))
406 .limit(1);
407 let events = match client
408 .fetch_events(filter)
409 .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(8)))
410 .await
411 {
412 Ok(e) => e,
413 Err(e) => {
414 crate::log_debug!("[BlossomServers] foreign 10063 fetch failed for {}: {}", key, e);
415 return Vec::new();
416 }
417 };
418
419 let servers: Vec<String> = events
420 .into_iter()
421 .max_by_key(|e| e.created_at)
422 .map(|event| {
423 event
424 .tags
425 .iter()
426 .filter_map(|t| {
427 if t.kind() == "server" {
428 t.content()
429 .and_then(|s| validate_url(s).ok())
430 .filter(|u| u.starts_with("https://"))
433 } else {
434 None
435 }
436 })
437 .take(USER_SERVER_LIST_MAX)
438 .collect()
439 })
440 .unwrap_or_default();
441
442 if servers.is_empty() {
443 let any_connected = client
446 .relays()
447 .await
448 .values()
449 .any(|r| r.status() == RelayStatus::Connected);
450 if !any_connected {
451 return servers;
452 }
453 }
454
455 if let Ok(mut cache) = USER_SERVER_LIST_CACHE.lock() {
456 if cache.len() > 512 {
459 cache.clear();
460 }
461 cache.insert(key, (servers.clone(), web_time::Instant::now()));
462 }
463 servers
464}
465
466pub async fn author_swap_servers(author_npub: Option<&str>, is_own_blob: bool) -> Vec<String> {
470 let me = crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok());
471 if is_own_blob || (author_npub.is_some() && author_npub == me.as_deref()) {
472 return compute_enabled_servers();
473 }
474 let Some(author) = author_npub else {
475 return Vec::new();
476 };
477 match (crate::state::nostr_client(), PublicKey::parse(author)) {
478 (Some(client), Ok(pk)) => fetch_user_server_list(&client, pk).await,
479 _ => Vec::new(),
480 }
481}
482
483#[cfg(test)]
484mod tests {
485
486 #[test]
487 fn a_list_published_before_a_default_existed_does_not_disable_it() {
488 let new = "https://magnitude.vectorapp.io";
489 let added = default_added_at(new);
490 let others: HashSet<String> = DEFAULT_BLOSSOM_SERVERS.iter().filter(|d| **d != new).map(|d| d.to_lowercase()).collect();
491 let (disabled, _) = reconcile_defaults(&others, added - 1, Vec::new());
492 assert!(disabled.is_empty(), "an older list never chose against it: {disabled:?}");
493 let (disabled, changed) = reconcile_defaults(&others, added + 1, Vec::new());
494 assert_eq!((disabled, changed), (vec![new.to_string()], true), "a newer list that leaves it out does");
495 let all: HashSet<String> = DEFAULT_BLOSSOM_SERVERS.iter().map(|d| d.to_lowercase()).collect();
496 let (disabled, changed) = reconcile_defaults(&all, 0, vec![new.to_string()]);
497 assert_eq!((disabled.len(), changed), (0, true), "naming it turns it back on, whenever the list was made");
498 assert_eq!(default_added_at("https://blossom.ditto.pub"), 0);
499 }
500 use super::*;
501
502 #[test]
503 fn a_fresh_session_resolves_its_account_list_without_a_refresh() {
504 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
505 crate::db::close_database();
506 crate::db::clear_id_caches();
507 use nostr_sdk::prelude::ToBech32;
508 let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
509 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
510 crate::db::set_current_account(account.clone()).unwrap();
511 crate::db::init_database(&account).unwrap();
512
513 save_custom_blossom_servers(&[custom("https://self.hosted", true)]).unwrap();
514 save_disabled_default_blossom_servers(&[DEFAULT_BLOSSOM_SERVERS[0].to_string()]).unwrap();
515
516 let servers = crate::state::get_blossom_servers();
517 assert_eq!(servers.first().map(String::as_str), Some("https://self.hosted"));
518 assert!(!servers.iter().any(|s| s == DEFAULT_BLOSSOM_SERVERS[0]), "{servers:?}");
519 }
520
521 #[test]
522 fn a_custom_server_that_became_a_default_is_listed_once() {
523 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
524 crate::db::close_database();
525 crate::db::clear_id_caches();
526 use nostr_sdk::prelude::ToBech32;
527 let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
528 crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
529 crate::db::set_current_account(account.clone()).unwrap();
530 crate::db::init_database(&account).unwrap();
531
532 save_custom_blossom_servers(&[custom("https://magnitude.vectorapp.io/", true), custom("https://self.hosted", true)]).unwrap();
533 let rows: Vec<String> = list_all_servers().into_iter().map(|r| r.url.trim_end_matches('/').to_string()).collect();
534 assert_eq!(rows.iter().filter(|u| *u == "https://magnitude.vectorapp.io").count(), 1, "{rows:?}");
535 assert!(rows.contains(&"https://self.hosted".to_string()));
536 let enabled = compute_enabled_servers();
537 assert_eq!(enabled.iter().filter(|u| u.trim_end_matches('/') == "https://magnitude.vectorapp.io").count(), 1, "{enabled:?}");
538 }
539
540 fn custom(url: &str, enabled: bool) -> CustomBlossomServer {
541 CustomBlossomServer { url: url.to_string(), enabled }
542 }
543
544 #[test]
545 fn validate_url_strips_trailing_slash_and_whitespace() {
546 assert_eq!(validate_url(" https://example.com/ ").unwrap(), "https://example.com");
547 assert_eq!(validate_url("https://example.com").unwrap(), "https://example.com");
548 }
549
550 #[test]
551 fn validate_url_auto_prefixes_bare_domain_with_https() {
552 assert_eq!(validate_url("blossom.band").unwrap(), "https://blossom.band");
553 assert_eq!(validate_url(" blossom.primal.net/ ").unwrap(), "https://blossom.primal.net");
554 let b32 = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrst.b32.i2p";
555 assert_eq!(validate_url(b32).unwrap(), format!("http://{b32}"), "an eepsite rarely speaks TLS");
556 assert_eq!(validate_url("files.i2p:8080/").unwrap(), "http://files.i2p:8080");
557 assert_eq!(validate_url(&format!("https://{b32}")).unwrap(), format!("https://{b32}"), "a typed scheme is kept");
558 assert_eq!(validate_url("i2p.example.com").unwrap(), "https://i2p.example.com");
559 }
560
561 #[test]
562 fn validate_url_keeps_explicit_http_scheme() {
563 assert_eq!(validate_url("http://localhost:8080").unwrap(), "http://localhost:8080");
564 }
565
566 #[test]
567 fn validate_url_rejects_non_http_schemes() {
568 assert!(validate_url("ftp://example.com").is_err());
569 assert!(validate_url("wss://example.com").is_err());
570 assert!(validate_url("javascript:alert(1)").is_err());
571 }
572
573 #[test]
574 fn validate_url_rejects_empty_or_hostless() {
575 assert!(validate_url("").is_err());
576 assert!(validate_url("https://").is_err());
577 assert!(validate_url("not a url").is_err());
578 }
579
580 #[test]
581 fn is_default_server_normalizes() {
582 assert!(is_default_server("https://blossom.primal.net"));
583 assert!(is_default_server("https://blossom.primal.net/"));
584 assert!(is_default_server("HTTPS://BLOSSOM.PRIMAL.NET"));
585 assert!(!is_default_server("https://other.example.com"));
586 }
587
588 #[test]
589 fn merge_appends_new_urls_normalized() {
590 let incoming = vec![
591 "https://new.example.com/".to_string(),
592 "https://another.example.com".to_string(),
593 ];
594 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
595 assert_eq!(added, 2);
596 assert_eq!(out.len(), 2);
597 assert_eq!(out[0].url, "https://new.example.com");
598 assert!(out[0].enabled);
599 }
600
601 #[test]
602 fn merge_skips_urls_already_in_customs_regardless_of_slash_or_case() {
603 let existing = vec![custom("https://Existing.example.com", true)];
604 let incoming = vec![
605 "https://existing.example.com/".to_string(),
606 "HTTPS://EXISTING.EXAMPLE.COM".to_string(),
607 ];
608 let (out, added) = merge_urls_into_customs(&incoming, existing);
609 assert_eq!(added, 0);
610 assert_eq!(out.len(), 1);
611 }
612
613 #[test]
614 fn merge_skips_default_servers() {
615 let incoming = vec!["https://blossom.primal.net/".to_string()];
616 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
617 assert_eq!(added, 0);
618 assert!(out.is_empty());
619 }
620
621 #[test]
622 fn merge_drops_malformed_urls() {
623 let incoming = vec![
624 "".to_string(),
625 "not a url".to_string(),
626 "ftp://example.com".to_string(),
627 "https://".to_string(),
628 "https://valid.example.com".to_string(),
629 ];
630 let (out, added) = merge_urls_into_customs(&incoming, vec![]);
631 assert_eq!(added, 1);
632 assert_eq!(out[0].url, "https://valid.example.com");
633 }
634
635 #[test]
636 fn merge_preserves_existing_order_and_appends() {
637 let existing = vec![
638 custom("https://a.example.com", true),
639 custom("https://b.example.com", false),
640 ];
641 let incoming = vec!["https://c.example.com".to_string()];
642 let (out, _) = merge_urls_into_customs(&incoming, existing);
643 assert_eq!(out.len(), 3);
644 assert_eq!(out[0].url, "https://a.example.com");
645 assert_eq!(out[1].url, "https://b.example.com");
646 assert!(!out[1].enabled, "merge must not flip enabled state of existing rows");
647 assert_eq!(out[2].url, "https://c.example.com");
648 }
649}