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