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    normalized_url(value).map(|_| ())
371}
372
373pub fn normalized_url(url: &str) -> Result<String> {
374    if url.bytes().any(|b| b.is_ascii_control()) {
375        bail!(DomainError::new(ErrorCode::InvalidUrl));
376    }
377    let mut parsed = reqwest::Url::parse(url).context(DomainError::new(ErrorCode::InvalidUrl))?;
378    if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
379        bail!(DomainError::new(ErrorCode::InvalidUrl));
380    }
381    parsed.set_fragment(None);
382    Ok(parsed.into())
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn subtitle_model_defaults_change_without_overriding_explicit_selections() {
391        let dir = tempfile::tempdir().unwrap();
392        let path = dir.path().join("config.toml");
393        for (text, model) in [
394            ("", "sensevoice-small-int8"),
395            (
396                "[subtitles]\nenabled=true\nlanguage='yue'\n",
397                "sensevoice-small-int8",
398            ),
399            (
400                "[subtitles]\nmodel='sensevoice-small-yue-int8'\nlanguage='yue'\n",
401                "sensevoice-small-yue-int8",
402            ),
403            (
404                "[subtitles]\nmodel='qwen3-asr-0.6b-int8'\n",
405                "qwen3-asr-0.6b-int8",
406            ),
407        ] {
408            fs::write(&path, text).unwrap();
409            let config = Config::load(Some(&path), Some(dir.path()), None).unwrap();
410            assert_eq!(config.settings.subtitles.model, model);
411            assert_eq!(fs::read_to_string(&path).unwrap(), text);
412            assert!(!dir.path().join("speech").exists());
413        }
414    }
415
416    #[test]
417    fn subtitles_reject_invalid_models_languages_and_resource_limits() {
418        for text in [
419            "model='unknown'",
420            "language='fr'",
421            "threads=33",
422            "max_segment_secs=1",
423            "max_segment_secs=21",
424            "model='qwen3-asr-0.6b-int8'\nlanguage='yue'",
425            "model_mirror=''",
426            "model_mirror='file:///tmp/models'",
427            "model_mirror='https://example.com/models?token=secret'",
428            "model_mirror='https://example.com/models#part'",
429        ] {
430            let settings: Settings = toml::from_str(&format!("[subtitles]\n{text}")).unwrap();
431            assert!(settings.subtitles.validate().is_err(), "{text}");
432        }
433        let settings: Settings = toml::from_str("[subtitles]\nlanguage='yue'\nthreads=2").unwrap();
434        settings.subtitles.validate().unwrap();
435        assert_eq!(settings.subtitles.effective_threads(), 2);
436        let settings: Settings =
437            toml::from_str("[subtitles]\nmodel_mirror='https://example.com/radio/models/'")
438                .unwrap();
439        settings.subtitles.validate().unwrap();
440        assert!(toml::from_str::<Settings>("[subtitles]\nthread=2").is_err());
441    }
442
443    #[test]
444    fn asiafm_metadata_patch_is_an_explicit_boolean_and_defaults_off() {
445        let example: Settings = toml::from_str(include_str!("../config.example.toml")).unwrap();
446        assert!(!example.asiafm_metadata_patch);
447        assert!(!Settings::default().asiafm_metadata_patch);
448        let settings: Settings = toml::from_str("asiafm_metadata_patch = true").unwrap();
449        assert!(settings.asiafm_metadata_patch);
450        assert!(
451            toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
452                .unwrap()
453                .asiafm_metadata_patch
454        );
455        assert!(toml::from_str::<Settings>("asiafm_metadata_patch = 'true'").is_err());
456    }
457
458    #[test]
459    fn artwork_modes_are_explicit_and_disabled_by_default() {
460        assert_eq!(Settings::default().artwork, ArtworkMode::Off);
461        for (value, expected) in [
462            ("off", ArtworkMode::Off),
463            ("station", ArtworkMode::Station),
464            ("track", ArtworkMode::Track),
465        ] {
466            let settings: Settings = toml::from_str(&format!("artwork = {value:?}")).unwrap();
467            assert_eq!(settings.artwork, expected);
468            assert_eq!(
469                toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
470                    .unwrap()
471                    .artwork,
472                expected
473            );
474        }
475        assert!(toml::from_str::<Settings>("artwork = true").is_err());
476    }
477
478    #[test]
479    fn resume_accepts_booleans_or_selection_and_round_trips() {
480        for (value, expected) in [
481            ("false", ResumeMode::Disabled),
482            ("true", ResumeMode::Playback),
483            ("\"selection\"", ResumeMode::Selection),
484        ] {
485            let settings: Settings = toml::from_str(&format!("resume = {value}")).unwrap();
486            assert_eq!(settings.resume, expected);
487            let saved = toml::to_string(&settings).unwrap();
488            assert_eq!(toml::from_str::<Settings>(&saved).unwrap().resume, expected);
489        }
490        for value in ["\"select\"", "\"true\"", "1", "[]"] {
491            assert!(toml::from_str::<Settings>(&format!("resume = {value}")).is_err());
492        }
493    }
494
495    #[test]
496    fn jump_bindings_accept_sequences_and_named_keys_but_reserve_exit() {
497        use crossterm::event::{KeyCode, KeyModifiers};
498        for binding in [
499            "''",
500            "gp",
501            "<F6>",
502            "<Ctrl-p>",
503            "<Alt-p>",
504            "<Shift-P>",
505            "<Space>",
506        ] {
507            assert!(parse_keybinding(binding).is_some(), "{binding}");
508        }
509        for binding in [
510            "",
511            "abcde",
512            "a b",
513            "\n",
514            "<F13>",
515            "<Hyper-p>",
516            "<Ctrl-c>",
517            "<Ctrl-C>",
518            "<foo",
519        ] {
520            assert!(parse_keybinding(binding).is_none(), "{binding}");
521        }
522        assert_eq!(
523            parse_keybinding("<Ctrl-p>"),
524            Some(vec![(KeyCode::Char('p'), KeyModifiers::CONTROL)])
525        );
526        assert_eq!(parse_keybinding("<Ctrl-P>"), parse_keybinding("<Ctrl-p>"));
527        assert_eq!(
528            parse_keybinding("<Ctrl-Shift-p>"),
529            parse_keybinding("<Ctrl-p>")
530        );
531        assert_eq!(
532            parse_keybinding("<Shift-Tab>"),
533            Some(vec![(KeyCode::BackTab, KeyModifiers::NONE)])
534        );
535        let dir = tempfile::tempdir().unwrap();
536        let path = dir.path().join("keys.toml");
537        fs::write(&path, "[keybindings]\njump_to_playing = '<F6>'\n").unwrap();
538        assert_eq!(
539            Config::load(Some(&path), Some(dir.path()), None)
540                .unwrap()
541                .settings
542                .keybindings
543                .jump_to_playing,
544            "<F6>"
545        );
546        fs::write(&path, "[keybindings]\njump_to_playing = '<Ctrl-c>'\n").unwrap();
547        assert!(Config::load(Some(&path), Some(dir.path()), None).is_err());
548        fs::write(&path, "[keybindings]\njump_to_playing = ''\n").unwrap();
549        assert!(Config::load(Some(&path), Some(dir.path()), None).is_ok());
550    }
551
552    #[test]
553    fn recording_reserve_rejects_zero_and_byte_overflow() {
554        let dir = tempfile::tempdir().unwrap();
555        let path = dir.path().join("config.toml");
556        for value in [0_u64, 1_u64 << 44] {
557            fs::write(&path, format!("recording_min_free_mb = {value}")).unwrap();
558            let error = Config::load(Some(&path), Some(dir.path()), None).unwrap_err();
559            assert_eq!(
560                error.downcast_ref::<DomainError>().unwrap().code,
561                ErrorCode::InvalidSettings
562            );
563        }
564        fs::write(&path, "recording_min_free_mb = 1").unwrap();
565        assert_eq!(
566            Config::load(Some(&path), Some(dir.path()), None)
567                .unwrap()
568                .settings
569                .recording_min_free_mb,
570            1
571        );
572    }
573}
574
575#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
576#[serde(default, deny_unknown_fields)]
577pub struct PodcastSettings {
578    pub country: Option<String>,
579    pub directory: Option<PathBuf>,
580    pub refresh_hours: u16,
581}
582impl Default for PodcastSettings {
583    fn default() -> Self {
584        Self {
585            country: None,
586            directory: None,
587            refresh_hours: 6,
588        }
589    }
590}