|
| 1 | + |
| 2 | +package com.semosan.api.domain.demo.service; |
| 3 | + |
| 4 | +import com.semosan.api.common.config.DemoProperties; |
| 5 | +import com.semosan.api.common.config.MinioProperties; |
| 6 | +import com.semosan.api.domain.tracking.entity.TrackingPhoto; |
| 7 | +import com.semosan.api.domain.tracking.repository.TrackingPhotoRepository; |
| 8 | +import io.minio.GetPresignedObjectUrlArgs; |
| 9 | +import io.minio.MinioClient; |
| 10 | +import io.minio.http.Method; |
| 11 | +import lombok.RequiredArgsConstructor; |
| 12 | +import lombok.extern.slf4j.Slf4j; |
| 13 | +import org.springframework.stereotype.Service; |
| 14 | +import org.springframework.transaction.annotation.Transactional; |
| 15 | + |
| 16 | +import java.util.ArrayList; |
| 17 | +import java.util.Collections; |
| 18 | +import java.util.List; |
| 19 | +import java.util.concurrent.TimeUnit; |
| 20 | + |
| 21 | +@Slf4j |
| 22 | +@Service |
| 23 | +@RequiredArgsConstructor |
| 24 | +@Transactional(readOnly = true) |
| 25 | +public class DemoService { |
| 26 | + |
| 27 | + private static final String BUCKET = "tracking-photos"; |
| 28 | + |
| 29 | + private final DemoProperties demoProperties; |
| 30 | + private final MinioClient minioClient; |
| 31 | + private final MinioProperties minioProperties; |
| 32 | + private final TrackingPhotoRepository trackingPhotoRepository; |
| 33 | + |
| 34 | + public List<String> getDemoPhotos(Long sessionId, int count) { |
| 35 | + List<String> shuffled = new ArrayList<>(demoProperties.photoFilenames()); |
| 36 | + Collections.shuffle(shuffled); |
| 37 | + List<String> randomUrls = shuffled.subList(0, Math.min(count, shuffled.size())) |
| 38 | + .stream() |
| 39 | + .map(this::presignedGetUrl) |
| 40 | + .toList(); |
| 41 | + |
| 42 | + List<String> uploadedUrls = trackingPhotoRepository |
| 43 | + .findByTrackingSession_IdOrderByMilestoneIndexAsc(sessionId) |
| 44 | + .stream() |
| 45 | + .map(TrackingPhoto::getImageUrl) |
| 46 | + .toList(); |
| 47 | + |
| 48 | + List<String> combined = new ArrayList<>(randomUrls); |
| 49 | + combined.addAll(uploadedUrls); |
| 50 | + return combined; |
| 51 | + } |
| 52 | + |
| 53 | + private String presignedGetUrl(String objectKey) { |
| 54 | + try { |
| 55 | + String url = minioClient.getPresignedObjectUrl( |
| 56 | + GetPresignedObjectUrlArgs.builder() |
| 57 | + .method(Method.GET) |
| 58 | + .bucket(BUCKET) |
| 59 | + .object(objectKey) |
| 60 | + .expiry(1, TimeUnit.HOURS) |
| 61 | + .build() |
| 62 | + ); |
| 63 | + return url.replace(minioProperties.endpoint(), minioProperties.publicUrl()); |
| 64 | + } catch (Exception e) { |
| 65 | + log.warn("Failed to generate presigned URL for {}", objectKey, e); |
| 66 | + return minioProperties.publicUrl() + "/" + BUCKET + "/" + objectKey; |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments