Add unrar CLI fallback for RAR5 CBR/CBX files (#2948)
This commit is contained in:
@@ -19,6 +19,7 @@ import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.BookCoverUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -210,11 +211,37 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
return extractFirstImageFromRarViaCli(file);
|
||||
}
|
||||
log.error("Error extracting RAR: {}", e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractFirstImageFromRarViaCli(File file) {
|
||||
try {
|
||||
List<String> entries = UnrarHelper.listEntries(file.toPath());
|
||||
List<String> imageEntries = entries.stream()
|
||||
.filter(name -> IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN.matcher(name).matches())
|
||||
.sorted()
|
||||
.toList();
|
||||
for (String entry : imageEntries) {
|
||||
try {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(file.toPath(), entry);
|
||||
BufferedImage image = FileService.readImage(new ByteArrayInputStream(bytes));
|
||||
if (image != null) return Optional.of(image);
|
||||
} catch (Exception ex) {
|
||||
log.warn("Error reading RAR entry via CLI {}: {}", entry, ex.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("unrar CLI fallback also failed for {}: {}", file.getName(), e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private void extractAndSetMetadata(BookEntity bookEntity) {
|
||||
try {
|
||||
BookMetadata extracted = cbxMetadataExtractor.extractMetadata(new File(FileUtils.getBookFullPath(bookEntity)));
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.booklore.model.entity.CategoryEntity;
|
||||
import org.booklore.model.entity.TagEntity;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
@@ -263,6 +264,14 @@ public class CbxConversionService {
|
||||
log.warn("Error extracting image {}: {}", fileHeader.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbrFile.getName(), e.getMessage());
|
||||
return extractImagesFromRarViaCli(cbrFile, extractedImagesDir);
|
||||
}
|
||||
if (e instanceof IOException ioe) throw ioe;
|
||||
if (e instanceof RarException re) throw re;
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
log.debug("Found {} image entries in CBR file", imagePaths.size());
|
||||
@@ -270,6 +279,26 @@ public class CbxConversionService {
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromRarViaCli(File cbrFile, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
List<String> entries = UnrarHelper.listEntries(cbrFile.toPath());
|
||||
for (String entryName : entries) {
|
||||
if (!isImageFile(entryName)) continue;
|
||||
try {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(cbrFile.toPath(), entryName);
|
||||
validateImageSize(entryName, bytes.length);
|
||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entryName));
|
||||
Files.write(outputPath, bytes);
|
||||
imagePaths.add(outputPath);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error extracting image via CLI {}: {}", entryName, e.getMessage());
|
||||
}
|
||||
}
|
||||
log.debug("Found {} image entries in CBR file (via unrar CLI)", imagePaths.size());
|
||||
imagePaths.sort(Comparator.comparing(path -> path.getFileName().toString().toLowerCase()));
|
||||
return imagePaths;
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFrom7z(File cb7File, Path extractedImagesDir) throws IOException {
|
||||
List<Path> imagePaths = new ArrayList<>();
|
||||
|
||||
|
||||
+80
-2
@@ -9,6 +9,7 @@ import org.apache.commons.io.FilenameUtils;
|
||||
import org.booklore.model.dto.BookMetadata;
|
||||
import org.booklore.model.dto.ComicMetadata;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
@@ -22,6 +23,7 @@ import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.file.Path;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
@@ -108,7 +110,15 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
log.warn("Failed to extract metadata from CBR", e);
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
try {
|
||||
return extractMetadataFromRarViaCli(file.toPath(), baseName);
|
||||
} catch (Exception ex) {
|
||||
log.warn("unrar CLI fallback also failed for {}", file.getName(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
@@ -749,7 +759,16 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
log.warn("Failed to extract cover image from CBR", e);
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI for cover: {}", file.getName(), e.getMessage());
|
||||
try {
|
||||
byte[] coverBytes = extractCoverFromRarViaCli(file.toPath());
|
||||
if (coverBytes != null) return coverBytes;
|
||||
} catch (Exception ex) {
|
||||
log.warn("unrar CLI cover fallback also failed for {}", file.getName(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1127,4 +1146,63 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
String lower = n.toLowerCase();
|
||||
return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml");
|
||||
}
|
||||
|
||||
private BookMetadata extractMetadataFromRarViaCli(Path rarPath, String baseName) throws Exception {
|
||||
List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataExtractor::isComicInfoName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry == null) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes == null || xmlBytes.length == 0) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
return mapDocumentToMetadata(document, baseName);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] extractCoverFromRarViaCli(Path rarPath) throws Exception {
|
||||
List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataExtractor::isComicInfoName)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry != null) {
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes != null && xmlBytes.length > 0) {
|
||||
try (InputStream is = new ByteArrayInputStream(xmlBytes)) {
|
||||
Document document = buildSecureDocument(is);
|
||||
String imageName = findFrontCoverImageName(document);
|
||||
if (imageName != null) {
|
||||
String match = entries.stream()
|
||||
.filter(e -> e.equalsIgnoreCase(imageName) || baseName(e).equalsIgnoreCase(baseName(imageName)))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (match != null) {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, match);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> imageEntries = entries.stream()
|
||||
.filter(this::isImageEntry)
|
||||
.sorted(this::naturalCompare)
|
||||
.toList();
|
||||
List<String> sorted = new ArrayList<>(imageEntries);
|
||||
sorted.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a)), !likelyCoverName(baseName(b))));
|
||||
for (String entry : sorted) {
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entry);
|
||||
if (canDecode(bytes)) return bytes;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
+58
@@ -22,6 +22,7 @@ import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.model.enums.ComicCreatorRole;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.util.ArchiveUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.jsoup.Jsoup;
|
||||
import org.jsoup.safety.Safelist;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -196,9 +197,32 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
return new ComicInfo();
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", file.getName(), e.getMessage());
|
||||
return loadFromRarViaCli(file.toPath());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private ComicInfo loadFromRarViaCli(Path rarPath) throws Exception {
|
||||
java.util.List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
String comicInfoEntry = entries.stream()
|
||||
.filter(CbxMetadataWriter::isComicInfoXml)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
if (comicInfoEntry != null) {
|
||||
byte[] xmlBytes = UnrarHelper.extractEntryBytes(rarPath, comicInfoEntry);
|
||||
if (xmlBytes != null && xmlBytes.length > 0) {
|
||||
try (InputStream stream = new ByteArrayInputStream(xmlBytes)) {
|
||||
return parseComicInfo(stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new ComicInfo();
|
||||
}
|
||||
|
||||
private void applyMetadataChanges(ComicInfo info, BookMetadataEntity metadata, MetadataClearFlags clearFlags) {
|
||||
MetadataCopyHelper helper = new MetadataCopyHelper(metadata);
|
||||
|
||||
@@ -604,6 +628,13 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI extractAll: {}", rarFile.getName(), e.getMessage());
|
||||
UnrarHelper.extractAll(rarFile.toPath(), targetDir);
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -631,6 +662,13 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI for RAR-to-ZIP: {}", rarFile.getName(), e.getMessage());
|
||||
convertRarToZipViaCli(rarFile.toPath(), tempZip, xmlContent);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz");
|
||||
@@ -644,6 +682,26 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void convertRarToZipViaCli(Path rarPath, Path tempZip, byte[] xmlContent) throws Exception {
|
||||
java.util.List<String> entries = UnrarHelper.listEntries(rarPath);
|
||||
try (ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) {
|
||||
for (String entryName : entries) {
|
||||
if (isComicInfoXml(entryName)) continue;
|
||||
if (!isPathSafe(entryName)) {
|
||||
log.warn("Skipping unsafe RAR entry name: {}", entryName);
|
||||
continue;
|
||||
}
|
||||
byte[] bytes = UnrarHelper.extractEntryBytes(rarPath, entryName);
|
||||
zipOutput.putNextEntry(new ZipEntry(entryName));
|
||||
zipOutput.write(bytes);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml"));
|
||||
zipOutput.write(xmlContent);
|
||||
zipOutput.closeEntry();
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreOriginalFile(Path backupPath, File targetFile) {
|
||||
try {
|
||||
if (backupPath != null) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.booklore.model.entity.BookFileEntity;
|
||||
import org.booklore.model.enums.BookFileType;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.util.FileUtils;
|
||||
import org.booklore.util.UnrarHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
@@ -396,7 +397,14 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage());
|
||||
entries = UnrarHelper.listEntries(cbxPath).stream()
|
||||
.filter(this::isImageFile)
|
||||
.collect(Collectors.toCollection(ArrayList::new));
|
||||
} else {
|
||||
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
sortNaturally(entries);
|
||||
return entries;
|
||||
@@ -411,6 +419,11 @@ public class CbxReaderService {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (UnrarHelper.isAvailable()) {
|
||||
log.info("junrar failed for {}, falling back to unrar CLI: {}", cbxPath.getFileName(), e.getMessage());
|
||||
UnrarHelper.extractEntry(cbxPath, entryName, outputStream);
|
||||
return;
|
||||
}
|
||||
throw new IOException("Failed to extract from RAR archive: " + e.getMessage(), e);
|
||||
}
|
||||
throw new FileNotFoundException("Entry not found in RAR archive: " + entryName);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
package org.booklore.util;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@UtilityClass
|
||||
public class UnrarHelper {
|
||||
|
||||
private static final String UNRAR_BIN_ENV = "BOOKLORE_UNRAR_BIN";
|
||||
private static final String DEFAULT_UNRAR_BIN = "unrar";
|
||||
private static final int PROCESS_TIMEOUT_SECONDS = 120;
|
||||
private static volatile Boolean cachedAvailability;
|
||||
|
||||
public static boolean isAvailable() {
|
||||
if (cachedAvailability != null) {
|
||||
return cachedAvailability;
|
||||
}
|
||||
synchronized (UnrarHelper.class) {
|
||||
if (cachedAvailability != null) {
|
||||
return cachedAvailability;
|
||||
}
|
||||
try {
|
||||
Process process = new ProcessBuilder(getUnrarBin())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.readAllBytes();
|
||||
}
|
||||
boolean finished = process.waitFor(5, TimeUnit.SECONDS);
|
||||
cachedAvailability = finished;
|
||||
} catch (Exception e) {
|
||||
log.debug("unrar binary not available: {}", e.getMessage());
|
||||
cachedAvailability = false;
|
||||
}
|
||||
if (cachedAvailability) {
|
||||
log.info("unrar CLI detected, RAR5 fallback enabled");
|
||||
}
|
||||
return cachedAvailability;
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> listEntries(Path rarPath) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(getUnrarBin(), "lb", rarPath.toAbsolutePath().toString());
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
String output;
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
output = new String(is.readAllBytes());
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar list timed out for: " + rarPath);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar list interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar list failed (exit " + process.exitValue() + ") for: " + rarPath);
|
||||
}
|
||||
return Arrays.stream(output.split("\n"))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public static void extractEntry(Path rarPath, String entryName, OutputStream out) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
getUnrarBin(), "p", "-inul", rarPath.toAbsolutePath().toString(), entryName
|
||||
);
|
||||
pb.redirectErrorStream(false);
|
||||
Process process = pb.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.transferTo(out);
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar extract timed out for entry: " + entryName);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar extract interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar extract failed (exit " + process.exitValue() + ") for entry: " + entryName);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] extractEntryBytes(Path rarPath, String entryName) throws IOException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
extractEntry(rarPath, entryName, baos);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
|
||||
public static void extractAll(Path rarPath, Path targetDir) throws IOException {
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
getUnrarBin(), "x", "-o+", rarPath.toAbsolutePath().toString(), targetDir.toAbsolutePath() + "/"
|
||||
);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
try (InputStream is = process.getInputStream()) {
|
||||
is.readAllBytes();
|
||||
}
|
||||
try {
|
||||
if (!process.waitFor(PROCESS_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("unrar extractAll timed out for: " + rarPath);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("unrar extractAll interrupted", e);
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
throw new IOException("unrar extractAll failed (exit " + process.exitValue() + ") for: " + rarPath);
|
||||
}
|
||||
}
|
||||
|
||||
private static String getUnrarBin() {
|
||||
String env = System.getenv(UNRAR_BIN_ENV);
|
||||
return (env != null && !env.isBlank()) ? env : DEFAULT_UNRAR_BIN;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user