Skip to main content

cosmic_applet_avestruz/nostr/
compose.rs

1// SPDX-License-Identifier: MIT
2
3//! What someone wrote, made into an event ready to be signed: a note of its
4//! own, a reply to another, or a note that quotes another.
5//!
6//! The text goes out as it was written. The tags say what a relay or another
7//! client can't be expected to read out of the text: which conversation a
8//! reply belongs to and whom it answers, who is mentioned, which notes are
9//! quoted, and the hashtags.
10//!
11//! What a reply is depends on what it answers. An answer to a text note is
12//! a text note (NIP-10). An answer to anything else — a comment, or what
13//! comments are about — is a comment (NIP-22): the two don't mix.
14//!
15//! A quote is a note with the address of another in its text (NIP-18),
16//! which [`quote`] puts under what was written. Nothing else sets it apart:
17//! whatever names a note in its text quotes it.
18//!
19//! ```mermaid
20//! flowchart TD
21//!     written["What was written, and what it was written to"] --> target{"Written to?"}
22//!     target -->|"nothing"| note["Kind 1, with no reply tags"]
23//!     target -->|"nothing, about a note"| quoted["Kind 1. The note's address goes under the text"]
24//!     target -->|"a note"| parent{"What kind is the note answered?"}
25//!     parent -->|"a text note, kind 1"| reply["Kind 1. e tags: the root, and the note answered. p tags: its author, and everyone it spoke to"]
26//!     parent -->|"anything else"| comment["Kind 1111. What the comments are about, in capitals, then the note answered"]
27//!     note --> text
28//!     quoted --> text
29//!     reply --> text
30//!     comment --> text["Then what the text calls for: a p for each mention, a t for each hashtag, a q for each note quoted"]
31//! ```
32//!
33//! One kind of tag is not read out of the text, since the text doesn't
34//! say it: what the note says of a file it links to that was sent to a
35//! media server from here (`imeta`, NIP-92; see
36//! [`crate::nostr::blossom::imeta`]). Those are added to what [`build`]
37//! made, by whoever publishes it.
38//!
39//! Everything here is pure: text and an event in, an unsigned event out.
40//! Signing and sending are elsewhere (see [`crate::guide::flows`]).
41
42use 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/// What is written to.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum Target {
54    /// Nothing: a note of its own.
55    Note,
56    /// This note: a reply.
57    Reply(EventId),
58    /// Nothing, about this note: a note of its own that quotes it.
59    Quote(EventId),
60}
61
62/// What a quote of `quoted` says, when `text` was written about it: the
63/// text, and under it the note's address, where other clients show the note.
64/// The address says who wrote the note and what kind of event it is, so
65/// that it can be found by those who don't have it. With nothing written,
66/// the address is all there is.
67pub 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
78/// The tags the text itself calls for: a `p` for everyone mentioned, a `t`
79/// for every hashtag, and a `q` for every note quoted, with a `p` for who
80/// wrote it, as far as its address says. Each once; `author`, who writes
81/// the text, is not told of quoting themselves.
82fn 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            // Hashtags are matched in lowercase, whatever case they were
91            // written in.
92            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
105/// The tags that make a note a reply to `parent`, written by `author`.
106///
107/// The conversation's root and the note answered are named with markers; a
108/// reply to the root itself names it once, as the root. Everyone the parent
109/// spoke to is spoken to again, and its author first: that is who hears of
110/// the reply. The one replying is not told of their own reply.
111fn 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
127/// The tags that make a comment an answer to `parent`, which is not a text
128/// note (NIP-22).
129///
130/// What the comments are about is named first, in capitals: what `parent`
131/// says that is, if it is a comment itself, and `parent`, if it is what is
132/// commented on. Then `parent`, as what is answered. Something that is
133/// known by an address (an article) is named by it, and by its id as well,
134/// which is the version answered.
135fn 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
151/// `text` as an event of `author`'s, yet to be signed: a note; a reply to
152/// `parent`, if that is a text note; or a comment on `parent`, if it is
153/// anything else. A note that quotes another is a note, whatever it quotes.
154/// A tag the reply already carries is not added again for the text's sake.
155pub 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    /// The tags of `event`, each as its fields.
181    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(&note), 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(&note), [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(&note), [vec!["t", "rust"]]);
216        assert_eq!(note.content, text, "the text is left as it was written, marks and all");
217
218        // What is in a cell of a table is tagged as what is in a line is.
219        let note = signed(build("| tag |\n|---|\n| #nostr |", None, me.public_key()), &me);
220        assert_eq!(tags(&note), [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        // They answered me, and I answer back, mentioning them by key.
259        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        // A picture, and a comment on it.
272        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        // An answer to the comment is about the picture still, and answers
291        // the comment.
292        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        // Under the article, as far as threads go.
332        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(&note), 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", &quoted);
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        // The address says what was quoted: who wrote it, and its kind.
358        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        // With nothing said about it, the note's address is the quote.
367        let bare = signed(build(&quote("", &quoted), 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(&quote(&quote(&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(&quote("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}