Skip to main content

cosmic_applet_avestruz/nostr/
kept_drafts.rs

1// SPDX-License-Identifier: MIT
2
3//! Drafts as events (NIP-37): what is written and not published, as the
4//! relay Avestruz runs itself keeps it.
5//!
6//! A draft is kept as a draft wrap (kind 31234): an addressable event the
7//! account signs, whose content is the note the draft would be, unsigned,
8//! as JSON, encrypted to the account itself (NIP-44). Its `d` tag says
9//! which draft it is, so that a later one replaces it, and its `k` tag
10//! what kind of event it wraps. A wrap with no content is a draft that
11//! was done with: published, or cleared.
12//!
13//! There is one draft for each thing that can be written to, as in
14//! [`crate::drafts`], and the `d` tag is which: a note of its own, a reply
15//! to a note, a quote of one.
16//!
17//! ```mermaid
18//! flowchart TD
19//!     text["What was written"] --> note["The note it would be: kind 1, unsigned, as JSON"]
20//!     note -- "encrypted to the account (NIP-44)" --> content
21//!     subgraph wrap["A draft wrap, kind 31234, signed by the account"]
22//!         direction TB
23//!         d["d: which draft it is"]
24//!         k["k: 1, the kind it wraps"]
25//!         e["e: the note answered or quoted, if any"]
26//!         content["content: the encrypted note, or nothing for a draft done with"]
27//!     end
28//!     wrap --> relay["The relay Avestruz runs itself, and no other"]
29//! ```
30//!
31//! | Written to | `d` tag |
32//! |---|---|
33//! | A note of its own | `avestruz:note` |
34//! | A reply to a note | `avestruz:reply:` and the note's id |
35//! | A quote of a note | `avestruz:quote:` and the note's id |
36//!
37//! Wraps with any other `d` tag are another client's drafts, and are left
38//! alone.
39
40use nostr_sdk::prelude::{Event, EventBuilder, EventId, Kind, PublicKey, Tag, Timestamp};
41use serde_json::{Value, json};
42
43use crate::nostr::blossom;
44use crate::nostr::compose::Target;
45
46/// The kind of a draft wrap.
47pub const DRAFT_KIND: Kind = Kind::Custom(31234);
48
49/// What the `d` tag of a draft says, by what the draft is of: a note of
50/// its own; or, before the id of the note it is about, a reply or a quote.
51const NOTE: &str = "avestruz:note";
52const REPLY: &str = "avestruz:reply:";
53const QUOTE: &str = "avestruz:quote:";
54
55/// What the `d` tag of the draft for `target` says.
56pub fn identifier(target: Target) -> String {
57    match target {
58        Target::Note => NOTE.to_string(),
59        Target::Reply(note) => format!("{REPLY}{}", note.to_hex()),
60        Target::Quote(note) => format!("{QUOTE}{}", note.to_hex()),
61    }
62}
63
64/// What the draft whose `d` tag says `identifier` is a draft of, if it is
65/// one of this client's.
66pub fn target_of(identifier: &str) -> Option<Target> {
67    let about = |id: &str| EventId::from_hex(id).ok();
68    if identifier == NOTE {
69        Some(Target::Note)
70    } else if let Some(id) = identifier.strip_prefix(REPLY) {
71        about(id).map(Target::Reply)
72    } else {
73        identifier.strip_prefix(QUOTE).and_then(about).map(Target::Quote)
74    }
75}
76
77/// What a draft wrap's content is before it is encrypted: the note `text`
78/// would be if `account` published it at `now`, unsigned, as JSON. Of its
79/// tags it has those in `said`: what it says of the files it links to
80/// (NIP-92), which nothing but having sent them tells.
81pub fn written(account: PublicKey, text: &str, said: &[Tag], now: Timestamp) -> String {
82    let tags: Vec<&[String]> = said.iter().map(Tag::as_slice).collect();
83    let note = json!({
84        "kind": Kind::TextNote.as_u16(),
85        "pubkey": account.to_hex(),
86        "created_at": now.as_secs(),
87        "tags": tags,
88        "content": text,
89    });
90    note.to_string()
91}
92
93/// What the draft that `json` is says of the files it links to: its
94/// `imeta` tags. None if it is no event, or has none.
95pub fn said_of(json: &str) -> Vec<Tag> {
96    let draft: Value = serde_json::from_str(json).unwrap_or_default();
97    let tags = draft.get("tags").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
98    let fields =
99        |tag: &Value| -> Option<Vec<String>> { tag.as_array()?.iter().map(|field| field.as_str().map(str::to_string)).collect() };
100    tags.iter()
101        .filter_map(fields)
102        .filter_map(|fields| Tag::parse(fields).ok())
103        .filter(|tag| blossom::imeta_url(tag).is_some())
104        .collect()
105}
106
107/// The text of the draft that `json` is, which is what a draft wrap's
108/// content says once it is decrypted. `None` if it is no event, or says
109/// nothing.
110pub fn text_of(json: &str) -> Option<String> {
111    let draft: Value = serde_json::from_str(json).ok()?;
112    let text = draft.get("content")?.as_str()?;
113    (!text.trim().is_empty()).then(|| text.to_string())
114}
115
116/// The draft wrap for `target`, with `content` for what it wraps:
117/// encrypted, or nothing at all for a draft that is done with. Written at
118/// `now` or, if `earlier`, the wrap it replaces, claims to be from later,
119/// after it: it has to be the newer of the two.
120pub fn wrap(target: Target, content: String, earlier: Option<&Event>, now: Timestamp) -> EventBuilder {
121    let mut tags = vec![Tag::identifier(identifier(target))];
122    // What kind of event it wraps: a note.
123    tags.extend(Tag::parse(["k", Kind::TextNote.as_u16().to_string().as_str()]).ok());
124    // What it is about, for whoever reads the drafts elsewhere.
125    if let Target::Reply(note) | Target::Quote(note) = target {
126        tags.push(Tag::event(note));
127    }
128    let after = earlier.map_or(now, |earlier| now.max(Timestamp::from_secs(earlier.created_at.as_secs() + 1)));
129    EventBuilder::new(DRAFT_KIND, content).tags(tags).custom_created_at(after)
130}
131
132/// What the draft wrap `event` is a draft of, and its content, which is
133/// empty when the draft is done with. `None` if it is no draft wrap, or
134/// not one of this client's.
135pub fn kept(event: &Event) -> Option<(Target, &str)> {
136    if event.kind != DRAFT_KIND {
137        return None;
138    }
139    Some((target_of(&event.tags.identifier()?)?, event.content.as_str()))
140}
141
142#[cfg(test)]
143mod tests {
144    use super::{DRAFT_KIND, identifier, kept, said_of, target_of, text_of, wrap, written};
145    use crate::nostr::compose::Target;
146    use nostr_sdk::prelude::{EventBuilder, EventId, FinalizeEvent, Keys, Kind, Tag, Timestamp};
147
148    fn id(byte: u8) -> EventId {
149        EventId::from_byte_array([byte; 32])
150    }
151
152    #[test]
153    fn each_thing_written_to_has_a_draft_of_its_own() {
154        for target in [Target::Note, Target::Reply(id(1)), Target::Quote(id(1)), Target::Reply(id(2))] {
155            assert_eq!(target_of(&identifier(target)), Some(target));
156        }
157        assert_ne!(identifier(Target::Reply(id(1))), identifier(Target::Quote(id(1))));
158        for not_ours in ["", "note", "avestruz:reply:", "avestruz:reply:xyz", "some-other-client-draft"] {
159            assert_eq!(target_of(not_ours), None, "{not_ours}");
160        }
161    }
162
163    #[test]
164    fn a_draft_is_the_note_it_would_be_and_reads_back_as_its_text() {
165        let keys = Keys::generate();
166        let json = written(keys.public_key(), "half a thought\nand a line", &[], Timestamp::from_secs(100));
167        assert!(json.contains(r#""kind":1"#) && json.contains(&keys.public_key().to_hex()), "{json}");
168        assert_eq!(text_of(&json).as_deref(), Some("half a thought\nand a line"));
169        assert!(said_of(&json).is_empty());
170
171        // As another client may have written one, and what is no draft.
172        assert_eq!(text_of(r#"{"kind":1,"content":"theirs","tags":[]}"#).as_deref(), Some("theirs"));
173        for nothing in ["", "[]", r#"{"content":"  "}"#, r#"{"content":7}"#, "not json"] {
174            assert_eq!(text_of(nothing), None, "{nothing}");
175        }
176    }
177
178    #[test]
179    fn a_draft_keeps_what_it_says_of_the_files_it_links_to() {
180        let keys = Keys::generate();
181        let said = Tag::parse(["imeta", "url https://cdn.example.com/abc.png", "m image/png", "dim 3x2"]).unwrap();
182        let json = written(
183            keys.public_key(),
184            "look https://cdn.example.com/abc.png",
185            std::slice::from_ref(&said),
186            Timestamp::from_secs(100),
187        );
188        assert_eq!(said_of(&json), [said]);
189        assert_eq!(text_of(&json).as_deref(), Some("look https://cdn.example.com/abc.png"));
190
191        // Of another client's draft, only what is said of a link.
192        let theirs = r#"{"kind":1,"content":"x","tags":[["t","nostr"],["imeta","m image/png"],["imeta","url https://a.example/b.jpg"],[1]]}"#;
193        assert_eq!(said_of(theirs), [Tag::parse(["imeta", "url https://a.example/b.jpg"]).unwrap()]);
194        for nothing in ["", "[]", r#"{"tags":7}"#, "not json"] {
195            assert!(said_of(nothing).is_empty(), "{nothing}");
196        }
197    }
198
199    #[test]
200    fn a_draft_wrap_says_which_draft_it_is_and_replaces_the_one_before() {
201        let keys = Keys::generate();
202        let now = Timestamp::from_secs(200);
203        let first = wrap(Target::Reply(id(3)), "encrypted".to_string(), None, now).finalize(&keys).unwrap();
204        assert_eq!((first.kind, first.created_at), (DRAFT_KIND, now));
205        let fields: Vec<Vec<String>> = first.tags.iter().map(|tag| tag.as_slice().to_vec()).collect();
206        assert_eq!(
207            fields,
208            [
209                vec!["d".to_string(), identifier(Target::Reply(id(3)))],
210                vec!["k".into(), "1".into()],
211                vec!["e".into(), id(3).to_hex()]
212            ]
213        );
214        assert_eq!(kept(&first), Some((Target::Reply(id(3)), "encrypted")));
215
216        // Done with: no content. Written in the same second, it is still
217        // the later of the two.
218        let done = wrap(Target::Reply(id(3)), String::new(), Some(&first), now).finalize(&keys).unwrap();
219        assert_eq!(done.created_at.as_secs(), 201);
220        assert_eq!(kept(&done), Some((Target::Reply(id(3)), "")));
221        let note = wrap(Target::Note, "x".to_string(), None, now).finalize(&keys).unwrap();
222        assert_eq!(note.tags.len(), 2);
223
224        // Another client's draft, and what is no draft at all.
225        let theirs = EventBuilder::new(DRAFT_KIND, "x").tag(nostr_sdk::prelude::Tag::identifier("abc")).finalize(&keys).unwrap();
226        assert_eq!(kept(&theirs), None);
227        assert_eq!(kept(&EventBuilder::new(Kind::TextNote, "x").finalize(&keys).unwrap()), None);
228    }
229}