1use serde::{Deserialize, Serialize};
4use std::fmt;
5use std::path::PathBuf;
6
7#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
9#[serde(rename_all = "lowercase")]
10pub enum AlbumArtMode {
11 #[default]
12 Image,
13 Halfblock,
14 Off,
15 #[serde(other)]
17 Other,
18}
19
20impl AlbumArtMode {
21 pub fn is_off(&self) -> bool {
23 *self == Self::Off
24 }
25}
26
27impl fmt::Display for AlbumArtMode {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 match self {
30 Self::Image | Self::Other => write!(f, "image"),
31 Self::Halfblock => write!(f, "halfblock"),
32 Self::Off => write!(f, "off"),
33 }
34 }
35}
36
37impl Serialize for AlbumArtMode {
39 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40 serializer.serialize_str(&self.to_string())
41 }
42}
43
44#[derive(Debug, Clone, Deserialize, Serialize)]
46#[serde(default)]
47pub struct Config {
48 #[serde(skip_serializing_if = "Option::is_none")]
50 pub default_group: Option<String>,
51 pub theme: String,
53 pub album_art_mode: AlbumArtMode,
55}
56
57impl Default for Config {
58 fn default() -> Self {
59 Self {
60 default_group: None,
61 theme: "default".to_string(),
62 album_art_mode: AlbumArtMode::default(),
63 }
64 }
65}
66
67fn config_path() -> Option<PathBuf> {
69 std::env::var("SONOS_CONFIG_DIR")
70 .ok()
71 .filter(|s| !s.is_empty())
72 .map(PathBuf::from)
73 .filter(|p| p.is_absolute())
74 .or_else(|| dirs::config_dir().map(|p| p.join("sonos")))
75 .map(|d| d.join("config.toml"))
76}
77
78impl Config {
79 pub fn load() -> Self {
81 let mut config: Config = config_path()
82 .and_then(|p| std::fs::read_to_string(p).ok())
83 .and_then(|s| toml::from_str(&s).ok())
84 .unwrap_or_default();
85
86 if let Ok(group) = std::env::var("SONOS_DEFAULT_GROUP") {
88 config.default_group = Some(group);
89 }
90
91 config
92 }
93
94 pub fn save(&self) -> anyhow::Result<()> {
96 let path =
97 config_path().ok_or_else(|| anyhow::anyhow!("cannot determine config directory"))?;
98 if let Some(dir) = path.parent() {
99 std::fs::create_dir_all(dir)?;
100 }
101 let content = toml::to_string_pretty(self)?;
102 std::fs::write(path, content)?;
103 Ok(())
104 }
105}