use std::fs::File; use std::path::PathBuf; use std::io::Read; use std::time::{SystemTime, UNIX_EPOCH}; use time::{OffsetDateTime, format_description::well_known::Rfc2822}; use serde::{Serialize, Deserialize}; use serde_json; #[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 { match Metadata::read_metadata_file(file_path) { Some(metadata) => metadata, None => { let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|duration| duration.as_millis() as u64) .unwrap_or_else(|_| 0); return Metadata { id: timestamp.to_string(), created_on: timestamp } } } } pub fn created_on_utc(&self) -> Option { let date = OffsetDateTime::from_unix_timestamp_nanos( (self.created_on * 1_000_000).into() ).ok()?; return date.format(&Rfc2822).ok(); } fn read_metadata_file(file_path: &PathBuf) -> Option { 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() } }