]> git.r.bdr.sh - rbdr/blog/blob - src/metadata.rs
Add release
[rbdr/blog] / src / metadata.rs
1 use std::fs::File;
2 use std::path::PathBuf;
3 use std::io::Read;
4 use std::time::{SystemTime, UNIX_EPOCH};
5 use time::{OffsetDateTime, format_description::well_known::Rfc2822};
6 use serde::{Serialize, Deserialize};
7 use serde_json;
8
9 #[derive(Serialize, Deserialize)]
10 pub struct Metadata {
11 pub id: String,
12 #[serde(alias = "createdOn")]
13 pub created_on: u64
14 }
15
16 impl Metadata {
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)
23 .map(|duration| duration.as_millis() as u64)
24 .unwrap_or_else(|_| 0);
25 return Metadata {
26 id: timestamp.to_string(),
27 created_on: timestamp
28 }
29 }
30 }
31 }
32
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
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()?;
45 serde_json::from_str(&contents).ok()
46 }
47 }