2022-07-04 14:52:25 +00:00
|
|
|
use std::{fs::File, path::Path};
|
|
|
|
|
2022-04-23 18:44:02 +00:00
|
|
|
use homedisk_database::Database;
|
2022-06-08 19:16:12 +00:00
|
|
|
use homedisk_server::serve_http;
|
|
|
|
use homedisk_types::config::Config;
|
2022-07-11 21:20:47 +00:00
|
|
|
use tracing::{info, warn};
|
|
|
|
|
|
|
|
mod logger;
|
2022-07-04 14:52:25 +00:00
|
|
|
|
|
|
|
pub const DATABASE_FILE: &str = "homedisk.db";
|
2022-04-16 18:19:38 +00:00
|
|
|
|
|
|
|
#[tokio::main]
|
2022-06-18 11:55:56 +00:00
|
|
|
async fn main() {
|
2022-07-11 21:20:47 +00:00
|
|
|
logger::init();
|
2022-04-16 18:19:38 +00:00
|
|
|
|
2022-08-29 11:12:16 +00:00
|
|
|
let config = Config::parse().expect("Failed to parse configuration file");
|
2022-04-16 19:22:01 +00:00
|
|
|
|
2022-06-07 20:36:26 +00:00
|
|
|
// open database connection
|
2022-07-04 14:52:25 +00:00
|
|
|
let db =
|
|
|
|
// if database file doesn't exists create it
|
|
|
|
if !Path::new(DATABASE_FILE).exists() {
|
|
|
|
warn!("Database file doesn't exists.");
|
|
|
|
info!("Creating database file...");
|
|
|
|
|
|
|
|
// create an empty database file
|
2022-08-29 11:12:16 +00:00
|
|
|
File::create(DATABASE_FILE).expect("Failed to create a database file");
|
2022-07-04 14:52:25 +00:00
|
|
|
|
|
|
|
// open database file
|
|
|
|
let db = Database::open(DATABASE_FILE)
|
|
|
|
.await
|
2022-08-29 11:12:16 +00:00
|
|
|
.expect("Failed to open database file");
|
2022-07-04 14:52:25 +00:00
|
|
|
|
|
|
|
// create tables in the database
|
|
|
|
db.create_tables()
|
|
|
|
.await
|
2022-08-29 11:12:16 +00:00
|
|
|
.expect("Failed to create tables in the database");
|
2022-07-04 14:52:25 +00:00
|
|
|
|
|
|
|
db
|
|
|
|
}
|
|
|
|
// if database file exists
|
|
|
|
else {
|
2022-07-04 14:59:38 +00:00
|
|
|
Database::open(DATABASE_FILE)
|
2022-07-04 14:52:25 +00:00
|
|
|
.await
|
2022-08-29 11:12:16 +00:00
|
|
|
.expect("Failed to open database file")
|
2022-07-04 14:52:25 +00:00
|
|
|
};
|
2022-04-17 22:07:37 +00:00
|
|
|
|
2022-04-18 12:13:15 +00:00
|
|
|
// change the type from Vec<String> to Vec<HeaderValue> so that the http server can correctly detect CORS hosts
|
|
|
|
let origins = config
|
|
|
|
.http
|
|
|
|
.cors
|
|
|
|
.iter()
|
2022-06-07 20:36:26 +00:00
|
|
|
.map(|e| e.parse().expect("parse CORS hosts"))
|
2022-04-18 12:13:15 +00:00
|
|
|
.collect();
|
2022-04-17 22:07:37 +00:00
|
|
|
|
2022-06-08 19:16:12 +00:00
|
|
|
// format host ip and port
|
2022-04-19 13:25:56 +00:00
|
|
|
let host = format!(
|
|
|
|
"{host}:{port}",
|
|
|
|
host = config.http.host,
|
|
|
|
port = config.http.port
|
|
|
|
);
|
|
|
|
|
2022-06-18 13:22:43 +00:00
|
|
|
serve_http(host, origins, db, config)
|
|
|
|
.await
|
|
|
|
.expect("start http server");
|
2022-06-08 19:16:12 +00:00
|
|
|
}
|