1use std::collections::HashSet;
43
44use nostr_sdk::prelude::{
45 CommentTarget, Event, EventBuilder, EventId, Kind, Nip18Tag, Nip19Event, PublicKey, Tag, ToBech32, nip22,
46};
47
48use crate::nostr::content::{self, Quote, Segment};
49use crate::nostr::models::{Note, reply_to};
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum Target {
54 Note,
56 Reply(EventId),
58 Quote(EventId),
60}
61
62pub fn quote(text: &str, quoted: &Note) -> String {
68 let address = Nip19Event::new(quoted.id).author(quoted.author).kind(quoted.kind).to_bech32().unwrap_or_else(|_| {
69 let Ok(address) = quoted.id.to_bech32();
70 address
71 });
72 match text {
73 "" => format!("nostr:{address}"),
74 text => format!("{text}\nnostr:{address}"),
75 }
76}
77
78fn content_tags(text: &str, author: PublicKey) -> Vec<Tag> {
83 let mut seen_people = HashSet::new();
84 let mut seen_hashtags = HashSet::new();
85 let mut tags = Vec::new();
86 let said = content::parse(text, usize::MAX);
87 for segment in content::inline(&said.segments) {
88 match segment {
89 Segment::Mention(person) if seen_people.insert(*person) => tags.push(Tag::public_key(*person)),
90 Segment::Hashtag(hashtag) if seen_hashtags.insert(hashtag.to_lowercase()) => tags.push(Tag::hashtag(hashtag)),
93 _ => {}
94 }
95 }
96 for Quote { id, author: quoted, relay, .. } in said.quotes {
97 tags.push(Nip18Tag::Quote { id, relay_hint: relay, public_key: quoted }.into());
98 if let Some(quoted) = quoted.filter(|quoted| *quoted != author && seen_people.insert(*quoted)) {
99 tags.push(Tag::public_key(quoted));
100 }
101 }
102 tags
103}
104
105fn reply_tags(parent: &Event, author: PublicKey) -> Vec<Tag> {
112 let marked = |id: EventId, marker: &str| Tag::custom("e", [id.to_hex(), String::new(), marker.to_string()]);
113 let mut tags = match reply_to(parent) {
114 Some(above) => vec![marked(above.root, "root"), marked(parent.id, "reply")],
115 None => vec![marked(parent.id, "root")],
116 };
117 let mut seen = HashSet::from([author]);
118 tags.extend(
119 std::iter::once(parent.pubkey)
120 .chain(parent.tags.public_keys())
121 .filter(|person| seen.insert(*person))
122 .map(Tag::public_key),
123 );
124 tags
125}
126
127fn comment_tags(parent: &Event) -> Vec<Tag> {
136 let answered = CommentTarget::from(parent);
137 let about = match parent.kind {
138 Kind::Comment => nip22::extract_root(parent),
139 _ => None,
140 }
141 .unwrap_or_else(|| answered.clone());
142
143 let mut tags = about.as_vec(true);
144 tags.extend(answered.as_vec(false));
145 if parent.coordinate().is_some() {
146 tags.push(Tag::event(parent.id));
147 }
148 tags
149}
150
151pub fn build(text: &str, parent: Option<&Event>, author: PublicKey) -> EventBuilder {
156 let (kind, mut tags) = match parent {
157 None => (Kind::TextNote, Vec::new()),
158 Some(parent) if parent.kind == Kind::TextNote => (Kind::TextNote, reply_tags(parent, author)),
159 Some(parent) => (Kind::Comment, comment_tags(parent)),
160 };
161 for tag in content_tags(text, author) {
162 if !tags.contains(&tag) {
163 tags.push(tag);
164 }
165 }
166 EventBuilder::new(kind, text).tags(tags)
167}
168
169#[cfg(test)]
170mod tests {
171 use super::{build, quote};
172 use crate::nostr::content;
173 use crate::nostr::models::{Note, ReplyTo, reply_to};
174 use nostr_sdk::prelude::{Event, EventBuilder, FinalizeEvent, FromBech32, Keys, Kind, Nip19Event, Tag, ToBech32};
175
176 fn signed(builder: EventBuilder, keys: &Keys) -> Event {
177 builder.finalize(keys).unwrap()
178 }
179
180 fn tags(event: &Event) -> Vec<Vec<&str>> {
182 event.tags.iter().map(|tag| tag.as_slice().iter().map(String::as_str).collect()).collect()
183 }
184
185 #[test]
186 fn a_note_goes_out_as_written_with_no_tags_it_did_not_ask_for() {
187 let me = Keys::generate();
188 let note = signed(build("gm, everyone", None, me.public_key()), &me);
189
190 assert_eq!(note.kind, Kind::TextNote);
191 assert_eq!(note.content, "gm, everyone");
192 assert!(note.tags.is_empty());
193 assert_eq!(reply_to(¬e), None);
194 }
195
196 #[test]
197 fn mentions_and_hashtags_are_tagged_each_once() {
198 let me = Keys::generate();
199 let friend = Keys::generate().public_key();
200 let npub = friend.to_bech32().unwrap();
201 let text = format!("#Nostr with nostr:{npub}, again nostr:{npub} #nostr #rust");
202 let note = signed(build(&text, None, me.public_key()), &me);
203
204 let friend = friend.to_hex();
205 assert_eq!(tags(¬e), [vec!["t", "nostr"], vec!["p", friend.as_str()], vec!["t", "rust"]]);
206 assert_eq!(note.content, text, "the text is left as it was written");
207 }
208
209 #[test]
210 fn what_is_written_as_code_is_not_tagged_and_what_is_stressed_is() {
211 let me = Keys::generate();
212 let text = "run `cargo test #[ignore] #slow` on **#rust**";
213 let note = signed(build(text, None, me.public_key()), &me);
214
215 assert_eq!(tags(¬e), [vec!["t", "rust"]]);
216 assert_eq!(note.content, text, "the text is left as it was written, marks and all");
217
218 let note = signed(build("| tag |\n|---|\n| #nostr |", None, me.public_key()), &me);
220 assert_eq!(tags(¬e), [vec!["t", "nostr"]]);
221 }
222
223 #[test]
224 fn a_reply_to_a_note_that_starts_a_conversation_names_it_as_the_root() {
225 let (me, them) = (Keys::generate(), Keys::generate());
226 let root = signed(build("it starts", None, them.public_key()), &them);
227 let reply = signed(build("an answer", Some(&root), me.public_key()), &me);
228
229 let (root_id, their_key) = (root.id.to_hex(), them.public_key().to_hex());
230 assert_eq!(tags(&reply), [vec!["e", root_id.as_str(), "", "root"], vec!["p", their_key.as_str()]]);
231 assert_eq!(reply_to(&reply), Some(ReplyTo { root: root.id, parent: root.id }));
232 }
233
234 #[test]
235 fn a_reply_further_down_names_the_root_the_parent_and_everyone_spoken_to() {
236 let (me, starter, answerer) = (Keys::generate(), Keys::generate(), Keys::generate());
237 let root = signed(build("it starts", None, starter.public_key()), &starter);
238 let parent = signed(build("an answer", Some(&root), answerer.public_key()), &answerer);
239 let reply = signed(build("an answer to the answer", Some(&parent), me.public_key()), &me);
240
241 let (root_id, parent_id) = (root.id.to_hex(), parent.id.to_hex());
242 let (starter_key, answerer_key) = (starter.public_key().to_hex(), answerer.public_key().to_hex());
243 assert_eq!(
244 tags(&reply),
245 [
246 vec!["e", root_id.as_str(), "", "root"],
247 vec!["e", parent_id.as_str(), "", "reply"],
248 vec!["p", answerer_key.as_str()],
249 vec!["p", starter_key.as_str()],
250 ]
251 );
252 assert_eq!(reply_to(&reply), Some(ReplyTo { root: root.id, parent: parent.id }));
253 }
254
255 #[test]
256 fn replying_tells_nobody_twice_and_not_oneself() {
257 let (me, them) = (Keys::generate(), Keys::generate());
258 let mine = signed(build("it starts", None, me.public_key()), &me);
260 let theirs = signed(build("an answer", Some(&mine), them.public_key()), &them);
261 let text = format!("thanks nostr:{}", them.public_key().to_bech32().unwrap());
262 let reply = signed(build(&text, Some(&theirs), me.public_key()), &me);
263
264 let people: Vec<Tag> = reply.tags.iter().filter(|tag| tag.kind() == "p").cloned().collect();
265 assert_eq!(people, [Tag::public_key(them.public_key())]);
266 }
267
268 #[test]
269 fn an_answer_to_a_comment_is_a_comment_under_what_the_comments_are_about() {
270 let (me, them, artist) = (Keys::generate(), Keys::generate(), Keys::generate());
271 let picture = signed(EventBuilder::new(Kind::Custom(20), "a heron"), &artist);
273 let comment = signed(build("what a bird", Some(&picture), them.public_key()), &them);
274 let (picture_id, artist_key) = (picture.id.to_hex(), artist.public_key().to_hex());
275
276 assert_eq!(comment.kind, Kind::Comment);
277 assert_eq!(
278 tags(&comment),
279 [
280 vec!["E", picture_id.as_str(), "", artist_key.as_str()],
281 vec!["P", artist_key.as_str()],
282 vec!["K", "20"],
283 vec!["e", picture_id.as_str(), "", artist_key.as_str()],
284 vec!["p", artist_key.as_str()],
285 vec!["k", "20"],
286 ]
287 );
288 assert_eq!(reply_to(&comment), Some(ReplyTo { root: picture.id, parent: picture.id }));
289
290 let answer = signed(build("isn't it", Some(&comment), me.public_key()), &me);
293 let (comment_id, their_key) = (comment.id.to_hex(), them.public_key().to_hex());
294
295 assert_eq!(answer.kind, Kind::Comment);
296 assert_eq!(
297 tags(&answer),
298 [
299 vec!["E", picture_id.as_str(), "", artist_key.as_str()],
300 vec!["P", artist_key.as_str()],
301 vec!["K", "20"],
302 vec!["e", comment_id.as_str(), "", their_key.as_str()],
303 vec!["p", their_key.as_str()],
304 vec!["k", "1111"],
305 ]
306 );
307 assert_eq!(reply_to(&answer), Some(ReplyTo { root: picture.id, parent: comment.id }));
308 }
309
310 #[test]
311 fn a_comment_on_an_article_names_it_by_its_address_and_its_id() {
312 let (me, writer) = (Keys::generate(), Keys::generate());
313 let article = signed(EventBuilder::new(Kind::LongFormTextNote, "# On herons").tag(Tag::identifier("herons")), &writer);
314 let comment = signed(build("well put", Some(&article), me.public_key()), &me);
315 let address = format!("30023:{}:herons", writer.public_key().to_hex());
316 let (article_id, writer_key) = (article.id.to_hex(), writer.public_key().to_hex());
317
318 assert_eq!(comment.kind, Kind::Comment);
319 assert_eq!(
320 tags(&comment),
321 [
322 vec!["A", address.as_str()],
323 vec!["P", writer_key.as_str()],
324 vec!["K", "30023"],
325 vec!["a", address.as_str()],
326 vec!["p", writer_key.as_str()],
327 vec!["k", "30023"],
328 vec!["e", article_id.as_str()],
329 ]
330 );
331 assert_eq!(reply_to(&comment), Some(ReplyTo { root: article.id, parent: article.id }));
333 }
334
335 #[test]
336 fn an_answer_to_a_text_note_is_never_a_comment() {
337 let (me, them) = (Keys::generate(), Keys::generate());
338 let note = signed(build("gm", None, them.public_key()), &them);
339 assert_eq!(signed(build("gm!", Some(¬e), me.public_key()), &me).kind, Kind::TextNote);
340 }
341
342 #[test]
343 fn a_quote_names_the_note_in_its_text_and_its_tags_and_tells_its_author() {
344 let (me, them) = (Keys::generate(), Keys::generate());
345 let quoted = Note::from(signed(build("worth a second look", None, them.public_key()), &them));
346
347 let text = quote("look at this", "ed);
348 assert!(text.starts_with("look at this\nnostr:nevent1"), "{text}");
349 let published = signed(build(&text, None, me.public_key()), &me);
350
351 assert_eq!(published.kind, Kind::TextNote);
352 assert_eq!(published.content, text, "the address is in the text, where other clients look for it");
353 let (quoted_id, their_key) = (quoted.id.to_hex(), them.public_key().to_hex());
354 assert_eq!(tags(&published), [vec!["q", quoted_id.as_str(), "", their_key.as_str()], vec!["p", their_key.as_str()]]);
355 assert_eq!(reply_to(&published), None, "a quote answers nothing");
356
357 let named = content::parse(&text, usize::MAX).quotes;
359 assert_eq!(
360 named.iter().map(|quote| (quote.id, quote.author)).collect::<Vec<_>>(),
361 [(quoted.id, Some(them.public_key()))]
362 );
363 let address = text.rsplit("nostr:").next().unwrap();
364 assert_eq!(Nip19Event::from_bech32(address).unwrap().kind, Some(Kind::TextNote));
365
366 let bare = signed(build("e("", "ed), None, me.public_key()), &me);
368 assert_eq!(bare.content, format!("nostr:{address}"));
369 assert_eq!(tags(&bare), tags(&published));
370 }
371
372 #[test]
373 fn quoting_tags_each_note_once_and_tells_nobody_twice_nor_oneself() {
374 let (me, them) = (Keys::generate(), Keys::generate());
375 let mine = Note::from(signed(build("as I said", None, me.public_key()), &me));
376 let theirs = Note::from(signed(build("as they said", None, them.public_key()), &them));
377 let bare = theirs.id.to_bech32().unwrap();
378
379 let text = format!("nostr:{} said", them.public_key().to_bech32().unwrap());
380 let text = quote("e("e(&text, &theirs), &theirs), &mine);
381 let text = format!("{text} nostr:{bare}");
382 let published = signed(build(&text, None, me.public_key()), &me);
383
384 let (their_id, my_id) = (theirs.id.to_hex(), mine.id.to_hex());
385 let (their_key, my_key) = (them.public_key().to_hex(), me.public_key().to_hex());
386 assert_eq!(
387 tags(&published),
388 [
389 vec!["p", their_key.as_str()],
390 vec!["q", their_id.as_str(), "", their_key.as_str()],
391 vec!["q", my_id.as_str(), "", my_key.as_str()],
392 ]
393 );
394 }
395
396 #[test]
397 fn a_reply_that_quotes_is_a_reply_still() {
398 let (me, them, third) = (Keys::generate(), Keys::generate(), Keys::generate());
399 let root = signed(build("it starts", None, them.public_key()), &them);
400 let elsewhere = Note::from(signed(build("said elsewhere", None, third.public_key()), &third));
401 let reply = signed(build("e("see", &elsewhere), Some(&root), me.public_key()), &me);
402
403 assert_eq!(reply_to(&reply), Some(ReplyTo { root: root.id, parent: root.id }));
404 let quoted: Vec<&str> = reply.tags.iter().filter(|tag| tag.kind() == "q").filter_map(|tag| tag.content()).collect();
405 assert_eq!(quoted, [elsewhere.id.to_hex()]);
406 }
407}