cosmic_applet_avestruz/nostr/
share.rs1use nostr_sdk::prelude::{EventId, Kind, Nip19Event, PublicKey, RelayUrl, ToBech32};
17
18use crate::nostr::outbox::public;
19
20pub(crate) const SHARE_GATEWAY: &str = "https://njump.me/";
22
23const SHARE_HINTS: usize = 2;
26
27pub fn share_link(id: EventId, author: PublicKey, kind: Kind, seen_on: &[RelayUrl]) -> String {
31 let hints = seen_on.iter().filter(|relay| public(relay)).take(SHARE_HINTS).cloned();
32 let named = Nip19Event::new(id).author(author).kind(kind).relays(hints);
33 let address = named.to_bech32().unwrap_or_else(|_| {
36 let Ok(note) = id.to_bech32();
37 note
38 });
39 format!("{SHARE_GATEWAY}{address}")
40}
41
42#[cfg(test)]
43mod tests {
44 use super::{SHARE_GATEWAY, share_link};
45 use nostr_sdk::prelude::{EventId, FromBech32, Keys, Kind, Nip19Event, RelayUrl};
46
47 fn relay(address: &str) -> RelayUrl {
48 RelayUrl::parse(address).unwrap()
49 }
50
51 fn named(link: &str) -> Nip19Event {
53 Nip19Event::from_bech32(link.strip_prefix(SHARE_GATEWAY).unwrap()).unwrap()
54 }
55
56 #[test]
57 fn a_share_link_is_a_web_address_that_names_the_note_and_where_it_is() {
58 let (id, author) = (EventId::from_byte_array([7; 32]), Keys::generate().public_key());
59 let seen_on = [relay("wss://one.example.com"), relay("wss://two.example.com"), relay("wss://three.example.com")];
60
61 let link = share_link(id, author, Kind::TextNote, &seen_on);
62 assert!(link.starts_with("https://njump.me/nevent1"), "{link}");
63 let note = named(&link);
64 assert_eq!((note.event_id, note.author, note.kind), (id, Some(author), Some(Kind::TextNote)));
65 assert_eq!(note.relays, seen_on[..2]);
67
68 assert_eq!(named(&share_link(id, author, Kind::Comment, &[])).kind, Some(Kind::Comment));
70 }
71
72 #[test]
73 fn a_share_link_names_no_relay_only_this_machine_can_reach() {
74 let (id, author) = (EventId::from_byte_array([7; 32]), Keys::generate().public_key());
75 let seen_on = [
76 relay("ws://127.0.0.1:10547"),
77 relay("wss://192.168.1.20"),
78 relay("ws://plain.example.com"),
79 relay("wss://far.example.com"),
80 ];
81 assert_eq!(named(&share_link(id, author, Kind::TextNote, &seen_on)).relays, [relay("wss://far.example.com")]);
82
83 let unseen = named(&share_link(id, author, Kind::TextNote, &[]));
85 assert!(unseen.relays.is_empty());
86 assert_eq!(unseen.author, Some(author));
87 }
88}