Skip to main content

qualia_client_core/
mail_accounts.rs

1//! Local registry for multiple interoperable mail accounts.
2//!
3//! Account configuration is cold-path user configuration. Imported messages
4//! always enter the single governed product inbox, while `account_id` and
5//! `label` stay with the import receipt so provenance is not discarded.
6
7use crate::mail_transport::{ImapConfig, Pop3Config, SmtpConfig};
8use crate::state::app_meta_dir;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeSet;
11use std::fs;
12
13const ACCOUNTS_FILE: &str = "mail_accounts.json";
14const MAX_ACCOUNTS: usize = 64;
15const POP3_RECEIPTS_FILE: &str = "mail_pop3_receipts.json";
16const MAX_POP3_RECEIPTS: usize = 20_000;
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct MailAccount {
20    pub id: String,
21    pub label: String,
22    pub address: String,
23    #[serde(default)]
24    pub smtp: Option<SmtpConfig>,
25    #[serde(default)]
26    pub imap: Option<ImapConfig>,
27    #[serde(default)]
28    pub pop3: Option<Pop3Config>,
29}
30
31fn path() -> std::path::PathBuf {
32    app_meta_dir().join(ACCOUNTS_FILE)
33}
34
35/// Lists.
36pub fn list() -> Vec<MailAccount> {
37    fs::read_to_string(path())
38        .ok()
39        .and_then(|text| serde_json::from_str(&text).ok())
40        .unwrap_or_default()
41}
42
43/// Saves.
44pub fn save(account: MailAccount) -> Result<Vec<MailAccount>, String> {
45    if account.id.trim().is_empty()
46        || account.label.trim().is_empty()
47        || !account.address.contains('@')
48    {
49        return Err("Each account needs an id, a label, and a mailbox address.".to_string());
50    }
51    if account.imap.is_none() && account.pop3.is_none() && account.smtp.is_none() {
52        return Err("Configure at least SMTP, IMAP, or POP3S for this account.".to_string());
53    }
54    let mut accounts = list();
55    if let Some(existing) = accounts.iter_mut().find(|item| item.id == account.id) {
56        *existing = account;
57    } else {
58        if accounts.len() >= MAX_ACCOUNTS {
59            return Err("The local account limit has been reached.".to_string());
60        }
61        accounts.push(account);
62    }
63    if let Some(parent) = path().parent() {
64        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65    }
66    fs::write(
67        path(),
68        serde_json::to_string_pretty(&accounts).map_err(|e| e.to_string())?,
69    )
70    .map_err(|e| e.to_string())?;
71    Ok(accounts)
72}
73
74/// Finds.
75pub fn find(id: &str) -> Option<MailAccount> {
76    list().into_iter().find(|account| account.id == id)
77}
78
79fn pop3_receipts_path() -> std::path::PathBuf {
80    app_meta_dir().join(POP3_RECEIPTS_FILE)
81}
82
83fn pop3_receipts() -> BTreeSet<String> {
84    fs::read_to_string(pop3_receipts_path())
85        .ok()
86        .and_then(|text| serde_json::from_str(&text).ok())
87        .unwrap_or_default()
88}
89
90/// POP3 has no standard unseen state. A UIDL receipt is therefore recorded
91/// locally once a fetched message has passed through delivery evaluation.
92pub fn has_pop3_receipt(account_id: &str, uid: &str) -> bool {
93    pop3_receipts().contains(&format!("{account_id}:{uid}"))
94}
95
96/// Records a POP3 receipt.
97pub fn record_pop3_receipt(account_id: &str, uid: &str) -> Result<(), String> {
98    let mut receipts = pop3_receipts();
99    receipts.insert(format!("{account_id}:{uid}"));
100    while receipts.len() > MAX_POP3_RECEIPTS {
101        let Some(oldest) = receipts.iter().next().cloned() else {
102            break;
103        };
104        receipts.remove(&oldest);
105    }
106    if let Some(parent) = pop3_receipts_path().parent() {
107        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
108    }
109    fs::write(
110        pop3_receipts_path(),
111        serde_json::to_string(&receipts).map_err(|e| e.to_string())?,
112    )
113    .map_err(|e| e.to_string())
114}