use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rustbasic_core::sha2::{Digest, Sha256};
use rustbasic_core::image;
use rustbasic_core::image::imageops::FilterType;
use rustbasic_core::serde::{Serialize, Deserialize};
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
#[serde(crate = "rustbasic_core::serde")]
pub struct MediaFile {
pub filename: String,
pub original_name: String,
pub size: usize,
pub mime_type: String,
pub category: String,
pub url: String,
}
pub trait StorageBackend: Send + Sync {
fn store(&self, filename: &str, data: &[u8]) -> Result<String, String>;
fn delete(&self, filepath: &str) -> Result<(), String>;
fn read(&self, filepath: &str) -> Result<Vec<u8>, String>;
fn get_base_path(&self) -> String;
}
pub struct LocalStorageBackend {
pub base_dir: PathBuf,
}
impl LocalStorageBackend {
pub fn new(base_dir: impl Into<PathBuf>) -> Self {
let dir = base_dir.into();
fs::create_dir_all(&dir).ok();
Self { base_dir: dir }
}
}
impl StorageBackend for LocalStorageBackend {
fn store(&self, filename: &str, data: &[u8]) -> Result<String, String> {
let path = self.base_dir.join(filename);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
fs::write(&path, data).map_err(|e| e.to_string())?;
Ok(path.to_string_lossy().to_string())
}
fn delete(&self, filepath: &str) -> Result<(), String> {
let path = self.base_dir.join(filepath);
if path.exists() {
fs::remove_file(path).map_err(|e| e.to_string())?;
}
Ok(())
}
fn read(&self, filepath: &str) -> Result<Vec<u8>, String> {
let path = self.base_dir.join(filepath);
fs::read(path).map_err(|e| e.to_string())
}
fn get_base_path(&self) -> String {
self.base_dir.to_string_lossy().to_string()
}
}
pub struct S3StorageBackend {
pub bucket: String,
}
impl S3StorageBackend {
pub fn new(bucket: impl Into<String>) -> Self {
Self { bucket: bucket.into() }
}
}
impl StorageBackend for S3StorageBackend {
fn store(&self, filename: &str, _data: &[u8]) -> Result<String, String> {
Ok(format!("https://{}.s3.amazonaws.com/{}", self.bucket, filename))
}
fn delete(&self, _filepath: &str) -> Result<(), String> {
Ok(())
}
fn read(&self, _filepath: &str) -> Result<Vec<u8>, String> {
Err("S3 Read tidak diaktifkan pada Mock S3 Storage".to_string())
}
fn get_base_path(&self) -> String {
format!("s3://{}", self.bucket)
}
}
pub struct MediaLibrary {
pub backend: Arc<dyn StorageBackend>,
pub max_size: Option<usize>,
pub allowed_types: Vec<String>,
}
impl MediaLibrary {
pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
Self {
backend,
max_size: None,
allowed_types: Vec::new(),
}
}
pub fn max_size(mut self, size: usize) -> Self {
self.max_size = Some(size);
self
}
pub fn allow_mime(mut self, mime: impl Into<String>) -> Self {
self.allowed_types.push(mime.into());
self
}
pub fn upload(&self, original_name: &str, mime_type: &str, data: &[u8]) -> Result<MediaFile, String> {
if self.max_size.is_some_and(|limit| data.len() > limit) {
let limit = self.max_size.unwrap_or(0);
return Err(format!("File terlalu besar. Maksimal: {} bytes, diterima: {} bytes.", limit, data.len()));
}
if !self.allowed_types.is_empty() && !self.allowed_types.iter().any(|t| t == mime_type) {
return Err(format!("Format berkas '{}' tidak didukung.", mime_type));
}
let mut hasher = Sha256::new();
hasher.update(data);
let hash_result = format!("{:x}", hasher.finalize());
let extension = Path::new(original_name)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("bin");
let unique_filename = format!("{}.{}", hash_result, extension);
let _stored_path = self.backend.store(&unique_filename, data)?;
let url = self.generate_relative_url(&unique_filename);
let category = Self::get_category(mime_type);
Ok(MediaFile {
filename: unique_filename,
original_name: original_name.to_string(),
size: data.len(),
mime_type: mime_type.to_string(),
category,
url,
})
}
pub fn delete(&self, file: &MediaFile) -> Result<(), String> {
self.backend.delete(&file.filename)
}
pub fn create_thumbnail(&self, source_file: &MediaFile, width: u32, height: u32) -> Result<MediaFile, String> {
let raw_bytes = self.backend.read(&source_file.filename)?;
let img = image::load_from_memory(&raw_bytes)
.map_err(|e| format!("Gagal memuat gambar: {}", e))?;
let processed_img = img.resize_to_fill(width, height, FilterType::Lanczos3);
let mut buffer = std::io::Cursor::new(Vec::new());
processed_img.write_to(&mut buffer, image::ImageFormat::Png)
.map_err(|e| format!("Gagal menulis hasil olahan gambar: {}", e))?;
let result_bytes = buffer.into_inner();
let base_name = Path::new(&source_file.filename)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("image");
let thumb_filename = format!("{}_thumb_{}x{}.png", base_name, width, height);
let _stored_path = self.backend.store(&thumb_filename, &result_bytes)?;
let url = self.generate_relative_url(&thumb_filename);
Ok(MediaFile {
filename: thumb_filename,
original_name: format!("thumb_{}", source_file.original_name),
size: result_bytes.len(),
mime_type: "image/png".to_string(),
category: "image".to_string(),
url,
})
}
pub fn convert_to_webp(&self, source_file: &MediaFile) -> Result<MediaFile, String> {
let raw_bytes = self.backend.read(&source_file.filename)?;
let img = image::load_from_memory(&raw_bytes)
.map_err(|e| format!("Gagal memuat gambar: {}", e))?;
let mut buffer = std::io::Cursor::new(Vec::new());
img.write_to(&mut buffer, image::ImageFormat::WebP)
.map_err(|e| format!("Gagal mengonversi gambar ke WebP: {}", e))?;
let result_bytes = buffer.into_inner();
let base_name = Path::new(&source_file.filename)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("image");
let webp_filename = format!("{}.webp", base_name);
let _stored_path = self.backend.store(&webp_filename, &result_bytes)?;
let url = self.generate_relative_url(&webp_filename);
Ok(MediaFile {
filename: webp_filename,
original_name: source_file.original_name.replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp"),
size: result_bytes.len(),
mime_type: "image/webp".to_string(),
category: "image".to_string(),
url,
})
}
fn generate_relative_url(&self, filename: &str) -> String {
let base = self.backend.get_base_path();
if let Some(stripped) = base.strip_prefix("public/") {
format!("/{}", stripped.trim_matches('/'))
} else if let Some(stripped) = base.strip_prefix("public") {
format!("/{}", stripped.trim_matches('/'))
} else if let Some(stripped) = base.strip_prefix("s3://") {
format!("https://{}.s3.amazonaws.com/{}", stripped, filename)
} else {
format!("/{}/{}", base.trim_matches('/'), filename)
}
}
pub fn get_category(mime_type: &str) -> String {
let mime = mime_type.to_lowercase();
if mime.starts_with("image/") {
"image".to_string()
} else if mime.starts_with("video/") {
"video".to_string()
} else if mime.starts_with("audio/") {
"audio".to_string()
} else if mime == "application/pdf"
|| mime.starts_with("text/")
|| mime.contains("document")
|| mime.contains("sheet")
|| mime.contains("presentation")
|| mime.contains("msword")
{
"document".to_string()
} else if mime.contains("zip")
|| mime.contains("tar")
|| mime.contains("rar")
|| mime.contains("compressed")
|| mime.contains("archive")
{
"archive".to_string()
} else {
"other".to_string()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_upload_validation_flow() {
let backend = Arc::new(LocalStorageBackend::new("target/test_uploads"));
let library = MediaLibrary::new(backend)
.max_size(100) .allow_mime("image/png");
let large_data = vec![0u8; 150];
let res = library.upload("test.png", "image/png", &large_data);
assert!(res.is_err());
assert!(res.unwrap_err().contains("File terlalu besar"));
let ok_data = vec![0u8; 50];
let res = library.upload("test.pdf", "application/pdf", &ok_data);
assert!(res.is_err());
assert!(res.unwrap_err().contains("Format berkas"));
let res = library.upload("test.png", "image/png", &ok_data);
assert!(res.is_ok());
let file = res.unwrap();
assert_eq!(file.original_name, "test.png");
assert_eq!(file.mime_type, "image/png");
assert_eq!(file.category, "image");
let _ = library.delete(&file);
}
#[test]
fn test_image_processing_integration() {
let backend = Arc::new(LocalStorageBackend::new("target/test_images"));
let library = MediaLibrary::new(backend);
let mut img = image::ImageBuffer::new(10, 10);
for (x, y, pixel) in img.enumerate_pixels_mut() {
*pixel = image::Rgb([(x * 10) as u8, (y * 10) as u8, 255u8]);
}
let mut buffer = std::io::Cursor::new(Vec::new());
image::DynamicImage::ImageRgb8(img).write_to(&mut buffer, image::ImageFormat::Png).unwrap();
let raw_bytes = buffer.into_inner();
let original_file = library.upload("virtual.png", "image/png", &raw_bytes).unwrap();
assert_eq!(original_file.mime_type, "image/png");
assert_eq!(original_file.category, "image");
let webp_file = library.convert_to_webp(&original_file).unwrap();
assert_eq!(webp_file.mime_type, "image/webp");
assert_eq!(webp_file.category, "image");
assert!(webp_file.filename.ends_with(".webp"));
let thumb_file = library.create_thumbnail(&webp_file, 5, 5).unwrap();
assert_eq!(thumb_file.mime_type, "image/png");
assert!(thumb_file.filename.contains("thumb_5x5"));
let _ = library.delete(&original_file);
let _ = library.delete(&webp_file);
let _ = library.delete(&thumb_file);
}
}