cosmic_applet_avestruz/nostr/
kept_drafts.rs1use 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
46pub const DRAFT_KIND: Kind = Kind::Custom(31234);
48
49const NOTE: &str = "avestruz:note";
52const REPLY: &str = "avestruz:reply:";
53const QUOTE: &str = "avestruz:quote:";
54
55pub 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
64pub 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
77pub 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
93pub 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
107pub 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
116pub fn wrap(target: Target, content: String, earlier: Option<&Event>, now: Timestamp) -> EventBuilder {
121 let mut tags = vec![Tag::identifier(identifier(target))];
122 tags.extend(Tag::parse(["k", Kind::TextNote.as_u16().to_string().as_str()]).ok());
124 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
132pub 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 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 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 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 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}