root/src/configfile.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// configfile.rs
// Copyright 2023 nee <nee-git@patchouli.garden>
// SPDX-License-Identifier: AGPL-3.0-or-later
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ConfigFile {
    pub music_dir: PathBuf,
    pub playlist_dir: PathBuf,
    pub password: String,
    pub net_address: String,
}

impl Default for ConfigFile {
    fn default() -> Self {
        ConfigFile {
            music_dir: dirs::audio_dir().unwrap_or_default(),
            playlist_dir: dirs::audio_dir().unwrap_or_default(),
            password: "".to_string(),
            net_address: "127.0.0.1:6600".to_string(),
        }
    }
}

impl ConfigFile {
    pub fn write(&self) -> Option<()> {
        let mut path = dirs::config_dir()?;
        path.push("mpdr");
        std::fs::create_dir_all(&path).ok();
        path.push("config.toml");
        let config_str = toml::to_string(&self).ok()?;
        fs::write(path, config_str).ok()?;
        Some(())
    }

    pub fn read() -> Option<ConfigFile> {
        let mut path = dirs::config_dir()?;
        path.push("mpdr/config.toml");
        let config: ConfigFile = toml::from_str(&fs::read_to_string(path).ok()?).ok()?;
        Some(config)
    }
}