use bytes::Bytes;
use crate::error::{Error, Result};
use crate::storage::Store;
use crate::upload::Upload;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Style {
pub name: &'static str,
pub width: u32,
pub height: u32,
}
impl Style {
pub const fn fit(name: &'static str, width: u32, height: u32) -> Self {
Self {
name,
width,
height,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Attachment {
pub path: &'static str,
pub styles: &'static [Style],
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stored {
pub file_name: String,
pub content_type: String,
pub file_size: i32,
pub updated_at: chrono::NaiveDateTime,
}
impl Attachment {
pub fn path(&self, class: &str, id: i64, style: &str, file_name: &str) -> String {
self.path
.replace(":class", class)
.replace(":id", &id.to_string())
.replace(":style", style)
.replace(":filename", file_name)
}
pub async fn store(
&self,
store: &Store,
class: &str,
id: i64,
upload: &Upload,
) -> Result<Stored> {
let file_name = sanitize_filename(&upload.filename);
let key = |style: &str| self.path(class, id, style, &file_name);
store
.put(&key("original"), upload.bytes.clone(), &upload.content_type)
.await?;
for style in self.styles {
let resized = resize(&upload.bytes, style.width, style.height)?;
store
.put(&key(style.name), resized, &upload.content_type)
.await?;
}
Ok(Stored {
file_name,
content_type: upload.content_type.clone(),
file_size: i32::try_from(upload.len()).unwrap_or(i32::MAX),
updated_at: chrono::Utc::now().naive_utc(),
})
}
pub async fn remove(&self, store: &Store, class: &str, id: i64, file_name: &str) -> Result<()> {
store
.delete(&self.path(class, id, "original", file_name))
.await?;
for style in self.styles {
store
.delete(&self.path(class, id, style.name, file_name))
.await?;
}
Ok(())
}
}
pub fn sanitize_filename(name: &str) -> String {
name.chars()
.map(|c| {
if "&$+,/:;=?@<>[]{}|\\^~%# ".contains(c) {
'_'
} else {
c
}
})
.collect()
}
pub fn resize(bytes: &[u8], width: u32, height: u32) -> Result<Bytes> {
use image::ImageDecoder;
let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| Error::unprocessable(format!("not an image: {e}")))?;
let format = reader
.format()
.ok_or_else(|| Error::unprocessable("not an image in a known format"))?;
let mut decoder = reader
.into_decoder()
.map_err(|e| Error::unprocessable(format!("not an image: {e}")))?;
let orientation = decoder.orientation().ok();
let mut picture = image::DynamicImage::from_decoder(decoder)
.map_err(|e| Error::unprocessable(format!("not an image: {e}")))?;
if let Some(orientation) = orientation {
picture.apply_orientation(orientation);
}
let resized = picture.resize(width, height, image::imageops::FilterType::Lanczos3);
let mut out = std::io::Cursor::new(Vec::new());
resized
.write_to(&mut out, format)
.map_err(|e| Error::internal(format!("writing an image: {e}")))?;
Ok(out.into_inner().into())
}
#[cfg(test)]
mod tests {
use super::*;
fn png(width: u32, height: u32) -> Bytes {
let picture = image::DynamicImage::new_rgb8(width, height);
let mut out = std::io::Cursor::new(Vec::new());
picture.write_to(&mut out, image::ImageFormat::Png).unwrap();
out.into_inner().into()
}
fn size(bytes: &[u8]) -> (u32, u32) {
let picture = image::load_from_memory(bytes).unwrap();
(picture.width(), picture.height())
}
const NOTE_IMAGE: Attachment = Attachment {
path: "/:class/:id/:style/:filename",
styles: &[Style::fit("large", 960, 720), Style::fit("thumb", 132, 120)],
};
#[test]
fn builds_paths_and_safe_names() {
assert_eq!(
NOTE_IMAGE.path("comments", 7, "thumb", "a.png"),
"/comments/7/thumb/a.png"
);
assert_eq!(
sanitize_filename("my photo (1)#2.png"),
"my_photo_(1)_2.png"
);
}
#[test]
fn fits_images_in_their_style_boxes() {
assert_eq!(
size(&resize(&png(2000, 1000), 960, 720).unwrap()),
(960, 480)
);
assert_eq!(size(&resize(&png(100, 200), 132, 120).unwrap()), (60, 120));
assert_eq!(
size(&resize(&png(50, 40), 960, 720).unwrap()),
(900, 720),
"small images grow"
);
assert!(resize(b"not an image", 10, 10).is_err());
}
#[tokio::test]
async fn stores_the_original_and_each_style() {
let root = std::env::temp_dir().join(format!("glacier-attach-{}", std::process::id()));
let store = Store::Disk(root.clone());
let upload = Upload {
filename: "shelf photo.png".into(),
content_type: "image/png".into(),
bytes: png(1920, 1080),
};
let stored = NOTE_IMAGE
.store(&store, "comments", 7, &upload)
.await
.unwrap();
assert_eq!(stored.file_name, "shelf_photo.png");
assert_eq!(stored.content_type, "image/png");
let thumb = store
.get("/comments/7/thumb/shelf_photo.png")
.await
.unwrap()
.unwrap();
assert_eq!(size(&thumb), (132, 74));
assert!(
store
.get("/comments/7/original/shelf_photo.png")
.await
.unwrap()
.is_some()
);
NOTE_IMAGE
.remove(&store, "comments", 7, "shelf_photo.png")
.await
.unwrap();
assert!(
store
.get("/comments/7/large/shelf_photo.png")
.await
.unwrap()
.is_none()
);
std::fs::remove_dir_all(root).ok();
}
}