cosmic_applet_avestruz/
drafts.rs1use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16
17use crate::nostr::compose::Target;
18
19#[derive(Debug, Default)]
21pub struct Drafts {
22 texts: HashMap<Target, String>,
23}
24
25impl Drafts {
26 pub fn get(&self, target: Target) -> &str {
28 self.texts.get(&target).map_or("", String::as_str)
29 }
30
31 pub fn set(&mut self, target: Target, text: String) {
34 if text.trim().is_empty() {
35 self.texts.remove(&target);
36 } else {
37 self.texts.insert(target, text);
38 }
39 }
40}
41
42pub fn default_draft_path() -> PathBuf {
45 dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")).join("cosmic-applet-avestruz").join("draft.txt")
46}
47
48pub async fn load(path: PathBuf) -> String {
50 match tokio::fs::read_to_string(&path).await {
51 Ok(text) => text,
52 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
53 Err(e) => {
54 tracing::warn!("the draft at {} could not be read: {e}", path.display());
55 String::new()
56 }
57 }
58}
59
60async fn write(path: &Path, text: &str) -> std::io::Result<()> {
63 if let Some(directory) = path.parent() {
64 tokio::fs::create_dir_all(directory).await?;
65 }
66 let partial = path.with_extension("partial");
67 tokio::fs::write(&partial, text).await?;
68 tokio::fs::rename(&partial, path).await
69}
70
71pub async fn save(path: PathBuf, text: String) {
74 let result = if text.trim().is_empty() {
75 match tokio::fs::remove_file(&path).await {
76 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
77 _ => Ok(()),
78 }
79 } else {
80 write(&path, &text).await
81 };
82 if let Err(e) = result {
83 tracing::warn!("the draft could not be kept at {}: {e}", path.display());
84 }
85}
86
87#[cfg(test)]
88mod tests {
89 use super::{Drafts, load, save};
90 use crate::nostr::compose::Target;
91 use nostr_sdk::prelude::EventId;
92
93 #[test]
94 fn each_target_has_its_own_draft_and_a_blank_one_is_none() {
95 let (one, other) = (Target::Reply(EventId::from_byte_array([1; 32])), Target::Reply(EventId::from_byte_array([2; 32])));
96 let mut drafts = Drafts::default();
97 assert_eq!(drafts.get(Target::Note), "");
98
99 drafts.set(Target::Note, "a note".into());
100 drafts.set(one, "a reply".into());
101 assert_eq!(drafts.get(Target::Note), "a note");
102 assert_eq!(drafts.get(one), "a reply");
103 assert_eq!(drafts.get(other), "");
104
105 drafts.set(one, " \n ".into());
106 assert_eq!(drafts.get(one), "");
107 assert_eq!(drafts.get(Target::Note), "a note");
108 }
109
110 #[test]
111 fn the_draft_of_a_note_is_there_after_a_restart_until_it_is_blank() {
112 let directory = std::env::temp_dir().join(format!("avestruz-test-{}-draft", std::process::id()));
113 let _ = std::fs::remove_dir_all(&directory);
114 let path = directory.join("nested").join("draft.txt");
115 let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
116
117 runtime.block_on(async {
118 assert_eq!(load(path.clone()).await, "", "no file, no draft");
119
120 save(path.clone(), "half a thought\nand a line".into()).await;
121 assert_eq!(load(path.clone()).await, "half a thought\nand a line");
122
123 save(path.clone(), " ".into()).await;
124 assert_eq!(load(path.clone()).await, "");
125 assert!(!path.exists(), "a blank draft leaves no file");
126 save(path.clone(), String::new()).await;
128 });
129 let _ = std::fs::remove_dir_all(&directory);
130 }
131}