fix(os_x-conversion): ignore __MACOSX directory for conversions (#2479)
Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+133
-112
@@ -4,30 +4,29 @@ import com.adityachandel.booklore.model.entity.AuthorEntity;
|
|||||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
import com.adityachandel.booklore.model.entity.CategoryEntity;
|
||||||
import com.adityachandel.booklore.model.entity.TagEntity;
|
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.cache.ClassTemplateLoader;
|
||||||
import freemarker.template.Configuration;
|
import freemarker.template.Configuration;
|
||||||
import freemarker.template.Template;
|
import freemarker.template.Template;
|
||||||
import freemarker.template.TemplateException;
|
import freemarker.template.TemplateException;
|
||||||
import freemarker.template.TemplateExceptionHandler;
|
import freemarker.template.TemplateExceptionHandler;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
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.ZipArchiveEntry;
|
||||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
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.stereotype.Service;
|
||||||
import org.springframework.util.FileSystemUtils;
|
import org.springframework.util.FileSystemUtils;
|
||||||
|
|
||||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
import javax.imageio.IIOImage;
|
||||||
import com.adityachandel.booklore.util.FileService;
|
|
||||||
|
|
||||||
import javax.imageio.ImageIO;
|
import javax.imageio.ImageIO;
|
||||||
import javax.imageio.ImageWriteParam;
|
import javax.imageio.ImageWriteParam;
|
||||||
import javax.imageio.ImageWriter;
|
import javax.imageio.ImageWriter;
|
||||||
import javax.imageio.IIOImage;
|
|
||||||
import javax.imageio.stream.ImageOutputStream;
|
import javax.imageio.stream.ImageOutputStream;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.io.*;
|
import java.io.*;
|
||||||
@@ -43,9 +42,9 @@ import java.util.*;
|
|||||||
* <p>
|
* <p>
|
||||||
* This service supports the following comic book archive formats:
|
* This service supports the following comic book archive formats:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li><b>CBZ</b> - Comic book ZIP archive</li>
|
* <li><b>CBZ</b> - Comic book ZIP archive</li>
|
||||||
* <li><b>CBR</b> - Comic book RAR archive</li>
|
* <li><b>CBR</b> - Comic book RAR archive</li>
|
||||||
* <li><b>CB7</b> - Comic book 7z archive</li>
|
* <li><b>CB7</b> - Comic book 7z archive</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
* </p>
|
* </p>
|
||||||
* <p>
|
* <p>
|
||||||
@@ -54,7 +53,7 @@ import java.util.*;
|
|||||||
*
|
*
|
||||||
* <h3>Size Limits</h3>
|
* <h3>Size Limits</h3>
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>Maximum individual image size: 50 MB</li>
|
* <li>Maximum individual image size: 50 MB</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* @see KepubConversionService
|
* @see KepubConversionService
|
||||||
@@ -73,7 +72,7 @@ public class CbxConversionService {
|
|||||||
private static final String MIMETYPE_CONTENT = "application/epub+zip";
|
private static final String MIMETYPE_CONTENT = "application/epub+zip";
|
||||||
private static final long MAX_IMAGE_SIZE_BYTES = 50L * 1024 * 1024;
|
private static final long MAX_IMAGE_SIZE_BYTES = 50L * 1024 * 1024;
|
||||||
private static final String EXTRACTED_IMAGES_SUBDIR = "cbx_extracted_images";
|
private static final String EXTRACTED_IMAGES_SUBDIR = "cbx_extracted_images";
|
||||||
|
|
||||||
private final Configuration freemarkerConfig;
|
private final Configuration freemarkerConfig;
|
||||||
|
|
||||||
public CbxConversionService() {
|
public CbxConversionService() {
|
||||||
@@ -88,39 +87,41 @@ public class CbxConversionService {
|
|||||||
* <p>
|
* <p>
|
||||||
* The conversion process:
|
* The conversion process:
|
||||||
* <ol>
|
* <ol>
|
||||||
* <li>Extracts all images from the archive to a temporary directory</li>
|
* <li>Extracts all images from the archive to a temporary directory</li>
|
||||||
* <li>Creates an EPUB structure with one XHTML page per image</li>
|
* <li>Creates an EPUB structure with one XHTML page per image</li>
|
||||||
* <li>Includes proper EPUB metadata from the book entity</li>
|
* <li>Includes proper EPUB metadata from the book entity</li>
|
||||||
* <li>JPEG images are passed through directly; other formats are converted to JPEG (85% quality)</li>
|
* <li>JPEG images are passed through directly; other formats are converted to
|
||||||
|
* JPEG (85% quality)</li>
|
||||||
* </ol>
|
* </ol>
|
||||||
* </p>
|
* </p>
|
||||||
*
|
*
|
||||||
* @param cbxFile the comic book archive file (must be CBZ, CBR, or CB7)
|
* @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 tempDir the temporary directory where the output EPUB will be
|
||||||
|
* created
|
||||||
* @param bookEntity the book metadata to include in the EPUB
|
* @param bookEntity the book metadata to include in the EPUB
|
||||||
* @return the converted EPUB file
|
* @return the converted EPUB file
|
||||||
* @throws IOException if file I/O operations fail
|
* @throws IOException if file I/O operations fail
|
||||||
* @throws TemplateException if EPUB template processing fails
|
* @throws TemplateException if EPUB template processing fails
|
||||||
* @throws RarException if RAR extraction fails (for CBR files)
|
* @throws RarException if RAR extraction fails (for CBR files)
|
||||||
* @throws IllegalArgumentException if the file format is not supported
|
* @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)
|
public File convertCbxToEpub(File cbxFile, File tempDir, BookEntity bookEntity, int compressionPercentage)
|
||||||
throws IOException, TemplateException, RarException {
|
throws IOException, TemplateException, RarException {
|
||||||
validateInputs(cbxFile, tempDir);
|
validateInputs(cbxFile, tempDir);
|
||||||
|
|
||||||
log.info("Starting CBX to EPUB conversion for: {}", cbxFile.getName());
|
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)",
|
log.info("Successfully converted {} to {} (size: {} bytes)",
|
||||||
cbxFile.getName(), outputFile.getName(), outputFile.length());
|
cbxFile.getName(), outputFile.getName(), outputFile.length());
|
||||||
return outputFile;
|
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 {
|
throws IOException, TemplateException, RarException {
|
||||||
|
|
||||||
Path epubFilePath = Paths.get(tempDir.getAbsolutePath(), cbxFile.getName() + ".epub");
|
Path epubFilePath = Paths.get(tempDir.getAbsolutePath(), cbxFile.getName() + ".epub");
|
||||||
File epubFile = epubFilePath.toFile();
|
File epubFile = epubFilePath.toFile();
|
||||||
|
|
||||||
@@ -138,9 +139,9 @@ public class CbxConversionService {
|
|||||||
addMimetypeEntry(zipOut);
|
addMimetypeEntry(zipOut);
|
||||||
addMetaInfContainer(zipOut);
|
addMetaInfContainer(zipOut);
|
||||||
addStylesheet(zipOut);
|
addStylesheet(zipOut);
|
||||||
|
|
||||||
List<EpubContentFileGroup> contentGroups = addImagesAndPages(zipOut, imagePaths,compressionPercentage);
|
List<EpubContentFileGroup> contentGroups = addImagesAndPages(zipOut, imagePaths, compressionPercentage);
|
||||||
|
|
||||||
addContentOpf(zipOut, bookEntity, contentGroups);
|
addContentOpf(zipOut, bookEntity, contentGroups);
|
||||||
addTocNcx(zipOut, bookEntity, contentGroups);
|
addTocNcx(zipOut, bookEntity, contentGroups);
|
||||||
addNavXhtml(zipOut, bookEntity, contentGroups);
|
addNavXhtml(zipOut, bookEntity, contentGroups);
|
||||||
@@ -150,7 +151,7 @@ public class CbxConversionService {
|
|||||||
|
|
||||||
return epubFile;
|
return epubFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void deleteDirectory(Path directory) {
|
private void deleteDirectory(Path directory) {
|
||||||
try {
|
try {
|
||||||
FileSystemUtils.deleteRecursively(directory);
|
FileSystemUtils.deleteRecursively(directory);
|
||||||
@@ -165,10 +166,10 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isSupportedCbxFormat(cbxFile.getName())) {
|
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");
|
". Supported formats: CBZ, CBR, CB7");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tempDir == null || !tempDir.isDirectory()) {
|
if (tempDir == null || !tempDir.isDirectory()) {
|
||||||
throw new IllegalArgumentException("Invalid temp directory: " + tempDir);
|
throw new IllegalArgumentException("Invalid temp directory: " + tempDir);
|
||||||
}
|
}
|
||||||
@@ -194,7 +195,7 @@ public class CbxConversionService {
|
|||||||
default -> throw new IllegalArgumentException("Unsupported archive format: " + cbxFile.getName());
|
default -> throw new IllegalArgumentException("Unsupported archive format: " + cbxFile.getName());
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
||||||
// Fast path: Try reading from Central Directory
|
// Fast path: Try reading from Central Directory
|
||||||
try (ZipFile zipFile = ZipFile.builder()
|
try (ZipFile zipFile = ZipFile.builder()
|
||||||
@@ -203,7 +204,8 @@ public class CbxConversionService {
|
|||||||
.setIgnoreLocalFileHeader(true)
|
.setIgnoreLocalFileHeader(true)
|
||||||
.get()) {
|
.get()) {
|
||||||
List<Path> paths = extractImagesFromZipFile(zipFile, extractedImagesDir);
|
List<Path> paths = extractImagesFromZipFile(zipFile, extractedImagesDir);
|
||||||
if (!paths.isEmpty()) return paths;
|
if (!paths.isEmpty())
|
||||||
|
return paths;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.debug("Fast path extraction failed for {}: {}", cbzFile.getName(), e.getMessage());
|
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.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.debug("Found {} image entries in CBZ file", imagePaths.size());
|
log.debug("Found {} image entries in CBZ file", imagePaths.size());
|
||||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||||
return imagePaths;
|
return imagePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> extractImagesFromRar(File cbrFile, Path extractedImagesDir) throws IOException, RarException {
|
private List<Path> extractImagesFromRar(File cbrFile, Path extractedImagesDir) throws IOException, RarException {
|
||||||
List<Path> imagePaths = new ArrayList<>();
|
List<Path> imagePaths = new ArrayList<>();
|
||||||
|
|
||||||
try (Archive rarFile = new Archive(cbrFile)) {
|
try (Archive rarFile = new Archive(cbrFile)) {
|
||||||
for (FileHeader fileHeader : rarFile) {
|
for (FileHeader fileHeader : rarFile) {
|
||||||
if (fileHeader.isDirectory() || !isImageFile(fileHeader.getFileName())) {
|
if (fileHeader.isDirectory() || !isImageFile(fileHeader.getFileName())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
validateImageSize(fileHeader.getFileName(), fileHeader.getFullUnpackSize());
|
validateImageSize(fileHeader.getFileName(), fileHeader.getFullUnpackSize());
|
||||||
|
|
||||||
try (InputStream inputStream = rarFile.getInputStream(fileHeader)) {
|
try (InputStream inputStream = rarFile.getInputStream(fileHeader)) {
|
||||||
Path outputPath = extractedImagesDir.resolve(extractFileName(fileHeader.getFileName()));
|
Path outputPath = extractedImagesDir.resolve(extractFileName(fileHeader.getFileName()));
|
||||||
Files.copy(inputStream, outputPath);
|
Files.copy(inputStream, outputPath);
|
||||||
@@ -262,28 +264,28 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.debug("Found {} image entries in CBR file", imagePaths.size());
|
log.debug("Found {} image entries in CBR file", imagePaths.size());
|
||||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||||
return imagePaths;
|
return imagePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException {
|
private List<Path> extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException {
|
||||||
List<Path> imagePaths = new ArrayList<>();
|
List<Path> imagePaths = new ArrayList<>();
|
||||||
|
|
||||||
try (SevenZFile sevenZFile = SevenZFile.builder().setFile(cb7File).get()) {
|
try (SevenZFile sevenZFile = SevenZFile.builder().setFile(cb7File).get()) {
|
||||||
SevenZArchiveEntry entry;
|
SevenZArchiveEntry entry;
|
||||||
while ((entry = sevenZFile.getNextEntry()) != null) {
|
while ((entry = sevenZFile.getNextEntry()) != null) {
|
||||||
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
validateImageSize(entry.getName(), entry.getSize());
|
validateImageSize(entry.getName(), entry.getSize());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
||||||
try (InputStream entryInputStream = sevenZFile.getInputStream(entry);
|
try (InputStream entryInputStream = sevenZFile.getInputStream(entry);
|
||||||
OutputStream fileOutputStream = Files.newOutputStream(outputPath)) {
|
OutputStream fileOutputStream = Files.newOutputStream(outputPath)) {
|
||||||
entryInputStream.transferTo(fileOutputStream);
|
entryInputStream.transferTo(fileOutputStream);
|
||||||
}
|
}
|
||||||
imagePaths.add(outputPath);
|
imagePaths.add(outputPath);
|
||||||
@@ -292,16 +294,16 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.debug("Found {} image entries in CB7 file", imagePaths.size());
|
log.debug("Found {} image entries in CB7 file", imagePaths.size());
|
||||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||||
return imagePaths;
|
return imagePaths;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String extractFileName(String entryPath) {
|
private String extractFileName(String entryPath) {
|
||||||
return Path.of(entryPath).getFileName().toString();
|
return Path.of(entryPath).getFileName().toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateImageSize(String imageName, long size) throws IOException {
|
private void validateImageSize(String imageName, long size) throws IOException {
|
||||||
if (size > MAX_IMAGE_SIZE_BYTES) {
|
if (size > MAX_IMAGE_SIZE_BYTES) {
|
||||||
throw new IOException(String.format("Image '%s' exceeds maximum size limit: %d bytes (max: %d 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) {
|
private boolean isImageFile(String fileName) {
|
||||||
|
if (shouldIgnoreEntry(fileName)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
String lowerName = fileName.toLowerCase();
|
String lowerName = fileName.toLowerCase();
|
||||||
|
|
||||||
return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
|
return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") ||
|
||||||
lowerName.endsWith(".png") || lowerName.endsWith(".webp") ||
|
lowerName.endsWith(".png") || lowerName.endsWith(".webp") ||
|
||||||
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") ||
|
lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") ||
|
||||||
lowerName.endsWith(".avif") || lowerName.endsWith(".heic");
|
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) {
|
private boolean isJpegFile(Path path) {
|
||||||
@@ -335,7 +355,7 @@ public class CbxConversionService {
|
|||||||
mimetypeEntry.setMethod(ZipArchiveEntry.STORED);
|
mimetypeEntry.setMethod(ZipArchiveEntry.STORED);
|
||||||
mimetypeEntry.setSize(mimetypeBytes.length);
|
mimetypeEntry.setSize(mimetypeBytes.length);
|
||||||
mimetypeEntry.setCrc(calculateCrc32(mimetypeBytes));
|
mimetypeEntry.setCrc(calculateCrc32(mimetypeBytes));
|
||||||
|
|
||||||
zipOut.putArchiveEntry(mimetypeEntry);
|
zipOut.putArchiveEntry(mimetypeEntry);
|
||||||
zipOut.write(mimetypeBytes);
|
zipOut.write(mimetypeBytes);
|
||||||
zipOut.closeArchiveEntry();
|
zipOut.closeArchiveEntry();
|
||||||
@@ -344,9 +364,9 @@ public class CbxConversionService {
|
|||||||
private void addMetaInfContainer(ZipArchiveOutputStream zipOut) throws IOException, TemplateException {
|
private void addMetaInfContainer(ZipArchiveOutputStream zipOut) throws IOException, TemplateException {
|
||||||
Map<String, Object> model = new HashMap<>();
|
Map<String, Object> model = new HashMap<>();
|
||||||
model.put("contentOpfPath", CONTENT_OPF_PATH);
|
model.put("contentOpfPath", CONTENT_OPF_PATH);
|
||||||
|
|
||||||
String containerXml = processTemplate("xml/container.xml.ftl", model);
|
String containerXml = processTemplate("xml/container.xml.ftl", model);
|
||||||
|
|
||||||
ZipArchiveEntry containerEntry = new ZipArchiveEntry("META-INF/container.xml");
|
ZipArchiveEntry containerEntry = new ZipArchiveEntry("META-INF/container.xml");
|
||||||
zipOut.putArchiveEntry(containerEntry);
|
zipOut.putArchiveEntry(containerEntry);
|
||||||
zipOut.write(containerXml.getBytes(StandardCharsets.UTF_8));
|
zipOut.write(containerXml.getBytes(StandardCharsets.UTF_8));
|
||||||
@@ -355,20 +375,21 @@ public class CbxConversionService {
|
|||||||
|
|
||||||
private void addStylesheet(ZipArchiveOutputStream zipOut) throws IOException {
|
private void addStylesheet(ZipArchiveOutputStream zipOut) throws IOException {
|
||||||
String stylesheetContent = loadResourceAsString("/templates/epub/css/stylesheet.css");
|
String stylesheetContent = loadResourceAsString("/templates/epub/css/stylesheet.css");
|
||||||
|
|
||||||
ZipArchiveEntry stylesheetEntry = new ZipArchiveEntry(STYLESHEET_CSS_PATH);
|
ZipArchiveEntry stylesheetEntry = new ZipArchiveEntry(STYLESHEET_CSS_PATH);
|
||||||
zipOut.putArchiveEntry(stylesheetEntry);
|
zipOut.putArchiveEntry(stylesheetEntry);
|
||||||
zipOut.write(stylesheetContent.getBytes(StandardCharsets.UTF_8));
|
zipOut.write(stylesheetContent.getBytes(StandardCharsets.UTF_8));
|
||||||
zipOut.closeArchiveEntry();
|
zipOut.closeArchiveEntry();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<EpubContentFileGroup> addImagesAndPages(ZipArchiveOutputStream zipOut, List<Path> imagePaths,int compressionPercentage)
|
private List<EpubContentFileGroup> addImagesAndPages(ZipArchiveOutputStream zipOut, List<Path> imagePaths,
|
||||||
|
int compressionPercentage)
|
||||||
throws IOException, TemplateException {
|
throws IOException, TemplateException {
|
||||||
|
|
||||||
List<EpubContentFileGroup> contentGroups = new ArrayList<>();
|
List<EpubContentFileGroup> contentGroups = new ArrayList<>();
|
||||||
|
|
||||||
if (!imagePaths.isEmpty()) {
|
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++) {
|
for (int i = 0; i < imagePaths.size(); i++) {
|
||||||
@@ -380,7 +401,7 @@ public class CbxConversionService {
|
|||||||
String imagePath = IMAGE_ROOT_PATH + imageFileName;
|
String imagePath = IMAGE_ROOT_PATH + imageFileName;
|
||||||
String htmlPath = HTML_ROOT_PATH + htmlFileName;
|
String htmlPath = HTML_ROOT_PATH + htmlFileName;
|
||||||
|
|
||||||
addImageToZipFromPath(zipOut, imagePath, imageSourcePath,compressionPercentage);
|
addImageToZipFromPath(zipOut, imagePath, imageSourcePath, compressionPercentage);
|
||||||
|
|
||||||
String htmlContent = generatePageHtml(imageFileName, i + 1);
|
String htmlContent = generatePageHtml(imageFileName, i + 1);
|
||||||
ZipArchiveEntry htmlEntry = new ZipArchiveEntry(htmlPath);
|
ZipArchiveEntry htmlEntry = new ZipArchiveEntry(htmlPath);
|
||||||
@@ -394,11 +415,12 @@ public class CbxConversionService {
|
|||||||
return contentGroups;
|
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 {
|
throws IOException {
|
||||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry(epubImagePath);
|
ZipArchiveEntry imageEntry = new ZipArchiveEntry(epubImagePath);
|
||||||
zipOut.putArchiveEntry(imageEntry);
|
zipOut.putArchiveEntry(imageEntry);
|
||||||
|
|
||||||
if (isJpegFile(sourceImagePath)) {
|
if (isJpegFile(sourceImagePath)) {
|
||||||
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
|
try (InputStream fis = Files.newInputStream(sourceImagePath)) {
|
||||||
fis.transferTo(zipOut);
|
fis.transferTo(zipOut);
|
||||||
@@ -413,7 +435,7 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (image != null) {
|
if (image != null) {
|
||||||
writeJpegImage(image, zipOut, compressionPercentage/100f);
|
writeJpegImage(image, zipOut, compressionPercentage / 100f);
|
||||||
} else {
|
} else {
|
||||||
log.warn("Could not decode image {}, copying raw bytes", sourceImagePath.getFileName());
|
log.warn("Could not decode image {}, copying raw bytes", sourceImagePath.getFileName());
|
||||||
try (InputStream rawStream = Files.newInputStream(sourceImagePath)) {
|
try (InputStream rawStream = Files.newInputStream(sourceImagePath)) {
|
||||||
@@ -422,11 +444,11 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
zipOut.closeArchiveEntry();
|
zipOut.closeArchiveEntry();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void writeJpegImage(BufferedImage image, ZipArchiveOutputStream zipOut, float quality)
|
private void writeJpegImage(BufferedImage image, ZipArchiveOutputStream zipOut, float quality)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
BufferedImage rgbImage = image;
|
BufferedImage rgbImage = image;
|
||||||
if (image.getType() != BufferedImage.TYPE_INT_RGB) {
|
if (image.getType() != BufferedImage.TYPE_INT_RGB) {
|
||||||
@@ -434,9 +456,9 @@ public class CbxConversionService {
|
|||||||
rgbImage.getGraphics().drawImage(image, 0, 0, null);
|
rgbImage.getGraphics().drawImage(image, 0, 0, null);
|
||||||
rgbImage.getGraphics().dispose();
|
rgbImage.getGraphics().dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
|
||||||
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
|
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
|
||||||
if (!writers.hasNext()) {
|
if (!writers.hasNext()) {
|
||||||
throw new IOException("No JPEG image writer available");
|
throw new IOException("No JPEG image writer available");
|
||||||
@@ -444,19 +466,19 @@ public class CbxConversionService {
|
|||||||
ImageWriter writer = writers.next();
|
ImageWriter writer = writers.next();
|
||||||
|
|
||||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||||
|
|
||||||
if (param.canWriteCompressed()) {
|
if (param.canWriteCompressed()) {
|
||||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||||
param.setCompressionQuality(quality);
|
param.setCompressionQuality(quality);
|
||||||
}
|
}
|
||||||
|
|
||||||
try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
|
try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
|
||||||
writer.setOutput(ios);
|
writer.setOutput(ios);
|
||||||
writer.write(null, new IIOImage(rgbImage, null, null), param);
|
writer.write(null, new IIOImage(rgbImage, null, null), param);
|
||||||
} finally {
|
} finally {
|
||||||
writer.dispose();
|
writer.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
zipOut.write(baos.toByteArray());
|
zipOut.write(baos.toByteArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,60 +487,59 @@ public class CbxConversionService {
|
|||||||
model.put("imageFileName", "../Images/" + imageFileName);
|
model.put("imageFileName", "../Images/" + imageFileName);
|
||||||
model.put("pageNumber", pageNumber);
|
model.put("pageNumber", pageNumber);
|
||||||
model.put("stylesheetPath", "../Styles/stylesheet.css");
|
model.put("stylesheetPath", "../Styles/stylesheet.css");
|
||||||
|
|
||||||
return processTemplate("xml/image_page.xhtml.ftl", model);
|
return processTemplate("xml/image_page.xhtml.ftl", model);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addContentOpf(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
private void addContentOpf(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||||
|
|
||||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||||
|
|
||||||
List<EpubContentFileGroup> relativeContentGroups = contentGroups.stream()
|
List<EpubContentFileGroup> relativeContentGroups = contentGroups.stream()
|
||||||
.map(group -> new EpubContentFileGroup(
|
.map(group -> new EpubContentFileGroup(
|
||||||
group.contentKey(),
|
group.contentKey(),
|
||||||
makeRelativeToOebps(group.imagePath()),
|
makeRelativeToOebps(group.imagePath()),
|
||||||
makeRelativeToOebps(group.htmlPath())
|
makeRelativeToOebps(group.htmlPath())))
|
||||||
))
|
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
model.put("contentFileGroups", relativeContentGroups);
|
model.put("contentFileGroups", relativeContentGroups);
|
||||||
model.put("coverImagePath", makeRelativeToOebps(COVER_IMAGE_PATH));
|
model.put("coverImagePath", makeRelativeToOebps(COVER_IMAGE_PATH));
|
||||||
model.put("tocNcxPath", makeRelativeToOebps(TOC_NCX_PATH));
|
model.put("tocNcxPath", makeRelativeToOebps(TOC_NCX_PATH));
|
||||||
model.put("navXhtmlPath", makeRelativeToOebps(NAV_XHTML_PATH));
|
model.put("navXhtmlPath", makeRelativeToOebps(NAV_XHTML_PATH));
|
||||||
model.put("stylesheetCssPath", makeRelativeToOebps(STYLESHEET_CSS_PATH));
|
model.put("stylesheetCssPath", makeRelativeToOebps(STYLESHEET_CSS_PATH));
|
||||||
model.put("firstPageId", contentGroups.isEmpty() ? "" : "page_" + contentGroups.getFirst().contentKey());
|
model.put("firstPageId", contentGroups.isEmpty() ? "" : "page_" + contentGroups.getFirst().contentKey());
|
||||||
|
|
||||||
String contentOpf = processTemplate("xml/content.opf.ftl", model);
|
String contentOpf = processTemplate("xml/content.opf.ftl", model);
|
||||||
|
|
||||||
ZipArchiveEntry contentEntry = new ZipArchiveEntry(CONTENT_OPF_PATH);
|
ZipArchiveEntry contentEntry = new ZipArchiveEntry(CONTENT_OPF_PATH);
|
||||||
zipOut.putArchiveEntry(contentEntry);
|
zipOut.putArchiveEntry(contentEntry);
|
||||||
zipOut.write(contentOpf.getBytes(StandardCharsets.UTF_8));
|
zipOut.write(contentOpf.getBytes(StandardCharsets.UTF_8));
|
||||||
zipOut.closeArchiveEntry();
|
zipOut.closeArchiveEntry();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addTocNcx(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
private void addTocNcx(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||||
|
|
||||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||||
model.put("contentFileGroups", contentGroups);
|
model.put("contentFileGroups", contentGroups);
|
||||||
|
|
||||||
String tocNcx = processTemplate("xml/toc.xml.ftl", model);
|
String tocNcx = processTemplate("xml/toc.xml.ftl", model);
|
||||||
|
|
||||||
ZipArchiveEntry tocEntry = new ZipArchiveEntry(TOC_NCX_PATH);
|
ZipArchiveEntry tocEntry = new ZipArchiveEntry(TOC_NCX_PATH);
|
||||||
zipOut.putArchiveEntry(tocEntry);
|
zipOut.putArchiveEntry(tocEntry);
|
||||||
zipOut.write(tocNcx.getBytes(StandardCharsets.UTF_8));
|
zipOut.write(tocNcx.getBytes(StandardCharsets.UTF_8));
|
||||||
zipOut.closeArchiveEntry();
|
zipOut.closeArchiveEntry();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void addNavXhtml(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
private void addNavXhtml(ZipArchiveOutputStream zipOut, BookEntity bookEntity,
|
||||||
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
List<EpubContentFileGroup> contentGroups) throws IOException, TemplateException {
|
||||||
|
|
||||||
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
Map<String, Object> model = createBookMetadataModel(bookEntity);
|
||||||
model.put("contentFileGroups", contentGroups);
|
model.put("contentFileGroups", contentGroups);
|
||||||
|
|
||||||
String navXhtml = processTemplate("xml/nav.xhtml.ftl", model);
|
String navXhtml = processTemplate("xml/nav.xhtml.ftl", model);
|
||||||
|
|
||||||
ZipArchiveEntry navEntry = new ZipArchiveEntry(NAV_XHTML_PATH);
|
ZipArchiveEntry navEntry = new ZipArchiveEntry(NAV_XHTML_PATH);
|
||||||
zipOut.putArchiveEntry(navEntry);
|
zipOut.putArchiveEntry(navEntry);
|
||||||
zipOut.write(navXhtml.getBytes(StandardCharsets.UTF_8));
|
zipOut.write(navXhtml.getBytes(StandardCharsets.UTF_8));
|
||||||
@@ -527,20 +548,20 @@ public class CbxConversionService {
|
|||||||
|
|
||||||
private Map<String, Object> createBookMetadataModel(BookEntity bookEntity) {
|
private Map<String, Object> createBookMetadataModel(BookEntity bookEntity) {
|
||||||
Map<String, Object> model = new HashMap<>();
|
Map<String, Object> model = new HashMap<>();
|
||||||
|
|
||||||
if (bookEntity != null && bookEntity.getMetadata() != null) {
|
if (bookEntity != null && bookEntity.getMetadata() != null) {
|
||||||
var metadata = bookEntity.getMetadata();
|
var metadata = bookEntity.getMetadata();
|
||||||
|
|
||||||
model.put("title", metadata.getTitle() != null ? metadata.getTitle() : "Unknown Comic");
|
model.put("title", metadata.getTitle() != null ? metadata.getTitle() : "Unknown Comic");
|
||||||
model.put("language", metadata.getLanguage() != null ? metadata.getLanguage() : "en");
|
model.put("language", metadata.getLanguage() != null ? metadata.getLanguage() : "en");
|
||||||
|
|
||||||
if (metadata.getSubtitle() != null && !metadata.getSubtitle().trim().isEmpty()) {
|
if (metadata.getSubtitle() != null && !metadata.getSubtitle().trim().isEmpty()) {
|
||||||
model.put("subtitle", metadata.getSubtitle());
|
model.put("subtitle", metadata.getSubtitle());
|
||||||
}
|
}
|
||||||
if (metadata.getDescription() != null && !metadata.getDescription().trim().isEmpty()) {
|
if (metadata.getDescription() != null && !metadata.getDescription().trim().isEmpty()) {
|
||||||
model.put("description", metadata.getDescription());
|
model.put("description", metadata.getDescription());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getSeriesName() != null && !metadata.getSeriesName().trim().isEmpty()) {
|
if (metadata.getSeriesName() != null && !metadata.getSeriesName().trim().isEmpty()) {
|
||||||
model.put("seriesName", metadata.getSeriesName());
|
model.put("seriesName", metadata.getSeriesName());
|
||||||
}
|
}
|
||||||
@@ -550,7 +571,7 @@ public class CbxConversionService {
|
|||||||
if (metadata.getSeriesTotal() != null) {
|
if (metadata.getSeriesTotal() != null) {
|
||||||
model.put("seriesTotal", metadata.getSeriesTotal());
|
model.put("seriesTotal", metadata.getSeriesTotal());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getPublisher() != null && !metadata.getPublisher().trim().isEmpty()) {
|
if (metadata.getPublisher() != null && !metadata.getPublisher().trim().isEmpty()) {
|
||||||
model.put("publisher", metadata.getPublisher());
|
model.put("publisher", metadata.getPublisher());
|
||||||
}
|
}
|
||||||
@@ -560,7 +581,7 @@ public class CbxConversionService {
|
|||||||
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) {
|
if (metadata.getPageCount() != null && metadata.getPageCount() > 0) {
|
||||||
model.put("pageCount", metadata.getPageCount());
|
model.put("pageCount", metadata.getPageCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getIsbn13() != null && !metadata.getIsbn13().trim().isEmpty()) {
|
if (metadata.getIsbn13() != null && !metadata.getIsbn13().trim().isEmpty()) {
|
||||||
model.put("isbn13", metadata.getIsbn13());
|
model.put("isbn13", metadata.getIsbn13());
|
||||||
}
|
}
|
||||||
@@ -573,38 +594,38 @@ public class CbxConversionService {
|
|||||||
if (metadata.getGoodreadsId() != null && !metadata.getGoodreadsId().trim().isEmpty()) {
|
if (metadata.getGoodreadsId() != null && !metadata.getGoodreadsId().trim().isEmpty()) {
|
||||||
model.put("goodreadsId", metadata.getGoodreadsId());
|
model.put("goodreadsId", metadata.getGoodreadsId());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) {
|
if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) {
|
||||||
model.put("authors", metadata.getAuthors().stream()
|
model.put("authors", metadata.getAuthors().stream()
|
||||||
.map(AuthorEntity::getName)
|
.map(AuthorEntity::getName)
|
||||||
.toList());
|
.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getCategories() != null && !metadata.getCategories().isEmpty()) {
|
if (metadata.getCategories() != null && !metadata.getCategories().isEmpty()) {
|
||||||
model.put("categories", metadata.getCategories().stream()
|
model.put("categories", metadata.getCategories().stream()
|
||||||
.map(CategoryEntity::getName)
|
.map(CategoryEntity::getName)
|
||||||
.toList());
|
.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metadata.getTags() != null && !metadata.getTags().isEmpty()) {
|
if (metadata.getTags() != null && !metadata.getTags().isEmpty()) {
|
||||||
model.put("tags", metadata.getTags().stream()
|
model.put("tags", metadata.getTags().stream()
|
||||||
.map(TagEntity::getName)
|
.map(TagEntity::getName)
|
||||||
.toList());
|
.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
||||||
} else {
|
} else {
|
||||||
model.put("title", "Unknown Comic");
|
model.put("title", "Unknown Comic");
|
||||||
model.put("language", "en");
|
model.put("language", "en");
|
||||||
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
model.put("identifier", "urn:uuid:" + UUID.randomUUID());
|
||||||
}
|
}
|
||||||
|
|
||||||
model.put("modified", Instant.now().toString());
|
model.put("modified", Instant.now().toString());
|
||||||
|
|
||||||
return model;
|
return model;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String processTemplate(String templateName, Map<String, Object> model)
|
private String processTemplate(String templateName, Map<String, Object> model)
|
||||||
throws IOException, TemplateException {
|
throws IOException, TemplateException {
|
||||||
try {
|
try {
|
||||||
Template template = freemarkerConfig.getTemplate(templateName);
|
Template template = freemarkerConfig.getTemplate(templateName);
|
||||||
@@ -630,11 +651,11 @@ public class CbxConversionService {
|
|||||||
private String makeRelativeToOebps(String fullPath) {
|
private String makeRelativeToOebps(String fullPath) {
|
||||||
Path oebpsPath = Paths.get("OEBPS");
|
Path oebpsPath = Paths.get("OEBPS");
|
||||||
Path targetPath = Paths.get(fullPath);
|
Path targetPath = Paths.get(fullPath);
|
||||||
|
|
||||||
if (targetPath.startsWith(oebpsPath)) {
|
if (targetPath.startsWith(oebpsPath)) {
|
||||||
return oebpsPath.relativize(targetPath).toString().replace('\\', '/');
|
return oebpsPath.relativize(targetPath).toString().replace('\\', '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
return fullPath;
|
return fullPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -649,9 +670,9 @@ public class CbxConversionService {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
String lowerName = fileName.toLowerCase();
|
String lowerName = fileName.toLowerCase();
|
||||||
return lowerName.endsWith(".cbz") ||
|
return lowerName.endsWith(".cbz") ||
|
||||||
lowerName.endsWith(".cbr") ||
|
lowerName.endsWith(".cbr") ||
|
||||||
lowerName.endsWith(".cb7");
|
lowerName.endsWith(".cb7");
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user