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-yue-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-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
187pub(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 subtitles_reject_invalid_models_languages_and_resource_limits() {
378 for text in [
379 "model='unknown'",
380 "language='fr'",
381 "threads=33",
382 "max_segment_secs=1",
383 "max_segment_secs=21",
384 "model='qwen3-asr-0.6b-int8'\nlanguage='yue'",
385 "model_mirror=''",
386 "model_mirror='file:///tmp/models'",
387 "model_mirror='https://example.com/models?token=secret'",
388 "model_mirror='https://example.com/models#part'",
389 ] {
390 let settings: Settings = toml::from_str(&format!("[subtitles]\n{text}")).unwrap();
391 assert!(settings.subtitles.validate().is_err(), "{text}");
392 }
393 let settings: Settings = toml::from_str("[subtitles]\nlanguage='yue'\nthreads=2").unwrap();
394 settings.subtitles.validate().unwrap();
395 assert_eq!(settings.subtitles.effective_threads(), 2);
396 let settings: Settings =
397 toml::from_str("[subtitles]\nmodel_mirror='https://example.com/radio/models/'")
398 .unwrap();
399 settings.subtitles.validate().unwrap();
400 assert!(toml::from_str::<Settings>("[subtitles]\nthread=2").is_err());
401 }
402
403 #[test]
404 fn asiafm_metadata_patch_is_an_explicit_boolean_and_defaults_off() {
405 let example: Settings = toml::from_str(include_str!("../config.example.toml")).unwrap();
406 assert!(!example.asiafm_metadata_patch);
407 assert!(!Settings::default().asiafm_metadata_patch);
408 let settings: Settings = toml::from_str("asiafm_metadata_patch = true").unwrap();
409 assert!(settings.asiafm_metadata_patch);
410 assert!(
411 toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
412 .unwrap()
413 .asiafm_metadata_patch
414 );
415 assert!(toml::from_str::<Settings>("asiafm_metadata_patch = 'true'").is_err());
416 }
417
418 #[test]
419 fn artwork_modes_are_explicit_and_disabled_by_default() {
420 assert_eq!(Settings::default().artwork, ArtworkMode::Off);
421 for (value, expected) in [
422 ("off", ArtworkMode::Off),
423 ("station", ArtworkMode::Station),
424 ("track", ArtworkMode::Track),
425 ] {
426 let settings: Settings = toml::from_str(&format!("artwork = {value:?}")).unwrap();
427 assert_eq!(settings.artwork, expected);
428 assert_eq!(
429 toml::from_str::<Settings>(&toml::to_string(&settings).unwrap())
430 .unwrap()
431 .artwork,
432 expected
433 );
434 }
435 assert!(toml::from_str::<Settings>("artwork = true").is_err());
436 }
437
438 #[test]
439 fn resume_accepts_booleans_or_selection_and_round_trips() {
440 for (value, expected) in [
441 ("false", ResumeMode::Disabled),
442 ("true", ResumeMode::Playback),
443 ("\"selection\"", ResumeMode::Selection),
444 ] {
445 let settings: Settings = toml::from_str(&format!("resume = {value}")).unwrap();
446 assert_eq!(settings.resume, expected);
447 let saved = toml::to_string(&settings).unwrap();
448 assert_eq!(toml::from_str::<Settings>(&saved).unwrap().resume, expected);
449 }
450 for value in ["\"select\"", "\"true\"", "1", "[]"] {
451 assert!(toml::from_str::<Settings>(&format!("resume = {value}")).is_err());
452 }
453 }
454
455 #[test]
456 fn jump_bindings_accept_sequences_and_named_keys_but_reserve_exit() {
457 use crossterm::event::{KeyCode, KeyModifiers};
458 for binding in [
459 "''",
460 "gp",
461 "<F6>",
462 "<Ctrl-p>",
463 "<Alt-p>",
464 "<Shift-P>",
465 "<Space>",
466 ] {
467 assert!(parse_keybinding(binding).is_some(), "{binding}");
468 }
469 for binding in [
470 "",
471 "abcde",
472 "a b",
473 "\n",
474 "<F13>",
475 "<Hyper-p>",
476 "<Ctrl-c>",
477 "<Ctrl-C>",
478 "<foo",
479 ] {
480 assert!(parse_keybinding(binding).is_none(), "{binding}");
481 }
482 assert_eq!(
483 parse_keybinding("<Ctrl-p>"),
484 Some(vec![(KeyCode::Char('p'), KeyModifiers::CONTROL)])
485 );
486 assert_eq!(parse_keybinding("<Ctrl-P>"), parse_keybinding("<Ctrl-p>"));
487 assert_eq!(
488 parse_keybinding("<Ctrl-Shift-p>"),
489 parse_keybinding("<Ctrl-p>")
490 );
491 assert_eq!(
492 parse_keybinding("<Shift-Tab>"),
493 Some(vec![(KeyCode::BackTab, KeyModifiers::NONE)])
494 );
495 let dir = tempfile::tempdir().unwrap();
496 let path = dir.path().join("keys.toml");
497 fs::write(&path, "[keybindings]\njump_to_playing = '<F6>'\n").unwrap();
498 assert_eq!(
499 Config::load(Some(&path), Some(dir.path()), None)
500 .unwrap()
501 .settings
502 .keybindings
503 .jump_to_playing,
504 "<F6>"
505 );
506 fs::write(&path, "[keybindings]\njump_to_playing = '<Ctrl-c>'\n").unwrap();
507 assert!(Config::load(Some(&path), Some(dir.path()), None).is_err());
508 fs::write(&path, "[keybindings]\njump_to_playing = ''\n").unwrap();
509 assert!(Config::load(Some(&path), Some(dir.path()), None).is_ok());
510 }
511
512 #[test]
513 fn recording_reserve_rejects_zero_and_byte_overflow() {
514 let dir = tempfile::tempdir().unwrap();
515 let path = dir.path().join("config.toml");
516 for value in [0_u64, 1_u64 << 44] {
517 fs::write(&path, format!("recording_min_free_mb = {value}")).unwrap();
518 let error = Config::load(Some(&path), Some(dir.path()), None).unwrap_err();
519 assert_eq!(
520 error.downcast_ref::<DomainError>().unwrap().code,
521 ErrorCode::InvalidSettings
522 );
523 }
524 fs::write(&path, "recording_min_free_mb = 1").unwrap();
525 assert_eq!(
526 Config::load(Some(&path), Some(dir.path()), None)
527 .unwrap()
528 .settings
529 .recording_min_free_mb,
530 1
531 );
532 }
533}