first fully working version

This commit is contained in:
hexlocation pc 2024-07-12 21:36:35 +02:00
parent 473bd34e4f
commit db01e0494f
6 changed files with 205 additions and 31 deletions

37
src/logger.rs Normal file
View file

@ -0,0 +1,37 @@
extern crate supports_color;
pub mod iwakulog {
use supports_color::Stream;
pub enum LogLevel {
Fail,
Warn,
Info
}
const COLOR_RESET: &str = "\x1b[0m";
const COLOR_FAIL: &str = "\x1b[0;31m";
const COLOR_WARN: &str = "\x1b[0;33m";
const COLOR_INFO: &str = "\x1b[0;34m";
fn _prefix(p: &str, c1: &str, c2: &str, c3: &str, color_support: bool) -> String {
if color_support {
return format!("{}[{}{}{}]", c1, c2, p, c3);
}
return format!("[{}]", p);
}
fn prefix(level: LogLevel) -> String {
let color_support = supports_color::on(Stream::Stdout);
let prefixa = match level {
LogLevel::Fail => _prefix("f", COLOR_RESET, COLOR_FAIL, COLOR_RESET, color_support.is_some()),
LogLevel::Warn => _prefix("w", COLOR_RESET, COLOR_WARN, COLOR_RESET, color_support.is_some()),
LogLevel::Info => _prefix("i", COLOR_RESET, COLOR_INFO, COLOR_RESET, color_support.is_some()),
};
return prefixa;
}
pub fn log(level: LogLevel, message: &str) {
println!("{}: {}", prefix(level), message);
}
}

View file

@ -1,48 +1,97 @@
mod logger;
extern crate rocket;
extern crate rocket_dyn_templates;
use rocket::{get,launch, build, routes};
use rocket::response::content::RawJson;
use rocket::{get, post, launch, build, routes};
use rocket::fs::FileServer;
use rocket_dyn_templates::{Template, context};
use rocket::serde::{Deserialize, Serialize, json::Json};
use chrono::Local;
use std::borrow::Cow;
use std::io::Write;
use std::path::Path;
use std::fs::File;
use std::fs::read_to_string;
use serde_json::{Value, json};
use crate::logger::iwakulog::{LogLevel, log};
const ASSETS_DIR: &str = "./assets";
const GUEST_MESSAGES: &str = "./guests.json";
const DATE_TIME_FORMAT: &str = "%Y-%m%d | %H:%M";
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
struct GuestMessage<'r> {
name: Cow<'r, str>,
body: Cow<'r, str>,
}
static ASSETS_DIR: &str = "./assets";
static GUEST_MESSAGES: &str = "./guests.json";
fn check_file(path: &str) -> bool {
Path::new(path).exists()
}
fn read_guest_messages() -> Result<Value, Box<dyn std::error::Error>> {
let file = read_to_string(GUEST_MESSAGES)?;
let json: Value = serde_json::from_str(&file)?;
Ok(json)
}
fn post_guest_message(name: &str, body: &str) {
let mut guest_json = match read_guest_messages() {
Ok(x) => x,
Err(x) => panic!("Error while reading guest messages: {x:?}")
};
let messages = guest_json["messages"]
.as_array_mut()
.expect("Object is not an array?");
let date = Local::now().format(DATE_TIME_FORMAT);
messages.push(json!({
"name": name,
"body": body,
"date": date.to_string(),
}));
let mut file = File::create(GUEST_MESSAGES).expect("Couldn't read msgs");
file.write_all(guest_json.to_string().as_bytes()).expect("wah");
}
#[get("/")]
fn index() -> Template {
let cx = context! {
hi: "no",
};
Template::render("index", &cx)
Template::render("index", context! {})
}
#[post("/post_message", data = "<input>")]
fn post_msg(input: Json<GuestMessage<'_>>) {
post_guest_message(&input.name, &input.body);
return;
}
#[get("/guestbook")]
fn guests() -> Template {
let cx = context! {
messages: [
context!{
name: "hexlocation",
date: "12 Jun.",
body: "<h1>xd1</h1>",
}
]
let guest_json = match read_guest_messages() {
Ok(x) => x,
Err(x) => panic!("Error while reading guest messages: {x:?}")
};
Template::render("guest", &cx)
Template::render("guest", &guest_json)
}
#[launch]
fn rocket() -> _ {
if !check_file(GUEST_MESSAGES) {
File::create(GUEST_MESSAGES).unwrap();
log(LogLevel::Warn, format!("Guest messages file ({}) has not been found. Creating a new one.", GUEST_MESSAGES).as_str());
let mut file = File::create(GUEST_MESSAGES).expect("Failed to create file.");
file.write_all(b"{\"messages\":[]}").expect("Failed to write to file.");
}
build()
.mount("/", routes![index, guests])
.mount("/", routes![index, guests, post_msg])
.mount("/assets", FileServer::from(ASSETS_DIR))
.attach(Template::fairing())
}