use crate::core::application::AppState;
use axum::{
body::Body,
extract::{FromRequest, Multipart},
http::Request,
};
use image::ImageFormat;
use std::collections::HashMap;
use std::io::Cursor;
#[derive(Clone)]
pub struct UploadedFile {
pub name: String,
pub original_name: String,
pub content_type: String,
pub data: Vec<u8>,
}
impl UploadedFile {
pub fn extension(&self) -> String {
std::path::Path::new(&self.original_name)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase()
}
pub fn size(&self) -> usize {
self.data.len()
}
pub fn is_image(&self) -> bool {
self.content_type.starts_with("image/")
}
pub async fn store(
&self,
req: &crate::core::request::Request,
directory: &str,
) -> Result<String, String> {
let hash = uuid::Uuid::new_v4().to_string(); let filename = format!("{}.{}", hash, self.extension());
let path = format!("{}/{}", directory.trim_end_matches('/'), filename);
req.state.storage.put(&path, &self.data).await?;
Ok(path)
}
pub async fn store_as(
&self,
req: &crate::core::request::Request,
directory: &str,
name: &str,
) -> Result<String, String> {
let path = format!("{}/{}", directory.trim_end_matches('/'), name);
req.state.storage.put(&path, &self.data).await?;
Ok(path)
}
pub fn resize(mut self, width: u32, height: u32) -> Self {
if let Ok(img) = image::load_from_memory(&self.data) {
let resized = img.resize(width, height, image::imageops::FilterType::Lanczos3);
let mut buf = Cursor::new(Vec::new());
let format = ImageFormat::from_extension(self.extension()).unwrap_or(ImageFormat::Png);
if resized.write_to(&mut buf, format).is_ok() {
self.data = buf.into_inner();
}
}
self
}
pub fn thumbnail(mut self, width: u32, height: u32) -> Self {
if let Ok(img) = image::load_from_memory(&self.data) {
let thumb = img.thumbnail(width, height);
let mut buf = Cursor::new(Vec::new());
let format = ImageFormat::from_extension(self.extension()).unwrap_or(ImageFormat::Png);
if thumb.write_to(&mut buf, format).is_ok() {
self.data = buf.into_inner();
}
}
self
}
pub fn grayscale(mut self) -> Self {
if let Ok(img) = image::load_from_memory(&self.data) {
let gray = img.grayscale();
let mut buf = Cursor::new(Vec::new());
let format = ImageFormat::from_extension(self.extension()).unwrap_or(ImageFormat::Png);
if gray.write_to(&mut buf, format).is_ok() {
self.data = buf.into_inner();
}
}
self
}
}
pub struct PakemMultipart {
pub fields: HashMap<String, String>,
pub files: HashMap<String, Vec<UploadedFile>>,
}
impl<S> FromRequest<S> for PakemMultipart
where
S: Send + Sync,
AppState: axum::extract::FromRef<S>,
{
type Rejection = crate::core::error::AppError;
async fn from_request(req: Request<Body>, state: &S) -> Result<Self, Self::Rejection> {
let mut multipart = Multipart::from_request(req, state).await.map_err(|_| {
crate::core::error::AppError::BadRequest("Format multipart tidak valid".into())
})?;
let mut fields = HashMap::new();
let mut files: HashMap<String, Vec<UploadedFile>> = HashMap::new();
while let Some(field) = multipart.next_field().await.map_err(|e| {
crate::core::error::AppError::BadRequest(format!("Gagal membaca field: {}", e))
})? {
let name = field.name().unwrap_or_default().to_string();
let file_name = field.file_name().map(|s| s.to_string());
let content_type = field
.content_type()
.map(|s| s.to_string())
.unwrap_or_default();
if let Some(orig_name) = file_name {
let data = field
.bytes()
.await
.map_err(|e| {
crate::core::error::AppError::BadRequest(format!(
"Gagal membaca data file: {}",
e
))
})?
.to_vec();
if !data.is_empty() {
let uploaded = UploadedFile {
name: name.clone(),
original_name: orig_name,
content_type,
data,
};
files.entry(name).or_default().push(uploaded);
}
} else {
let value = field.text().await.map_err(|e| {
crate::core::error::AppError::BadRequest(format!(
"Gagal membaca text field: {}",
e
))
})?;
fields.insert(name, value);
}
}
Ok(Self { fields, files })
}
}
impl PakemMultipart {
pub fn file(&self, name: &str) -> Option<&UploadedFile> {
self.files.get(name).and_then(|v| v.first())
}
pub fn files(&self, name: &str) -> Vec<&UploadedFile> {
self.files
.get(name)
.map(|v| v.iter().collect())
.unwrap_or_default()
}
pub fn input(&self, name: &str) -> Option<&String> {
self.fields.get(name)
}
pub fn has_file(&self, name: &str) -> bool {
self.files.contains_key(name)
}
}