1use std::collections::HashSet;
45use std::fmt;
46
47use nostr_sdk::prelude::{Event, EventBuilder, EventId, Kind, PublicKey, RelayUrl, Tag, Timestamp};
48
49use crate::nostr::outbox::Whereabouts;
50
51pub type PrivateTags = Vec<Vec<String>>;
54
55pub fn decode(json: &str) -> Result<PrivateTags, String> {
61 serde_json::from_str(json).map_err(|_| "what was decrypted is not a list of tags".to_string())
62}
63
64pub fn encode(tags: &PrivateTags) -> String {
66 serde_json::to_string(tags).unwrap_or_else(|_| "[]".to_string())
67}
68
69fn note_named(fields: &[String]) -> Option<EventId> {
71 match fields {
72 [name, id, ..] if name == "e" => EventId::from_hex(id).ok(),
73 _ => None,
74 }
75}
76
77fn whereabouts_named(fields: &[String]) -> Whereabouts {
82 let said = || fields.iter().skip(2);
83 let relay = said().find_map(|field| RelayUrl::parse(field).ok());
84 let author = said().find_map(|field| PublicKey::from_hex(field).ok());
85 Whereabouts { author, relay }
86}
87
88fn names_something_else(fields: &[String]) -> bool {
92 fields.len() > 1 && fields.first().is_some_and(|name| ["a", "t", "r"].contains(&name.as_str()))
93}
94
95fn naming(note: EventId, hint: Option<&RelayUrl>) -> Vec<String> {
97 let mut fields = vec!["e".to_string(), note.to_hex()];
98 fields.extend(hint.map(ToString::to_string));
99 fields
100}
101
102#[derive(Clone, Default, PartialEq, Eq)]
105pub struct Bookmarks {
106 list: Option<Event>,
108 private: PrivateTags,
110 notes: HashSet<EventId>,
112}
113
114impl fmt::Debug for Bookmarks {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.debug_struct("Bookmarks")
119 .field("list", &self.list.as_ref().map(|list| list.id))
120 .field("notes", &self.notes.len())
121 .finish_non_exhaustive()
122 }
123}
124
125impl Bookmarks {
126 pub fn new(list: Option<Event>, private: PrivateTags) -> Self {
128 let notes = private.iter().filter_map(|fields| note_named(fields)).collect();
129 Self { list, private, notes }
130 }
131
132 pub fn list(&self) -> Option<&Event> {
134 self.list.as_ref()
135 }
136
137 pub fn has(&self, note: &EventId) -> bool {
139 self.notes.contains(note)
140 }
141
142 pub fn count(&self) -> usize {
144 self.notes.len()
145 }
146
147 pub fn notes(&self) -> Vec<EventId> {
151 let mut seen = HashSet::new();
152 let mut notes: Vec<EventId> =
153 self.private.iter().filter_map(|fields| note_named(fields)).filter(|note| seen.insert(*note)).collect();
154 notes.reverse();
155 notes
156 }
157
158 pub fn whereabouts(&self, note: &EventId) -> Whereabouts {
163 let naming = self.private.iter().filter(|fields| note_named(fields).as_ref() == Some(note));
164 naming.map(|fields| whereabouts_named(fields)).find(|said| *said != Whereabouts::default()).unwrap_or_default()
165 }
166
167 pub fn others(&self) -> usize {
169 self.private.iter().filter(|fields| names_something_else(fields)).count()
170 }
171
172 pub fn changed(&self, note: EventId, hint: Option<&RelayUrl>, bookmark: bool) -> Option<PrivateTags> {
179 if self.has(¬e) == bookmark {
180 return None;
181 }
182 let mut private = self.private.clone();
183 if bookmark {
184 private.push(naming(note, hint));
185 } else {
186 private.retain(|fields| note_named(fields) != Some(note));
187 }
188 Some(private)
189 }
190}
191
192pub fn list(earlier: Option<&Event>, content: String, now: Timestamp) -> EventBuilder {
197 let tags: Vec<Tag> = earlier.map(|earlier| earlier.tags.iter().cloned().collect()).unwrap_or_default();
198 let after = earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)));
199 EventBuilder::new(Kind::Bookmarks, content).tags(tags).custom_created_at(after)
200}
201
202#[cfg(test)]
203mod tests {
204 use super::{Bookmarks, PrivateTags, decode, encode, list};
205 use crate::nostr::outbox::Whereabouts;
206 use nostr_sdk::prelude::{Event, EventBuilder, EventId, FinalizeEvent, Keys, Kind, RelayUrl, Tag, Timestamp};
207
208 fn id(byte: u8) -> EventId {
209 EventId::from_byte_array([byte; 32])
210 }
211
212 fn e(note: EventId) -> Vec<String> {
213 vec!["e".to_string(), note.to_hex()]
214 }
215
216 fn tag(fields: &[&str]) -> Tag {
217 Tag::parse(fields.iter().copied()).unwrap()
218 }
219
220 fn a_list(tags: Vec<Tag>, at: u64) -> Event {
223 EventBuilder::new(Kind::Bookmarks, "encrypted")
224 .tags(tags)
225 .custom_created_at(Timestamp::from_secs(at))
226 .finalize(&Keys::generate())
227 .unwrap()
228 }
229
230 fn fields(tags: &[Tag]) -> Vec<Vec<String>> {
231 tags.iter().map(|tag| tag.as_slice().to_vec()).collect()
232 }
233
234 #[test]
235 fn what_a_list_keeps_to_itself_is_tags_as_compact_json() {
236 let json = format!(r#"[["e","{}"],["e","{}","wss://relay.example.com/"],["a","30023:abc:post"]]"#, id(1), id(2));
238 let tags = decode(&json).unwrap();
239 assert_eq!(tags.len(), 3);
240 assert_eq!(tags[1], ["e", &id(2).to_hex(), "wss://relay.example.com/"]);
241 assert_eq!(encode(&tags), json, "and it is written as it was read");
242
243 assert_eq!(decode("[]"), Ok(PrivateTags::new()));
244 for not_tags in ["", "{}", "[1]", r#"[["e",1]]"#, r#"["secret words"]"#] {
246 let error = decode(not_tags).unwrap_err();
247 assert!(!error.contains("secret"), "{error}");
248 }
249 }
250
251 #[test]
252 fn only_a_note_the_list_keeps_to_itself_is_bookmarked() {
253 let public = a_list(vec![Tag::event(id(1)), tag(&["t", "nostr"])], 100);
256 let private =
257 vec![e(id(2)), vec!["a".into(), "30023:abc:post".into()], vec!["e".into()], vec!["e".into(), "no id".into()]];
258 let bookmarks = Bookmarks::new(Some(public), private);
259 assert!(!bookmarks.has(&id(1)));
260 assert!(bookmarks.has(&id(2)));
261 assert_eq!(bookmarks.count(), 1);
262 assert_eq!(bookmarks.notes(), [id(2)]);
263
264 let none = Bookmarks::default();
265 assert!(!none.has(&id(1)));
266 assert_eq!(none.list(), None);
267 }
268
269 #[test]
270 fn the_notes_are_listed_from_the_last_bookmarked_each_once() {
271 let article = vec!["a".to_string(), "30023:abc:post".to_string()];
272 let link = vec!["r".to_string(), "https://example.com".to_string()];
273 let public = a_list(vec![Tag::event(id(1)), tag(&["t", "nostr"]), tag(&["a", "30023:abc:other"])], 100);
274 let bookmarks = Bookmarks::new(Some(public), vec![e(id(3)), article, e(id(4)), link, e(id(2)), e(id(3))]);
275
276 assert_eq!(bookmarks.notes(), [id(2), id(4), id(3)], "a note named twice is where it was named first");
277 assert_eq!(bookmarks.others(), 2);
279
280 let none = Bookmarks::default();
281 assert!(none.notes().is_empty());
282 assert_eq!(none.others(), 0);
283 }
284
285 #[test]
286 fn a_bookmark_is_added_to_what_is_kept_private_after_the_others() {
287 let tags = vec![Tag::event(id(1)), tag(&["title", "Mine"])];
288 let private = vec![e(id(2)), vec!["t".to_string(), "nostr".to_string()]];
289 let bookmarks = Bookmarks::new(Some(a_list(tags, 100)), private.clone());
290
291 let changed = bookmarks.changed(id(3), None, true).unwrap();
292 assert_eq!(changed, [private[0].clone(), private[1].clone(), e(id(3))]);
293
294 let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
296 let hinted = bookmarks.changed(id(3), Some(&relay), true).unwrap();
297 assert_eq!(hinted.last().unwrap(), &["e".to_string(), id(3).to_hex(), relay.to_string()]);
298
299 assert!(bookmarks.changed(id(2), None, true).is_none());
301 assert_eq!(bookmarks.changed(id(1), None, true).unwrap().last(), Some(&e(id(1))));
304 }
305
306 #[test]
307 fn a_bookmark_says_where_its_note_is_when_it_does() {
308 let author = Keys::generate().public_key();
309 let relay = "wss://relay.example.com";
310 let private = vec![
311 e(id(1)),
312 vec!["e".into(), id(2).to_hex(), relay.into()],
313 vec!["e".into(), id(3).to_hex(), author.to_hex()],
315 vec!["e".into(), id(4).to_hex(), "not a relay".into(), "not a key".into()],
316 e(id(5)),
318 vec!["e".into(), id(5).to_hex(), relay.into(), author.to_hex()],
319 ];
320 let bookmarks = Bookmarks::new(None, private);
321 let relay = RelayUrl::parse(relay).unwrap();
322
323 assert_eq!(bookmarks.whereabouts(&id(1)), Whereabouts::default());
324 assert_eq!(bookmarks.whereabouts(&id(2)), Whereabouts { author: None, relay: Some(relay.clone()) });
325 assert_eq!(bookmarks.whereabouts(&id(3)), Whereabouts { author: Some(author), relay: None });
326 assert_eq!(bookmarks.whereabouts(&id(4)), Whereabouts::default());
327 assert_eq!(bookmarks.whereabouts(&id(5)), Whereabouts { author: Some(author), relay: Some(relay) });
328 assert_eq!(bookmarks.whereabouts(&id(6)), Whereabouts::default(), "not bookmarked");
329 }
330
331 #[test]
332 fn the_first_bookmark_of_an_account_with_no_list_is_a_list_of_one() {
333 assert_eq!(Bookmarks::default().changed(id(1), None, true), Some(vec![e(id(1))]));
334 assert!(Bookmarks::default().changed(id(1), None, false).is_none(), "and there is nothing to take off");
335 }
336
337 #[test]
338 fn taking_a_bookmark_off_takes_the_note_out_of_what_is_kept_private_and_nothing_else() {
339 let hinted = vec!["e".to_string(), id(2).to_hex(), "wss://relay.example.com".to_string()];
340 let link = vec!["r".to_string(), "https://example.com".to_string()];
341 let private = vec![e(id(1)), hinted, e(id(3)), link, e(id(2))];
342 let bookmarks = Bookmarks::new(Some(a_list(vec![Tag::event(id(4))], 100)), private.clone());
343
344 assert_eq!(bookmarks.changed(id(2), None, false).unwrap(), [private[0].clone(), private[2].clone(), private[3].clone()]);
346 assert_eq!(bookmarks.changed(id(3), None, false).unwrap().len(), 4);
347
348 assert!(bookmarks.changed(id(5), None, false).is_none());
351 assert!(bookmarks.changed(id(4), None, false).is_none());
352 }
353
354 #[test]
355 fn a_changed_list_is_a_newer_bookmark_list_with_the_tags_of_the_one_it_replaces() {
356 let tags = vec![Tag::event(id(1)), tag(&["title", "Mine"]), tag(&["client", "Amethyst"])];
357 let earlier = a_list(tags.clone(), 1_000);
358 let build = |earlier: Option<&Event>, now: u64| {
359 list(earlier, "kept private".to_string(), Timestamp::from_secs(now)).finalize(&Keys::generate()).unwrap()
360 };
361 let changed = build(Some(&earlier), 2_000);
362 assert_eq!(changed.kind, Kind::Bookmarks);
363 assert_eq!(changed.kind.as_u16(), 10_003);
364 assert_eq!(changed.content, "kept private");
365 assert_eq!(fields(&changed.tags.to_vec()), fields(&tags), "what it says to anyone is as it was");
366 assert_eq!(changed.created_at.as_secs(), 2_000);
367
368 assert_eq!(build(Some(&earlier), 500).created_at.as_secs(), 1_001);
370 let first = build(None, 500);
372 assert!(first.tags.is_empty());
373 assert_eq!(first.created_at.as_secs(), 500);
374 }
375}