aboutsummaryrefslogtreecommitdiff
path: root/src/metadata.rs
blob: fe657e4e90bceaf45374bd3c215b08c79dcfc7ab (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
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use time::{format_description::well_known::Rfc2822, OffsetDateTime};

#[derive(Serialize, Deserialize)]
pub struct Metadata {
    pub id: String,
    #[serde(alias = "createdOn")]
    pub created_on: u64,
}

impl Metadata {
    pub fn read_or_create(file_path: &PathBuf) -> Metadata {
        if let Some(metadata) = Metadata::read_metadata_file(file_path) {
            metadata
        } else {
            let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).map_or_else(
                |_| 0,
                |duration| u64::try_from(duration.as_millis()).expect("Timestamp is too big!"),
            );
            Metadata {
                id: timestamp.to_string(),
                created_on: timestamp,
            }
        }
    }

    pub fn created_on_utc(&self) -> Option<String> {
        let date =
            OffsetDateTime::from_unix_timestamp_nanos((self.created_on * 1_000_000).into()).ok()?;
        date.format(&Rfc2822).ok()
    }

    fn read_metadata_file(file_path: &PathBuf) -> Option<Metadata> {
        let mut file = File::open(file_path).ok()?;
        let mut contents = String::new();
        file.read_to_string(&mut contents).ok()?;
        serde_json::from_str(&contents).ok()
    }
}