aboutsummaryrefslogtreecommitdiff
path: root/src/blog.rs
blob: e549fb2b5a88dd5de475938f001e493a0ab854e8 (plain)
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
use rust_embed::RustEmbed;
use sailfish::TemplateOnce;
use chrono::NaiveDate;
use regex::{Regex};
use std::str;

const BLOG_REGEX: &str = r"(?P<date>[\d]{4}-[\d]{2}-[\d]{2})(?P<title>[a-zA-Z0-9_]*)";

#[derive(RustEmbed)]
#[folder = "content/posts/"]
struct PostAsset;


#[derive(TemplateOnce)]
#[template(path = "index.html")]
struct IndexTemplate {
    posts: Vec<BlogEntry>,
}

#[derive(TemplateOnce)]
#[template(path = "post.html")]
struct PostTemplate {
    content: String,
    title: String,
    date: String
}

pub struct BlogEntry {
    pub title: String,
    pub datetime: NaiveDate,
    pub file: String,
}

impl BlogEntry {
    pub fn new(path: &String) -> BlogEntry {
        let re = Regex::new(BLOG_REGEX).unwrap();
        let caps = re.captures(path).unwrap();
        let date = &caps["date"];
        let title = str::replace(&caps["title"], "_", " ");

        BlogEntry {
            title: String::from(title),
            file: String::from(path),
            datetime: NaiveDate::parse_from_str(date, "%Y-%m-%d").unwrap()
        }
    }

    pub fn read_assets() -> Vec<BlogEntry> {
        PostAsset::iter()
            .map(|e| format!("{}", e))
            .map(|e| BlogEntry::new(&e))
            .collect()
    }
}

fn get_file_content(path: &str) -> String {
    let buffer = PostAsset::get(path)
        .unwrap()
        .data
        .into_owned();

    return String::from_utf8(buffer).unwrap();
}


pub fn render_post_page(path: &String) -> String {
    let blog = BlogEntry::new(path);

    PostTemplate {
        content: get_file_content(path),
        title: blog.title,
        date: blog.datetime.format("%Y-%m-%d").to_string()
    }
        .render_once()
        .unwrap()
}

pub fn render_index_page() -> String {
    IndexTemplate { posts: BlogEntry::read_assets() }
        .render_once()
        .unwrap()
}