image.rs 1.32 KB
use std::fmt::Display;

use crate::{models::image, AppData};

use actix_web::{Error, web};
use anyhow::Result;
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize, Serialize)]
#[serde (rename_all = "lowercase")]
pub enum Size {
    Original,
    Large,
    Medium,
    Small
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SizeQuery {
    size :Option<Size>,
}

impl Display for Size {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let size_str = match self {
            Size::Original => "original",
            Size::Large => "large",
            Size::Medium => "medium",
            Size::Small => "small"
        };

        write!(f, "{}", size_str)
    }
}

pub async fn get_image( app_data: web::Data<AppData>
                      , ident: web::Path<i32>
                      , size: web::Query<SizeQuery>
                      ) -> Result<actix_files::NamedFile, Error>
{
    let pool = app_data.database_pool.clone();
    let ident = ident.into_inner();
    let size = size.into_inner().size.or(Some(Size::Large)).unwrap();

    let image = web::block(move || image::get_image(pool, ident)).await?;
    let path = image.path(size);

    Ok( actix_files::NamedFile::open(path)?
      . set_content_type(image.mime_type.parse().unwrap())
      . disable_content_disposition() )
}