Skip to main content

sonos_cli/
config.rs

1//! Configuration system for the sonos-cli application.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::fmt;
6use std::path::PathBuf;
7
8/// Album art rendering mode.
9#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum AlbumArtMode {
12    #[default]
13    Image,
14    Halfblock,
15    Off,
16    /// Catch-all for unrecognized values (e.g. old "auto") — behaves like Image.
17    #[serde(other)]
18    Other,
19}
20
21impl AlbumArtMode {
22    /// Returns true when album art should be disabled.
23    pub fn is_off(&self) -> bool {
24        *self == Self::Off
25    }
26}
27
28impl fmt::Display for AlbumArtMode {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            Self::Image | Self::Other => write!(f, "image"),
32            Self::Halfblock => write!(f, "halfblock"),
33            Self::Off => write!(f, "off"),
34        }
35    }
36}
37
38/// Custom Serialize: `Other` normalizes to `"image"` on save.
39impl Serialize for AlbumArtMode {
40    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41        serializer.serialize_str(&self.to_string())
42    }
43}
44
45/// User configuration loaded from config file with environment variable overrides.
46#[derive(Debug, Clone, Deserialize, Serialize)]
47#[serde(default)]
48pub struct Config {
49    /// Default group to target when --speaker/--group not specified
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub default_group: Option<String>,
52    /// TUI color theme: "default", "bw", "minimal", or "dance_party"
53    pub theme: String,
54    /// Album art rendering mode: "image", "halfblock", or "off"
55    pub album_art_mode: AlbumArtMode,
56    /// Speaker/group aliases: key = full name, value = short alias
57    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
58    pub aliases: HashMap<String, String>,
59}
60
61impl Default for Config {
62    fn default() -> Self {
63        Self {
64            default_group: None,
65            theme: "default".to_string(),
66            album_art_mode: AlbumArtMode::default(),
67            aliases: HashMap::new(),
68        }
69    }
70}
71
72/// Return the path to the config file.
73fn config_path() -> Option<PathBuf> {
74    std::env::var("SONOS_CONFIG_DIR")
75        .ok()
76        .filter(|s| !s.is_empty())
77        .map(PathBuf::from)
78        .filter(|p| p.is_absolute())
79        .or_else(|| dirs::config_dir().map(|p| p.join("sonos")))
80        .map(|d| d.join("config.toml"))
81}
82
83impl Config {
84    /// Load from config file with environment variable overrides.
85    pub fn load() -> Self {
86        let mut config: Config = config_path()
87            .and_then(|p| std::fs::read_to_string(p).ok())
88            .and_then(|s| toml::from_str(&s).ok())
89            .unwrap_or_default();
90
91        // Environment variable overrides
92        if let Ok(group) = std::env::var("SONOS_DEFAULT_GROUP") {
93            config.default_group = Some(group);
94        }
95
96        config
97    }
98
99    /// Persist the current config to disk.
100    pub fn save(&self) -> anyhow::Result<()> {
101        let path =
102            config_path().ok_or_else(|| anyhow::anyhow!("cannot determine config directory"))?;
103        if let Some(dir) = path.parent() {
104            std::fs::create_dir_all(dir)?;
105        }
106        let content = toml::to_string_pretty(self)?;
107        std::fs::write(path, content)?;
108        Ok(())
109    }
110
111    /// Resolve an alias to the full speaker/group name.
112    /// If `input` matches an alias value, returns the corresponding key (full name).
113    /// Otherwise returns `input` unchanged.
114    pub fn resolve_alias<'a>(&'a self, input: &'a str) -> &'a str {
115        for (name, alias) in &self.aliases {
116            if alias.eq_ignore_ascii_case(input) {
117                return name;
118            }
119        }
120        input
121    }
122
123    /// Set or replace an alias for a speaker/group name.
124    pub fn set_alias(&mut self, name: &str, alias: &str) {
125        self.aliases.insert(name.to_string(), alias.to_string());
126    }
127
128    /// Clear the alias for a speaker/group name. Returns the old alias if one existed.
129    pub fn clear_alias(&mut self, name: &str) -> Option<String> {
130        self.aliases.remove(name)
131    }
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    #[test]
139    fn resolve_alias_returns_full_name() {
140        let mut config = Config::default();
141        config.set_alias("Master Bedroom", "bed");
142        assert_eq!(config.resolve_alias("bed"), "Master Bedroom");
143    }
144
145    #[test]
146    fn resolve_alias_passthrough_when_no_match() {
147        let config = Config::default();
148        assert_eq!(config.resolve_alias("Kitchen"), "Kitchen");
149    }
150
151    #[test]
152    fn set_alias_replaces_existing() {
153        let mut config = Config::default();
154        config.set_alias("Master Bedroom", "bed");
155        config.set_alias("Master Bedroom", "mb");
156        assert_eq!(config.resolve_alias("mb"), "Master Bedroom");
157        assert_eq!(config.resolve_alias("bed"), "bed");
158    }
159
160    #[test]
161    fn clear_alias_removes_and_returns_old() {
162        let mut config = Config::default();
163        config.set_alias("Master Bedroom", "bed");
164        let old = config.clear_alias("Master Bedroom");
165        assert_eq!(old, Some("bed".to_string()));
166        assert_eq!(config.resolve_alias("bed"), "bed");
167    }
168
169    #[test]
170    fn clear_alias_returns_none_when_absent() {
171        let mut config = Config::default();
172        assert_eq!(config.clear_alias("Kitchen"), None);
173    }
174
175    #[test]
176    fn aliases_roundtrip_through_toml() {
177        let mut config = Config::default();
178        config.set_alias("Master Bedroom", "bed");
179        config.set_alias("Kitchen", "kit");
180        let serialized = toml::to_string_pretty(&config).unwrap();
181        let deserialized: Config = toml::from_str(&serialized).unwrap();
182        assert_eq!(deserialized.resolve_alias("bed"), "Master Bedroom");
183        assert_eq!(deserialized.resolve_alias("kit"), "Kitchen");
184    }
185
186    #[test]
187    fn empty_aliases_not_serialized() {
188        let config = Config::default();
189        let serialized = toml::to_string_pretty(&config).unwrap();
190        assert!(!serialized.contains("[aliases]"));
191    }
192
193    #[test]
194    fn resolve_alias_case_insensitive() {
195        let mut config = Config::default();
196        config.set_alias("Master Bedroom", "bed");
197        assert_eq!(config.resolve_alias("Bed"), "Master Bedroom");
198        assert_eq!(config.resolve_alias("BED"), "Master Bedroom");
199        assert_eq!(config.resolve_alias("bed"), "Master Bedroom");
200    }
201}