new-home-proxy 0.1.2

This is a part of the New Home IoT System. It is used to make the core available in the www.
//! # Example Config
//!
//! ```yaml
//! # Here is the part for the users.yaml file stored. It has to contains an array of
//! # [User](new_home_proxy::auth::User) struct in the yaml format. You can see an example
//! # in the documentation of the [auth](new_home_proxy::auth) module.
//! users_file_path: resources/users.yaml
//!
//! # The address on which the new-home-core is hosted
//! # The proxy and core are supposed to be hosted on the same machine so the default is the localhost.
//! core_host: http://127.0.0.1:5354
//!
//! # The address for the proxy server.
//! # The default is the one, that is hosted by me.
//! proxy_url: "wss://proxy.new-home.yannik-sc.de"
//!
//! # The name for the current client.
//! # This name is generated from 2 firstnames and a lastname.
//! # This helps to remember the client better.
//! client_id: melissa-christian-fernandez
//! ```
//!
//!
use crate::client::name_generator::NameGenerator;
use crate::proxy_error::ProxyResult;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::path::PathBuf;

/// This config struct contains all properties that are required for proxy server to run
#[derive(Serialize, Deserialize)]
pub struct Config {
    /// This contains the path to the file where the users are stored
    pub users_file_path: String,

    /// This contains the address on which the new-home-core is reachable
    pub core_host: String,

    /// This contains the protocol, address and port on which the proxy server listens
    pub proxy_url: String,

    /// This contains the client_id
    /// The ID will be automatically generated by the NameGenerator struct
    pub client_id: String,
}

impl Config {
    pub fn initialize(file: PathBuf) -> ProxyResult<Self> {
        if !file.exists() {
            let file = File::create(file.clone())?;

            serde_yaml::to_writer(file, &Self::default())?;
        }

        Self::load_from_file(file)
    }

    fn load_from_file(file: PathBuf) -> ProxyResult<Self> {
        let file = File::open(file)?;

        Ok(serde_yaml::from_reader(file)?)
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            users_file_path: String::from("resources/users.yaml"),
            core_host: String::from("http://127.0.0.1:5354"),
            proxy_url: String::from("wss://proxy.new-home.yannik-sc.de:13370"),
            client_id: NameGenerator::new().generate_name(2),
        }
    }
}