Skip to main content

macfly_core/
config.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::MacflyError;
8
9/// Single Point of Truth: `~/.config/macfly/config.json` (oder `$MACFLY_CONFIG`).
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Config {
12    #[serde(default = "default_schema_version")]
13    pub schema_version: String,
14    #[serde(default = "default_profile_name")]
15    pub default_profile: String,
16    #[serde(default = "default_timeout_secs")]
17    pub script_timeout_secs: u64,
18    #[serde(default = "default_profiles")]
19    pub profiles: BTreeMap<String, ProfileConfig>,
20}
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct ProfileConfig {
24    #[serde(default)]
25    pub notes: NotesScopeConfig,
26    #[serde(default)]
27    pub mail: MailScopeConfig,
28    #[serde(default)]
29    pub dlp: DlpConfig,
30}
31
32#[derive(Debug, Clone, Default, Serialize, Deserialize)]
33pub struct NotesScopeConfig {
34    /// Wenn nicht leer, sind nur diese Accounts erlaubt.
35    #[serde(default)]
36    pub allow_accounts: Vec<String>,
37    /// Wenn nicht leer, sind nur diese Ordnernamen erlaubt.
38    #[serde(default)]
39    pub allow_folders: Vec<String>,
40    /// Ordner, die niemals gelesen/ausgegeben werden (z. B. "Passwörter", "Privat").
41    #[serde(default = "default_deny_folders")]
42    pub deny_folders: Vec<String>,
43    /// Passwortgeschützte Apple-Notizen standardmäßig überspringen.
44    #[serde(default = "default_true")]
45    pub skip_password_protected: bool,
46}
47
48#[derive(Debug, Clone, Default, Serialize, Deserialize)]
49pub struct MailScopeConfig {
50    #[serde(default)]
51    pub allow_accounts: Vec<String>,
52    #[serde(default)]
53    pub deny_mailboxes: Vec<String>,
54    /// Single Point of Truth für Footer/Signaturen: direkt aus Apple Mail beziehen.
55    #[serde(default)]
56    pub signature: MailSignatureConfig,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[serde(tag = "source", rename_all = "kebab-case")]
61pub enum MailSignatureConfig {
62    /// Bezieht die Signatur direkt aus Apple Mail (kein doppelter Footer in der Config nötig).
63    AppleMail {
64        /// Optionaler Name der Signatur in Apple Mail; wenn None, wird die Standard-Signatur verwendet.
65        #[serde(default)]
66        name: Option<String>,
67    },
68    /// Optionaler expliziter Override, falls für KI-Antworten ein abweichender Footer gewünscht ist.
69    Inline { text: String },
70    /// Kein Footer anhängen.
71    None,
72}
73
74impl Default for MailSignatureConfig {
75    fn default() -> Self {
76        Self::AppleMail { name: None }
77    }
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct DlpConfig {
82    #[serde(default = "default_true")]
83    pub enabled: bool,
84    #[serde(default = "default_dlp_rules")]
85    pub redact: Vec<String>,
86    #[serde(default = "default_max_body_chars")]
87    pub max_body_chars: usize,
88}
89
90impl Default for DlpConfig {
91    fn default() -> Self {
92        Self {
93            enabled: true,
94            redact: default_dlp_rules(),
95            max_body_chars: default_max_body_chars(),
96        }
97    }
98}
99
100impl Default for ProfileConfig {
101    fn default() -> Self {
102        Self {
103            notes: NotesScopeConfig {
104                allow_accounts: Vec::new(),
105                allow_folders: Vec::new(),
106                deny_folders: default_deny_folders(),
107                skip_password_protected: true,
108            },
109            mail: MailScopeConfig::default(),
110            dlp: DlpConfig::default(),
111        }
112    }
113}
114
115impl Default for Config {
116    fn default() -> Self {
117        Self {
118            schema_version: default_schema_version(),
119            default_profile: default_profile_name(),
120            script_timeout_secs: default_timeout_secs(),
121            profiles: default_profiles(),
122        }
123    }
124}
125
126impl Config {
127    pub fn default_path() -> PathBuf {
128        if let Ok(env_path) = std::env::var("MACFLY_CONFIG") {
129            return PathBuf::from(env_path);
130        }
131        if let Some(home) = dirs::home_dir() {
132            return home.join(".config").join("macfly").join("config.json");
133        }
134        PathBuf::from("macfly.config.json")
135    }
136
137    pub fn load_or_default(path: Option<&Path>) -> Result<(Self, PathBuf, bool), MacflyError> {
138        let cfg_path = path
139            .map(PathBuf::from)
140            .unwrap_or_else(Self::default_path);
141        if !cfg_path.exists() {
142            return Ok((Self::default(), cfg_path, false));
143        }
144        let raw = fs::read_to_string(&cfg_path).map_err(|e| MacflyError::ConfigError {
145            path: cfg_path.display().to_string(),
146            detail: e.to_string(),
147        })?;
148        let parsed: Self = serde_json::from_str(&raw).map_err(|e| MacflyError::ConfigError {
149            path: cfg_path.display().to_string(),
150            detail: e.to_string(),
151        })?;
152        Ok((parsed, cfg_path, true))
153    }
154
155    pub fn write_default(path: Option<&Path>, force: bool) -> Result<PathBuf, MacflyError> {
156        let cfg_path = path
157            .map(PathBuf::from)
158            .unwrap_or_else(Self::default_path);
159        if cfg_path.exists() && !force {
160            return Err(MacflyError::ConfigError {
161                path: cfg_path.display().to_string(),
162                detail: "Config existiert bereits (nutze --force zum Überschreiben)".to_string(),
163            });
164        }
165        if let Some(parent) = cfg_path.parent() {
166            fs::create_dir_all(parent)?;
167        }
168        let json = serde_json::to_string_pretty(&Self::default())?;
169        fs::write(&cfg_path, format!("{json}\n"))?;
170        Ok(cfg_path)
171    }
172
173    pub fn profile(&self, name: Option<&str>) -> Result<(&str, &ProfileConfig), MacflyError> {
174        let target = name.unwrap_or(&self.default_profile);
175        self.profiles
176            .get_key_value(target)
177            .map(|(k, p)| (k.as_str(), p))
178            .ok_or_else(|| MacflyError::ConfigError {
179                path: Self::default_path().display().to_string(),
180                detail: format!("Unbekanntes Profil '{target}'"),
181            })
182    }
183}
184
185impl NotesScopeConfig {
186    pub fn is_account_allowed(&self, account: &str) -> bool {
187        if self.allow_accounts.is_empty() {
188            return true;
189        }
190        self.allow_accounts
191            .iter()
192            .any(|a| a.eq_ignore_ascii_case(account))
193    }
194
195    pub fn is_folder_allowed(&self, folder: &str) -> bool {
196        if self
197            .deny_folders
198            .iter()
199            .any(|d| d.eq_ignore_ascii_case(folder))
200        {
201            return false;
202        }
203        if self.allow_folders.is_empty() {
204            return true;
205        }
206        self.allow_folders
207            .iter()
208            .any(|a| a.eq_ignore_ascii_case(folder))
209    }
210}
211
212impl MailScopeConfig {
213    pub fn is_account_allowed(&self, account: &str) -> bool {
214        if self.allow_accounts.is_empty() {
215            return true;
216        }
217        self.allow_accounts
218            .iter()
219            .any(|a| a.eq_ignore_ascii_case(account))
220    }
221
222    pub fn is_mailbox_allowed(&self, mailbox: &str) -> bool {
223        !self
224            .deny_mailboxes
225            .iter()
226            .any(|d| d.eq_ignore_ascii_case(mailbox))
227    }
228}
229
230pub fn data_dir() -> PathBuf {
231    if let Ok(env_dir) = std::env::var("MACFLY_DATA_DIR") {
232        return PathBuf::from(env_dir);
233    }
234    if let Some(home) = dirs::home_dir() {
235        return home.join(".local").join("share").join("macfly");
236    }
237    PathBuf::from(".macfly-data")
238}
239
240fn default_schema_version() -> String {
241    "1.0".to_string()
242}
243
244fn default_profile_name() -> String {
245    "default".to_string()
246}
247
248fn default_timeout_secs() -> u64 {
249    25
250}
251
252fn default_true() -> bool {
253    true
254}
255
256fn default_max_body_chars() -> usize {
257    12_000
258}
259
260fn default_deny_folders() -> Vec<String> {
261    vec![
262        "Passwörter".to_string(),
263        "Passwords".to_string(),
264        "Zuletzt gelöscht".to_string(),
265        "Recently Deleted".to_string(),
266    ]
267}
268
269fn default_dlp_rules() -> Vec<String> {
270    vec![
271        "private_key".to_string(),
272        "api_key".to_string(),
273        "iban".to_string(),
274        "credit_card".to_string(),
275        "otp_code".to_string(),
276    ]
277}
278
279fn default_profiles() -> BTreeMap<String, ProfileConfig> {
280    let mut map = BTreeMap::new();
281    map.insert("default".to_string(), ProfileConfig::default());
282    map
283}