2023-09-29 12:15:07 +02:00
|
|
|
/*
|
|
|
|
env.rs - The environment loader. It loads all the .env config to a convenient `Env` struct.
|
|
|
|
This file provides the `loadenv` function that will do just that.
|
|
|
|
*/
|
|
|
|
|
2023-10-01 06:43:04 +02:00
|
|
|
use std::{env::var, net::SocketAddr, path::Path, fs};
|
2023-09-29 12:15:07 +02:00
|
|
|
|
2023-10-01 02:14:35 +02:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct Redis {
|
|
|
|
pub pass: String,
|
|
|
|
pub host: String,
|
|
|
|
pub port: u16,
|
|
|
|
pub prefix: String
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
2023-09-29 12:15:07 +02:00
|
|
|
pub struct Env {
|
2023-09-29 12:57:53 +02:00
|
|
|
pub logging: bool,
|
2023-10-01 02:14:35 +02:00
|
|
|
pub listen: SocketAddr,
|
|
|
|
pub redis: Redis,
|
2023-10-01 13:08:12 +02:00
|
|
|
pub filedir: String,
|
2023-10-07 11:29:11 +02:00
|
|
|
pub instanceurl: String,
|
|
|
|
pub uploadspath: String
|
2023-09-29 12:15:07 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fn get_var<T: Into<String>, O: From<String>>(name: T) -> Result<O, String> {
|
|
|
|
let name: String = name.into();
|
|
|
|
let v = var(name.clone());
|
|
|
|
if v.is_err() {
|
|
|
|
return Err(format!("Variable {name} does not exist!"));
|
|
|
|
}
|
|
|
|
return Ok(v.unwrap().into())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn loadenv() -> Result<Env, Box<dyn std::error::Error>> {
|
|
|
|
Ok(
|
|
|
|
Env {
|
|
|
|
logging: get_var::<&str, String>("APP_LOGGING")?.to_lowercase() == "true",
|
2023-10-01 02:14:35 +02:00
|
|
|
listen: get_var::<&str, String>("APP_HOST")?.parse::<SocketAddr>().unwrap(),
|
|
|
|
redis: Redis {
|
|
|
|
pass: get_var("REDIS_PASS")?,
|
|
|
|
host: get_var("REDIS_HOST")?,
|
|
|
|
port: get_var::<&str, String>("REDIS_PORT")?.parse().unwrap(),
|
|
|
|
prefix: get_var("REDIS_PREFIX")?
|
2023-10-01 06:17:58 +02:00
|
|
|
},
|
|
|
|
filedir: {
|
|
|
|
let spath: String = get_var("USERCONTENT_DIR")?;
|
|
|
|
let path = Path::new(&spath);
|
|
|
|
if ! path.exists() {
|
2023-10-01 06:43:04 +02:00
|
|
|
fs::create_dir_all(path)?;
|
|
|
|
}
|
|
|
|
if ! path.is_dir() {
|
|
|
|
return Err(format!("USERCONTENT_DIR is set to \"{}\", which exists but is not a directory!", &spath).into())
|
2023-10-01 06:17:58 +02:00
|
|
|
}
|
|
|
|
spath
|
2023-10-01 13:08:12 +02:00
|
|
|
},
|
2023-10-07 11:29:11 +02:00
|
|
|
instanceurl: get_var("INSTANCE_URL")?,
|
|
|
|
uploadspath: get_var("UPLOADS_PATH")?
|
2023-09-29 12:15:07 +02:00
|
|
|
}
|
|
|
|
)
|
2023-10-01 06:17:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Env {
|
|
|
|
pub fn usercontent_dir(self: &Self) -> Box<&Path> {
|
|
|
|
Box::new(Path::new(&self.filedir))
|
|
|
|
}
|
2023-09-29 12:15:07 +02:00
|
|
|
}
|