Skip to main content

qualia_client_core/
mail_store.rs

1//! Local mail message store — where delivered mail actually lives.
2//!
3//! Inbound mail (local SMTP receiver, inject, or optional IMAP import) is resolved and ruled,
4//! then persisted under `app_meta_dir()/mail_messages.json`. This is the product inbox — not a
5//! pointer at a paid provider.
6
7use serde::{Deserialize, Serialize};
8use std::fs;
9use std::path::PathBuf;
10
11use crate::state::app_meta_dir;
12
13/// A delivered (or quarantined) message in the local inbox.
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15pub struct StoredMail {
16    pub id: String,
17    pub received_at: u64,
18    pub from_address: String,
19    pub to_address: String,
20    /// Mailbox address that accepted delivery (exact or catchall surface).
21    pub mailbox: String,
22    pub subject: String,
23    pub body: String,
24    /// `exact` | `catchall`
25    pub via: String,
26    pub quarantined: bool,
27    pub priority: i8,
28    pub read: bool,
29    #[serde(default)]
30    pub reasons: Vec<String>,
31    /// Size in bytes of the original body (for UI).
32    #[serde(default)]
33    pub size_bytes: usize,
34    /// Label of the configured account that imported this message. `None`
35    /// denotes direct local SMTP or mesh delivery.
36    #[serde(default)]
37    pub source_account: Option<String>,
38}
39
40fn messages_path() -> PathBuf {
41    app_meta_dir().join("mail_messages.json")
42}
43
44fn load_all() -> Vec<StoredMail> {
45    fs::read_to_string(messages_path())
46        .ok()
47        .and_then(|t| serde_json::from_str(&t).ok())
48        .unwrap_or_default()
49}
50
51fn save_all(msgs: &[StoredMail]) -> Result<(), String> {
52    let path = messages_path();
53    if let Some(p) = path.parent() {
54        fs::create_dir_all(p).map_err(|e| e.to_string())?;
55    }
56    let text = serde_json::to_string_pretty(msgs).map_err(|e| e.to_string())?;
57    fs::write(path, text).map_err(|e| e.to_string())
58}
59
60fn now_unix() -> u64 {
61    std::time::SystemTime::now()
62        .duration_since(std::time::UNIX_EPOCH)
63        .map(|d| d.as_secs())
64        .unwrap_or(0)
65}
66
67fn new_id() -> String {
68    // Compact unique-enough id without pulling uuid into hot API paths unnecessarily.
69    let n = now_unix();
70    let r: u32 = rand::random();
71    format!("m-{n:x}-{r:08x}")
72}
73
74static STORE_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
75
76/// Append a delivered message. Returns the stored record.
77pub fn append(msg: StoredMail) -> Result<StoredMail, String> {
78    let _guard = STORE_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
79    let mut all = load_all();
80    all.insert(0, msg.clone()); // newest first
81                                // Soft cap — keep last 5_000 messages so the file stays bounded.
82    if all.len() > 5_000 {
83        all.truncate(5_000);
84    }
85    save_all(&all)?;
86    Ok(msg)
87}
88
89/// Build + append from delivery fields.
90pub fn store_delivery(
91    from: &str,
92    to: &str,
93    mailbox: &str,
94    subject: &str,
95    body: &str,
96    via: &str,
97    quarantined: bool,
98    priority: i8,
99    reasons: Vec<String>,
100) -> Result<StoredMail, String> {
101    let body = body.to_string();
102    let size_bytes = body.len();
103    let msg = StoredMail {
104        id: new_id(),
105        received_at: now_unix(),
106        from_address: from.to_string(),
107        to_address: to.to_string(),
108        mailbox: mailbox.to_string(),
109        subject: subject.to_string(),
110        body,
111        via: via.to_string(),
112        quarantined,
113        priority,
114        read: false,
115        reasons,
116        size_bytes,
117        source_account: None,
118    };
119    append(msg)
120}
121
122/// Attach cold-path import provenance after a message has passed the same
123/// delivery rules as every other local message.
124pub fn set_source_account(id: &str, source_account: &str) -> Result<(), String> {
125    let _guard = STORE_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
126    let mut all = load_all();
127    let message = all
128        .iter_mut()
129        .find(|message| message.id == id)
130        .ok_or_else(|| format!("unknown message '{id}'"))?;
131    message.source_account = Some(source_account.to_string());
132    save_all(&all)
133}
134
135/// List messages, newest first. `mailbox` filters by accepting mailbox when set.
136/// `include_quarantine` includes quarantined messages (default true for full inbox; UI can filter).
137pub fn list(mailbox: Option<&str>, include_quarantine: bool) -> Vec<StoredMail> {
138    load_all()
139        .into_iter()
140        .filter(|m| {
141            if let Some(mb) = mailbox {
142                if !m.mailbox.eq_ignore_ascii_case(mb) && !m.to_address.eq_ignore_ascii_case(mb) {
143                    return false;
144                }
145            }
146            if !include_quarantine && m.quarantined {
147                return false;
148            }
149            true
150        })
151        .collect()
152}
153
154/// Gets.
155pub fn get(id: &str) -> Option<StoredMail> {
156    load_all().into_iter().find(|m| m.id == id)
157}
158
159/// Sets read.
160pub fn set_read(id: &str, read: bool) -> Result<StoredMail, String> {
161    let _guard = STORE_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
162    let mut all = load_all();
163    let msg = all
164        .iter_mut()
165        .find(|m| m.id == id)
166        .ok_or_else(|| format!("unknown message '{id}'"))?;
167    msg.read = read;
168    let out = msg.clone();
169    save_all(&all)?;
170    Ok(out)
171}
172
173/// Deletes.
174pub fn delete(id: &str) -> Result<(), String> {
175    let _guard = STORE_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
176    let mut all = load_all();
177    let before = all.len();
178    all.retain(|m| m.id != id);
179    if all.len() == before {
180        return Err(format!("unknown message '{id}'"));
181    }
182    save_all(&all)
183}
184
185/// Counts for the UI badge.
186pub fn counts() -> (usize, usize, usize) {
187    let all = load_all();
188    let total = all.len();
189    let unread = all.iter().filter(|m| !m.read).count();
190    let quarantine = all.iter().filter(|m| m.quarantined).count();
191    (total, unread, quarantine)
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn store_list_read_delete_roundtrip() {
200        // Isolate: only exercises pure helpers that don't need a special dir if app_meta works;
201        // use unique subject markers and clean up.
202        let marker = format!("test-subject-{}", now_unix());
203        let stored = store_delivery(
204            "a@b.example",
205            "frontdoor@c.example",
206            "frontdoor@c.example",
207            &marker,
208            "hello body",
209            "exact",
210            false,
211            1,
212            vec!["test".into()],
213        )
214        .expect("store");
215        assert!(!stored.id.is_empty());
216        assert!(list(None, true).iter().any(|m| m.id == stored.id));
217        let got = get(&stored.id).expect("get");
218        assert_eq!(got.subject, marker);
219        set_read(&stored.id, true).expect("read");
220        assert!(get(&stored.id).unwrap().read);
221        delete(&stored.id).expect("delete");
222        assert!(get(&stored.id).is_none());
223    }
224}