perf(cbz): optimize CBZ reading (#1980)
* perf(cbz): improve zip file compatibility by enabling Unicode extra fields and ignoring local file headers Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(perf): Implement robust ZipFile optimization with fallback Updated ZipFile reading logic in CbxReaderService, CbxProcessor, and CbxConversionService. Implemented a 'Fast Path' (Central Directory only) for speed (20x faster on large archives). Implemented a 'Slow Path' (Local Header scanning) fallback if the fast path fails or finds no images. Ensures compatibility with older or malformed archives where Unicode names are only present in local headers. Refactored extraction logic to helper methods where appropriate to support retry mechanism. --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
+26
-5
@@ -114,7 +114,32 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
|
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
|
||||||
try (ZipFile zipFile = ZipFile.builder().setFile(file).get()) {
|
// Fast path: Try reading from Central Directory
|
||||||
|
try (ZipFile zipFile = ZipFile.builder()
|
||||||
|
.setFile(file)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(true)
|
||||||
|
.get()) {
|
||||||
|
Optional<BufferedImage> image = findAndReadFirstImage(zipFile);
|
||||||
|
if (image.isPresent()) return image;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Fast path failed for ZIP extraction: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slow path: Fallback to scanning local file headers
|
||||||
|
try (ZipFile zipFile = ZipFile.builder()
|
||||||
|
.setFile(file)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(false)
|
||||||
|
.get()) {
|
||||||
|
return findAndReadFirstImage(zipFile);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Error extracting ZIP: {}", e.getMessage());
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Optional<BufferedImage> findAndReadFirstImage(ZipFile zipFile) {
|
||||||
return Collections.list(zipFile.getEntries()).stream()
|
return Collections.list(zipFile.getEntries()).stream()
|
||||||
.filter(e -> !e.isDirectory() && IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(e.getName()).matches())
|
.filter(e -> !e.isDirectory() && IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(e.getName()).matches())
|
||||||
.min(Comparator.comparing(ZipArchiveEntry::getName))
|
.min(Comparator.comparing(ZipArchiveEntry::getName))
|
||||||
@@ -126,10 +151,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error extracting ZIP: {}", e.getMessage());
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private Optional<BufferedImage> extractFirstImageFrom7z(File file) {
|
private Optional<BufferedImage> extractFirstImageFrom7z(File file) {
|
||||||
|
|||||||
+26
-5
@@ -196,25 +196,46 @@ public class CbxConversionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
||||||
List<Path> imagePaths = new ArrayList<>();
|
// Fast path: Try reading from Central Directory
|
||||||
|
try (ZipFile zipFile = ZipFile.builder()
|
||||||
|
.setFile(cbzFile)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(true)
|
||||||
|
.get()) {
|
||||||
|
List<Path> paths = extractImagesFromZipFile(zipFile, extractedImagesDir);
|
||||||
|
if (!paths.isEmpty()) return paths;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Fast path extraction failed for {}: {}", cbzFile.getName(), e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
try (ZipFile zipFile = ZipFile.builder().setFile(cbzFile).get()) {
|
// Slow path: Fallback to scanning local file headers
|
||||||
|
try (ZipFile zipFile = ZipFile.builder()
|
||||||
|
.setFile(cbzFile)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(false)
|
||||||
|
.get()) {
|
||||||
|
return extractImagesFromZipFile(zipFile, extractedImagesDir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<Path> extractImagesFromZipFile(ZipFile zipFile, Path extractedImagesDir) {
|
||||||
|
List<Path> imagePaths = new ArrayList<>();
|
||||||
for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
|
for (ZipArchiveEntry entry : Collections.list(zipFile.getEntries())) {
|
||||||
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
if (entry.isDirectory() || !isImageFile(entry.getName())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
validateImageSize(entry.getName(), entry.getSize());
|
validateImageSize(entry.getName(), entry.getSize());
|
||||||
|
|
||||||
try (InputStream inputStream = zipFile.getInputStream(entry)) {
|
|
||||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
||||||
|
try (InputStream inputStream = zipFile.getInputStream(entry)) {
|
||||||
Files.copy(inputStream, outputPath);
|
Files.copy(inputStream, outputPath);
|
||||||
imagePaths.add(outputPath);
|
imagePaths.add(outputPath);
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
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()));
|
||||||
|
|||||||
+33
-9
@@ -137,25 +137,36 @@ public class CbxReaderService {
|
|||||||
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
|
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
|
||||||
|
|
||||||
for (String encoding : encodingsToTry) {
|
for (String encoding : encodingsToTry) {
|
||||||
|
Charset charset = Charset.forName(encoding);
|
||||||
try {
|
try {
|
||||||
extractZipWithEncoding(cbzPath, targetDir, Charset.forName(encoding));
|
// Fast path: Try reading from Central Directory only
|
||||||
return;
|
if (extractZipWithEncoding(cbzPath, targetDir, charset, true)) return;
|
||||||
} catch (IllegalArgumentException | java.util.zip.ZipException e) {
|
} catch (Exception e) {
|
||||||
log.debug("Failed to extract with encoding {}: {}", encoding, e.getMessage());
|
log.debug("Fast path failed for encoding {}: {}", encoding, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Slow path: Fallback to scanning local file headers
|
||||||
|
if (extractZipWithEncoding(cbzPath, targetDir, charset, false)) return;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Slow path failed for encoding {}: {}", encoding, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new IOException("Unable to extract ZIP archive with any supported encoding");
|
throw new IOException("Unable to extract ZIP archive with any supported encoding");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void extractZipWithEncoding(Path cbzPath, Path targetDir, Charset charset) throws IOException {
|
private boolean extractZipWithEncoding(Path cbzPath, Path targetDir, Charset charset, boolean useFastPath) throws IOException {
|
||||||
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
|
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
|
||||||
org.apache.commons.compress.archivers.zip.ZipFile.builder()
|
org.apache.commons.compress.archivers.zip.ZipFile.builder()
|
||||||
.setPath(cbzPath)
|
.setPath(cbzPath)
|
||||||
.setCharset(charset)
|
.setCharset(charset)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(useFastPath)
|
||||||
.get()) {
|
.get()) {
|
||||||
|
|
||||||
var entries = zipFile.getEntries();
|
var entries = zipFile.getEntries();
|
||||||
|
boolean foundImages = false;
|
||||||
while (entries.hasMoreElements()) {
|
while (entries.hasMoreElements()) {
|
||||||
ZipArchiveEntry entry = entries.nextElement();
|
ZipArchiveEntry entry = entries.nextElement();
|
||||||
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
if (!entry.isDirectory() && isImageFile(entry.getName())) {
|
||||||
@@ -163,9 +174,11 @@ public class CbxReaderService {
|
|||||||
Path target = targetDir.resolve(fileName);
|
Path target = targetDir.resolve(fileName);
|
||||||
try (InputStream in = zipFile.getInputStream(entry)) {
|
try (InputStream in = zipFile.getInputStream(entry)) {
|
||||||
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
|
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
foundImages = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return foundImages;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,10 +346,19 @@ public class CbxReaderService {
|
|||||||
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
|
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
|
||||||
|
|
||||||
for (String encoding : encodingsToTry) {
|
for (String encoding : encodingsToTry) {
|
||||||
|
Charset charset = Charset.forName(encoding);
|
||||||
try {
|
try {
|
||||||
return estimateCbzWithEncoding(cbxPath, Charset.forName(encoding));
|
long size = estimateCbzWithEncoding(cbxPath, charset, true);
|
||||||
} catch (IllegalArgumentException | java.util.zip.ZipException e) {
|
if (size > 0) return size;
|
||||||
log.debug("Failed to estimate with encoding {}: {}", encoding, e.getMessage());
|
} catch (Exception e) {
|
||||||
|
log.debug("Fast path estimation failed for encoding {}: {}", encoding, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
long size = estimateCbzWithEncoding(cbxPath, charset, false);
|
||||||
|
if (size > 0) return size;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("Slow path estimation failed for encoding {}: {}", encoding, e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,11 +366,13 @@ public class CbxReaderService {
|
|||||||
return Long.MAX_VALUE;
|
return Long.MAX_VALUE;
|
||||||
}
|
}
|
||||||
|
|
||||||
private long estimateCbzWithEncoding(Path cbxPath, Charset charset) throws IOException {
|
private long estimateCbzWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException {
|
||||||
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
|
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
|
||||||
org.apache.commons.compress.archivers.zip.ZipFile.builder()
|
org.apache.commons.compress.archivers.zip.ZipFile.builder()
|
||||||
.setPath(cbxPath)
|
.setPath(cbxPath)
|
||||||
.setCharset(charset)
|
.setCharset(charset)
|
||||||
|
.setUseUnicodeExtraFields(true)
|
||||||
|
.setIgnoreLocalFileHeader(useFastPath)
|
||||||
.get()) {
|
.get()) {
|
||||||
|
|
||||||
long total = 0;
|
long total = 0;
|
||||||
|
|||||||
Reference in New Issue
Block a user