]> git.r.bdr.sh - rbdr/blog/blame - src/metadata.rs
Make smaller
[rbdr/blog] / src / metadata.rs
CommitLineData
a9c6be41
RBR
1use std::fs::File;
2use std::path::PathBuf;
3use std::io::Read;
4use std::time::{SystemTime, UNIX_EPOCH};
f6a545b0
RBR
5use time::{OffsetDateTime, format_description::well_known::Rfc2822};
6use serde::{Serialize, Deserialize};
7use serde_json;
a9c6be41 8
f6a545b0 9#[derive(Serialize, Deserialize)]
a9c6be41
RBR
10pub struct Metadata {
11 pub id: String,
f6a545b0
RBR
12 #[serde(alias = "createdOn")]
13 pub created_on: u64
a9c6be41
RBR
14}
15
16impl Metadata {
a9c6be41
RBR
17 pub fn read_or_create(file_path: &PathBuf) -> Metadata {
18 match Metadata::read_metadata_file(file_path) {
19 Some(metadata) => metadata,
20 None => {
21 let timestamp = SystemTime::now()
22 .duration_since(UNIX_EPOCH)
f6a545b0 23 .map(|duration| duration.as_millis() as u64)
a9c6be41
RBR
24 .unwrap_or_else(|_| 0);
25 return Metadata {
26 id: timestamp.to_string(),
27 created_on: timestamp
28 }
29 }
30 }
31 }
32
f6a545b0
RBR
33 pub fn created_on_utc(&self) -> Option<String> {
34 let date = OffsetDateTime::from_unix_timestamp_nanos(
35 (self.created_on * 1_000_000).into()
36 ).ok()?;
37 return date.format(&Rfc2822).ok();
38 }
39
40
a9c6be41
RBR
41 fn read_metadata_file(file_path: &PathBuf) -> Option<Metadata> {
42 let mut file = File::open(file_path).ok()?;
43 let mut contents = String::new();
44 file.read_to_string(&mut contents).ok()?;
f6a545b0 45 serde_json::from_str(&contents).ok()
a9c6be41
RBR
46 }
47}