2023-09-23 23:15:56 +00:00
|
|
|
use crate::FileId;
|
|
|
|
|
2023-09-23 19:17:49 +00:00
|
|
|
use super::{ReadFileError, WriteFileError};
|
2023-09-23 03:43:45 +00:00
|
|
|
use chrono::prelude::*;
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use serde_json;
|
2023-09-23 19:17:49 +00:00
|
|
|
use std::{
|
|
|
|
io::{Read, Write},
|
|
|
|
path::PathBuf,
|
|
|
|
};
|
2023-09-23 03:43:45 +00:00
|
|
|
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
|
|
pub struct FileInfo {
|
2023-09-23 23:15:56 +00:00
|
|
|
pub id: FileId,
|
2023-09-23 03:43:45 +00:00
|
|
|
pub size: usize,
|
|
|
|
pub created: DateTime<Utc>,
|
|
|
|
pub file_type: String,
|
|
|
|
pub hash: String,
|
2023-09-23 23:15:56 +00:00
|
|
|
pub extension: String,
|
2023-09-23 03:43:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FileInfo {
|
|
|
|
pub fn load(path: PathBuf) -> Result<Self, ReadFileError> {
|
|
|
|
let mut content: Vec<u8> = Vec::new();
|
2023-09-23 23:15:56 +00:00
|
|
|
let mut file =
|
|
|
|
std::fs::File::open(path.clone()).map_err(|_| ReadFileError::FileNotFound(path))?;
|
2023-09-23 03:43:45 +00:00
|
|
|
file.read_to_end(&mut content)?;
|
|
|
|
let js = serde_json::from_slice(&content)?;
|
|
|
|
|
|
|
|
Ok(js)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn save(&self, path: PathBuf) -> Result<(), WriteFileError> {
|
|
|
|
let ser = serde_json::to_string(self).unwrap();
|
|
|
|
let mut file = std::fs::File::create(path)?;
|
|
|
|
file.write(ser.as_bytes())?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
2023-09-25 04:58:35 +00:00
|
|
|
use crate::store::FileId;
|
|
|
|
use tempdir::TempDir;
|
2023-09-23 03:43:45 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn it_saves_and_loads_metadata() {
|
2023-09-25 04:58:35 +00:00
|
|
|
let tmp = TempDir::new("var").unwrap();
|
2023-09-23 03:43:45 +00:00
|
|
|
let created = Utc::now();
|
|
|
|
|
|
|
|
let info = FileInfo {
|
2023-09-23 23:15:56 +00:00
|
|
|
id: FileId("temp-id".to_owned()),
|
2023-09-23 03:43:45 +00:00
|
|
|
size: 23777,
|
|
|
|
created,
|
|
|
|
file_type: "image/png".to_owned(),
|
|
|
|
hash: "abcdefg".to_owned(),
|
2023-09-23 23:15:56 +00:00
|
|
|
extension: "png".to_owned(),
|
2023-09-23 03:43:45 +00:00
|
|
|
};
|
2023-09-25 04:58:35 +00:00
|
|
|
let mut path = tmp.path().to_owned();
|
|
|
|
path.push(&PathBuf::from(info.id.clone()));
|
|
|
|
info.save(path.clone()).unwrap();
|
2023-09-23 03:43:45 +00:00
|
|
|
|
2023-09-25 04:58:35 +00:00
|
|
|
let info_ = FileInfo::load(path).unwrap();
|
2023-09-23 03:43:45 +00:00
|
|
|
assert_eq!(info_.size, 23777);
|
|
|
|
assert_eq!(info_.created, info.created);
|
|
|
|
assert_eq!(info_.file_type, "image/png");
|
|
|
|
assert_eq!(info_.hash, info.hash);
|
|
|
|
}
|
|
|
|
}
|