Skip to main content

radio_cli/
config.rs

1use crate::error::{DomainError, ErrorCode};
2use anyhow::{Context, Result, bail};
3use directories::ProjectDirs;
4use serde::{Deserialize, Serialize};
5use std::{
6    fs,
7    path::{Path, PathBuf},
8};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11#[serde(default, deny_unknown_fields)]
12pub struct Settings {
13    pub artwork: ArtworkMode,
14    pub keybindings: Keybindings,
15    pub mouse: bool,
16    pub theme: Theme,
17    pub recording_min_free_mb: u64,
18    pub auto_sync_days: u16,
19    pub resume: ResumeMode,
20    pub language: Option<String>,
21    pub api_url: Option<String>,
22    pub mpv: String,
23    pub normalize_loudness: bool,
24    pub audio_device: Option<String>,
25    pub ffmpeg: String,
26    pub ffprobe: String,
27    pub connect_timeout_secs: u64,
28    pub request_timeout_secs: u64,
29    pub playback_timeout_secs: u64,
30    pub probe_timeout_secs: u64,
31    pub volume: u8,
32    pub recording_dir: Option<PathBuf>,
33}
34
35impl Default for Settings {
36    fn default() -> Self {
37        Self {
38            artwork: ArtworkMode::Off,
39            keybindings: Keybindings::default(),
40            mouse: true,
41            theme: Theme::Default,
42            recording_min_free_mb: 16,
43            auto_sync_days: 7,
44            resume: ResumeMode::Disabled,
45            language: None,
46            api_url: None,
47            mpv: "mpv".into(),
48            normalize_loudness: false,
49            audio_device: None,
50            ffmpeg: "ffmpeg".into(),
51            ffprobe: "ffprobe".into(),
52            connect_timeout_secs: 5,
53            request_timeout_secs: 20,
54            playback_timeout_secs: 12,
55            probe_timeout_secs: 5,
56            volume: 80,
57            recording_dir: None,
58        }
59    }
60}
61
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "lowercase")]
64pub enum ArtworkMode {
65    #[default]
66    Off,
67    Station,
68    Track,
69}
70
71#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
72pub enum ResumeMode {
73    #[default]
74    Disabled,
75    Selection,
76    Playback,
77}
78
79impl Serialize for ResumeMode {
80    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
81        match self {
82            Self::Disabled => serializer.serialize_bool(false),
83            Self::Playback => serializer.serialize_bool(true),
84            Self::Selection => serializer.serialize_str("selection"),
85        }
86    }
87}
88
89impl<'de> Deserialize<'de> for ResumeMode {
90    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
91        #[derive(Deserialize)]
92        #[serde(untagged)]
93        enum Value {
94            Boolean(bool),
95            Text(String),
96        }
97        match Value::deserialize(deserializer)? {
98            Value::Boolean(false) => Ok(Self::Disabled),
99            Value::Boolean(true) => Ok(Self::Playback),
100            Value::Text(value) if value == "selection" => Ok(Self::Selection),
101            _ => Err(serde::de::Error::custom(
102                "expected false, true, or \"selection\"",
103            )),
104        }
105    }
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
109#[serde(default, deny_unknown_fields)]
110pub struct Keybindings {
111    pub jump_to_playing: String,
112}
113impl Default for Keybindings {
114    fn default() -> Self {
115        Self {
116            jump_to_playing: "''".into(),
117        }
118    }
119}
120
121/// Printable sequences (up to four keys), or a named key with optional modifiers.
122pub(crate) fn parse_keybinding(
123    value: &str,
124) -> Option<Vec<(crossterm::event::KeyCode, crossterm::event::KeyModifiers)>> {
125    use crossterm::event::{KeyCode, KeyModifiers};
126    if let Some(named) = value.strip_prefix('<').and_then(|v| v.strip_suffix('>')) {
127        let mut parts = named.split('-');
128        let mut modifiers = KeyModifiers::NONE;
129        while parts.clone().count() > 1 {
130            modifiers |= match parts.next()?.to_ascii_lowercase().as_str() {
131                "ctrl" => KeyModifiers::CONTROL,
132                "alt" => KeyModifiers::ALT,
133                "shift" => KeyModifiers::SHIFT,
134                _ => return None,
135            };
136        }
137        let name = parts.next()?;
138        let code = match name.to_ascii_lowercase().as_str() {
139            "space" => KeyCode::Char(' '),
140            "home" => KeyCode::Home,
141            "end" => KeyCode::End,
142            "enter" => KeyCode::Enter,
143            "tab" => KeyCode::Tab,
144            "left" => KeyCode::Left,
145            "right" => KeyCode::Right,
146            "up" => KeyCode::Up,
147            "down" => KeyCode::Down,
148            s if s.starts_with('f') && s.len() > 1 => {
149                let number = s[1..].parse::<u8>().ok()?;
150                if !(1..=12).contains(&number) {
151                    return None;
152                }
153                KeyCode::F(number)
154            }
155            _ if name.chars().count() == 1 => KeyCode::Char(name.chars().next()?),
156            _ => return None,
157        };
158        if matches!(code, KeyCode::Char('c' | 'C')) && modifiers.contains(KeyModifiers::CONTROL) {
159            return None;
160        }
161        if code == KeyCode::Tab && modifiers.contains(KeyModifiers::SHIFT) {
162            modifiers.remove(KeyModifiers::SHIFT);
163            return Some(vec![(KeyCode::BackTab, modifiers)]);
164        }
165        if let KeyCode::Char(c) = code {
166            let c = if modifiers.contains(KeyModifiers::CONTROL) {
167                c.to_ascii_lowercase()
168            } else if modifiers.contains(KeyModifiers::SHIFT) {
169                c.to_ascii_uppercase()
170            } else {
171                c
172            };
173            modifiers.remove(KeyModifiers::SHIFT);
174            return Some(vec![(KeyCode::Char(c), modifiers)]);
175        }
176        Some(vec![(code, modifiers)])
177    } else if !value.starts_with('<')
178        && (1..=4).contains(&value.chars().count())
179        && value.chars().all(|c| !c.is_control() && !c.is_whitespace())
180    {
181        Some(
182            value
183                .chars()
184                .map(|c| (KeyCode::Char(c), KeyModifiers::NONE))
185                .collect(),
186        )
187    } else {
188        None
189    }
190}
191
192#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "lowercase")]
194pub enum Theme {
195    #[default]
196    Default,
197    Mono,
198    Light,
199}
200
201impl Theme {
202    pub fn effective(self, no_color: bool) -> Self {
203        if no_color { Self::Mono } else { self }
204    }
205}
206
207#[derive(Debug, Clone)]
208pub struct Config {
209    pub settings: Settings,
210    pub config_path: PathBuf,
211    pub data_dir: PathBuf,
212    pub runtime_dir: PathBuf,
213    pub recording_dir: PathBuf,
214}
215
216impl Config {
217    pub fn load(
218        config_path: Option<&Path>,
219        data_dir: Option<&Path>,
220        api: Option<&str>,
221    ) -> Result<Self> {
222        let dirs = ProjectDirs::from("", "", "radio-cli")
223            .context(DomainError::new(ErrorCode::DataDirectory))?;
224        let path = config_path
225            .map(PathBuf::from)
226            .unwrap_or_else(|| dirs.config_dir().join("config.toml"));
227        let mut settings: Settings = match fs::read_to_string(&path) {
228            Ok(text) => toml::from_str(&text).with_context(|| {
229                DomainError::new(ErrorCode::InvalidConfig).with("path", path.display())
230            })?,
231            Err(e) if e.kind() == std::io::ErrorKind::NotFound && config_path.is_none() => {
232                Settings::default()
233            }
234            Err(e) => {
235                return Err(e).with_context(|| {
236                    DomainError::new(ErrorCode::ReadConfig).with("path", path.display())
237                });
238            }
239        };
240        if let Some(api) = api {
241            settings.api_url = Some(api.to_owned());
242        }
243        if (!settings.keybindings.jump_to_playing.is_empty()
244            && parse_keybinding(&settings.keybindings.jump_to_playing).is_none())
245            || settings.recording_min_free_mb == 0
246            || settings
247                .recording_min_free_mb
248                .checked_mul(1024 * 1024)
249                .is_none()
250            || settings.volume > 100
251            || settings
252                .audio_device
253                .as_ref()
254                .is_some_and(|value| value.chars().any(char::is_control))
255            || settings.connect_timeout_secs == 0
256            || settings.request_timeout_secs == 0
257            || settings.playback_timeout_secs == 0
258            || settings.probe_timeout_secs == 0
259            || settings.connect_timeout_secs > 300
260            || settings.request_timeout_secs > 300
261            || settings.playback_timeout_secs > 300
262            || settings.probe_timeout_secs > 300
263        {
264            bail!(DomainError::new(ErrorCode::InvalidSettings));
265        }
266        if let Some(api) = &settings.api_url {
267            validate_url(api)?;
268        }
269        let data_dir = data_dir
270            .map(PathBuf::from)
271            .unwrap_or_else(|| dirs.data_dir().to_path_buf());
272        let data_dir = std::path::absolute(data_dir)?;
273        let recording_dir = settings
274            .recording_dir
275            .clone()
276            .unwrap_or_else(|| data_dir.join("recordings"));
277        let recording_dir = std::path::absolute(recording_dir)?;
278        let runtime_dir = data_dir.join("run");
279        Ok(Self {
280            settings,
281            config_path: path,
282            data_dir,
283            runtime_dir,
284            recording_dir,
285        })
286    }
287
288    pub fn prepare(&self) -> Result<()> {
289        fs::create_dir_all(&self.data_dir)?;
290        fs::create_dir_all(&self.runtime_dir)?;
291        use std::os::unix::fs::PermissionsExt;
292        fs::set_permissions(&self.runtime_dir, fs::Permissions::from_mode(0o700))?;
293        Ok(())
294    }
295}
296
297pub fn validate_url(value: &str) -> Result<()> {
298    let url = reqwest::Url::parse(value).context(DomainError::new(ErrorCode::InvalidUrl))?;
299    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
300        bail!(DomainError::new(ErrorCode::InvalidUrl));
301    }
302    Ok(())
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308
309    #[test]
310    fn artwork_modes_are_explicit_and_disabled_by_default() {
311        assert_eq!(Settings::default().artwork, ArtworkMode::Off);
312        for (value, expected) in [
313            ("off", ArtworkMode::Off),
314            ("station", ArtworkMode::Station),
315            ("track", ArtworkMode::Track),
316        ] {
317            let settings: Settings = toml::from_str(&format!("artwork = {value:?}")).unwrap();
318            assert_eq!(settings.artwork, expected);
319            assert_eq!(
320                toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
321                    .unwrap()
322                    .artwork,
323                expected
324            );
325        }
326        assert!(toml::from_str::<Settings>("artwork = true").is_err());
327    }
328
329    #[test]
330    fn resume_accepts_booleans_or_selection_and_round_trips() {
331        for (value, expected) in [
332            ("false", ResumeMode::Disabled),
333            ("true", ResumeMode::Playback),
334            ("\"selection\"", ResumeMode::Selection),
335        ] {
336            let settings: Settings = toml::from_str(&format!("resume = {value}")).unwrap();
337            assert_eq!(settings.resume, expected);
338            let saved = toml::to_string(&settings).unwrap();
339            assert_eq!(toml::from_str::<Settings>(&saved).unwrap().resume, expected);
340        }
341        for value in ["\"select\"", "\"true\"", "1", "[]"] {
342            assert!(toml::from_str::<Settings>(&format!("resume = {value}")).is_err());
343        }
344    }
345
346    #[test]
347    fn jump_bindings_accept_sequences_and_named_keys_but_reserve_exit() {
348        use crossterm::event::{KeyCode, KeyModifiers};
349        for binding in [
350            "''",
351            "gp",
352            "<F6>",
353            "<Ctrl-p>",
354            "<Alt-p>",
355            "<Shift-P>",
356            "<Space>",
357        ] {
358            assert!(parse_keybinding(binding).is_some(), "{binding}");
359        }
360        for binding in [
361            "",
362            "abcde",
363            "a b",
364            "\n",
365            "<F13>",
366            "<Hyper-p>",
367            "<Ctrl-c>",
368            "<Ctrl-C>",
369            "<foo",
370        ] {
371            assert!(parse_keybinding(binding).is_none(), "{binding}");
372        }
373        assert_eq!(
374            parse_keybinding("<Ctrl-p>"),
375            Some(vec![(KeyCode::Char('p'), KeyModifiers::CONTROL)])
376        );
377        assert_eq!(parse_keybinding("<Ctrl-P>"), parse_keybinding("<Ctrl-p>"));
378        assert_eq!(
379            parse_keybinding("<Ctrl-Shift-p>"),
380            parse_keybinding("<Ctrl-p>")
381        );
382        assert_eq!(
383            parse_keybinding("<Shift-Tab>"),
384            Some(vec![(KeyCode::BackTab, KeyModifiers::NONE)])
385        );
386        let dir = tempfile::tempdir().unwrap();
387        let path = dir.path().join("keys.toml");
388        fs::write(&path, "[keybindings]\njump_to_playing = '<F6>'\n").unwrap();
389        assert_eq!(
390            Config::load(Some(&path), Some(dir.path()), None)
391                .unwrap()
392                .settings
393                .keybindings
394                .jump_to_playing,
395            "<F6>"
396        );
397        fs::write(&path, "[keybindings]\njump_to_playing = '<Ctrl-c>'\n").unwrap();
398        assert!(Config::load(Some(&path), Some(dir.path()), None).is_err());
399        fs::write(&path, "[keybindings]\njump_to_playing = ''\n").unwrap();
400        assert!(Config::load(Some(&path), Some(dir.path()), None).is_ok());
401    }
402
403    #[test]
404    fn recording_reserve_rejects_zero_and_byte_overflow() {
405        let dir = tempfile::tempdir().unwrap();
406        let path = dir.path().join("config.toml");
407        for value in [0_u64, 1_u64 << 44] {
408            fs::write(&path, format!("recording_min_free_mb = {value}")).unwrap();
409            let error = Config::load(Some(&path), Some(dir.path()), None).unwrap_err();
410            assert_eq!(
411                error.downcast_ref::<DomainError>().unwrap().code,
412                ErrorCode::InvalidSettings
413            );
414        }
415        fs::write(&path, "recording_min_free_mb = 1").unwrap();
416        assert_eq!(
417            Config::load(Some(&path), Some(dir.path()), None)
418                .unwrap()
419                .settings
420                .recording_min_free_mb,
421            1
422        );
423    }
424}