core/emgauwa-core/src/main.rs

76 lines
2.4 KiB
Rust

use std::collections::HashMap;
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
use actix_cors::Cors;
use actix_web::middleware::TrailingSlash;
use actix_web::{middleware, web, App, HttpServer};
use emgauwa_lib::db::DbController;
use emgauwa_lib::types::ConnectedControllersType;
use emgauwa_lib::utils::init_logging;
use crate::utils::drop_privileges;
mod handlers;
mod settings;
mod utils;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let settings = settings::init();
init_logging(&settings.logging.level);
let listener = TcpListener::bind(format!("{}:{}", settings.host, settings.port))
.expect("Error creating listener");
drop_privileges(&settings).expect("Error dropping privileges");
let pool = emgauwa_lib::db::init(&settings.database).await;
// This block is to ensure that the connection is dropped after use.
{
let mut conn = pool.acquire().await.unwrap();
DbController::all_inactive(&mut conn)
.await
.expect("Error setting all controllers inactive");
}
let connected_controllers: ConnectedControllersType = Arc::new(Mutex::new(HashMap::new()));
log::info!("Starting server on {}:{}", settings.host, settings.port);
HttpServer::new(move || {
let cors = Cors::default().allow_any_method().allow_any_header();
let origins = settings.origins.clone();
let cors = match settings.origins.is_empty() {
true => cors.allow_any_origin(),
false => cors.allowed_origin_fn(move |origin, _req_head| {
origins.contains(&origin.to_str().unwrap_or_default().to_string())
}),
};
App::new()
.wrap(cors)
.wrap(middleware::Logger::default())
.wrap(middleware::NormalizePath::new(TrailingSlash::Trim))
.app_data(web::JsonConfig::default().error_handler(handlers::json_error_handler))
.app_data(web::Data::new(pool.clone()))
.app_data(web::Data::new(connected_controllers.clone()))
.service(handlers::v1::controllers::index)
.service(handlers::v1::controllers::show)
.service(handlers::v1::controllers::update)
.service(handlers::v1::controllers::delete)
.service(handlers::v1::relays::index)
.service(handlers::v1::schedules::index)
.service(handlers::v1::schedules::tagged)
.service(handlers::v1::schedules::show)
.service(handlers::v1::schedules::add)
.service(handlers::v1::schedules::add_list)
.service(handlers::v1::schedules::update)
.service(handlers::v1::schedules::delete)
.service(handlers::v1::ws::ws_controllers)
})
.listen(listener)?
.run()
.await
}