Adds file type detection, and beefs up error states for file uploads

This commit is contained in:
2026-05-14 11:13:19 -05:00
parent 5ca7a685dd
commit 1dd904055c
6 changed files with 80 additions and 7 deletions

View File

@@ -1,6 +1,8 @@
package net.halfbinary.scavengerhuntapi.service
import net.coobird.thumbnailator.Thumbnails
import net.coobird.thumbnailator.tasks.UnsupportedFormatException
import net.halfbinary.scavengerhuntapi.error.exception.BadFileException
import net.halfbinary.scavengerhuntapi.model.HuntId
import net.halfbinary.scavengerhuntapi.model.ItemId
import net.halfbinary.scavengerhuntapi.model.PhotoStatus
@@ -18,9 +20,21 @@ import java.time.LocalDateTime
class PhotoService(
private val photoRepository: PhotoRepository,
private val hunterService: HunterService,
private val s3StorageService: S3StorageService
private val s3StorageService: S3StorageService,
private val fileProbeService: FileProbeService
) {
fun submitPhoto(huntId: HuntId, itemId: ItemId, email: String, file: MultipartFile): Photo {
val originalBytes = file.bytes
val fileType = fileProbeService.getFileType(originalBytes)
if(!fileProbeService.isImageType(fileType)) throw BadFileException("Not an image")
val originalAsJpeg = try {
toJpeg(file.bytes)
} catch (_: UnsupportedFormatException) {
throw BadFileException("Image type is not supported")
}
val hunter = hunterService.getHunterByEmail(email)
val now = LocalDateTime.now()
val photo = Photo(
@@ -34,14 +48,25 @@ class PhotoService(
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)
s3StorageService.upload("$baseName${fileProbeService.getFileExtension(fileType)}", originalBytes, fileType)
s3StorageService.upload("${baseName}_large.jpg", originalAsJpeg, MediaType.IMAGE_JPEG_VALUE)
s3StorageService.upload("${baseName}_medium.jpg", resize(originalBytes, 800), MediaType.IMAGE_JPEG_VALUE)
s3StorageService.upload("${baseName}_small.jpg", resize(originalBytes, 200), MediaType.IMAGE_JPEG_VALUE)
return photo
}
private fun toJpeg(bytes: ByteArray): ByteArray {
val output = ByteArrayOutputStream()
Thumbnails.of(ByteArrayInputStream(bytes))
.scale(1.0)
.outputFormat("jpg")
.toOutputStream(output)
return output.toByteArray()
}
private fun resize(bytes: ByteArray, width: Int): ByteArray {
val output = ByteArrayOutputStream()
Thumbnails.of(ByteArrayInputStream(bytes))