X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=backend%2Fsrc%2Fmain.rs;h=1fbfbc53e357fd319bd3a50c964a81ea8ef369eb;hb=5e4e0862477f46a6ea477a56f01fd84e720a9546;hp=faf7e9c09dc4fc3496e3c06d18c952686c56573f;hpb=c65b9e9e44d0adb48a982da64b3ff4a7f3a8358b;p=recipes.git diff --git a/backend/src/main.rs b/backend/src/main.rs index faf7e9c..1fbfbc5 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -1,24 +1,30 @@ -use std::io::prelude::*; -use std::{fs::File, env::args}; +use std::fs::File; +use std::sync::Mutex; use actix_files as fs; -use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpResponse, web::Query, middleware::Logger}; - -use askama::Template; -use listenfd::ListenFd; +use actix_web::{get, web, Responder, middleware, App, HttpServer, HttpRequest}; +use askama_actix::Template; +use chrono::prelude::*; +use clap::Parser; use ron::de::from_reader; use serde::Deserialize; -use env_logger; - -use itertools::Itertools; mod consts; mod db; +mod hash; +mod model; + +#[derive(Template)] +#[template(path = "home.html")] +struct HomeTemplate { + recipes: Vec<(i32, String)>, +} #[derive(Template)] -#[template(path = "main.html")] -struct MainTemplate<'a> { - test: &'a str, +#[template(path = "view_recipe.html")] +struct ViewRecipeTemplate { + recipes: Vec<(i32, String)>, + current_recipe: model::Recipe, } #[derive(Deserialize)] @@ -26,12 +32,17 @@ pub struct Request { m: Option } -fn main_page(query: Query) -> HttpResponse { - - let main_template = MainTemplate { test: &"*** test ***" }; +#[get("/")] +async fn home_page(req: HttpRequest, connection: web::Data) -> impl Responder { + HomeTemplate { recipes: connection.get_all_recipe_titles().unwrap() } // TODO: unwrap. +} - let s = main_template.render().unwrap(); - HttpResponse::Ok().content_type("text/html").body(s) +#[get("/recipe/view/{id}")] +async fn view_recipe(req: HttpRequest, path: web::Path<(i32,)>, connection: web::Data) -> impl Responder { + ViewRecipeTemplate { + recipes: connection.get_all_recipe_titles().unwrap(), + current_recipe: connection.get_recipe(path.0).unwrap(), + } } #[derive(Debug, Deserialize)] @@ -45,10 +56,13 @@ fn get_exe_name() -> String { first_arg[first_arg.rfind(sep).unwrap()+1..].to_string() } -#[actix_rt::main] +#[actix_web::main] async fn main() -> std::io::Result<()> { if process_args() { return Ok(()) } + std::env::set_var("RUST_LOG", "actix_web=debug"); + env_logger::init(); + println!("Starting Recipes as web server..."); let config: Config = { @@ -61,35 +75,59 @@ async fn main() -> std::io::Result<()> { println!("Configuration: {:?}", config); - // let database_connection = db::create_or_update(); + let db_connection = web::Data::new(db::Connection::new().unwrap()); // TODO: remove unwrap. std::env::set_var("RUST_LOG", "actix_web=info"); - env_logger::init(); - let mut listenfd = ListenFd::from_env(); let mut server = HttpServer::new( - || { + move || { App::new() + .wrap(middleware::Logger::default()) .wrap(middleware::Compress::default()) - .wrap(Logger::default()) - .wrap(Logger::new("%a %{User-Agent}i")) - .service(web::resource("/").to(main_page)) + .app_data(db_connection.clone()) + .service(home_page) + .service(view_recipe) .service(fs::Files::new("/static", "static").show_files_listing()) } ); - server = - if let Some(l) = listenfd.take_tcp_listener(0).unwrap() { - server.listen(l).unwrap() - } else { - server.bind(&format!("0.0.0.0:{}", config.port)).unwrap() - }; + server = server.bind(&format!("0.0.0.0:{}", config.port)).unwrap(); server.run().await } +#[derive(Parser, Debug)] +struct Args { + #[arg(long)] + dbtest: bool +} + fn process_args() -> bool { + let args = Args::parse(); + + if args.dbtest { + match db::Connection::new() { + Ok(con) => { + if let Err(error) = con.execute_file("sql/data_test.sql") { + println!("Error: {:?}", error); + } + // Set the creation datetime to 'now'. + con.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc::now()]).unwrap(); + }, + Err(error) => { + println!("Error: {:?}", error) + }, + } + + return true; + } + + false + + /* + + fn print_usage() { println!("Usage:"); println!(" {} [--help] [--test]", get_exe_name()); @@ -101,10 +139,12 @@ fn process_args() -> bool { print_usage(); return true } else if args.iter().any(|arg| arg == "--test") { - let db_connection = db::Connection::new(); - db_connection.create_or_update(); + match db::Connection::new() { + Ok(_) => (), + Err(error) => println!("Error: {:?}", error) + } return true } - false + */ }