Skip to main content

cosmic_applet_avestruz/
drafts.rs

1// SPDX-License-Identifier: MIT
2
3//! What has been written and not published: one text for each thing that
4//! can be written to.
5//!
6//! Leaving the composer keeps the text, so that coming back to the same
7//! note finds it. What is kept here lasts as long as the session. What is
8//! there after a restart is what the relay Avestruz runs itself keeps (see
9//! [`crate::nostr::kept_drafts`]), which every draft is sent to when the
10//! composer is left; and, when that relay can't be given the draft of a
11//! new note, the file that draft was kept in before there was such a
12//! relay.
13
14use std::collections::HashMap;
15use std::path::{Path, PathBuf};
16
17use crate::nostr::compose::Target;
18
19/// The unpublished text for each target that has any.
20#[derive(Debug, Default)]
21pub struct Drafts {
22    texts: HashMap<Target, String>,
23}
24
25impl Drafts {
26    /// What was written to `target` and left there. Empty if nothing.
27    pub fn get(&self, target: Target) -> &str {
28        self.texts.get(&target).map_or("", String::as_str)
29    }
30
31    /// Keep `text` as what is written to `target`. Text that is blank is no
32    /// draft: nothing is kept.
33    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
42/// Where the draft of a new note is kept: the user's data directory, beside
43/// the event store.
44pub fn default_draft_path() -> PathBuf {
45    dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")).join("cosmic-applet-avestruz").join("draft.txt")
46}
47
48/// The draft kept at `path`. No file is no draft.
49pub 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
60/// Write `text` to `path` in a way that leaves either the old draft or the
61/// new one, never half of one.
62async 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
71/// Keep `text` at `path` as the draft of a new note. A blank text is no
72/// draft, and takes the file away.
73pub 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            // And taking away what is not there is not an error.
127            save(path.clone(), String::new()).await;
128        });
129        let _ = std::fs::remove_dir_all(&directory);
130    }
131}