monorepo/file-service/src/store/thumbnail.rs

85 lines
2.1 KiB
Rust
Raw Normal View History

use image::imageops::FilterType;
use std::fs::remove_file;
use std::path::{Path, PathBuf};
use super::{ReadFileError, WriteFileError};
#[derive(Clone, Debug, PartialEq)]
pub struct Thumbnail {
2023-09-23 19:17:49 +00:00
pub path: PathBuf,
}
impl Thumbnail {
2023-09-23 19:17:49 +00:00
pub fn open(
origin_path: PathBuf,
thumbnail_path: PathBuf,
) -> Result<Thumbnail, WriteFileError> {
let s = Thumbnail {
path: PathBuf::from(thumbnail_path),
};
2023-09-23 19:17:49 +00:00
if !s.path.exists() {
let img = image::open(&origin_path)?;
let tn = img.resize(640, 640, FilterType::Nearest);
2023-09-23 19:17:49 +00:00
tn.save(&s.path)?;
}
2023-09-23 19:17:49 +00:00
Ok(s)
}
/*
pub fn from_path(path: &Path) -> Result<Thumbnail, ReadFileError> {
let id = path
.file_name()
.map(|s| String::from(s.to_string_lossy()))
.ok_or(ReadFileError::NotAnImage(PathBuf::from(path)))?;
2023-09-23 19:17:49 +00:00
let path = path
.parent()
.ok_or(ReadFileError::FileNotFound(PathBuf::from(path)))?;
Thumbnail::open(&id, root)
}
*/
2023-09-23 19:17:49 +00:00
/*
fn thumbnail_path(id: &str, root: &Path) -> PathBuf {
let mut path = PathBuf::from(root);
path.push(".thumbnails");
path.push(id.clone());
path
}
2023-09-23 19:17:49 +00:00
*/
pub fn stream(&self) -> Result<std::fs::File, ReadFileError> {
2023-09-23 19:17:49 +00:00
std::fs::File::open(self.path.clone()).map_err(|err| {
if err.kind() == std::io::ErrorKind::NotFound {
ReadFileError::FileNotFound
} else {
ReadFileError::from(err)
}
})
}
2023-09-23 19:17:49 +00:00
pub fn delete(self) -> Result<(), WriteFileError> {
remove_file(self.path).map_err(WriteFileError::from)
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::store::utils::FileCleanup;
#[test]
fn it_creates_a_thumbnail_if_one_does_not_exist() {
2023-09-23 19:17:49 +00:00
let _ = FileCleanup(PathBuf::from("var/rawr.tn.png"));
let _ = Thumbnail::open(
PathBuf::from("fixtures/rawr.png"),
PathBuf::from("var/rawr.tn.png"),
)
.expect("thumbnail open must work");
assert!(Path::new("var/rawr.tn.png").is_file());
}
}