1use std::fs;
2use std::path::{Path, PathBuf};
3use std::sync::Arc;
4use sha2::{Digest, Sha256};
5use image::imageops::FilterType;
6
7#[derive(Clone, serde::Serialize, serde::Deserialize, Debug, PartialEq)]
9pub struct MediaFile {
10 pub filename: String,
11 pub original_name: String,
12 pub size: usize,
13 pub mime_type: String,
14 pub category: String,
15 pub url: String,
16}
17
18pub trait StorageBackend: Send + Sync {
20 fn store(&self, filename: &str, data: &[u8]) -> Result<String, String>;
22 fn delete(&self, filepath: &str) -> Result<(), String>;
24 fn read(&self, filepath: &str) -> Result<Vec<u8>, String>;
26 fn get_base_path(&self) -> String;
28}
29
30pub struct LocalStorageBackend {
34 pub base_dir: PathBuf,
35}
36
37impl LocalStorageBackend {
38 pub fn new(base_dir: impl Into<PathBuf>) -> Self {
39 let dir = base_dir.into();
40 fs::create_dir_all(&dir).ok();
41 Self { base_dir: dir }
42 }
43}
44
45impl StorageBackend for LocalStorageBackend {
46 fn store(&self, filename: &str, data: &[u8]) -> Result<String, String> {
47 let path = self.base_dir.join(filename);
48 if let Some(parent) = path.parent() {
49 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
50 }
51 fs::write(&path, data).map_err(|e| e.to_string())?;
52 Ok(path.to_string_lossy().to_string())
53 }
54
55 fn delete(&self, filepath: &str) -> Result<(), String> {
56 let path = self.base_dir.join(filepath);
57 if path.exists() {
58 fs::remove_file(path).map_err(|e| e.to_string())?;
59 }
60 Ok(())
61 }
62
63 fn read(&self, filepath: &str) -> Result<Vec<u8>, String> {
64 let path = self.base_dir.join(filepath);
65 fs::read(path).map_err(|e| e.to_string())
66 }
67
68 fn get_base_path(&self) -> String {
69 self.base_dir.to_string_lossy().to_string()
70 }
71}
72
73pub struct S3StorageBackend {
77 pub bucket: String,
78}
79
80impl S3StorageBackend {
81 pub fn new(bucket: impl Into<String>) -> Self {
82 Self { bucket: bucket.into() }
83 }
84}
85
86impl StorageBackend for S3StorageBackend {
87 fn store(&self, filename: &str, _data: &[u8]) -> Result<String, String> {
88 Ok(format!("https://{}.s3.amazonaws.com/{}", self.bucket, filename))
90 }
91
92 fn delete(&self, _filepath: &str) -> Result<(), String> {
93 Ok(())
94 }
95
96 fn read(&self, _filepath: &str) -> Result<Vec<u8>, String> {
97 Err("S3 Read tidak diaktifkan pada Mock S3 Storage".to_string())
98 }
99
100 fn get_base_path(&self) -> String {
101 format!("s3://{}", self.bucket)
102 }
103}
104
105pub struct MediaLibrary {
109 pub backend: Arc<dyn StorageBackend>,
110 pub max_size: Option<usize>,
111 pub allowed_types: Vec<String>,
112}
113
114impl MediaLibrary {
115 pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
116 Self {
117 backend,
118 max_size: None,
119 allowed_types: Vec::new(),
120 }
121 }
122
123 pub fn max_size(mut self, size: usize) -> Self {
125 self.max_size = Some(size);
126 self
127 }
128
129 pub fn allow_mime(mut self, mime: impl Into<String>) -> Self {
131 self.allowed_types.push(mime.into());
132 self
133 }
134
135 pub fn upload(&self, original_name: &str, mime_type: &str, data: &[u8]) -> Result<MediaFile, String> {
137 if self.max_size.is_some_and(|limit| data.len() > limit) {
139 let limit = self.max_size.unwrap_or(0);
140 return Err(format!("File terlalu besar. Maksimal: {} bytes, diterima: {} bytes.", limit, data.len()));
141 }
142
143 if !self.allowed_types.is_empty() && !self.allowed_types.iter().any(|t| t == mime_type) {
145 return Err(format!("Format berkas '{}' tidak didukung.", mime_type));
146 }
147
148 let mut hasher = Sha256::new();
150 hasher.update(data);
151 let hash_result = format!("{:x}", hasher.finalize());
152
153 let extension = Path::new(original_name)
155 .extension()
156 .and_then(|ext| ext.to_str())
157 .unwrap_or("bin");
158
159 let unique_filename = format!("{}.{}", hash_result, extension);
160
161 let _stored_path = self.backend.store(&unique_filename, data)?;
163
164 let url = self.generate_relative_url(&unique_filename);
166
167 let category = Self::get_category(mime_type);
168
169 Ok(MediaFile {
170 filename: unique_filename,
171 original_name: original_name.to_string(),
172 size: data.len(),
173 mime_type: mime_type.to_string(),
174 category,
175 url,
176 })
177 }
178
179 pub fn delete(&self, file: &MediaFile) -> Result<(), String> {
181 self.backend.delete(&file.filename)
182 }
183
184 pub fn create_thumbnail(&self, source_file: &MediaFile, width: u32, height: u32) -> Result<MediaFile, String> {
186 let raw_bytes = self.backend.read(&source_file.filename)?;
188
189 let img = image::load_from_memory(&raw_bytes)
191 .map_err(|e| format!("Gagal memuat gambar: {}", e))?;
192
193 let processed_img = img.resize_to_fill(width, height, FilterType::Lanczos3);
195
196 let mut buffer = std::io::Cursor::new(Vec::new());
198 processed_img.write_to(&mut buffer, image::ImageFormat::Png)
199 .map_err(|e| format!("Gagal menulis hasil olahan gambar: {}", e))?;
200 let result_bytes = buffer.into_inner();
201
202 let base_name = Path::new(&source_file.filename)
204 .file_stem()
205 .and_then(|s| s.to_str())
206 .unwrap_or("image");
207
208 let thumb_filename = format!("{}_thumb_{}x{}.png", base_name, width, height);
209
210 let _stored_path = self.backend.store(&thumb_filename, &result_bytes)?;
212 let url = self.generate_relative_url(&thumb_filename);
213
214 Ok(MediaFile {
215 filename: thumb_filename,
216 original_name: format!("thumb_{}", source_file.original_name),
217 size: result_bytes.len(),
218 mime_type: "image/png".to_string(),
219 category: "image".to_string(),
220 url,
221 })
222 }
223
224 pub fn convert_to_webp(&self, source_file: &MediaFile) -> Result<MediaFile, String> {
226 let raw_bytes = self.backend.read(&source_file.filename)?;
227
228 let img = image::load_from_memory(&raw_bytes)
229 .map_err(|e| format!("Gagal memuat gambar: {}", e))?;
230
231 let mut buffer = std::io::Cursor::new(Vec::new());
232 img.write_to(&mut buffer, image::ImageFormat::WebP)
233 .map_err(|e| format!("Gagal mengonversi gambar ke WebP: {}", e))?;
234 let result_bytes = buffer.into_inner();
235
236 let base_name = Path::new(&source_file.filename)
237 .file_stem()
238 .and_then(|s| s.to_str())
239 .unwrap_or("image");
240
241 let webp_filename = format!("{}.webp", base_name);
242
243 let _stored_path = self.backend.store(&webp_filename, &result_bytes)?;
244 let url = self.generate_relative_url(&webp_filename);
245
246 Ok(MediaFile {
247 filename: webp_filename,
248 original_name: source_file.original_name.replace(".png", ".webp").replace(".jpg", ".webp").replace(".jpeg", ".webp"),
249 size: result_bytes.len(),
250 mime_type: "image/webp".to_string(),
251 category: "image".to_string(),
252 url,
253 })
254 }
255
256 fn generate_relative_url(&self, filename: &str) -> String {
257 let base = self.backend.get_base_path();
258 if let Some(stripped) = base.strip_prefix("public/") {
259 format!("/{}", stripped.trim_matches('/'))
261 } else if let Some(stripped) = base.strip_prefix("public") {
262 format!("/{}", stripped.trim_matches('/'))
263 } else if let Some(stripped) = base.strip_prefix("s3://") {
264 format!("https://{}.s3.amazonaws.com/{}", stripped, filename)
265 } else {
266 format!("/{}/{}", base.trim_matches('/'), filename)
267 }
268 }
269
270 pub fn get_category(mime_type: &str) -> String {
272 let mime = mime_type.to_lowercase();
273 if mime.starts_with("image/") {
274 "image".to_string()
275 } else if mime.starts_with("video/") {
276 "video".to_string()
277 } else if mime.starts_with("audio/") {
278 "audio".to_string()
279 } else if mime == "application/pdf"
280 || mime.starts_with("text/")
281 || mime.contains("document")
282 || mime.contains("sheet")
283 || mime.contains("presentation")
284 || mime.contains("msword")
285 {
286 "document".to_string()
287 } else if mime.contains("zip")
288 || mime.contains("tar")
289 || mime.contains("rar")
290 || mime.contains("compressed")
291 || mime.contains("archive")
292 {
293 "archive".to_string()
294 } else {
295 "other".to_string()
296 }
297 }
298}
299
300#[cfg(test)]
304mod tests {
305 use super::*;
306
307 #[test]
308 fn test_upload_validation_flow() {
309 let backend = Arc::new(LocalStorageBackend::new("target/test_uploads"));
310 let library = MediaLibrary::new(backend)
311 .max_size(100) .allow_mime("image/png");
313
314 let large_data = vec![0u8; 150];
316 let res = library.upload("test.png", "image/png", &large_data);
317 assert!(res.is_err());
318 assert!(res.unwrap_err().contains("File terlalu besar"));
319
320 let ok_data = vec![0u8; 50];
322 let res = library.upload("test.pdf", "application/pdf", &ok_data);
323 assert!(res.is_err());
324 assert!(res.unwrap_err().contains("Format berkas"));
325
326 let res = library.upload("test.png", "image/png", &ok_data);
328 assert!(res.is_ok());
329 let file = res.unwrap();
330 assert_eq!(file.original_name, "test.png");
331 assert_eq!(file.mime_type, "image/png");
332 assert_eq!(file.category, "image");
333
334 let _ = library.delete(&file);
336 }
337
338 #[test]
339 fn test_image_processing_integration() {
340 let backend = Arc::new(LocalStorageBackend::new("target/test_images"));
341 let library = MediaLibrary::new(backend);
342
343 let mut img = image::ImageBuffer::new(10, 10);
345 for (x, y, pixel) in img.enumerate_pixels_mut() {
346 *pixel = image::Rgb([(x * 10) as u8, (y * 10) as u8, 255u8]);
347 }
348
349 let mut buffer = std::io::Cursor::new(Vec::new());
351 image::DynamicImage::ImageRgb8(img).write_to(&mut buffer, image::ImageFormat::Png).unwrap();
352 let raw_bytes = buffer.into_inner();
353
354 let original_file = library.upload("virtual.png", "image/png", &raw_bytes).unwrap();
356 assert_eq!(original_file.mime_type, "image/png");
357 assert_eq!(original_file.category, "image");
358
359 let webp_file = library.convert_to_webp(&original_file).unwrap();
361 assert_eq!(webp_file.mime_type, "image/webp");
362 assert_eq!(webp_file.category, "image");
363 assert!(webp_file.filename.ends_with(".webp"));
364
365 let thumb_file = library.create_thumbnail(&webp_file, 5, 5).unwrap();
367 assert_eq!(thumb_file.mime_type, "image/png");
368 assert!(thumb_file.filename.contains("thumb_5x5"));
369
370 let _ = library.delete(&original_file);
372 let _ = library.delete(&webp_file);
373 let _ = library.delete(&thumb_file);
374 }
375}