Skip to main content

rustbasic_medialibrary/
engine.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use rustbasic_core::sha2::{Digest, Sha256};
5use rustbasic_core::image;
6use rustbasic_core::image::imageops::FilterType;
7
8use rustbasic_core::serde::{Serialize, Deserialize};
9
10#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
11#[serde(crate = "rustbasic_core::serde")]
12pub struct MediaFile {
13    pub filename: String,
14    pub original_name: String,
15    pub size: usize,
16    pub mime_type: String,
17    pub category: String,
18    pub url: String,
19}
20
21/// Trait Asinkron untuk Backend Penyimpanan Media (Storage Backend)
22pub trait StorageBackend: Send + Sync {
23    /// Menyimpan byte file ke backend
24    fn store(&self, filename: &str, data: &[u8]) -> Result<String, String>;
25    /// Menghapus file dari backend
26    fn delete(&self, filepath: &str) -> Result<(), String>;
27    /// Membaca byte file dari backend
28    fn read(&self, filepath: &str) -> Result<Vec<u8>, String>;
29    /// Mendapatkan base path penyimpanan berkas
30    fn get_base_path(&self) -> String;
31}
32
33// ---------------------------------------------------------
34// 1. Local Storage Backend (Penyimpanan Disk Lokal)
35// ---------------------------------------------------------
36pub struct LocalStorageBackend {
37    pub base_dir: PathBuf,
38}
39
40impl LocalStorageBackend {
41    pub fn new(base_dir: impl Into<PathBuf>) -> Self {
42        let dir = base_dir.into();
43        fs::create_dir_all(&dir).ok();
44        Self { base_dir: dir }
45    }
46}
47
48impl StorageBackend for LocalStorageBackend {
49    fn store(&self, filename: &str, data: &[u8]) -> Result<String, String> {
50        let path = self.base_dir.join(filename);
51        if let Some(parent) = path.parent() {
52            fs::create_dir_all(parent).map_err(|e| e.to_string())?;
53        }
54        fs::write(&path, data).map_err(|e| e.to_string())?;
55        Ok(path.to_string_lossy().to_string())
56    }
57
58    fn delete(&self, filepath: &str) -> Result<(), String> {
59        let path = self.base_dir.join(filepath);
60        if path.exists() {
61            fs::remove_file(path).map_err(|e| e.to_string())?;
62        }
63        Ok(())
64    }
65
66    fn read(&self, filepath: &str) -> Result<Vec<u8>, String> {
67        let path = self.base_dir.join(filepath);
68        fs::read(path).map_err(|e| e.to_string())
69    }
70
71    fn get_base_path(&self) -> String {
72        self.base_dir.to_string_lossy().to_string()
73    }
74}
75
76// ---------------------------------------------------------
77// 2. S3 Storage Backend (Mock Terstruktur Cloud Storage)
78// ---------------------------------------------------------
79pub struct S3StorageBackend {
80    pub bucket: String,
81}
82
83impl S3StorageBackend {
84    pub fn new(bucket: impl Into<String>) -> Self {
85        Self { bucket: bucket.into() }
86    }
87}
88
89impl StorageBackend for S3StorageBackend {
90    fn store(&self, filename: &str, _data: &[u8]) -> Result<String, String> {
91        // Simulasi sukses upload ke cloud AWS S3 / Cloudflare R2
92        Ok(format!("https://{}.s3.amazonaws.com/{}", self.bucket, filename))
93    }
94
95    fn delete(&self, _filepath: &str) -> Result<(), String> {
96        Ok(())
97    }
98
99    fn read(&self, _filepath: &str) -> Result<Vec<u8>, String> {
100        Err("S3 Read tidak diaktifkan pada Mock S3 Storage".to_string())
101    }
102
103    fn get_base_path(&self) -> String {
104        format!("s3://{}", self.bucket)
105    }
106}
107
108// ---------------------------------------------------------
109// 3. MediaLibrary Manager
110// ---------------------------------------------------------
111pub struct MediaLibrary {
112    pub backend: Arc<dyn StorageBackend>,
113    pub max_size: Option<usize>,
114    pub allowed_types: Vec<String>,
115}
116
117impl MediaLibrary {
118    pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
119        Self {
120            backend,
121            max_size: None,
122            allowed_types: Vec::new(),
123        }
124    }
125
126    /// Menetapkan batas ukuran file maksimal (Bytes)
127    pub fn max_size(mut self, size: usize) -> Self {
128        self.max_size = Some(size);
129        self
130    }
131
132    /// Mendaftarkan MIME type yang diizinkan (misal "image/png")
133    pub fn allow_mime(mut self, mime: impl Into<String>) -> Self {
134        self.allowed_types.push(mime.into());
135        self
136    }
137
138    /// Melakukan upload berkas mentah (raw bytes) dengan validasi lengkap
139    pub fn upload(&self, original_name: &str, mime_type: &str, data: &[u8]) -> Result<MediaFile, String> {
140        // 1. Validasi Ukuran File
141        if self.max_size.is_some_and(|limit| data.len() > limit) {
142            let limit = self.max_size.unwrap_or(0);
143            return Err(format!("File terlalu besar. Maksimal: {} bytes, diterima: {} bytes.", limit, data.len()));
144        }
145
146        // 2. Validasi Tipe MIME
147        if !self.allowed_types.is_empty() && !self.allowed_types.iter().any(|t| t == mime_type) {
148            return Err(format!("Format berkas '{}' tidak didukung.", mime_type));
149        }
150
151        // 3. Hitung SHA-256 Hash data agar nama berkas unik dan terhindar dari duplikasi
152        let mut hasher = Sha256::new();
153        hasher.update(data);
154        let hash_result = format!("{:x}", hasher.finalize());
155
156        // 4. Dapatkan ekstensi asli berkas
157        let extension = Path::new(original_name)
158            .extension()
159            .and_then(|ext| ext.to_str())
160            .unwrap_or("bin");
161
162        let unique_filename = format!("{}.{}", hash_result, extension);
163
164        // 5. Simpan berkas melalui backend aktif
165        let _stored_path = self.backend.store(&unique_filename, data)?;
166
167        // 6. Buat URL publik relatif
168        let url = self.generate_relative_url(&unique_filename);
169
170        let category = Self::get_category(mime_type);
171
172        Ok(MediaFile {
173            filename: unique_filename,
174            original_name: original_name.to_string(),
175            size: data.len(),
176            mime_type: mime_type.to_string(),
177            category,
178            url,
179        })
180    }
181
182    /// Menghapus file media dari penyimpanan backend
183    pub fn delete(&self, file: &MediaFile) -> Result<(), String> {
184        self.backend.delete(&file.filename)
185    }
186
187    /// Mengubah ukuran gambar (resize & crop) menjadi thumbnail kotak/persegi
188    pub fn create_thumbnail(&self, source_file: &MediaFile, width: u32, height: u32) -> Result<MediaFile, String> {
189        // 1. Baca byte dari penyimpanan
190        let raw_bytes = self.backend.read(&source_file.filename)?;
191
192        // 2. Load gambar menggunakan image crate
193        let img = image::load_from_memory(&raw_bytes)
194            .map_err(|e| format!("Gagal memuat gambar: {}", e))?;
195
196        // 3. Potong (crop) dan ubah ukuran secara seimbang menjaga aspek rasio
197        let processed_img = img.resize_to_fill(width, height, FilterType::Lanczos3);
198
199        // 4. Tulis hasil ke memory buffer (virtual bytes)
200        let mut buffer = std::io::Cursor::new(Vec::new());
201        processed_img.write_to(&mut buffer, image::ImageFormat::Png)
202            .map_err(|e| format!("Gagal menulis hasil olahan gambar: {}", e))?;
203        let result_bytes = buffer.into_inner();
204
205        // 5. Beri nama baru berkas hasil crop
206        let base_name = Path::new(&source_file.filename)
207            .file_stem()
208            .and_then(|s| s.to_str())
209            .unwrap_or("image");
210
211        let thumb_filename = format!("{}_thumb_{}x{}.png", base_name, width, height);
212
213        // 6. Simpan hasil olahan via backend
214        let _stored_path = self.backend.store(&thumb_filename, &result_bytes)?;
215        let url = self.generate_relative_url(&thumb_filename);
216
217        Ok(MediaFile {
218            filename: thumb_filename,
219            original_name: format!("thumb_{}", source_file.original_name),
220            size: result_bytes.len(),
221            mime_type: "image/png".to_string(),
222            category: "image".to_string(),
223            url,
224        })
225    }
226
227    /// Mengkonversi gambar PNG/JPEG menjadi format WebP modern ultra-ringan
228    pub fn convert_to_webp(&self, source_file: &MediaFile) -> Result<MediaFile, String> {
229        let raw_bytes = self.backend.read(&source_file.filename)?;
230
231        let img = image::load_from_memory(&raw_bytes)
232            .map_err(|e| format!("Gagal memuat gambar: {}", e))?;
233
234        let mut buffer = std::io::Cursor::new(Vec::new());
235        img.write_to(&mut buffer, image::ImageFormat::WebP)
236            .map_err(|e| format!("Gagal mengonversi gambar ke WebP: {}", e))?;
237        let result_bytes = buffer.into_inner();
238
239        let base_name = Path::new(&source_file.filename)
240            .file_stem()
241            .and_then(|s| s.to_str())
242            .unwrap_or("image");
243
244        let webp_filename = format!("{}.webp", base_name);
245
246        let _stored_path = self.backend.store(&webp_filename, &result_bytes)?;
247        let url = self.generate_relative_url(&webp_filename);
248
249        Ok(MediaFile {
250            filename: webp_filename,
251            original_name: source_file.original_name.replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp"),
252            size: result_bytes.len(),
253            mime_type: "image/webp".to_string(),
254            category: "image".to_string(),
255            url,
256        })
257    }
258
259    fn generate_relative_url(&self, filename: &str) -> String {
260        let base = self.backend.get_base_path();
261        if let Some(stripped) = base.strip_prefix("public/") {
262            // Trim public/ prefix agar menjadi relative URL ramah web browser (cth "/uploads/...")
263            format!("/{}", stripped.trim_matches('/'))
264        } else if let Some(stripped) = base.strip_prefix("public") {
265            format!("/{}", stripped.trim_matches('/'))
266        } else if let Some(stripped) = base.strip_prefix("s3://") {
267            format!("https://{}.s3.amazonaws.com/{}", stripped, filename)
268        } else {
269            format!("/{}/{}", base.trim_matches('/'), filename)
270        }
271    }
272
273    /// Mengkategorikan tipe file secara otomatis berdasarkan MIME type
274    pub fn get_category(mime_type: &str) -> String {
275        let mime = mime_type.to_lowercase();
276        if mime.starts_with("image/") {
277            "image".to_string()
278        } else if mime.starts_with("video/") {
279            "video".to_string()
280        } else if mime.starts_with("audio/") {
281            "audio".to_string()
282        } else if mime == "application/pdf"
283            || mime.starts_with("text/")
284            || mime.contains("document")
285            || mime.contains("sheet")
286            || mime.contains("presentation")
287            || mime.contains("msword")
288        {
289            "document".to_string()
290        } else if mime.contains("zip")
291            || mime.contains("tar")
292            || mime.contains("rar")
293            || mime.contains("compressed")
294            || mime.contains("archive")
295        {
296            "archive".to_string()
297        } else {
298            "other".to_string()
299        }
300    }
301}
302
303// ---------------------------------------------------------
304// 🧪 Integration Unit Tests
305// ---------------------------------------------------------
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn test_upload_validation_flow() {
312        let backend = Arc::new(LocalStorageBackend::new("target/test_uploads"));
313        let library = MediaLibrary::new(backend)
314            .max_size(100) // Maks 100 bytes
315            .allow_mime("image/png");
316
317        // 1. Test data terlalu besar
318        let large_data = vec![0u8; 150];
319        let res = library.upload("test.png", "image/png", &large_data);
320        assert!(res.is_err());
321        assert!(res.unwrap_err().contains("File terlalu besar"));
322
323        // 2. Test format MIME tidak diizinkan
324        let ok_data = vec![0u8; 50];
325        let res = library.upload("test.pdf", "application/pdf", &ok_data);
326        assert!(res.is_err());
327        assert!(res.unwrap_err().contains("Format berkas"));
328
329        // 3. Test sukses upload & hashing unik
330        let res = library.upload("test.png", "image/png", &ok_data);
331        assert!(res.is_ok());
332        let file = res.unwrap();
333        assert_eq!(file.original_name, "test.png");
334        assert_eq!(file.mime_type, "image/png");
335        assert_eq!(file.category, "image");
336        
337        // Bersihkan hasil upload testing
338        let _ = library.delete(&file);
339    }
340
341    #[test]
342    fn test_image_processing_integration() {
343        let backend = Arc::new(LocalStorageBackend::new("target/test_images"));
344        let library = MediaLibrary::new(backend);
345
346        // 1. Buat gambar virtual 10x10 menggunakan image crate
347        let mut img = image::ImageBuffer::new(10, 10);
348        for (x, y, pixel) in img.enumerate_pixels_mut() {
349            *pixel = image::Rgb([(x * 10) as u8, (y * 10) as u8, 255u8]);
350        }
351
352        // Tulis virtual image ke buffer bytes (PNG format)
353        let mut buffer = std::io::Cursor::new(Vec::new());
354        image::DynamicImage::ImageRgb8(img).write_to(&mut buffer, image::ImageFormat::Png).unwrap();
355        let raw_bytes = buffer.into_inner();
356
357        // 2. Upload gambar asli
358        let original_file = library.upload("virtual.png", "image/png", &raw_bytes).unwrap();
359        assert_eq!(original_file.mime_type, "image/png");
360        assert_eq!(original_file.category, "image");
361
362        // 3. Transcode gambar ke WebP
363        let webp_file = library.convert_to_webp(&original_file).unwrap();
364        assert_eq!(webp_file.mime_type, "image/webp");
365        assert_eq!(webp_file.category, "image");
366        assert!(webp_file.filename.ends_with(".webp"));
367
368        // 4. Buat crop thumbnail kotak 5x5
369        let thumb_file = library.create_thumbnail(&webp_file, 5, 5).unwrap();
370        assert_eq!(thumb_file.mime_type, "image/png");
371        assert!(thumb_file.filename.contains("thumb_5x5"));
372
373        // Bersihkan seluruh berkas testing
374        let _ = library.delete(&original_file);
375        let _ = library.delete(&webp_file);
376        let _ = library.delete(&thumb_file);
377    }
378}