2.3 KiB · text History 1ce9641
use sea_orm::DatabaseConnection;
use std::env;

#[derive(Debug, Clone)]
pub struct Config {
    pub database_url: String,
    pub session_duration_hours: i64,
    pub registration_token_duration_days: i64,
    pub bind_address: String,
    pub storage_root: String,
    pub amqp_url: String,
    pub worker_prefetch: u16,
    pub max_upload_bytes: usize,
    pub auto_migrate: bool,
    pub registration_enabled: bool,
}

impl Config {
    pub fn from_env() -> Result<Self, env::VarError> {
        Ok(Config {
            database_url: env::var("DATABASE_URL")
                .unwrap_or_else(|_| "postgres://dms_user:dms_password@localhost:5433/dms".to_string()),
            session_duration_hours: env::var("SESSION_DURATION_HOURS")
                .unwrap_or_else(|_| "24".to_string())
                .parse()
                .unwrap_or(24),
            registration_token_duration_days: env::var("REGISTRATION_TOKEN_DURATION_DAYS")
                .unwrap_or_else(|_| "7".to_string())
                .parse()
                .unwrap_or(7),
            bind_address: env::var("BIND_ADDRESS")
                .unwrap_or_else(|_| "0.0.0.0:3007".to_string()),
            storage_root: env::var("STORAGE_ROOT")
                .unwrap_or_else(|_| "./storage".to_string()),
            amqp_url: env::var("AMQP_URL")
                .unwrap_or_else(|_| "amqp://dms_user:dms_password@localhost:5674/%2f".to_string()),
            worker_prefetch: env::var("WORKER_PREFETCH")
                .unwrap_or_else(|_| "4".to_string())
                .parse()
                .unwrap_or(4),
            max_upload_bytes: env::var("MAX_UPLOAD_BYTES")
                .unwrap_or_else(|_| "104857600".to_string()) // 100 MiB
                .parse()
                .unwrap_or(100 * 1024 * 1024),
            auto_migrate: env::var("AUTO_MIGRATE")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(true),
            registration_enabled: env::var("REGISTRATION_ENABLED")
                .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
                .unwrap_or(false),
        })
    }
}

pub async fn create_db_connection(database_url: &str) -> Result<DatabaseConnection, sea_orm::DbErr> {
    sea_orm::Database::connect(database_url).await
}