54 lines
2.1 KiB
Kotlin
54 lines
2.1 KiB
Kotlin
package net.halfbinary.scavengerhuntapi.service
|
|
|
|
import net.coobird.thumbnailator.Thumbnails
|
|
import net.halfbinary.scavengerhuntapi.model.HuntId
|
|
import net.halfbinary.scavengerhuntapi.model.ItemId
|
|
import net.halfbinary.scavengerhuntapi.model.PhotoStatus
|
|
import net.halfbinary.scavengerhuntapi.model.converter.toRecord
|
|
import net.halfbinary.scavengerhuntapi.model.domain.Photo
|
|
import net.halfbinary.scavengerhuntapi.repository.PhotoRepository
|
|
import org.springframework.http.MediaType
|
|
import org.springframework.stereotype.Service
|
|
import org.springframework.web.multipart.MultipartFile
|
|
import java.io.ByteArrayInputStream
|
|
import java.io.ByteArrayOutputStream
|
|
import java.time.LocalDateTime
|
|
|
|
@Service
|
|
class PhotoService(
|
|
private val photoRepository: PhotoRepository,
|
|
private val hunterService: HunterService,
|
|
private val s3StorageService: S3StorageService
|
|
) {
|
|
fun submitPhoto(huntId: HuntId, itemId: ItemId, email: String, file: MultipartFile): Photo {
|
|
val hunter = hunterService.getHunterByEmail(email)
|
|
val now = LocalDateTime.now()
|
|
val photo = Photo(
|
|
itemId = itemId,
|
|
huntId = huntId,
|
|
hunterId = hunter.id,
|
|
foundDateTime = now,
|
|
status = PhotoStatus.SUBMITTED,
|
|
statusChangeDateTime = now
|
|
)
|
|
val savedRecord = photoRepository.save(photo.toRecord())
|
|
val baseName = savedRecord.id.toString()
|
|
|
|
val originalBytes = file.bytes
|
|
s3StorageService.upload("$baseName.jpg", originalBytes, MediaType.IMAGE_JPEG_VALUE)
|
|
s3StorageService.upload("${baseName}_medium.jpg", resize(originalBytes, 800), MediaType.IMAGE_JPEG_VALUE)
|
|
s3StorageService.upload("${baseName}_thumb.jpg", resize(originalBytes, 200), MediaType.IMAGE_JPEG_VALUE)
|
|
|
|
return photo
|
|
}
|
|
|
|
private fun resize(bytes: ByteArray, width: Int): ByteArray {
|
|
val output = ByteArrayOutputStream()
|
|
Thumbnails.of(ByteArrayInputStream(bytes))
|
|
.width(width)
|
|
.outputFormat("jpg")
|
|
.toOutputStream(output)
|
|
return output.toByteArray()
|
|
}
|
|
}
|