summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: fe686cab2704a5dd41e2fbd3fcce412b386f7f8a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use axum::{
    routing::{get, post},
    http::StatusCode,
    response::Html,
    extract::{State, Query},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use chrono::Local;
use std::sync::Arc;
use std::fs::{create_dir_all, File};
use std::io::{self, Write};
use std::path::Path;

#[tokio::main]
async fn main() {
    // initialize tracing
    tracing_subscriber::fmt::init();

    // build our application with a route
    let app = Router::new()
        // `GET /` goes to `root`
        .route("/", get(root))
        // `POST /users` goes to `create_user`
        .route("/submit", post(submit_text));

    // run our app with hyper, listening globally on port 3000
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

fn create_directory_hierarchy(payload: String, tags: Vec<&str>) -> io::Result<()> {
    let now = Local::now();
    let base_dir = "/home/builder/chrons";
    let path = now.format("%Y/%m/%d/%H-%M.txt").to_string();
    let full_path = Path::new(base_dir).join(path);
    let dir_path = full_path.parent().unwrap();
    create_dir_all(dir_path)?;
    let mut file = File::create(&full_path)?;
    writeln!(file, "* Entry {}", now.format("%d-%m-%Y %H:%M").to_string())?;
    for tag in tags.iter() {
	writeln!(file, "tag: {}", tag.trim())?;
    }
    writeln!(file, "\n{payload}")?;

    Ok(())
}

fn get_current_datetime() -> String {
    let now = Local::now();
    now.format("%d-%m-%y %H:%M").to_string()
}

async fn root() -> Html<String> {
    let reg = handlebars::Handlebars::new();
    let html = reg.render_template(
        include_str!("../main.handlebars"),
        &json!({}),
    ).unwrap();
    let cfg = minify_html::Cfg {
        minify_css: true,
        minify_js: true,
        ..Default::default()
    };
    let html = minify_html::minify(html.as_bytes(), &cfg);
    let html = String::from_utf8_lossy(&html).to_string();
    Html(html)
}

async fn submit_text(
    // this argument tells axum to parse the request body
    // as JSON into a `CreateUser` type
    Json(payload): Json<Entry>,
) -> StatusCode {
    // insert your application logic here
    let tags: Vec<&str> = payload.tags.split(",").collect();
    println!("{}", payload.text);
    let _ = create_directory_hierarchy(payload.text, tags);

    // this will be converted into a JSON response
    // with a status code of `201 Created`
    StatusCode::CREATED
}

#[derive(Deserialize)]
struct Entry {
    tags: String,
    text: String,
}