-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.rs
102 lines (87 loc) · 2.38 KB
/
config.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
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
use std::{error::Error, fs::create_dir, io, path::PathBuf};
#[cfg(feature = "dotenvy")]
use dotenvy::dotenv;
use serde::Deserialize;
fn ensure_dir(path: &PathBuf) -> std::io::Result<()> {
match create_dir(&path) {
Err(e) => match e.kind() {
std::io::ErrorKind::AlreadyExists => Ok(()),
_ => Err(e),
},
ok => ok,
}
}
pub struct AppConfig {
pub env: EnvConfig,
pub audio_dir: PathBuf,
pub db_file: PathBuf,
}
impl AppConfig {
pub fn init() -> Result<Self, Box<dyn Error>> {
let env = EnvConfig::from_dotenv()?;
let data_dir = PathBuf::from(&env.data_dir);
let audio_dir = data_dir.join("audios");
let db_file = data_dir.join("bot.db");
ensure_dir(&data_dir)?;
ensure_dir(&audio_dir)?;
Ok(AppConfig {
env,
audio_dir,
db_file,
})
}
pub fn is_admin(&self, id: &i64) -> bool {
self.env.admin_users.contains(id)
}
}
#[derive(Deserialize, Debug)]
pub struct EnvConfig {
pub ahm_host: String,
#[serde(default = "default_ahm_port")]
pub ahm_port: u16,
pub bot_token: String,
pub admin_users: Vec<i64>,
pub player_command: String,
#[serde(default = "default_player_start_delay")]
pub player_start_delay: u64,
#[serde(default = "default_data_dir")]
pub data_dir: String,
pub heartbeat_endpoint: Option<String>,
#[serde(default = "default_heartbeat_interval")]
pub heartbeat_interval: u64,
#[serde(default = "default_mock_ahm_connection")]
pub mock_ahm_connection: bool,
}
fn default_ahm_port() -> u16 {
51325
}
fn default_player_start_delay() -> u64 {
0
}
fn default_data_dir() -> String {
"./data".into()
}
fn default_heartbeat_interval() -> u64 {
300000
}
fn default_mock_ahm_connection() -> bool {
false
}
impl EnvConfig {
pub fn from_dotenv() -> Result<Self, Box<dyn Error>> {
#[cfg(feature = "dotenvy")]
match dotenv() {
Err(dotenvy::Error::Io(err)) => match err.kind() {
io::ErrorKind::NotFound => log::warn!("no .env file found"),
_ => {
log::error!("{}", err)
}
},
Err(err) => {
log::error!("{}", err)
}
Ok(_) => {}
}
return Ok(envy::from_env::<EnvConfig>()?);
}
}