98 lines
2.5 KiB
Rust
98 lines
2.5 KiB
Rust
use std::{
|
|
fmt,
|
|
fs::{self, File},
|
|
};
|
|
|
|
use chrono::NaiveTime;
|
|
use ron::{
|
|
de::{from_reader, from_str},
|
|
ser::{PrettyConfig, to_string_pretty},
|
|
};
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::consts;
|
|
|
|
#[derive(Deserialize, Serialize, Clone)]
|
|
pub struct Config {
|
|
#[serde(default = "port_default")]
|
|
pub port: u16,
|
|
|
|
#[serde(default = "smtp_relay_address_default")]
|
|
pub smtp_relay_address: String,
|
|
|
|
#[serde(default = "smtp_login_default")]
|
|
pub smtp_login: String,
|
|
|
|
#[serde(default = "smtp_password_default")]
|
|
pub smtp_password: String,
|
|
|
|
#[serde(default)]
|
|
pub backup_time: Option<NaiveTime>, // If not set, no backup will be done.
|
|
|
|
#[serde(default = "backup_directory_default")]
|
|
pub backup_directory: String,
|
|
}
|
|
|
|
fn port_default() -> u16 {
|
|
8082
|
|
}
|
|
|
|
fn smtp_relay_address_default() -> String {
|
|
"mail.something.com".to_string()
|
|
}
|
|
|
|
fn smtp_login_default() -> String {
|
|
"login".to_string()
|
|
}
|
|
|
|
fn smtp_password_default() -> String {
|
|
"password".to_string()
|
|
}
|
|
|
|
fn backup_directory_default() -> String {
|
|
"data".to_string()
|
|
}
|
|
|
|
impl Config {
|
|
pub fn default() -> Self {
|
|
from_str("()").unwrap()
|
|
}
|
|
}
|
|
|
|
// Avoid to print passwords.
|
|
impl fmt::Debug for Config {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.debug_struct("Config")
|
|
.field("port", &self.port)
|
|
.field("smtp_relay_address", &self.smtp_relay_address)
|
|
.field("smtp_login", &self.smtp_login)
|
|
.field("smtp_password", &"*****")
|
|
.field("backup_time", &self.backup_time)
|
|
.field("backup_directory", &self.backup_directory)
|
|
.finish()
|
|
}
|
|
}
|
|
|
|
pub fn load() -> Config {
|
|
let config = match File::open(consts::FILE_CONF) {
|
|
Ok(file) => from_reader(file).unwrap_or_else(|error| {
|
|
panic!(
|
|
"Failed to open configuration file {}: {}",
|
|
consts::FILE_CONF,
|
|
error
|
|
)
|
|
}),
|
|
Err(_) => Config::default(),
|
|
};
|
|
|
|
// Rewrite the whole config, useful in the case
|
|
// when some fields are missing in the original or no config file at all.
|
|
// FIXME: It will remove any manually added comments.
|
|
let ron_string = to_string_pretty(&config, PrettyConfig::new())
|
|
.unwrap_or_else(|error| panic!("Failed to serialize ron configuration: {}", error));
|
|
|
|
fs::write(consts::FILE_CONF, ron_string)
|
|
.unwrap_or_else(|error| panic!("Failed to write default configuration file: {}", error));
|
|
|
|
config
|
|
}
|