|
| 1 | +package com.semosan.api.domain.image.service; |
| 2 | + |
| 3 | +import com.semosan.api.common.exception.GeneralException; |
| 4 | +import com.semosan.api.common.status.ErrorStatus; |
| 5 | +import com.semosan.api.domain.image.dto.response.PresignedUrlResponse; |
| 6 | +import io.minio.GetPresignedObjectUrlArgs; |
| 7 | +import io.minio.MinioClient; |
| 8 | +import io.minio.http.Method; |
| 9 | +import lombok.RequiredArgsConstructor; |
| 10 | +import org.springframework.beans.factory.annotation.Value; |
| 11 | +import org.springframework.stereotype.Service; |
| 12 | + |
| 13 | +import java.util.Set; |
| 14 | +import java.util.UUID; |
| 15 | +import java.util.concurrent.TimeUnit; |
| 16 | + |
| 17 | +@Service |
| 18 | +@RequiredArgsConstructor |
| 19 | +public class ImageService { |
| 20 | + |
| 21 | + private static final Set<String> ALLOWED_BUCKETS = Set.of("reviews", "mountains", "restaurants"); |
| 22 | + private static final Set<String> ALLOWED_EXTENSIONS = Set.of(".jpg", ".jpeg", ".png", ".webp"); |
| 23 | + |
| 24 | + private final MinioClient minioClient; |
| 25 | + |
| 26 | + @Value("${minio.endpoint}") |
| 27 | + private String endpoint; |
| 28 | + |
| 29 | + @Value("${minio.public-url}") |
| 30 | + private String publicUrl; |
| 31 | + |
| 32 | + public PresignedUrlResponse generatePresignedUrl(String bucket, String filename) { |
| 33 | + validateBucket(bucket); |
| 34 | + String extension = extractExtension(filename); |
| 35 | + validateExtension(extension); |
| 36 | + |
| 37 | + String key = UUID.randomUUID() + extension; |
| 38 | + |
| 39 | + try { |
| 40 | + String uploadUrl = minioClient.getPresignedObjectUrl( |
| 41 | + GetPresignedObjectUrlArgs.builder() |
| 42 | + .method(Method.PUT) |
| 43 | + .bucket(bucket) |
| 44 | + .object(key) |
| 45 | + .expiry(10, TimeUnit.MINUTES) |
| 46 | + .build() |
| 47 | + ); |
| 48 | + |
| 49 | + uploadUrl = uploadUrl.replace(endpoint, publicUrl); |
| 50 | + String imageUrl = publicUrl + "/" + bucket + "/" + key; |
| 51 | + |
| 52 | + return new PresignedUrlResponse(uploadUrl, imageUrl); |
| 53 | + } catch (Exception e) { |
| 54 | + throw new GeneralException(ErrorStatus.IMAGE_UPLOAD_FAILED); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private void validateBucket(String bucket) { |
| 59 | + if (bucket == null || !ALLOWED_BUCKETS.contains(bucket)) { |
| 60 | + throw new GeneralException(ErrorStatus.BAD_REQUEST); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + private void validateExtension(String extension) { |
| 65 | + if (extension.isEmpty() || !ALLOWED_EXTENSIONS.contains(extension.toLowerCase())) { |
| 66 | + throw new GeneralException(ErrorStatus.BAD_REQUEST); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private String extractExtension(String filename) { |
| 71 | + if (filename == null || !filename.contains(".")) { |
| 72 | + return ""; |
| 73 | + } |
| 74 | + return filename.substring(filename.lastIndexOf(".")); |
| 75 | + } |
| 76 | +} |
0 commit comments