glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Files attached to records, as Paperclip keeps them: the original and a
//! resized copy per style, under a path built from a pattern, with the
//! record's `<name>_file_name`, `_content_type`, `_file_size` and
//! `_updated_at` columns describing it.
//!
//! ```ignore
//! const NOTE_IMAGE: Attachment = Attachment {
//!     path: "/:class/:id/:style/:filename",
//!     styles: &[Style::fit("large", 960, 720), Style::fit("thumb", 132, 120)],
//! };
//! let stored = NOTE_IMAGE.store(&store, "comments", comment.id.into(), &upload).await?;
//! ```

use bytes::Bytes;

use crate::error::{Error, Result};
use crate::storage::Store;
use crate::upload::Upload;

/// A resized copy kept alongside the original: Paperclip's `"960x720"`,
/// scaled to fit within the box with its proportions kept.
#[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,
        }
    }
}

/// How a model keeps one attachment: where (a pattern with `:class`,
/// `:id`, `:style` and `:filename`) and in which styles.
#[derive(Debug, Clone, Copy)]
pub struct Attachment {
    pub path: &'static str,
    pub styles: &'static [Style],
}

/// What a record's columns record about its file.
#[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 {
    /// The path of a style (`original` for the file as sent), as
    /// Paperclip interpolates it.
    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)
    }

    /// Saves the upload and its styles for the record, returning what its
    /// columns should say.
    ///
    /// # Errors
    ///
    /// If an image style can't be made from it, or the store fails.
    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: crate::time::now().naive_utc(),
        })
    }

    /// Removes the file and its styles.
    ///
    /// # Errors
    ///
    /// If the store fails.
    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(())
    }
}

/// A file name as Paperclip keeps it: characters that are awkward in URLs
/// and paths become `_`.
pub fn sanitize_filename(name: &str) -> String {
    name.chars()
        .map(|c| {
            if "&$+,/:;=?@<>[]{}|\\^~%# ".contains(c) {
                '_'
            } else {
                c
            }
        })
        .collect()
}

/// The image scaled to fit within `width`×`height`, proportions kept,
/// turned upright from its EXIF orientation and saved in its own format,
/// as ImageMagick's `-auto-orient -resize WxH` does for Paperclip.
///
/// # Errors
///
/// If it isn't an image in a format Glacier reads (JPEG, PNG, GIF, WebP).
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();
    }
}