aboutsummaryrefslogtreecommitdiffstats
path: root/mumlib/src/config.rs
blob: 210dc7b8ed01fd4482a569fec4565e1417fbb0e1 (plain) (blame)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use serde::{Deserialize, Serialize};
use std::convert::TryFrom;
use std::fs;
use std::path::Path;
use toml::value::Array;
use toml::Value;

#[derive(Debug, Deserialize, Serialize)]
struct TOMLConfig {
    audio: Option<AudioConfig>,
    servers: Option<Array>,
}

#[derive(Clone, Debug, Default)]
pub struct Config {
    pub audio: AudioConfig,
    pub servers: Vec<ServerConfig>,
}

impl Config {
    pub fn write_default_cfg(&self, create: bool) -> Result<(), std::io::Error> {
        let path = if create {
            get_creatable_cfg_path()
        } else {
            get_cfg_path()
        };
        let path = std::path::Path::new(&path);
        // Possible race here. It's fine since it shows when:
        //   1) the file doesn't exist when checked and is then created
        //   2) the file exists when checked but is then removed
        // If 1) we don't do anything anyway so it's fine, and if 2) we
        // immediately re-create the file which, while not perfect, at least
        // should work. Unless the file is removed AND the permissions
        // change, but then we don't have permissions so we can't
        // do anything anyways.
        if !create && !path.exists() {
            return Ok(());
        }

        fs::write(
            path,
            toml::to_string(&TOMLConfig::from(self.clone())).unwrap(),
        )
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct AudioConfig {
    pub input_volume: Option<f32>,
    pub output_volume: Option<f32>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ServerConfig {
    pub name: String,
    pub host: String,
    pub port: Option<u16>,
    pub username: Option<String>,
    pub password: Option<String>,
}

pub fn get_cfg_path() -> String {
    if let Ok(var) = std::env::var("XDG_CONFIG_HOME") {
        let path = format!("{}/mumdrc", var);
        if Path::new(&path).exists() {
            return path;
        }
    } else if let Ok(var) = std::env::var("HOME") {
        let path = format!("{}/.config/mumdrc", var);
        if Path::new(&path).exists() {
            return path;
        }
    }

    "/etc/mumdrc".to_string()
}

pub fn get_creatable_cfg_path() -> String {
    if let Ok(var) = std::env::var("XDG_CONFIG_HOME") {
        let path = format!("{}/mumdrc", var);
        if !Path::new(&path).exists() {
            return path;
        }
    } else if let Ok(var) = std::env::var("HOME") {
        let path = format!("{}/.config/mumdrc", var);
        if !Path::new(&path).exists() {
            return path;
        }
    }

    "/etc/mumdrc".to_string()
}

pub fn cfg_exists() -> bool {
    if let Ok(var) = std::env::var("XDG_CONFIG_HOME") {
        let path = format!("{}/mumdrc", var);
        if Path::new(&path).exists() {
            return true;
        }
    } else if let Ok(var) = std::env::var("HOME") {
        let path = format!("{}/.config/mumdrc", var);
        if Path::new(&path).exists() {
            return true;
        }
    } else if Path::new("/etc/mumdrc").exists() {
        return true;
    }

    false
}

impl TryFrom<TOMLConfig> for Config {
    type Error = toml::de::Error;

    fn try_from(config: TOMLConfig) -> Result<Self, Self::Error> {
        Ok(Config {
            audio: config.audio.unwrap_or_default(),
            servers: config
                .servers
                .map(|servers| {
                    servers
                        .into_iter()
                        .map(|s| s.try_into::<ServerConfig>())
                        .collect()
                })
                .transpose()?
                .unwrap_or(Vec::new()),
        })
    }
}

impl From<Config> for TOMLConfig {
    fn from(config: Config) -> Self {
        TOMLConfig {
            audio: if config.audio.output_volume.is_some() || config.audio.input_volume.is_some() {
                Some(config.audio)
            } else {
                None
            },
            servers: Some(config.servers.into_iter()
                .map(|s| Value::try_from::<ServerConfig>(s).unwrap())
                .collect()),
        }
    }
}

pub fn read_default_cfg() -> Config {
    Config::try_from(
        toml::from_str::<TOMLConfig>(&match fs::read_to_string(get_cfg_path()) {
            Ok(f) => f,
            Err(_) => return Config::default(),
        }).expect("invalid TOML in config file"), //TODO
    ).expect("invalid config in TOML") //TODO
}