1use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7pub mod credentials;
8
9#[derive(Clone, Serialize, Deserialize)]
11pub struct AppConfig {
12 pub theme: AppTheme,
13 pub thumbnail_size: u32,
14 pub face_detection_confidence: f32,
15 pub face_clustering_threshold: f32,
16 pub burst_time_window_seconds: i64,
17 pub trash_auto_delete_days: u32,
18 pub scan_hidden_folders: bool,
19 #[serde(default = "default_true")]
22 pub scan_on_open: bool,
23 #[serde(default = "default_show_timeline_stacks")]
24 pub show_timeline_stacks: bool,
25 pub date_format: DateFormat,
26 pub remembered_drives: Vec<PathBuf>,
27 pub window_width: u32,
28 pub window_height: u32,
29 #[serde(default)]
32 pub window_maximized: bool,
33 pub sidebar_collapsed: bool,
34
35 #[serde(default = "default_map_cache_limit_mb")]
36 pub map_cache_limit_mb: u32,
37
38 #[serde(default = "default_weight_cooccurrence")]
41 pub weight_cooccurrence: f32,
42
43 #[serde(default = "default_weight_temporal")]
45 pub weight_temporal: f32,
46
47 #[serde(default = "default_memories_enabled")]
49 pub memories_enabled: bool,
50
51 #[serde(default)]
54 pub home_city_override: Option<String>,
55
56 #[serde(default)]
59 pub last_view: Option<String>,
60
61 #[serde(default)]
66 pub auto_update_check_enabled: bool,
67
68 #[serde(default)]
71 pub last_update_check_at_unix: Option<i64>,
72
73 #[serde(default = "default_show_first_run_update_prompt")]
76 pub show_first_run_update_prompt: bool,
77
78 #[serde(default)]
85 pub date_logic_version: u32,
86
87 #[serde(default)]
91 pub geonames_warning_seen: bool,
92
93 #[serde(default = "default_thumbnail_cache_gb")]
98 pub thumbnail_cache_gb: f64,
99
100 #[serde(default)]
102 pub face_gpu_bridge_url: Option<String>,
103
104 #[serde(default)]
106 pub face_gpu_bridge_enabled: bool,
107
108 #[serde(default)]
111 pub local_caches: std::collections::HashMap<String, std::path::PathBuf>,
112
113 #[serde(default)]
116 pub config_version: u32,
117
118 #[serde(default = "default_face_embedder_model")]
121 pub face_embedder_model: String,
122
123 #[serde(default = "default_assistant_enabled")]
126 pub assistant_enabled: bool,
127
128 #[serde(default)]
131 pub ai_features_enabled: bool,
132
133 #[serde(default = "default_assistant_provider")]
137 pub assistant_provider: String,
138
139 #[serde(default = "default_assistant_base_url")]
141 pub assistant_base_url: String,
142
143 #[serde(default = "default_assistant_model")]
145 pub assistant_model: String,
146
147 #[serde(default)]
149 #[serde(skip_serializing)]
150 pub assistant_api_key: Option<String>,
151}
152
153pub const CURRENT_DATE_LOGIC_VERSION: u32 = 2;
168
169fn default_show_first_run_update_prompt() -> bool {
170 true
171}
172
173fn default_weight_cooccurrence() -> f32 {
174 0.30
175}
176
177fn default_weight_temporal() -> f32 {
178 0.50
179}
180
181fn default_memories_enabled() -> bool {
182 true
183}
184
185fn default_map_cache_limit_mb() -> u32 {
186 500
187}
188
189fn default_thumbnail_cache_gb() -> f64 {
190 5.0
191}
192
193fn default_true() -> bool {
194 true
195}
196
197fn default_show_timeline_stacks() -> bool {
198 true
199}
200
201fn default_face_embedder_model() -> String {
202 "adaface_ir101_webface12m.onnx".to_string()
203}
204
205fn default_assistant_enabled() -> bool {
206 false
207}
208
209fn default_assistant_provider() -> String {
210 "openai_compatible".to_string()
211}
212
213fn default_assistant_base_url() -> String {
214 "https://openrouter.ai/api/v1".to_string()
215}
216
217fn default_assistant_model() -> String {
218 "deepseek/deepseek-v4-flash".to_string()
219}
220
221impl Default for AppConfig {
222 fn default() -> Self {
223 Self {
224 theme: AppTheme::Dark,
225 thumbnail_size: 500,
226 face_detection_confidence: 0.25,
227 face_clustering_threshold: 0.30,
228 burst_time_window_seconds: 3,
229 trash_auto_delete_days: 30,
230 scan_hidden_folders: false,
231 scan_on_open: true,
232 show_timeline_stacks: true,
233 date_format: DateFormat::Locale,
234 remembered_drives: Vec::new(),
235 window_width: 1600,
236 window_height: 1000,
237 window_maximized: false,
238 sidebar_collapsed: false,
239 map_cache_limit_mb: default_map_cache_limit_mb(),
240 weight_cooccurrence: default_weight_cooccurrence(),
241 weight_temporal: default_weight_temporal(),
242 memories_enabled: default_memories_enabled(),
243 home_city_override: None,
244 last_view: None,
245 auto_update_check_enabled: false,
246 last_update_check_at_unix: None,
247 show_first_run_update_prompt: true,
248 date_logic_version: 0,
249 geonames_warning_seen: false,
250 thumbnail_cache_gb: default_thumbnail_cache_gb(),
251 local_caches: Default::default(),
252 config_version: 4,
253 face_embedder_model: default_face_embedder_model(),
254 assistant_enabled: false,
255 ai_features_enabled: false,
256 assistant_provider: default_assistant_provider(),
257 assistant_base_url: default_assistant_base_url(),
258 assistant_model: default_assistant_model(),
259 assistant_api_key: None,
260 face_gpu_bridge_url: None,
261 face_gpu_bridge_enabled: false,
262 }
263 }
264}
265
266impl std::fmt::Debug for AppConfig {
267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268 f.debug_struct("AppConfig")
269 .field("theme", &self.theme)
270 .field("assistant_api_key_set", &self.assistant_api_key.is_some())
271 .finish_non_exhaustive()
272 }
273}
274
275impl AppConfig {
276 pub fn load() -> Self {
278 let mut cfg = Self::load_from_disk();
279 if cfg.assistant_api_key.is_none() {
280 cfg.assistant_api_key = credentials::load();
281 }
282 cfg
283 }
284
285 fn load_from_disk() -> Self {
286 let path = Self::config_path();
287 let read_path = if path.exists() {
290 path
291 } else {
292 let legacy = Self::legacy_config_path();
293 if legacy.exists() {
294 legacy
295 } else {
296 return Self::default();
297 }
298 };
299
300 match std::fs::read_to_string(&read_path) {
301 Ok(content) => match serde_json::from_str::<Self>(&content) {
302 Ok(mut cfg) => {
303 cfg.validate();
304 cfg.migrate_config_defaults();
305 cfg
306 }
307 Err(e) => {
308 tracing::warn!("Failed to parse config {}: {}", read_path.display(), e);
309 Self::default()
310 }
311 },
312 Err(e) => {
313 tracing::warn!("Failed to read config {}: {}", read_path.display(), e);
314 Self::default()
315 }
316 }
317 }
318
319 fn migrate_config_defaults(&mut self) {
322 if self.config_version < 1 {
323 if (self.face_clustering_threshold - 0.42).abs() < 0.001 {
326 self.face_clustering_threshold = 0.28;
327 }
328 self.config_version = 1;
329 }
330 if self.config_version < 2 {
331 if (self.face_clustering_threshold - 0.28).abs() < 0.001 {
333 self.face_clustering_threshold = 0.30;
334 }
335 self.config_version = 2;
336 }
337 if self.config_version < 3 {
338 self.face_embedder_model = default_face_embedder_model();
339 self.config_version = 3;
340 }
341 if self.config_version < 4 {
342 if self.assistant_provider == "local" {
343 self.assistant_provider = default_assistant_provider();
344 }
345 if self.assistant_base_url == "https://api.openai.com/v1" {
346 self.assistant_base_url = default_assistant_base_url();
347 }
348 if self.assistant_model == "gpt-4.1-mini" {
349 self.assistant_model = default_assistant_model();
350 }
351 self.config_version = 4;
352 }
353 }
354
355 pub fn validate(&mut self) {
357 if let Some(ref url) = self.face_gpu_bridge_url {
360 if !is_allowed_gpu_bridge_url(url) {
361 tracing::warn!(
362 "Invalid face_gpu_bridge_url — must use https:// or local http://. Disabling."
363 );
364 self.face_gpu_bridge_url = None;
365 self.face_gpu_bridge_enabled = false;
366 }
367 }
368
369 if !self.face_detection_confidence.is_finite() {
370 self.face_detection_confidence = Self::default().face_detection_confidence;
371 }
372 if !self.face_clustering_threshold.is_finite() {
373 self.face_clustering_threshold = Self::default().face_clustering_threshold;
374 }
375 if !self.weight_cooccurrence.is_finite() {
376 self.weight_cooccurrence = default_weight_cooccurrence();
377 }
378 if !self.weight_temporal.is_finite() {
379 self.weight_temporal = default_weight_temporal();
380 }
381 if !self.thumbnail_cache_gb.is_finite() {
382 self.thumbnail_cache_gb = default_thumbnail_cache_gb();
383 }
384
385 self.face_detection_confidence = self.face_detection_confidence.clamp(0.1, 0.95);
386 self.face_clustering_threshold = self.face_clustering_threshold.clamp(0.1, 0.8);
387 self.thumbnail_size = self.thumbnail_size.clamp(100, 1000);
388 self.burst_time_window_seconds = self.burst_time_window_seconds.clamp(1, 30);
389 self.trash_auto_delete_days = self.trash_auto_delete_days.clamp(1, 365);
390 self.window_width = self.window_width.clamp(400, 7680);
391 self.window_height = self.window_height.clamp(300, 4320);
392 self.weight_cooccurrence = self.weight_cooccurrence.clamp(0.0, 2.0);
393 self.weight_temporal = self.weight_temporal.clamp(0.0, 2.0);
394 self.map_cache_limit_mb = self.map_cache_limit_mb.clamp(50, 10_000);
395 self.thumbnail_cache_gb = self.thumbnail_cache_gb.clamp(0.5, 100.0);
396 if self.face_embedder_model != default_face_embedder_model() {
397 self.face_embedder_model = default_face_embedder_model();
398 }
399 if !matches!(
400 self.assistant_provider.as_str(),
401 "local" | "openai_compatible"
402 ) {
403 self.assistant_provider = default_assistant_provider();
404 }
405 if !is_allowed_assistant_url(&self.assistant_base_url) {
406 self.assistant_base_url = default_assistant_base_url();
407 }
408 if self.assistant_model.trim().is_empty() {
409 self.assistant_model = default_assistant_model();
410 }
411 if self
412 .assistant_api_key
413 .as_deref()
414 .is_some_and(|s| s.trim().is_empty())
415 {
416 self.assistant_api_key = None;
417 }
418 }
419
420 pub fn save(&self) -> std::io::Result<()> {
422 let path = Self::config_path();
423 if let Some(parent) = path.parent() {
424 std::fs::create_dir_all(parent)?;
425 }
426 let content = serde_json::to_string_pretty(self)?;
427 use std::io::Write;
428 let mut staged =
429 tempfile::NamedTempFile::new_in(path.parent().expect("config has a parent"))?;
430 staged.write_all(content.as_bytes())?;
431 staged.as_file().sync_all()?;
432 if let Some(key) = self.assistant_api_key.as_deref() {
435 credentials::store(Some(key))?;
436 }
437 staged.persist(path).map_err(|error| error.error)?;
438 Ok(())
439 }
440
441 pub fn config_path() -> PathBuf {
443 dirs::config_dir()
444 .unwrap_or_else(|| PathBuf::from("."))
445 .join("smriti")
446 .join("config.json")
447 }
448
449 fn legacy_config_path() -> PathBuf {
453 dirs::config_dir()
454 .unwrap_or_else(|| PathBuf::from("."))
455 .join("photovault")
456 .join("config.json")
457 }
458}
459
460pub fn is_allowed_assistant_url(value: &str) -> bool {
461 let Ok(url) = reqwest::Url::parse(value) else {
462 return false;
463 };
464 if !url.username().is_empty() || url.password().is_some() || url.host().is_none() {
465 return false;
466 }
467 let host = url.host_str().unwrap_or("");
468 let loopback = host == "localhost"
469 || host
470 .trim_matches(['[', ']'])
471 .parse::<std::net::IpAddr>()
472 .is_ok_and(|ip| ip.is_loopback());
473 url.scheme() == "https" || (url.scheme() == "http" && loopback)
474}
475
476pub fn is_allowed_gpu_bridge_url(url: &str) -> bool {
477 is_allowed_assistant_url(url)
478}
479
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
482#[serde(rename_all = "lowercase")]
483pub enum AppTheme {
484 Dark,
485 Light,
486 System,
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
491#[serde(rename_all = "lowercase")]
492pub enum DateFormat {
493 Locale,
494 Iso,
495 Us,
496 Eu,
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502
503 #[test]
504 fn credentials_are_never_serialized_or_debugged_but_legacy_keys_can_be_read() {
505 let cfg = AppConfig {
506 assistant_api_key: Some("private-key".into()),
507 ..Default::default()
508 };
509 assert!(!format!("{cfg:?}").contains("private-key"));
510 let mut json = serde_json::to_value(&cfg).unwrap();
511 assert!(json.get("assistant_api_key").is_none());
512 json["assistant_api_key"] = serde_json::json!("legacy-key");
513 let legacy: AppConfig = serde_json::from_value(json).unwrap();
514 assert_eq!(legacy.assistant_api_key.as_deref(), Some("legacy-key"));
515 }
516
517 #[test]
518 fn validate_forces_adaface_embedder() {
519 let mut cfg = AppConfig {
520 face_embedder_model: "legacy.onnx".to_string(),
521 ..Default::default()
522 };
523
524 cfg.validate();
525
526 assert_eq!(cfg.face_embedder_model, default_face_embedder_model());
527 }
528
529 #[test]
530 fn validate_replaces_non_finite_numeric_settings() {
531 let mut cfg = AppConfig {
532 face_detection_confidence: f32::NAN,
533 face_clustering_threshold: f32::INFINITY,
534 weight_cooccurrence: f32::NEG_INFINITY,
535 weight_temporal: f32::NAN,
536 thumbnail_cache_gb: f64::NAN,
537 ..Default::default()
538 };
539
540 cfg.validate();
541
542 assert_eq!(
543 cfg.face_detection_confidence,
544 AppConfig::default().face_detection_confidence
545 );
546 assert_eq!(
547 cfg.face_clustering_threshold,
548 AppConfig::default().face_clustering_threshold
549 );
550 assert_eq!(cfg.weight_cooccurrence, default_weight_cooccurrence());
551 assert_eq!(cfg.weight_temporal, default_weight_temporal());
552 assert_eq!(cfg.thumbnail_cache_gb, default_thumbnail_cache_gb());
553 }
554
555 #[test]
556 fn config_migration_forces_adaface_embedder() {
557 let mut cfg = AppConfig {
558 config_version: 2,
559 face_embedder_model: "legacy.onnx".to_string(),
560 ..Default::default()
561 };
562
563 cfg.migrate_config_defaults();
564
565 assert_eq!(cfg.config_version, 4);
566 assert_eq!(cfg.face_embedder_model, default_face_embedder_model());
567 }
568}