Skip to main content

lux_core/
config.rs

1use crate::error::{LuxError, Result};
2use crate::types::Quality;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::fs;
6use std::path::PathBuf;
7
8fn default_platform_priority() -> Vec<String> {
9    vec![
10        "wy".to_string(),
11        "kw".to_string(),
12        "tx".to_string(),
13        "mg".to_string(),
14        "kg".to_string(),
15    ]
16}
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct SourceSettings {
20    pub default_source: String,
21    pub default_quality: Quality,
22    pub quality_fallback: Vec<Quality>,
23    pub js_priority: bool,
24    pub priority: Vec<String>,
25    #[serde(default = "default_platform_priority")]
26    pub platform_priority: Vec<String>,
27}
28
29impl Default for SourceSettings {
30    fn default() -> Self {
31        Self {
32            default_source: "all".to_string(),
33            default_quality: Quality::Q320k,
34            quality_fallback: vec![Quality::Q320k, Quality::Q128k, Quality::Flac],
35            js_priority: true,
36            priority: vec![
37                "sixyin_v1.2.1".to_string(),
38                "ikun_v22".to_string(),
39                "huibq_v1.2.0".to_string(),
40            ],
41            platform_priority: default_platform_priority(),
42        }
43    }
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct SourceOverride {
48    pub enabled: bool,
49    pub quality: Option<Quality>,
50}
51
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct PlayerSettings {
54    pub default_volume: u8,
55    pub repeat: String, // "off", "one", "all"
56    pub shuffle: bool,
57    pub mpv_args: Vec<String>,
58    pub mpv_socket: Option<String>,
59    pub enable_mpris: bool,
60    pub auto_resume: bool,
61}
62
63impl Default for PlayerSettings {
64    fn default() -> Self {
65        Self {
66            default_volume: 80,
67            repeat: "off".to_string(),
68            shuffle: false,
69            mpv_args: vec![],
70            mpv_socket: None,
71            enable_mpris: true,
72            auto_resume: true,
73        }
74    }
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct DownloadSettings {
79    pub output_dir: String,
80    pub filename_template: String,
81    pub embed_metadata: bool,
82    pub embed_lyrics: bool,
83    pub embed_lyrics_lx: bool,
84    pub embed_lyrics_translated: bool,
85    pub embed_lyrics_romanized: bool,
86    pub embed_cover: bool,
87    pub save_lyrics_file: bool,
88    pub save_cover_file: bool,
89    pub lrc_encoding: String,
90    pub max_concurrent: usize,
91    pub skip_existing: bool,
92    pub use_other_source: bool,
93    pub group_by_source: bool,
94    pub timeout: u64,
95    pub beet_import: bool,
96    pub use_beets_library: bool,
97}
98
99impl Default for DownloadSettings {
100    fn default() -> Self {
101        Self {
102            output_dir: "~/Music/agent-lx-music".to_string(),
103            filename_template: "{singer} - {title}".to_string(),
104            embed_metadata: true,
105            embed_lyrics: true,
106            embed_lyrics_lx: true,
107            embed_lyrics_translated: false,
108            embed_lyrics_romanized: false,
109            embed_cover: true,
110            save_lyrics_file: false,
111            save_cover_file: false,
112            lrc_encoding: "utf8".to_string(),
113            max_concurrent: 3,
114            skip_existing: true,
115            use_other_source: true,
116            group_by_source: false,
117            timeout: 60,
118            beet_import: false,
119            use_beets_library: false,
120        }
121    }
122}
123
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct HistorySettings {
126    pub max_age_days: u64,
127}
128
129impl Default for HistorySettings {
130    fn default() -> Self {
131        Self { max_age_days: 90 }
132    }
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct DisplaySettings {
137    pub color: String,       // "auto", "always", "never"
138    pub table_style: String, // "rounded", "ascii", "compact"
139    pub show_progress: bool,
140}
141
142impl Default for DisplaySettings {
143    fn default() -> Self {
144        Self {
145            color: "auto".to_string(),
146            table_style: "rounded".to_string(),
147            show_progress: true,
148        }
149    }
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct NetworkSettings {
154    pub proxy: Option<String>,
155    pub timeout: u64,
156    pub max_retries: usize,
157}
158
159impl Default for NetworkSettings {
160    fn default() -> Self {
161        Self {
162            proxy: None,
163            timeout: 15,
164            max_retries: 2,
165        }
166    }
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize, Default)]
170pub struct Config {
171    pub source: SourceSettings,
172    #[serde(default)]
173    pub sources: HashMap<String, SourceOverride>,
174    #[serde(default)]
175    pub player: PlayerSettings,
176    #[serde(default)]
177    pub download: DownloadSettings,
178    pub history: HistorySettings,
179    pub display: DisplaySettings,
180    pub network: NetworkSettings,
181}
182
183#[derive(Debug, Clone)]
184pub struct XdgPaths {
185    pub config_file: PathBuf,
186    pub data_dir: PathBuf,
187    pub cache_dir: PathBuf,
188    pub sources_dir: PathBuf,
189    pub db_file: PathBuf,
190}
191
192pub fn resolve_paths() -> XdgPaths {
193    let home = std::env::var("ALX_HOME").ok().map(PathBuf::from);
194
195    let config_file = if let Some(ref h) = home {
196        h.join("config.toml")
197    } else if let Ok(c) = std::env::var("ALX_CONFIG") {
198        PathBuf::from(c)
199    } else {
200        dirs::config_dir()
201            .unwrap_or_else(|| PathBuf::from("/home/fuyu/.config"))
202            .join("agent-lx-music/config.toml")
203    };
204
205    let data_dir = if let Some(ref h) = home {
206        h.join("data")
207    } else if let Ok(d) = std::env::var("ALX_DATA") {
208        PathBuf::from(d)
209    } else {
210        dirs::data_dir()
211            .unwrap_or_else(|| PathBuf::from("/home/fuyu/.local/share"))
212            .join("agent-lx-music")
213    };
214
215    let cache_dir = if let Some(ref h) = home {
216        h.join("cache")
217    } else if let Ok(c) = std::env::var("ALX_CACHE") {
218        PathBuf::from(c)
219    } else {
220        dirs::cache_dir()
221            .unwrap_or_else(|| PathBuf::from("/home/fuyu/.cache"))
222            .join("agent-lx-music")
223    };
224
225    XdgPaths {
226        config_file,
227        sources_dir: data_dir.join("sources"),
228        db_file: data_dir.join("agent-lx-music.db"),
229        data_dir,
230        cache_dir,
231    }
232}
233
234impl Config {
235    pub fn load() -> Result<Self> {
236        let paths = resolve_paths();
237        if !paths.config_file.exists() {
238            Self::init_default(&paths)?;
239        }
240
241        let content = fs::read_to_string(&paths.config_file)
242            .map_err(|e| LuxError::Config(format!("Failed to read config file: {}", e)))?;
243
244        let config: Config = toml::from_str(&content)
245            .map_err(|e| LuxError::Config(format!("Failed to parse TOML config: {}", e)))?;
246
247        Ok(config)
248    }
249
250    pub fn save(&self) -> Result<()> {
251        let paths = resolve_paths();
252        if let Some(parent) = paths.config_file.parent() {
253            fs::create_dir_all(parent)
254                .map_err(|e| LuxError::Io(format!("Failed to create config dir: {}", e)))?;
255        }
256
257        let content = toml::to_string_pretty(self)
258            .map_err(|e| LuxError::Config(format!("Failed to serialize TOML config: {}", e)))?;
259
260        fs::write(&paths.config_file, content)
261            .map_err(|e| LuxError::Io(format!("Failed to write config file: {}", e)))?;
262
263        Ok(())
264    }
265
266    fn init_default(paths: &XdgPaths) -> Result<()> {
267        if let Some(parent) = paths.config_file.parent() {
268            fs::create_dir_all(parent)
269                .map_err(|e| LuxError::Io(format!("Failed to create config dir: {}", e)))?;
270        }
271        fs::create_dir_all(&paths.sources_dir)
272            .map_err(|e| LuxError::Io(format!("Failed to create sources dir: {}", e)))?;
273        fs::create_dir_all(&paths.cache_dir)
274            .map_err(|e| LuxError::Io(format!("Failed to create cache dir: {}", e)))?;
275
276        let default_toml = get_default_config_toml();
277        fs::write(&paths.config_file, default_toml)
278            .map_err(|e| LuxError::Io(format!("Failed to write default config: {}", e)))?;
279
280        Ok(())
281    }
282
283    pub fn get_resolved_download_dir(&self) -> PathBuf {
284        expand_path(&self.download.output_dir)
285    }
286}
287
288pub fn expand_path(path_str: &str) -> PathBuf {
289    let mut resolved = path_str.to_string();
290
291    // 1. Handle tilde (~) expansion
292    if resolved.starts_with("~/")
293        && let Some(home) = dirs::home_dir()
294    {
295        resolved = resolved.replacen(
296            "~/",
297            &format!("{}/", home.to_string_lossy().trim_end_matches('/')),
298            1,
299        );
300    } else if resolved == "~"
301        && let Some(home) = dirs::home_dir()
302    {
303        resolved = home.to_string_lossy().to_string();
304    }
305
306    // 2. Expand environment variables ($VAR and ${VAR})
307    let mut final_path = String::new();
308    let chars: Vec<char> = resolved.chars().collect();
309    let mut i = 0;
310    while i < chars.len() {
311        if chars[i] == '$' && i + 1 < chars.len() {
312            if chars[i + 1] == '{' {
313                let mut j = i + 2;
314                let mut var_name = String::new();
315                while j < chars.len() && chars[j] != '}' {
316                    var_name.push(chars[j]);
317                    j += 1;
318                }
319                if j < chars.len() && chars[j] == '}' {
320                    if let Ok(val) = std::env::var(&var_name) {
321                        final_path.push_str(&val);
322                    }
323                    i = j + 1;
324                    continue;
325                }
326            } else {
327                let mut j = i + 1;
328                let mut var_name = String::new();
329                while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
330                    var_name.push(chars[j]);
331                    j += 1;
332                }
333                if !var_name.is_empty() {
334                    if let Ok(val) = std::env::var(&var_name) {
335                        final_path.push_str(&val);
336                    }
337                    i = j;
338                    continue;
339                }
340            }
341        }
342        final_path.push(chars[i]);
343        i += 1;
344    }
345
346    PathBuf::from(final_path)
347}
348
349fn get_default_config_toml() -> &'static str {
350    r#"# ~/.config/rust-lx/config.toml
351# Default configuration for rust-lx (rlx)
352
353[source]
354# Default search source: "all" searches all sources in parallel
355default_source = "all"
356
357# Default quality (fallback order: try each until success)
358# Valid: "128k", "192k", "320k", "flac", "flac24bit", "ape", "wav"
359default_quality = "320k"
360
361# Quality fallback chain (tried in order when default unavailable)
362quality_fallback = ["320k", "128k", "flac"]
363
364# Prefer JS sources over native parsers for same platform
365js_priority = true
366
367# Source priority list — controls search order and URL resolution fallback
368# Sources not listed here get appended at the end in alphabetical order
369priority = ["sixyin_v1.2.1", "ikun_v22", "huibq_v1.2.0"]
370
371# Platform search and matching priority order
372platform_priority = ["wy", "kw", "tx", "mg", "kg"]
373
374[sources]
375# Source-specific overrides (optional)
376# [sources.sixyin_v1.2.1]
377# enabled = true
378# quality = "flac"
379
380[player]
381default_volume = 80
382repeat = "off" # "off", "one", "all"
383shuffle = false
384mpv_args = []
385enable_mpris = true
386auto_resume = true
387
388[download]
389output_dir = "~/Music/rust-lx"
390filename_template = "{singer} - {title}"
391embed_metadata = true
392embed_lyrics = true
393embed_lyrics_lx = true
394embed_lyrics_translated = false
395embed_lyrics_romanized = false
396embed_cover = true
397save_lyrics_file = false
398save_cover_file = false
399lrc_encoding = "utf8"
400max_concurrent = 3
401skip_existing = true
402use_other_source = true
403group_by_source = false
404timeout = 60
405beet_import = false
406use_beets_library = false
407
408[history]
409max_age_days = 90
410
411[display]
412color = "auto" # "auto", "always", "never"
413table_style = "rounded" # "rounded", "ascii", "compact"
414show_progress = true
415
416[network]
417# proxy = "socks5://127.0.0.1:1080"
418timeout = 15
419max_retries = 2
420"#
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use std::env;
427    use std::sync::Mutex;
428
429    static TEST_MUTEX: Mutex<()> = Mutex::new(());
430
431    #[test]
432    fn test_all_config_operations() {
433        let _guard = TEST_MUTEX.lock().unwrap();
434
435        // 1. Test resolve paths with home override
436        let temp_dir_home = env::temp_dir().join("alx-test-home");
437        if temp_dir_home.exists() {
438            let _ = fs::remove_dir_all(&temp_dir_home);
439        }
440        unsafe {
441            env::set_var("ALX_HOME", temp_dir_home.to_str().unwrap());
442        }
443
444        let paths = resolve_paths();
445        assert_eq!(paths.config_file, temp_dir_home.join("config.toml"));
446        assert_eq!(paths.data_dir, temp_dir_home.join("data"));
447        assert_eq!(paths.cache_dir, temp_dir_home.join("cache"));
448        assert_eq!(
449            paths.sources_dir,
450            temp_dir_home.join("data").join("sources")
451        );
452
453        unsafe {
454            env::remove_var("ALX_HOME");
455        }
456
457        // 2. Test config default load and save
458        let temp_dir_load = env::temp_dir().join("alx-test-default-load-save");
459        if temp_dir_load.exists() {
460            let _ = fs::remove_dir_all(&temp_dir_load);
461        }
462        unsafe {
463            env::set_var("ALX_HOME", temp_dir_load.to_str().unwrap());
464        }
465
466        // Loading should initialize the default config
467        let config = Config::load();
468        assert!(config.is_ok());
469
470        let mut config = config.unwrap();
471        assert_eq!(config.source.default_source, "all");
472        assert_eq!(config.source.default_quality, Quality::Q320k);
473
474        // Modify a setting and save
475        config.player.default_volume = 90;
476        assert!(config.save().is_ok());
477
478        // Reload to verify it preserved the change
479        let reloaded = Config::load().unwrap();
480        assert_eq!(reloaded.player.default_volume, 90);
481
482        let _ = fs::remove_dir_all(&temp_dir_load);
483        let _ = fs::remove_dir_all(&temp_dir_home);
484        unsafe {
485            env::remove_var("ALX_HOME");
486        }
487    }
488
489    #[test]
490    fn test_expand_path() {
491        let _guard = TEST_MUTEX.lock().unwrap();
492
493        // Test tilde expansion
494        if let Some(home) = dirs::home_dir() {
495            let expanded = expand_path("~/Music/agent-lx-music");
496            assert_eq!(expanded, home.join("Music/agent-lx-music"));
497
498            let expanded_only_tilde = expand_path("~");
499            assert_eq!(expanded_only_tilde, home);
500        }
501
502        // Test environment variable expansion
503        unsafe {
504            env::set_var("TEST_DIR", "foo");
505            env::set_var("TEST_SUB", "bar");
506        }
507
508        let expanded_simple = expand_path("/tmp/$TEST_DIR/baz");
509        assert_eq!(expanded_simple, PathBuf::from("/tmp/foo/baz"));
510
511        let expanded_braces = expand_path("/tmp/${TEST_DIR}_test/$TEST_SUB");
512        assert_eq!(expanded_braces, PathBuf::from("/tmp/foo_test/bar"));
513
514        unsafe {
515            env::remove_var("TEST_DIR");
516            env::remove_var("TEST_SUB");
517        }
518    }
519}