glacier-web 0.4.1

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,
    /// The type the bytes show ([`Upload::detected_type`]).
    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);
        // The type the bytes show, not the one declared, as Paperclip keeps.
        let content_type = upload.detected_type();
        store
            .put(&key("original"), upload.bytes.clone(), &content_type)
            .await?;
        for style in self.styles {
            let resized = resize(&upload.bytes, style.width, style.height)?;
            store.put(&key(style.name), resized, &content_type).await?;
        }
        Ok(Stored {
            file_name,
            content_type,
            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(())
    }
}

/// An upload a record is about to keep, from a model's `has_attached`:
/// its columns are set when the record is saved, and its files stored
/// once the record has an id.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct Pending {
    /// The attachment's name (`image`), for errors.
    pub name: &'static str,
    pub attachment: Attachment,
    /// The `:class` in its path: the model's table.
    pub class: &'static str,
    pub upload: Upload,
    /// The file it replaces, removed once the new one is stored.
    pub previous: Option<String>,
    /// The types it may be (`image/png`), as the bytes show; any if empty.
    pub content_types: &'static [&'static str],
}

impl Pending {
    /// What the record's columns should say about the file:
    /// its name, the type its bytes show, its size and the time.
    pub fn columns(&self) -> (String, String, i32, crate::db::Timestamp) {
        (
            sanitize_filename(&self.upload.filename),
            self.upload.detected_type(),
            i32::try_from(self.upload.len()).unwrap_or(i32::MAX),
            crate::time::now(),
        )
    }

    /// Paperclip's checks: that the file is what it says it is, and of an
    /// allowed type.
    pub(crate) fn validate(&self, errors: &mut crate::db::Errors) {
        if self.upload.is_spoofed() {
            errors.add(
                self.name,
                "has contents that are not what they are reported to be",
            );
        } else if !self.content_types.is_empty()
            && !self
                .content_types
                .contains(&self.upload.detected_type().as_str())
        {
            errors.add(self.name, "is invalid");
        }
    }

    /// Stores the file and its styles for the record with this id, then
    /// removes the file it replaced.
    pub(crate) async fn store(self, id: i64) -> Result<()> {
        let store = crate::storage::current();
        let stored = self
            .attachment
            .store(&store, self.class, id, &self.upload)
            .await?;
        if let Some(previous) = self.previous
            && previous != stored.file_name
        {
            self.attachment
                .remove(&store, self.class, id, &previous)
                .await?;
        }
        Ok(())
    }
}

/// A file a record keeps, removed with the record.
#[doc(hidden)]
#[derive(Debug, Clone)]
pub struct Attached {
    pub attachment: Attachment,
    pub class: &'static str,
    pub id: i64,
    pub file_name: String,
}

impl Attached {
    pub(crate) async fn remove(&self) -> Result<()> {
        self.attachment
            .remove(
                &crate::storage::current(),
                self.class,
                self.id,
                &self.file_name,
            )
            .await
    }
}

/// The URL of a record's file in a style (`original` for the file as
/// sent), from the app's store, good for five minutes on S3.
pub fn url(
    attachment: &Attachment,
    class: &str,
    id: i64,
    style: &str,
    file_name: Option<&str>,
) -> Option<String> {
    let name = file_name?;
    Some(crate::storage::current().url(&attachment.path(class, id, style, name), 300))
}

/// 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();
    }
}