5 use actix_web
::{get
, web
, Responder
, middleware
, App
, HttpServer
, HttpRequest
};
6 use askama_actix
::Template
;
7 use chrono
::prelude
::*;
9 use ron
::de
::from_reader
;
10 use serde
::Deserialize
;
18 #[template(path = "home.html")]
20 recipes
: Vec
<(i32, String
)>,
24 #[template(path = "view_recipe.html")]
25 struct ViewRecipeTemplate
{
26 recipes
: Vec
<(i32, String
)>,
27 current_recipe
: model
::Recipe
,
30 #[derive(Deserialize)]
36 async
fn home_page(req
: HttpRequest
, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
37 HomeTemplate
{ recipes
: connection
.get_all_recipe_titles().unwrap() } // TODO: unwrap.
40 #[get("/recipe/view/{id}")]
41 async
fn view_recipe(req
: HttpRequest
, path
: web
::Path
<(i32,)>, connection
: web
::Data
<db
::Connection
>) -> impl Responder
{
43 recipes
: connection
.get_all_recipe_titles().unwrap(),
44 current_recipe
: connection
.get_recipe(path
.0).unwrap(),
48 #[derive(Debug, Deserialize)]
53 fn get_exe_name() -> String
{
54 let first_arg
= std
::env
::args().nth(0).unwrap();
55 let sep
: &[_
] = &['
\\'
, '
/'
];
56 first_arg
[first_arg
.rfind(sep
).unwrap()+1..].to_string()
60 async
fn main() -> std
::io
::Result
<()> {
61 if process_args() { return Ok(()) }
63 std
::env
::set_var("RUST_LOG", "actix_web=debug");
66 println!("Starting Recipes as web server...");
68 let config
: Config
= {
69 let f
= File
::open(consts
::FILE_CONF
).unwrap_or_else(|_
| panic!("Failed to open configuration file {}", consts
::FILE_CONF
));
70 match from_reader(f
) {
72 Err(e
) => panic!("Failed to load config: {}", e
)
76 println!("Configuration: {:?}", config
);
78 let db_connection
= web
::Data
::new(db
::Connection
::new().unwrap()); // TODO: remove unwrap.
80 std
::env
::set_var("RUST_LOG", "actix_web=info");
86 .wrap(middleware
::Logger
::default())
87 .wrap(middleware
::Compress
::default())
88 .app_data(db_connection
.clone())
91 .service(fs
::Files
::new("/static", "static").show_files_listing())
95 server
= server
.bind(&format!("0.0.0.0:{}", config
.port
)).unwrap();
100 #[derive(Parser, Debug)]
106 fn process_args() -> bool
{
107 let args
= Args
::parse();
110 match db
::Connection
::new() {
112 if let Err(error
) = con
.execute_file("sql/data_test.sql") {
113 println!("Error: {:?}", error
);
115 // Set the creation datetime to 'now'.
116 con
.execute_sql("UPDATE [User] SET [creation_datetime] = ?1 WHERE [email] = 'paul@test.org'", [Utc
::now()]).unwrap();
119 println!("Error: {:?}", error
)
133 println!(" {} [--help] [--test]", get_exe_name());
136 let args: Vec<String> = args().collect();
138 if args.iter().any(|arg| arg == "--help") {
141 } else if args.iter().any(|arg| arg == "--test") {
142 match db::Connection::new() {
144 Err(error) => println!("Error: {:?}", error)