From f0444df6eed0dec1b5c20a491918f1a030a28ae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Thu, 8 Jan 2026 02:12:12 +0100 Subject: [PATCH] refactor(images): migrate to TwelveMonkeys ImageIO with graceful unsupported format handling (#2188) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs Co-authored-by: ACX <8075870+acx10@users.noreply.github.com> --- booklore-api/build.gradle | 9 ++- .../model/dto/kobo/KoboBookMetadata.java | 1 + .../service/file/BackgroundUploadService.java | 16 +++- .../service/fileprocessor/CbxProcessor.java | 6 +- .../service/fileprocessor/EpubProcessor.java | 4 +- .../service/fileprocessor/Fb2Processor.java | 13 ++-- .../service/kobo/CbxConversionService.java | 13 +++- .../service/reader/CbxReaderService.java | 2 +- .../booklore/util/FileService.java | 52 +++++++++---- .../booklore/util/FileServiceTest.java | 78 +++++++++++++------ 10 files changed, 134 insertions(+), 60 deletions(-) diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 69fa19505..474f9d92b 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -58,8 +58,13 @@ dependencies { implementation 'org.apache.pdfbox:pdfbox-io:3.0.6' implementation 'org.apache.pdfbox:xmpbox:3.0.6' implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4' - implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0' - implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0' + + // --- TwelveMonkeys ImageIO --- + implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0' + implementation 'io.documentnode:epub4j-core:4.2.2' // --- UNRAR Support --- diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java index 1d560f645..f3e5f5436 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java @@ -28,6 +28,7 @@ public class KoboBookMetadata { private String language = "en"; private String isbn; + @Builder.Default private String genre = "00000000-0000-0000-0000-000000000001"; private String slug; private String coverImageId; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java index 8a0cb53e2..b61f19e01 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java @@ -9,12 +9,15 @@ import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; +import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.file.Paths; import java.util.Objects; +import static net.lingala.zip4j.util.FileUtils.getFileExtension; + @Slf4j @Service @RequiredArgsConstructor @@ -34,20 +37,26 @@ public class BackgroundUploadService { String extension = getFileExtension(originalFilename); String filename = "1." + extension; + try (InputStream inputStream = file.getInputStream()) { BufferedImage originalImage; - try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); + try { + originalImage = FileService.readImage(inputStream); + } catch (IOException e) { + originalImage = null; } + if (originalImage == null) { throw new IllegalArgumentException("Invalid image file"); } + deleteExistingBackgroundFiles(userId); fileService.saveBackgroundImage(originalImage, filename, userId); originalImage.flush(); // Release resources after saving String fileUrl = FileService.getBackgroundUrl(filename, userId); return new UploadResponse(fileUrl); + } } catch (Exception e) { log.error("Failed to upload background file: {}", e.getMessage(), e); throw new RuntimeException("Failed to upload file: " + e.getMessage(), e); @@ -62,6 +71,9 @@ public class BackgroundUploadService { String filename = "1." + extension; BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); + if (originalImage == null) { + throw new IllegalArgumentException("Failed to download or decode image from URL"); + } deleteExistingBackgroundFiles(userId); fileService.saveBackgroundImage(originalImage, filename, userId); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 75ac24c27..8f32afaa3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -146,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce .min(Comparator.comparing(ZipArchiveEntry::getName)) .map(entry -> { try (InputStream is = zipFile.getInputStream(entry)) { - return ImageIO.read(is); + return FileService.readImage(is); } catch (Exception e) { log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage()); return null; @@ -177,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce if (bytesRead < 0) break; offset += bytesRead; } - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(content))); } } } @@ -198,7 +198,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce for (FileHeader header : imageHeaders) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { archive.extractFile(header, baos); - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray()))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(baos.toByteArray()))); } catch (Exception e) { log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage()); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index a4384c203..babf17a59 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc boolean saved; try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { - BufferedImage originalImage = ImageIO.read(bais); + BufferedImage originalImage = FileService.readImage(bais); if (originalImage == null) { - log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName()); + log.warn("Failed to decode cover image for EPUB '{}'", bookEntity.getFileName()); return false; } saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java index 09c58f3c4..1b0f25f5d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java @@ -125,13 +125,12 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce } private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception { - BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData)); - try { - return fileService.saveCoverImages(originalImage, bookId); - } finally { - if (originalImage != null) { - originalImage.flush(); // Release resources after processing - } + BufferedImage originalImage = FileService.readImage(coverData); + if (originalImage == null) { + log.warn("Failed to decode cover image for FB2"); + return false; } + + return fileService.saveCoverImages(originalImage, bookId); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java index 150d39922..d27de32b1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java @@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; +import com.adityachandel.booklore.util.FileService; + import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; @@ -314,7 +316,8 @@ public class CbxConversionService { return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".png") || lowerName.endsWith(".webp") || - lowerName.endsWith(".gif") || lowerName.endsWith(".bmp"); + lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") || + lowerName.endsWith(".avif") || lowerName.endsWith(".heic"); } private boolean isJpegFile(Path path) { @@ -404,7 +407,13 @@ public class CbxConversionService { } } else { try (InputStream fis = Files.newInputStream(sourceImagePath)) { - BufferedImage image = ImageIO.read(fis); + BufferedImage image = null; + try { + image = FileService.readImage(fis); + } catch (Exception e) { + log.debug("Failed to decode image {} with FileService: {}", sourceImagePath, e.getMessage()); + } + if (image != null) { writeJpegImage(image, zipOut, compressionPercentage/100f); } else { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java index 495f1115e..ff8e9cce8 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/reader/CbxReaderService.java @@ -40,7 +40,7 @@ public class CbxReaderService { private static final String CBZ_EXTENSION = ".cbz"; private static final String CBR_EXTENSION = ".cbr"; private static final String CB7_EXTENSION = ".cb7"; - private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}; + private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"}; private final BookRepository bookRepository; private final AppSettingService appSettingService; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java index 4d479c01e..2d168b3e9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/FileService.java @@ -144,6 +144,28 @@ public class FileService { // IMAGE OPERATIONS // ======================================== + public static BufferedImage readImage(InputStream inputStream) throws IOException { + return readImage(inputStream.readAllBytes()); + } + + public static BufferedImage readImage(byte[] imageData) throws IOException { + if (imageData == null || imageData.length == 0) { + throw new IOException("Image data is null or empty"); + } + try (InputStream is = new ByteArrayInputStream(imageData)) { + BufferedImage image = ImageIO.read(is); + if (image != null) { + return image; + } + } catch (Exception e) { + log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage()); + return null; + } + + log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)"); + return null; + } + public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) { Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); @@ -156,9 +178,10 @@ public class FileService { public static void saveImage(byte[] imageData, String filePath) throws IOException { BufferedImage originalImage = null; try { - originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); + originalImage = readImage(imageData); if (originalImage == null) { - throw new IOException("Invalid image data: unable to decode image"); + log.warn("Skipping saveImage for {}: decoded image is null", filePath); + return; } File outputFile = new File(filePath); File parentDir = outputFile.getParentFile(); @@ -191,13 +214,7 @@ public class FileService { // Validate and convert if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) { - BufferedImage image = ImageIO.read(inputStream); - if (image == null) { - throw new IOException("Downloaded content is not a supported image format."); - } - return image; - } + return readImage(response.getBody()); } else { throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); } @@ -216,10 +233,11 @@ public class FileService { validateCoverFile(file); BufferedImage originalImage; try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); + originalImage = readImage(inputStream); } if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Could not decode image from file, skipping thumbnail creation for book: {}", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -235,12 +253,10 @@ public class FileService { public void createThumbnailFromBytes(long bookId, byte[] imageBytes) { try { - BufferedImage originalImage; - try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) { - originalImage = ImageIO.read(inputStream); - } + BufferedImage originalImage = readImage(imageBytes); if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Skipping thumbnail creation for book {}: image decode failed", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -257,6 +273,10 @@ public class FileService { public void createThumbnailFromUrl(long bookId, String imageUrl) { try { BufferedImage originalImage = downloadImageFromUrl(imageUrl); + if (originalImage == null) { + log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId); + return; + } boolean success = saveCoverImages(originalImage, bookId); if (!success) { throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index 0773060a5..4195ff012 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -355,6 +355,40 @@ class FileServiceTest { @DisplayName("Image Operations") class ImageOperationsTests { + @Nested + @DisplayName("readImage") + class ReadImageTests { + @Test + void validData_returnsImage() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageData = imageToBytes(image); + + BufferedImage result = FileService.readImage(imageData); + + assertNotNull(result); + assertEquals(100, result.getWidth()); + assertEquals(100, result.getHeight()); + } + + @Test + void nullData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage((byte[]) null)); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void emptyData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage(new byte[0])); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void invalidData_returnsNull() throws IOException { + byte[] invalidData = "not an image".getBytes(); + assertNull(FileService.readImage(invalidData)); + } + } + @Nested @DisplayName("resizeImage") class ResizeImageTests { @@ -460,12 +494,13 @@ class FileServiceTest { } @Test - void invalidImageData_throwsException() { + void invalidImageData_skipsSave() { byte[] invalidData = "not an image".getBytes(); Path outputPath = tempDir.resolve("invalid.jpg"); - assertThrows(IOException.class, () -> + assertDoesNotThrow(() -> FileService.saveImage(invalidData, outputPath.toString())); + assertFalse(Files.exists(outputPath)); } @Test @@ -473,8 +508,9 @@ class FileServiceTest { byte[] emptyData = new byte[0]; Path outputPath = tempDir.resolve("empty.jpg"); - assertThrows(IOException.class, () -> + IOException ex = assertThrows(IOException.class, () -> FileService.saveImage(emptyData, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } @Test @@ -506,8 +542,9 @@ class FileServiceTest { @Test void nullImageData_throwsException() { Path outputPath = tempDir.resolve("null.jpg"); - assertThrows(NullPointerException.class, () -> + IOException ex = assertThrows(IOException.class, () -> FileService.saveImage(null, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } } } @@ -885,34 +922,28 @@ class FileServiceTest { } @Test - void invalidImageBytes_throwsRuntimeException() { + void invalidImageBytes_skipsThumbnail() { byte[] invalidData = "not an image".getBytes(); - RuntimeException exception = assertThrows(RuntimeException.class, () -> + assertDoesNotThrow(() -> fileService.createThumbnailFromBytes(16L, invalidData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L)))); } @Test void emptyImageBytes_throwsRuntimeException() { byte[] emptyData = new byte[0]; - // FileService wraps ImageIO exceptions in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromBytes(17L, emptyData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } @Test void nullImageBytes_throwsRuntimeException() { - // Null input causes NPE in ByteArrayInputStream constructor, which is caught and wrapped RuntimeException exception = assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromBytes(18L, null)); - assertNotNull(exception.getMessage(), "Exception should have a message"); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } } @@ -1009,18 +1040,15 @@ class FileServiceTest { } @Test - void corruptImageData_throwsRuntimeException() { + void corruptImageData_skipsThumbnail() { // Valid MIME type but corrupt image data byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); MockMultipartFile corruptFile = new MockMultipartFile( "file", "corrupt.jpg", "image/jpeg", corruptData); - // FileService wraps exceptions in RuntimeException via ApiError - RuntimeException exception = assertThrows(RuntimeException.class, () -> + assertDoesNotThrow(() -> fileService.createThumbnailFromFile(12L, corruptFile)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("not readable"), - "Exception message should indicate image processing failure"); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L)))); } @Test @@ -1209,9 +1237,9 @@ class FileServiceTest { } @Test - @DisplayName("throws exception when ImageIO cannot read bytes") + @DisplayName("returns null when ImageIO cannot read bytes") @Timeout(5) - void downloadImageFromUrl_invalidImageData_throwsException() { + void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException { String imageUrl = "http://example.com/image.jpg"; byte[] invalidBytes = "not an image".getBytes(); ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); @@ -1222,8 +1250,8 @@ class FileServiceTest { eq(byte[].class) )).thenReturn(responseEntity); - assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + BufferedImage result = fileService.downloadImageFromUrl(imageUrl); + assertNull(result); } @Test