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 subtitles: SubtitleSettings,
14    pub artwork: ArtworkMode,
15    pub keybindings: Keybindings,
16    pub mouse: bool,
17    pub theme: Theme,
18    pub recording_min_free_mb: u64,
19    pub auto_sync_days: u16,
20    pub resume: ResumeMode,
21    pub language: Option<String>,
22    pub api_url: Option<String>,
23    pub mpv: String,
24    pub normalize_loudness: bool,
25    pub asiafm_metadata_patch: bool,
26    pub audio_device: Option<String>,
27    pub ffmpeg: String,
28    pub ffprobe: String,
29    pub connect_timeout_secs: u64,
30    pub request_timeout_secs: u64,
31    pub playback_timeout_secs: u64,
32    pub probe_timeout_secs: u64,
33    pub volume: u8,
34    pub recording_dir: Option<PathBuf>,
35}
36
37impl Default for Settings {
38    fn default() -> Self {
39        Self {
40            subtitles: SubtitleSettings::default(),
41            artwork: ArtworkMode::Off,
42            keybindings: Keybindings::default(),
43            mouse: true,
44            theme: Theme::Default,
45            recording_min_free_mb: 16,
46            auto_sync_days: 7,
47            resume: ResumeMode::Disabled,
48            language: None,
49            api_url: None,
50            mpv: "mpv".into(),
51            normalize_loudness: false,
52            asiafm_metadata_patch: false,
53            audio_device: None,
54            ffmpeg: "ffmpeg".into(),
55            ffprobe: "ffprobe".into(),
56            connect_timeout_secs: 5,
57            request_timeout_secs: 20,
58            playback_timeout_secs: 12,
59            probe_timeout_secs: 5,
60            volume: 80,
61            recording_dir: None,
62        }
63    }
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
67#[serde(default, deny_unknown_fields)]
68pub struct SubtitleSettings {
69    pub enabled: bool,
70    pub model: String,
71    pub language: String,
72    pub threads: u8,
73    pub max_segment_secs: u8,
74    pub uv: String,
75    pub model_mirror: Option<String>,
76}
77
78impl Default for SubtitleSettings {
79    fn default() -> Self {
80        Self {
81            enabled: false,
82            model: "sensevoice-small-int8".into(),
83            language: "auto".into(),
84            threads: 0,
85            max_segment_secs: 8,
86            uv: "uv".into(),
87            model_mirror: None,
88        }
89    }
90}
91
92impl SubtitleSettings {
93    pub fn validate(&self) -> Result<()> {
94        let mirror_valid = self.model_mirror.as_ref().is_none_or(|value| {
95            reqwest::Url::parse(value).is_ok_and(|url| {
96                matches!(url.scheme(), "http" | "https")
97                    && url.host_str().is_some()
98                    && url.query().is_none()
99                    && url.fragment().is_none()
100            })
101        });
102        if !matches!(
103            self.model.as_str(),
104            "sensevoice-small-int8" | "sensevoice-small-yue-int8" | "qwen3-asr-0.6b-int8"
105        ) || !matches!(
106            self.language.as_str(),
107            "auto" | "zh" | "yue" | "en" | "ja" | "ko"
108        ) || (self.model == "qwen3-asr-0.6b-int8" && self.language != "auto")
109            || self.threads > 32
110            || !(2..=20).contains(&self.max_segment_secs)
111            || self.uv.trim().is_empty()
112            || !mirror_valid
113        {
114            bail!(DomainError::new(ErrorCode::SubtitleSettings));
115        }
116        Ok(())
117    }
118
119    pub fn effective_threads(&self) -> usize {
120        if self.threads == 0 {
121            (std::thread::available_parallelism().map_or(2, usize::from) / 2).clamp(1, 4)
122        } else {
123            usize::from(self.threads)
124        }
125    }
126}
127
128#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
129#[serde(rename_all = "lowercase")]
130pub enum ArtworkMode {
131    #[default]
132    Off,
133    Station,
134    Track,
135}
136
137#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
138pub enum ResumeMode {
139    #[default]
140    Disabled,
141    Selection,
142    Playback,
143}
144
145impl Serialize for ResumeMode {
146    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
147        match self {
148            Self::Disabled => serializer.serialize_bool(false),
149            Self::Playback => serializer.serialize_bool(true),
150            Self::Selection => serializer.serialize_str("selection"),
151        }
152    }
153}
154
155impl<'de> Deserialize<'de> for ResumeMode {
156    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
157        #[derive(Deserialize)]
158        #[serde(untagged)]
159        enum Value {
160            Boolean(bool),
161            Text(String),
162        }
163        match Value::deserialize(deserializer)? {
164            Value::Boolean(false) => Ok(Self::Disabled),
165            Value::Boolean(true) => Ok(Self::Playback),
166            Value::Text(value) if value == "selection" => Ok(Self::Selection),
167            _ => Err(serde::de::Error::custom(
168                "expected false, true, or \"selection\"",
169            )),
170        }
171    }
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize)]
175#[serde(default, deny_unknown_fields)]
176pub struct Keybindings {
177    pub jump_to_playing: String,
178}
179impl Default for Keybindings {
180    fn default() -> Self {
181        Self {
182            jump_to_playing: "''".into(),
183        }
184    }
185}
186
187/// Printable sequences (up to four keys), or a named key with optional modifiers.
188pub(crate) fn parse_keybinding(
189    value: &str,
190) -> Option<Vec<(crossterm::event::KeyCode, crossterm::event::KeyModifiers)>> {
191    use crossterm::event::{KeyCode, KeyModifiers};
192    if let Some(named) = value.strip_prefix('<').and_then(|v| v.strip_suffix('>')) {
193        let mut parts = named.split('-');
194        let mut modifiers = KeyModifiers::NONE;
195        while parts.clone().count() > 1 {
196            modifiers |= match parts.next()?.to_ascii_lowercase().as_str() {
197                "ctrl" => KeyModifiers::CONTROL,
198                "alt" => KeyModifiers::ALT,
199                "shift" => KeyModifiers::SHIFT,
200                _ => return None,
201            };
202        }
203        let name = parts.next()?;
204        let code = match name.to_ascii_lowercase().as_str() {
205            "space" => KeyCode::Char(' '),
206            "home" => KeyCode::Home,
207            "end" => KeyCode::End,
208            "enter" => KeyCode::Enter,
209            "tab" => KeyCode::Tab,
210            "left" => KeyCode::Left,
211            "right" => KeyCode::Right,
212            "up" => KeyCode::Up,
213            "down" => KeyCode::Down,
214            s if s.starts_with('f') && s.len() > 1 => {
215                let number = s[1..].parse::<u8>().ok()?;
216                if !(1..=12).contains(&number) {
217                    return None;
218                }
219                KeyCode::F(number)
220            }
221            _ if name.chars().count() == 1 => KeyCode::Char(name.chars().next()?),
222            _ => return None,
223        };
224        if matches!(code, KeyCode::Char('c' | 'C')) && modifiers.contains(KeyModifiers::CONTROL) {
225            return None;
226        }
227        if code == KeyCode::Tab && modifiers.contains(KeyModifiers::SHIFT) {
228            modifiers.remove(KeyModifiers::SHIFT);
229            return Some(vec![(KeyCode::BackTab, modifiers)]);
230        }
231        if let KeyCode::Char(c) = code {
232            let c = if modifiers.contains(KeyModifiers::CONTROL) {
233                c.to_ascii_lowercase()
234            } else if modifiers.contains(KeyModifiers::SHIFT) {
235                c.to_ascii_uppercase()
236            } else {
237                c
238            };
239            modifiers.remove(KeyModifiers::SHIFT);
240            return Some(vec![(KeyCode::Char(c), modifiers)]);
241        }
242        Some(vec![(code, modifiers)])
243    } else if !value.starts_with('<')
244        && (1..=4).contains(&value.chars().count())
245        && value.chars().all(|c| !c.is_control() && !c.is_whitespace())
246    {
247        Some(
248            value
249                .chars()
250                .map(|c| (KeyCode::Char(c), KeyModifiers::NONE))
251                .collect(),
252        )
253    } else {
254        None
255    }
256}
257
258#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(rename_all = "lowercase")]
260pub enum Theme {
261    #[default]
262    Default,
263    Mono,
264    Light,
265}
266
267impl Theme {
268    pub fn effective(self, no_color: bool) -> Self {
269        if no_color { Self::Mono } else { self }
270    }
271}
272
273#[derive(Debug, Clone)]
274pub struct Config {
275    pub settings: Settings,
276    pub config_path: PathBuf,
277    pub data_dir: PathBuf,
278    pub runtime_dir: PathBuf,
279    pub recording_dir: PathBuf,
280}
281
282impl Config {
283    pub fn load(
284        config_path: Option<&Path>,
285        data_dir: Option<&Path>,
286        api: Option<&str>,
287    ) -> Result<Self> {
288        let dirs = ProjectDirs::from("", "", "radio-cli")
289            .context(DomainError::new(ErrorCode::DataDirectory))?;
290        let path = config_path
291            .map(PathBuf::from)
292            .unwrap_or_else(|| dirs.config_dir().join("config.toml"));
293        let mut settings: Settings = match fs::read_to_string(&path) {
294            Ok(text) => toml::from_str(&text).with_context(|| {
295                DomainError::new(ErrorCode::InvalidConfig).with("path", path.display())
296            })?,
297            Err(e) if e.kind() == std::io::ErrorKind::NotFound && config_path.is_none() => {
298                Settings::default()
299            }
300            Err(e) => {
301                return Err(e).with_context(|| {
302                    DomainError::new(ErrorCode::ReadConfig).with("path", path.display())
303                });
304            }
305        };
306        if let Some(api) = api {
307            settings.api_url = Some(api.to_owned());
308        }
309        settings.subtitles.validate()?;
310        if (!settings.keybindings.jump_to_playing.is_empty()
311            && parse_keybinding(&settings.keybindings.jump_to_playing).is_none())
312            || settings.recording_min_free_mb == 0
313            || settings
314                .recording_min_free_mb
315                .checked_mul(1024 * 1024)
316                .is_none()
317            || settings.volume > 100
318            || settings
319                .audio_device
320                .as_ref()
321                .is_some_and(|value| value.chars().any(char::is_control))
322            || settings.connect_timeout_secs == 0
323            || settings.request_timeout_secs == 0
324            || settings.playback_timeout_secs == 0
325            || settings.probe_timeout_secs == 0
326            || settings.connect_timeout_secs > 300
327            || settings.request_timeout_secs > 300
328            || settings.playback_timeout_secs > 300
329            || settings.probe_timeout_secs > 300
330        {
331            bail!(DomainError::new(ErrorCode::InvalidSettings));
332        }
333        if let Some(api) = &settings.api_url {
334            validate_url(api)?;
335        }
336        let data_dir = data_dir
337            .map(PathBuf::from)
338            .unwrap_or_else(|| dirs.data_dir().to_path_buf());
339        let data_dir = std::path::absolute(data_dir)?;
340        let recording_dir = settings
341            .recording_dir
342            .clone()
343            .unwrap_or_else(|| data_dir.join("recordings"));
344        let recording_dir = std::path::absolute(recording_dir)?;
345        let runtime_dir = data_dir.join("run");
346        Ok(Self {
347            settings,
348            config_path: path,
349            data_dir,
350            runtime_dir,
351            recording_dir,
352        })
353    }
354
355    pub fn prepare(&self) -> Result<()> {
356        fs::create_dir_all(&self.data_dir)?;
357        fs::create_dir_all(&self.runtime_dir)?;
358        use std::os::unix::fs::PermissionsExt;
359        fs::set_permissions(&self.runtime_dir, fs::Permissions::from_mode(0o700))?;
360        Ok(())
361    }
362}
363
364pub fn validate_url(value: &str) -> Result<()> {
365    let url = reqwest::Url::parse(value).context(DomainError::new(ErrorCode::InvalidUrl))?;
366    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
367        bail!(DomainError::new(ErrorCode::InvalidUrl));
368    }
369    Ok(())
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn subtitle_model_defaults_change_without_overriding_explicit_selections() {
378        let dir = tempfile::tempdir().unwrap();
379        let path = dir.path().join("config.toml");
380        for (text, model) in [
381            ("", "sensevoice-small-int8"),
382            (
383                "[subtitles]\nenabled=true\nlanguage='yue'\n",
384                "sensevoice-small-int8",
385            ),
386            (
387                "[subtitles]\nmodel='sensevoice-small-yue-int8'\nlanguage='yue'\n",
388                "sensevoice-small-yue-int8",
389            ),
390            (
391                "[subtitles]\nmodel='qwen3-asr-0.6b-int8'\n",
392                "qwen3-asr-0.6b-int8",
393            ),
394        ] {
395            fs::write(&path, text).unwrap();
396            let config = Config::load(Some(&path), Some(dir.path()), None).unwrap();
397            assert_eq!(config.settings.subtitles.model, model);
398            assert_eq!(fs::read_to_string(&path).unwrap(), text);
399            assert!(!dir.path().join("speech").exists());
400        }
401    }
402
403    #[test]
404    fn subtitles_reject_invalid_models_languages_and_resource_limits() {
405        for text in [
406            "model='unknown'",
407            "language='fr'",
408            "threads=33",
409            "max_segment_secs=1",
410            "max_segment_secs=21",
411            "model='qwen3-asr-0.6b-int8'\nlanguage='yue'",
412            "model_mirror=''",
413            "model_mirror='file:///tmp/models'",
414            "model_mirror='https://example.com/models?token=secret'",
415            "model_mirror='https://example.com/models#part'",
416        ] {
417            let settings: Settings = toml::from_str(&format!("[subtitles]\n{text}")).unwrap();
418            assert!(settings.subtitles.validate().is_err(), "{text}");
419        }
420        let settings: Settings = toml::from_str("[subtitles]\nlanguage='yue'\nthreads=2").unwrap();
421        settings.subtitles.validate().unwrap();
422        assert_eq!(settings.subtitles.effective_threads(), 2);
423        let settings: Settings =
424            toml::from_str("[subtitles]\nmodel_mirror='https://example.com/radio/models/'")
425                .unwrap();
426        settings.subtitles.validate().unwrap();
427        assert!(toml::from_str::<Settings>("[subtitles]\nthread=2").is_err());
428    }
429
430    #[test]
431    fn asiafm_metadata_patch_is_an_explicit_boolean_and_defaults_off() {
432        let example: Settings = toml::from_str(include_str!("../config.example.toml")).unwrap();
433        assert!(!example.asiafm_metadata_patch);
434        assert!(!Settings::default().asiafm_metadata_patch);
435        let settings: Settings = toml::from_str("asiafm_metadata_patch = true").unwrap();
436        assert!(settings.asiafm_metadata_patch);
437        assert!(
438            toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
439                .unwrap()
440                .asiafm_metadata_patch
441        );
442        assert!(toml::from_str::<Settings>("asiafm_metadata_patch = 'true'").is_err());
443    }
444
445    #[test]
446    fn artwork_modes_are_explicit_and_disabled_by_default() {
447        assert_eq!(Settings::default().artwork, ArtworkMode::Off);
448        for (value, expected) in [
449            ("off", ArtworkMode::Off),
450            ("station", ArtworkMode::Station),
451            ("track", ArtworkMode::Track),
452        ] {
453            let settings: Settings = toml::from_str(&format!("artwork = {value:?}")).unwrap();
454            assert_eq!(settings.artwork, expected);
455            assert_eq!(
456                toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
457                    .unwrap()
458                    .artwork,
459                expected
460            );
461        }
462        assert!(toml::from_str::<Settings>("artwork = true").is_err());
463    }
464
465    #[test]
466    fn resume_accepts_booleans_or_selection_and_round_trips() {
467        for (value, expected) in [
468            ("false", ResumeMode::Disabled),
469            ("true", ResumeMode::Playback),
470            ("\"selection\"", ResumeMode::Selection),
471        ] {
472            let settings: Settings = toml::from_str(&format!("resume = {value}")).unwrap();
473            assert_eq!(settings.resume, expected);
474            let saved = toml::to_string(&settings).unwrap();
475            assert_eq!(toml::from_str::<Settings>(&saved).unwrap().resume, expected);
476        }
477        for value in ["\"select\"", "\"true\"", "1", "[]"] {
478            assert!(toml::from_str::<Settings>(&format!("resume = {value}")).is_err());
479        }
480    }
481
482    #[test]
483    fn jump_bindings_accept_sequences_and_named_keys_but_reserve_exit() {
484        use crossterm::event::{KeyCode, KeyModifiers};
485        for binding in [
486            "''",
487            "gp",
488            "<F6>",
489            "<Ctrl-p>",
490            "<Alt-p>",
491            "<Shift-P>",
492            "<Space>",
493        ] {
494            assert!(parse_keybinding(binding).is_some(), "{binding}");
495        }
496        for binding in [
497            "",
498            "abcde",
499            "a b",
500            "\n",
501            "<F13>",
502            "<Hyper-p>",
503            "<Ctrl-c>",
504            "<Ctrl-C>",
505            "<foo",
506        ] {
507            assert!(parse_keybinding(binding).is_none(), "{binding}");
508        }
509        assert_eq!(
510            parse_keybinding("<Ctrl-p>"),
511            Some(vec![(KeyCode::Char('p'), KeyModifiers::CONTROL)])
512        );
513        assert_eq!(parse_keybinding("<Ctrl-P>"), parse_keybinding("<Ctrl-p>"));
514        assert_eq!(
515            parse_keybinding("<Ctrl-Shift-p>"),
516            parse_keybinding("<Ctrl-p>")
517        );
518        assert_eq!(
519            parse_keybinding("<Shift-Tab>"),
520            Some(vec![(KeyCode::BackTab, KeyModifiers::NONE)])
521        );
522        let dir = tempfile::tempdir().unwrap();
523        let path = dir.path().join("keys.toml");
524        fs::write(&path, "[keybindings]\njump_to_playing = '<F6>'\n").unwrap();
525        assert_eq!(
526            Config::load(Some(&path), Some(dir.path()), None)
527                .unwrap()
528                .settings
529                .keybindings
530                .jump_to_playing,
531            "<F6>"
532        );
533        fs::write(&path, "[keybindings]\njump_to_playing = '<Ctrl-c>'\n").unwrap();
534        assert!(Config::load(Some(&path), Some(dir.path()), None).is_err());
535        fs::write(&path, "[keybindings]\njump_to_playing = ''\n").unwrap();
536        assert!(Config::load(Some(&path), Some(dir.path()), None).is_ok());
537    }
538
539    #[test]
540    fn recording_reserve_rejects_zero_and_byte_overflow() {
541        let dir = tempfile::tempdir().unwrap();
542        let path = dir.path().join("config.toml");
543        for value in [0_u64, 1_u64 << 44] {
544            fs::write(&path, format!("recording_min_free_mb = {value}")).unwrap();
545            let error = Config::load(Some(&path), Some(dir.path()), None).unwrap_err();
546            assert_eq!(
547                error.downcast_ref::<DomainError>().unwrap().code,
548                ErrorCode::InvalidSettings
549            );
550        }
551        fs::write(&path, "recording_min_free_mb = 1").unwrap();
552        assert_eq!(
553            Config::load(Some(&path), Some(dir.path()), None)
554                .unwrap()
555                .settings
556                .recording_min_free_mb,
557            1
558        );
559    }
560}