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.
extern crate actix_rt;
extern crate rustls;
extern crate webpki_roots;

use std::sync::Arc;

use actix::io::SinkWrite;
use actix::{Actor, StreamHandler};
use actix_rt::{Arbiter, System};
use futures_util::StreamExt;

use awc::ClientBuilder;
use new_home_proxy::auth::user_authenticator::UserAuthenticator;
use new_home_proxy::client::config::Config;
use new_home_proxy::client::handler::WebsocketHandler;
use rustls::ClientConfig;

fn main() {
    let system = System::new("websocket-client");

    Arbiter::spawn(run());

    system.run().unwrap();
}

async fn run() {
    let path = std::env::current_dir().unwrap();
    let config = match Config::initialize(path.join("client.yaml")) {
        Ok(config) => config,
        Err(error) => {
            println!("Could not initialize config: {}", error);
            return;
        }
    };

    println!("Client {} starting!", &config.client_id);

    let mut cfg = ClientConfig::new();
    cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
    cfg.root_store
        .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
    let proxy_server_url = format!("{}/connect/{}", &config.proxy_url, &config.client_id);

    let connector = awc::Connector::new().rustls(Arc::new(cfg)).finish();
    let client = ClientBuilder::new().connector(connector).finish();

    let ws_request = client.ws(proxy_server_url);
    let (_, frame) = match ws_request.connect().await {
        Ok(connected) => connected,
        _ => {
            println!("Websocket could not connect to server");

            System::current().stop();

            return;
        }
    };

    let authenticator = match UserAuthenticator::new(&config.users_file_path) {
        Ok(authenticator) => authenticator,
        Err(error) => {
            println!("Could not create the authenticator: {}", &error);

            System::current().stop();

            return;
        }
    };

    let (sink, stream) = frame.split();

    WebsocketHandler::create(|ctx| {
        WebsocketHandler::add_stream(stream, ctx);
        WebsocketHandler::new(
            config.core_host.clone(),
            SinkWrite::new(sink, ctx),
            Arc::new(authenticator),
        )
    });
}