1use std::collections::BTreeMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::MacflyError;
8
9#[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 shortcuts: ShortcutsScopeConfig,
30 #[serde(default)]
31 pub dlp: DlpConfig,
32}
33
34#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35pub struct ShortcutsScopeConfig {
36 #[serde(default)]
38 pub allow: Vec<String>,
39}
40
41impl ShortcutsScopeConfig {
42 pub fn is_allowed(&self, name: &str) -> bool {
43 self.allow.iter().any(|a| a.eq_ignore_ascii_case(name))
44 }
45}
46
47#[derive(Debug, Clone, Default, Serialize, Deserialize)]
48pub struct NotesScopeConfig {
49 #[serde(default)]
51 pub allow_accounts: Vec<String>,
52 #[serde(default)]
54 pub allow_folders: Vec<String>,
55 #[serde(default = "default_deny_folders")]
57 pub deny_folders: Vec<String>,
58 #[serde(default = "default_true")]
60 pub skip_password_protected: bool,
61}
62
63#[derive(Debug, Clone, Default, Serialize, Deserialize)]
64pub struct MailScopeConfig {
65 #[serde(default)]
66 pub allow_accounts: Vec<String>,
67 #[serde(default)]
68 pub deny_mailboxes: Vec<String>,
69 #[serde(default)]
71 pub signature: MailSignatureConfig,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
75#[serde(tag = "source", rename_all = "kebab-case")]
76pub enum MailSignatureConfig {
77 AppleMail {
79 #[serde(default)]
81 name: Option<String>,
82 },
83 Inline { text: String },
85 None,
87}
88
89impl Default for MailSignatureConfig {
90 fn default() -> Self {
91 Self::AppleMail { name: None }
92 }
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct DlpConfig {
97 #[serde(default = "default_true")]
98 pub enabled: bool,
99 #[serde(default = "default_dlp_rules")]
100 pub redact: Vec<String>,
101 #[serde(default = "default_max_body_chars")]
102 pub max_body_chars: usize,
103}
104
105impl Default for DlpConfig {
106 fn default() -> Self {
107 Self {
108 enabled: true,
109 redact: default_dlp_rules(),
110 max_body_chars: default_max_body_chars(),
111 }
112 }
113}
114
115impl Default for ProfileConfig {
116 fn default() -> Self {
117 Self {
118 notes: NotesScopeConfig {
119 allow_accounts: Vec::new(),
120 allow_folders: Vec::new(),
121 deny_folders: default_deny_folders(),
122 skip_password_protected: true,
123 },
124 mail: MailScopeConfig::default(),
125 shortcuts: ShortcutsScopeConfig::default(),
126 dlp: DlpConfig::default(),
127 }
128 }
129}
130
131impl Default for Config {
132 fn default() -> Self {
133 Self {
134 schema_version: default_schema_version(),
135 default_profile: default_profile_name(),
136 script_timeout_secs: default_timeout_secs(),
137 profiles: default_profiles(),
138 }
139 }
140}
141
142impl Config {
143 pub fn default_path() -> PathBuf {
144 if let Ok(env_path) = std::env::var("MACFLY_CONFIG") {
145 return PathBuf::from(env_path);
146 }
147 if let Some(home) = dirs::home_dir() {
148 return home.join(".config").join("macfly").join("config.json");
149 }
150 PathBuf::from("macfly.config.json")
151 }
152
153 pub fn load_or_default(path: Option<&Path>) -> Result<(Self, PathBuf, bool), MacflyError> {
154 let cfg_path = path
155 .map(PathBuf::from)
156 .unwrap_or_else(Self::default_path);
157 if !cfg_path.exists() {
158 return Ok((Self::default(), cfg_path, false));
159 }
160 let raw = fs::read_to_string(&cfg_path).map_err(|e| MacflyError::ConfigError {
161 path: cfg_path.display().to_string(),
162 detail: e.to_string(),
163 })?;
164 let parsed: Self = serde_json::from_str(&raw).map_err(|e| MacflyError::ConfigError {
165 path: cfg_path.display().to_string(),
166 detail: e.to_string(),
167 })?;
168 Ok((parsed, cfg_path, true))
169 }
170
171 pub fn write_default(path: Option<&Path>, force: bool) -> Result<PathBuf, MacflyError> {
172 let cfg_path = path
173 .map(PathBuf::from)
174 .unwrap_or_else(Self::default_path);
175 if cfg_path.exists() && !force {
176 return Err(MacflyError::ConfigError {
177 path: cfg_path.display().to_string(),
178 detail: "Config existiert bereits (nutze --force zum Überschreiben)".to_string(),
179 });
180 }
181 if let Some(parent) = cfg_path.parent() {
182 fs::create_dir_all(parent)?;
183 }
184 let json = serde_json::to_string_pretty(&Self::default())?;
185 fs::write(&cfg_path, format!("{json}\n"))?;
186 Ok(cfg_path)
187 }
188
189 pub fn profile(&self, name: Option<&str>) -> Result<(&str, &ProfileConfig), MacflyError> {
190 let target = name.unwrap_or(&self.default_profile);
191 self.profiles
192 .get_key_value(target)
193 .map(|(k, p)| (k.as_str(), p))
194 .ok_or_else(|| MacflyError::ConfigError {
195 path: Self::default_path().display().to_string(),
196 detail: format!("Unbekanntes Profil '{target}'"),
197 })
198 }
199}
200
201impl NotesScopeConfig {
202 pub fn is_account_allowed(&self, account: &str) -> bool {
203 if self.allow_accounts.is_empty() {
204 return true;
205 }
206 self.allow_accounts
207 .iter()
208 .any(|a| a.eq_ignore_ascii_case(account))
209 }
210
211 pub fn is_folder_allowed(&self, folder: &str) -> bool {
212 if self
213 .deny_folders
214 .iter()
215 .any(|d| d.eq_ignore_ascii_case(folder))
216 {
217 return false;
218 }
219 if self.allow_folders.is_empty() {
220 return true;
221 }
222 self.allow_folders
223 .iter()
224 .any(|a| a.eq_ignore_ascii_case(folder))
225 }
226}
227
228impl MailScopeConfig {
229 pub fn is_account_allowed(&self, account: &str) -> bool {
230 if self.allow_accounts.is_empty() {
231 return true;
232 }
233 self.allow_accounts
234 .iter()
235 .any(|a| a.eq_ignore_ascii_case(account))
236 }
237
238 pub fn is_mailbox_allowed(&self, mailbox: &str) -> bool {
239 !self
240 .deny_mailboxes
241 .iter()
242 .any(|d| d.eq_ignore_ascii_case(mailbox))
243 }
244}
245
246pub fn data_dir() -> PathBuf {
247 if let Ok(env_dir) = std::env::var("MACFLY_DATA_DIR") {
248 return PathBuf::from(env_dir);
249 }
250 if let Some(home) = dirs::home_dir() {
251 return home.join(".local").join("share").join("macfly");
252 }
253 PathBuf::from(".macfly-data")
254}
255
256fn default_schema_version() -> String {
257 "1.0".to_string()
258}
259
260fn default_profile_name() -> String {
261 "default".to_string()
262}
263
264fn default_timeout_secs() -> u64 {
265 25
266}
267
268fn default_true() -> bool {
269 true
270}
271
272fn default_max_body_chars() -> usize {
273 12_000
274}
275
276fn default_deny_folders() -> Vec<String> {
277 vec![
278 "Passwörter".to_string(),
279 "Passwords".to_string(),
280 "Zuletzt gelöscht".to_string(),
281 "Recently Deleted".to_string(),
282 ]
283}
284
285fn default_dlp_rules() -> Vec<String> {
286 vec![
287 "private_key".to_string(),
288 "api_key".to_string(),
289 "iban".to_string(),
290 "credit_card".to_string(),
291 "otp_code".to_string(),
292 ]
293}
294
295fn default_profiles() -> BTreeMap<String, ProfileConfig> {
296 let mut map = BTreeMap::new();
297 map.insert("default".to_string(), ProfileConfig::default());
298 map
299}