From fab7c140309c5a3b318a2923daf1f5dfd5a1e474 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: Tue, 27 Jan 2026 18:26:31 +0100 Subject: [PATCH] fix(os_x-conversion): ignore __MACOSX directory for conversions (#2479) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../service/kobo/CbxConversionService.java | 245 ++++++++++-------- 1 file changed, 133 insertions(+), 112 deletions(-) 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 207c23b9f..59f48dd9c 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 @@ -4,30 +4,29 @@ import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; import com.adityachandel.booklore.model.entity.TagEntity; +import com.adityachandel.booklore.util.ArchiveUtils; +import com.adityachandel.booklore.util.FileService; +import com.github.junrar.Archive; +import com.github.junrar.exception.RarException; +import com.github.junrar.rarfile.FileHeader; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; +import org.apache.commons.compress.archivers.sevenz.SevenZFile; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipFile; -import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; -import org.apache.commons.compress.archivers.sevenz.SevenZFile; -import com.github.junrar.Archive; -import com.github.junrar.rarfile.FileHeader; -import com.github.junrar.exception.RarException; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; -import com.adityachandel.booklore.util.ArchiveUtils; -import com.adityachandel.booklore.util.FileService; - +import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; -import javax.imageio.IIOImage; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.*; @@ -43,9 +42,9 @@ import java.util.*; *

* This service supports the following comic book archive formats: *

*

*

@@ -54,7 +53,7 @@ import java.util.*; * *

Size Limits

* * * @see KepubConversionService @@ -73,7 +72,7 @@ public class CbxConversionService { private static final String MIMETYPE_CONTENT = "application/epub+zip"; private static final long MAX_IMAGE_SIZE_BYTES = 50L * 1024 * 1024; private static final String EXTRACTED_IMAGES_SUBDIR = "cbx_extracted_images"; - + private final Configuration freemarkerConfig; public CbxConversionService() { @@ -88,39 +87,41 @@ public class CbxConversionService { *

* The conversion process: *

    - *
  1. Extracts all images from the archive to a temporary directory
  2. - *
  3. Creates an EPUB structure with one XHTML page per image
  4. - *
  5. Includes proper EPUB metadata from the book entity
  6. - *
  7. JPEG images are passed through directly; other formats are converted to JPEG (85% quality)
  8. + *
  9. Extracts all images from the archive to a temporary directory
  10. + *
  11. Creates an EPUB structure with one XHTML page per image
  12. + *
  13. Includes proper EPUB metadata from the book entity
  14. + *
  15. JPEG images are passed through directly; other formats are converted to + * JPEG (85% quality)
  16. *
*

* - * @param cbxFile the comic book archive file (must be CBZ, CBR, or CB7) - * @param tempDir the temporary directory where the output EPUB will be created + * @param cbxFile the comic book archive file (must be CBZ, CBR, or CB7) + * @param tempDir the temporary directory where the output EPUB will be + * created * @param bookEntity the book metadata to include in the EPUB * @return the converted EPUB file - * @throws IOException if file I/O operations fail - * @throws TemplateException if EPUB template processing fails - * @throws RarException if RAR extraction fails (for CBR files) + * @throws IOException if file I/O operations fail + * @throws TemplateException if EPUB template processing fails + * @throws RarException if RAR extraction fails (for CBR files) * @throws IllegalArgumentException if the file format is not supported - * @throws IllegalStateException if no valid images are found in the archive + * @throws IllegalStateException if no valid images are found in the archive */ public File convertCbxToEpub(File cbxFile, File tempDir, BookEntity bookEntity, int compressionPercentage) throws IOException, TemplateException, RarException { validateInputs(cbxFile, tempDir); - + log.info("Starting CBX to EPUB conversion for: {}", cbxFile.getName()); - - File outputFile = executeCbxConversion(cbxFile, tempDir, bookEntity,compressionPercentage); - + + File outputFile = executeCbxConversion(cbxFile, tempDir, bookEntity, compressionPercentage); + log.info("Successfully converted {} to {} (size: {} bytes)", cbxFile.getName(), outputFile.getName(), outputFile.length()); return outputFile; } - private File executeCbxConversion(File cbxFile, File tempDir, BookEntity bookEntity,int compressionPercentage) + private File executeCbxConversion(File cbxFile, File tempDir, BookEntity bookEntity, int compressionPercentage) throws IOException, TemplateException, RarException { - + Path epubFilePath = Paths.get(tempDir.getAbsolutePath(), cbxFile.getName() + ".epub"); File epubFile = epubFilePath.toFile(); @@ -138,9 +139,9 @@ public class CbxConversionService { addMimetypeEntry(zipOut); addMetaInfContainer(zipOut); addStylesheet(zipOut); - - List contentGroups = addImagesAndPages(zipOut, imagePaths,compressionPercentage); - + + List contentGroups = addImagesAndPages(zipOut, imagePaths, compressionPercentage); + addContentOpf(zipOut, bookEntity, contentGroups); addTocNcx(zipOut, bookEntity, contentGroups); addNavXhtml(zipOut, bookEntity, contentGroups); @@ -150,7 +151,7 @@ public class CbxConversionService { return epubFile; } - + private void deleteDirectory(Path directory) { try { FileSystemUtils.deleteRecursively(directory); @@ -165,10 +166,10 @@ public class CbxConversionService { } if (!isSupportedCbxFormat(cbxFile.getName())) { - throw new IllegalArgumentException("Unsupported file format: " + cbxFile.getName() + + throw new IllegalArgumentException("Unsupported file format: " + cbxFile.getName() + ". Supported formats: CBZ, CBR, CB7"); } - + if (tempDir == null || !tempDir.isDirectory()) { throw new IllegalArgumentException("Invalid temp directory: " + tempDir); } @@ -194,7 +195,7 @@ public class CbxConversionService { default -> throw new IllegalArgumentException("Unsupported archive format: " + cbxFile.getName()); }; } - + private List extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException { // Fast path: Try reading from Central Directory try (ZipFile zipFile = ZipFile.builder() @@ -203,7 +204,8 @@ public class CbxConversionService { .setIgnoreLocalFileHeader(true) .get()) { List paths = extractImagesFromZipFile(zipFile, extractedImagesDir); - if (!paths.isEmpty()) return paths; + if (!paths.isEmpty()) + return paths; } catch (Exception e) { log.debug("Fast path extraction failed for {}: {}", cbzFile.getName(), e.getMessage()); } @@ -236,23 +238,23 @@ public class CbxConversionService { log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage()); } } - + log.debug("Found {} image entries in CBZ file", imagePaths.size()); imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase())); return imagePaths; } - + private List extractImagesFromRar(File cbrFile, Path extractedImagesDir) throws IOException, RarException { List imagePaths = new ArrayList<>(); - + try (Archive rarFile = new Archive(cbrFile)) { for (FileHeader fileHeader : rarFile) { if (fileHeader.isDirectory() || !isImageFile(fileHeader.getFileName())) { continue; } - + validateImageSize(fileHeader.getFileName(), fileHeader.getFullUnpackSize()); - + try (InputStream inputStream = rarFile.getInputStream(fileHeader)) { Path outputPath = extractedImagesDir.resolve(extractFileName(fileHeader.getFileName())); Files.copy(inputStream, outputPath); @@ -262,28 +264,28 @@ public class CbxConversionService { } } } - + log.debug("Found {} image entries in CBR file", imagePaths.size()); imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase())); return imagePaths; } - + private List extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException { List imagePaths = new ArrayList<>(); - + try (SevenZFile sevenZFile = SevenZFile.builder().setFile(cb7File).get()) { SevenZArchiveEntry entry; while ((entry = sevenZFile.getNextEntry()) != null) { if (entry.isDirectory() || !isImageFile(entry.getName())) { continue; } - + validateImageSize(entry.getName(), entry.getSize()); - + try { Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName())); try (InputStream entryInputStream = sevenZFile.getInputStream(entry); - OutputStream fileOutputStream = Files.newOutputStream(outputPath)) { + OutputStream fileOutputStream = Files.newOutputStream(outputPath)) { entryInputStream.transferTo(fileOutputStream); } imagePaths.add(outputPath); @@ -292,16 +294,16 @@ public class CbxConversionService { } } } - + log.debug("Found {} image entries in CB7 file", imagePaths.size()); imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase())); return imagePaths; } - + private String extractFileName(String entryPath) { return Path.of(entryPath).getFileName().toString(); } - + private void validateImageSize(String imageName, long size) throws IOException { if (size > MAX_IMAGE_SIZE_BYTES) { throw new IOException(String.format("Image '%s' exceeds maximum size limit: %d bytes (max: %d bytes)", @@ -310,12 +312,30 @@ public class CbxConversionService { } private boolean isImageFile(String fileName) { + if (shouldIgnoreEntry(fileName)) { + return false; + } + String lowerName = fileName.toLowerCase(); return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || - lowerName.endsWith(".png") || lowerName.endsWith(".webp") || - lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") || - lowerName.endsWith(".avif") || lowerName.endsWith(".heic"); + lowerName.endsWith(".png") || lowerName.endsWith(".webp") || + lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") || + lowerName.endsWith(".avif") || lowerName.endsWith(".heic"); + } + + private boolean shouldIgnoreEntry(String entryName) { + if (entryName.contains("__MACOSX")) { + return true; + } + + String fileName = entryName; + int lastSlash = entryName.lastIndexOf('/'); + if (lastSlash >= 0) { + fileName = entryName.substring(lastSlash + 1); + } + + return fileName.startsWith("._"); } private boolean isJpegFile(Path path) { @@ -335,7 +355,7 @@ public class CbxConversionService { mimetypeEntry.setMethod(ZipArchiveEntry.STORED); mimetypeEntry.setSize(mimetypeBytes.length); mimetypeEntry.setCrc(calculateCrc32(mimetypeBytes)); - + zipOut.putArchiveEntry(mimetypeEntry); zipOut.write(mimetypeBytes); zipOut.closeArchiveEntry(); @@ -344,9 +364,9 @@ public class CbxConversionService { private void addMetaInfContainer(ZipArchiveOutputStream zipOut) throws IOException, TemplateException { Map model = new HashMap<>(); model.put("contentOpfPath", CONTENT_OPF_PATH); - + String containerXml = processTemplate("xml/container.xml.ftl", model); - + ZipArchiveEntry containerEntry = new ZipArchiveEntry("META-INF/container.xml"); zipOut.putArchiveEntry(containerEntry); zipOut.write(containerXml.getBytes(StandardCharsets.UTF_8)); @@ -355,20 +375,21 @@ public class CbxConversionService { private void addStylesheet(ZipArchiveOutputStream zipOut) throws IOException { String stylesheetContent = loadResourceAsString("/templates/epub/css/stylesheet.css"); - + ZipArchiveEntry stylesheetEntry = new ZipArchiveEntry(STYLESHEET_CSS_PATH); zipOut.putArchiveEntry(stylesheetEntry); zipOut.write(stylesheetContent.getBytes(StandardCharsets.UTF_8)); zipOut.closeArchiveEntry(); } - private List addImagesAndPages(ZipArchiveOutputStream zipOut, List imagePaths,int compressionPercentage) + private List addImagesAndPages(ZipArchiveOutputStream zipOut, List imagePaths, + int compressionPercentage) throws IOException, TemplateException { - + List contentGroups = new ArrayList<>(); if (!imagePaths.isEmpty()) { - addImageToZipFromPath(zipOut, COVER_IMAGE_PATH, imagePaths.getFirst(),compressionPercentage); + addImageToZipFromPath(zipOut, COVER_IMAGE_PATH, imagePaths.getFirst(), compressionPercentage); } for (int i = 0; i < imagePaths.size(); i++) { @@ -380,7 +401,7 @@ public class CbxConversionService { String imagePath = IMAGE_ROOT_PATH + imageFileName; String htmlPath = HTML_ROOT_PATH + htmlFileName; - addImageToZipFromPath(zipOut, imagePath, imageSourcePath,compressionPercentage); + addImageToZipFromPath(zipOut, imagePath, imageSourcePath, compressionPercentage); String htmlContent = generatePageHtml(imageFileName, i + 1); ZipArchiveEntry htmlEntry = new ZipArchiveEntry(htmlPath); @@ -394,11 +415,12 @@ public class CbxConversionService { return contentGroups; } - private void addImageToZipFromPath(ZipArchiveOutputStream zipOut, String epubImagePath, Path sourceImagePath,int compressionPercentage) + private void addImageToZipFromPath(ZipArchiveOutputStream zipOut, String epubImagePath, Path sourceImagePath, + int compressionPercentage) throws IOException { ZipArchiveEntry imageEntry = new ZipArchiveEntry(epubImagePath); zipOut.putArchiveEntry(imageEntry); - + if (isJpegFile(sourceImagePath)) { try (InputStream fis = Files.newInputStream(sourceImagePath)) { fis.transferTo(zipOut); @@ -413,7 +435,7 @@ public class CbxConversionService { } if (image != null) { - writeJpegImage(image, zipOut, compressionPercentage/100f); + writeJpegImage(image, zipOut, compressionPercentage / 100f); } else { log.warn("Could not decode image {}, copying raw bytes", sourceImagePath.getFileName()); try (InputStream rawStream = Files.newInputStream(sourceImagePath)) { @@ -422,11 +444,11 @@ public class CbxConversionService { } } } - + zipOut.closeArchiveEntry(); } - - private void writeJpegImage(BufferedImage image, ZipArchiveOutputStream zipOut, float quality) + + private void writeJpegImage(BufferedImage image, ZipArchiveOutputStream zipOut, float quality) throws IOException { BufferedImage rgbImage = image; if (image.getType() != BufferedImage.TYPE_INT_RGB) { @@ -434,9 +456,9 @@ public class CbxConversionService { rgbImage.getGraphics().drawImage(image, 0, 0, null); rgbImage.getGraphics().dispose(); } - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); - + Iterator writers = ImageIO.getImageWritersByFormatName("jpg"); if (!writers.hasNext()) { throw new IOException("No JPEG image writer available"); @@ -444,19 +466,19 @@ public class CbxConversionService { ImageWriter writer = writers.next(); ImageWriteParam param = writer.getDefaultWriteParam(); - + if (param.canWriteCompressed()) { param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(quality); } - + try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) { writer.setOutput(ios); writer.write(null, new IIOImage(rgbImage, null, null), param); } finally { writer.dispose(); } - + zipOut.write(baos.toByteArray()); } @@ -465,60 +487,59 @@ public class CbxConversionService { model.put("imageFileName", "../Images/" + imageFileName); model.put("pageNumber", pageNumber); model.put("stylesheetPath", "../Styles/stylesheet.css"); - + return processTemplate("xml/image_page.xhtml.ftl", model); } - private void addContentOpf(ZipArchiveOutputStream zipOut, BookEntity bookEntity, - List contentGroups) throws IOException, TemplateException { - + private void addContentOpf(ZipArchiveOutputStream zipOut, BookEntity bookEntity, + List contentGroups) throws IOException, TemplateException { + Map model = createBookMetadataModel(bookEntity); - + List relativeContentGroups = contentGroups.stream() .map(group -> new EpubContentFileGroup( group.contentKey(), makeRelativeToOebps(group.imagePath()), - makeRelativeToOebps(group.htmlPath()) - )) + makeRelativeToOebps(group.htmlPath()))) .toList(); - + model.put("contentFileGroups", relativeContentGroups); model.put("coverImagePath", makeRelativeToOebps(COVER_IMAGE_PATH)); model.put("tocNcxPath", makeRelativeToOebps(TOC_NCX_PATH)); model.put("navXhtmlPath", makeRelativeToOebps(NAV_XHTML_PATH)); model.put("stylesheetCssPath", makeRelativeToOebps(STYLESHEET_CSS_PATH)); model.put("firstPageId", contentGroups.isEmpty() ? "" : "page_" + contentGroups.getFirst().contentKey()); - + String contentOpf = processTemplate("xml/content.opf.ftl", model); - + ZipArchiveEntry contentEntry = new ZipArchiveEntry(CONTENT_OPF_PATH); zipOut.putArchiveEntry(contentEntry); zipOut.write(contentOpf.getBytes(StandardCharsets.UTF_8)); zipOut.closeArchiveEntry(); } - private void addTocNcx(ZipArchiveOutputStream zipOut, BookEntity bookEntity, - List contentGroups) throws IOException, TemplateException { - + private void addTocNcx(ZipArchiveOutputStream zipOut, BookEntity bookEntity, + List contentGroups) throws IOException, TemplateException { + Map model = createBookMetadataModel(bookEntity); model.put("contentFileGroups", contentGroups); - + String tocNcx = processTemplate("xml/toc.xml.ftl", model); - + ZipArchiveEntry tocEntry = new ZipArchiveEntry(TOC_NCX_PATH); zipOut.putArchiveEntry(tocEntry); zipOut.write(tocNcx.getBytes(StandardCharsets.UTF_8)); zipOut.closeArchiveEntry(); } - private void addNavXhtml(ZipArchiveOutputStream zipOut, BookEntity bookEntity, - List contentGroups) throws IOException, TemplateException { - + private void addNavXhtml(ZipArchiveOutputStream zipOut, BookEntity bookEntity, + List contentGroups) throws IOException, TemplateException { + Map model = createBookMetadataModel(bookEntity); model.put("contentFileGroups", contentGroups); - + String navXhtml = processTemplate("xml/nav.xhtml.ftl", model); - + ZipArchiveEntry navEntry = new ZipArchiveEntry(NAV_XHTML_PATH); zipOut.putArchiveEntry(navEntry); zipOut.write(navXhtml.getBytes(StandardCharsets.UTF_8)); @@ -527,20 +548,20 @@ public class CbxConversionService { private Map createBookMetadataModel(BookEntity bookEntity) { Map model = new HashMap<>(); - + if (bookEntity != null && bookEntity.getMetadata() != null) { var metadata = bookEntity.getMetadata(); - + model.put("title", metadata.getTitle() != null ? metadata.getTitle() : "Unknown Comic"); model.put("language", metadata.getLanguage() != null ? metadata.getLanguage() : "en"); - + if (metadata.getSubtitle() != null && !metadata.getSubtitle().trim().isEmpty()) { model.put("subtitle", metadata.getSubtitle()); } if (metadata.getDescription() != null && !metadata.getDescription().trim().isEmpty()) { model.put("description", metadata.getDescription()); } - + if (metadata.getSeriesName() != null && !metadata.getSeriesName().trim().isEmpty()) { model.put("seriesName", metadata.getSeriesName()); } @@ -550,7 +571,7 @@ public class CbxConversionService { if (metadata.getSeriesTotal() != null) { model.put("seriesTotal", metadata.getSeriesTotal()); } - + if (metadata.getPublisher() != null && !metadata.getPublisher().trim().isEmpty()) { model.put("publisher", metadata.getPublisher()); } @@ -560,7 +581,7 @@ public class CbxConversionService { if (metadata.getPageCount() != null && metadata.getPageCount() > 0) { model.put("pageCount", metadata.getPageCount()); } - + if (metadata.getIsbn13() != null && !metadata.getIsbn13().trim().isEmpty()) { model.put("isbn13", metadata.getIsbn13()); } @@ -573,38 +594,38 @@ public class CbxConversionService { if (metadata.getGoodreadsId() != null && !metadata.getGoodreadsId().trim().isEmpty()) { model.put("goodreadsId", metadata.getGoodreadsId()); } - + if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) { model.put("authors", metadata.getAuthors().stream() .map(AuthorEntity::getName) .toList()); } - + if (metadata.getCategories() != null && !metadata.getCategories().isEmpty()) { model.put("categories", metadata.getCategories().stream() .map(CategoryEntity::getName) .toList()); } - + if (metadata.getTags() != null && !metadata.getTags().isEmpty()) { model.put("tags", metadata.getTags().stream() .map(TagEntity::getName) .toList()); } - + model.put("identifier", "urn:uuid:" + UUID.randomUUID()); } else { model.put("title", "Unknown Comic"); model.put("language", "en"); model.put("identifier", "urn:uuid:" + UUID.randomUUID()); } - + model.put("modified", Instant.now().toString()); - + return model; } - private String processTemplate(String templateName, Map model) + private String processTemplate(String templateName, Map model) throws IOException, TemplateException { try { Template template = freemarkerConfig.getTemplate(templateName); @@ -630,11 +651,11 @@ public class CbxConversionService { private String makeRelativeToOebps(String fullPath) { Path oebpsPath = Paths.get("OEBPS"); Path targetPath = Paths.get(fullPath); - + if (targetPath.startsWith(oebpsPath)) { return oebpsPath.relativize(targetPath).toString().replace('\\', '/'); } - + return fullPath; } @@ -649,9 +670,9 @@ public class CbxConversionService { return false; } String lowerName = fileName.toLowerCase(); - return lowerName.endsWith(".cbz") || - lowerName.endsWith(".cbr") || - lowerName.endsWith(".cb7"); + return lowerName.endsWith(".cbz") || + lowerName.endsWith(".cbr") || + lowerName.endsWith(".cb7"); } }