feat(archive): add ArchiveType via Magic Numbers detection and integrate into book processing (#2220)
* feat(archive): add ArchiveType detection and integrate into book processing Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * feat(cbx): enhance archive type detection for CBX files Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> * refactor(tests): rename method for clarity in CbxMetadataWriterTest Signed-off-by: Balázs Szücs <bszucs1209@gmail.com> --------- Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
This commit is contained in:
@@ -2,10 +2,10 @@ package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
@@ -16,6 +16,7 @@ import java.util.Set;
|
||||
public class Book {
|
||||
private Long id;
|
||||
private BookFileType bookType;
|
||||
private ArchiveUtils.ArchiveType archiveType;
|
||||
private Long libraryId;
|
||||
private String libraryName;
|
||||
private String fileName;
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.model.entity;
|
||||
import com.adityachandel.booklore.convertor.BookRecommendationIdsListConverter;
|
||||
import com.adityachandel.booklore.model.dto.BookRecommendationLite;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -34,6 +35,10 @@ public class BookEntity {
|
||||
@Column(name = "book_type")
|
||||
private BookFileType bookType;
|
||||
|
||||
@Column(name = "archive_type")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private ArchiveUtils.ArchiveType archiveType;
|
||||
|
||||
@Column(name = "file_size_kb")
|
||||
private Long fileSizeKb;
|
||||
|
||||
|
||||
+7
-11
@@ -11,6 +11,7 @@ import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
@@ -58,6 +59,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
|
||||
bookEntity.setArchiveType(ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(bookEntity))));
|
||||
if (generateCover(bookEntity)) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
@@ -98,18 +100,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
|
||||
}
|
||||
|
||||
private Optional<BufferedImage> extractImagesFromArchive(File file) {
|
||||
String name = file.getName();
|
||||
String extension = FileUtils.getExtension(name).toLowerCase();
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(file);
|
||||
|
||||
if (!BookFileType.CBX.supports(extension)) {
|
||||
log.warn("Unsupported CBX format: {}", name);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return switch (extension) {
|
||||
case "cbz" -> extractFirstImageFromZip(file);
|
||||
case "cb7" -> extractFirstImageFrom7z(file);
|
||||
case "cbr" -> extractFirstImageFromRar(file);
|
||||
return switch (type) {
|
||||
case ZIP -> extractFirstImageFromZip(file);
|
||||
case SEVEN_ZIP -> extractFirstImageFrom7z(file);
|
||||
case RAR -> extractFirstImageFromRar(file);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
|
||||
+9
-11
@@ -21,6 +21,7 @@ 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.ImageIO;
|
||||
@@ -184,17 +185,14 @@ public class CbxConversionService {
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromCbx(File cbxFile, Path extractedImagesDir) throws IOException, RarException {
|
||||
String fileName = cbxFile.getName().toLowerCase();
|
||||
|
||||
if (fileName.endsWith(".cbz")) {
|
||||
return extractImagesFromZip(cbxFile, extractedImagesDir);
|
||||
} else if (fileName.endsWith(".cbr")) {
|
||||
return extractImagesFromRar(cbxFile, extractedImagesDir);
|
||||
} else if (fileName.endsWith(".cb7")) {
|
||||
return extractImagesFrom7z(cbxFile, extractedImagesDir);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Unsupported archive format: " + fileName);
|
||||
}
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxFile);
|
||||
|
||||
return switch (type) {
|
||||
case ZIP -> extractImagesFromZip(cbxFile, extractedImagesDir);
|
||||
case RAR -> extractImagesFromRar(cbxFile, extractedImagesDir);
|
||||
case SEVEN_ZIP -> extractImagesFrom7z(cbxFile, extractedImagesDir);
|
||||
default -> throw new IllegalArgumentException("Unsupported archive format: " + cbxFile.getName());
|
||||
};
|
||||
}
|
||||
|
||||
private List<Path> extractImagesFromZip(File cbzFile, Path extractedImagesDir) throws IOException {
|
||||
|
||||
+14
-19
@@ -39,6 +39,7 @@ import org.w3c.dom.Document;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
|
||||
@@ -54,15 +55,10 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
String baseName = FilenameUtils.getBaseName(file.getName());
|
||||
String lowerName = file.getName().toLowerCase();
|
||||
|
||||
// Non-archive (fallback)
|
||||
if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) {
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(file);
|
||||
|
||||
// CBZ path (ZIP)
|
||||
if (lowerName.endsWith(".cbz")) {
|
||||
if (type == ArchiveUtils.ArchiveType.ZIP) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
ZipEntry entry = findComicInfoEntry(zipFile);
|
||||
if (entry == null) {
|
||||
@@ -79,7 +75,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CB7 path (7z)
|
||||
if (lowerName.endsWith(".cb7")) {
|
||||
if (type == ArchiveUtils.ArchiveType.SEVEN_ZIP) {
|
||||
try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) {
|
||||
SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ);
|
||||
if (entry == null) {
|
||||
@@ -100,6 +96,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CBR path (RAR)
|
||||
if (type == ArchiveUtils.ArchiveType.RAR) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
try {
|
||||
FileHeader header = findComicInfoHeader(archive);
|
||||
@@ -120,7 +117,8 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
return BookMetadata.builder().title(baseName).build();
|
||||
}
|
||||
|
||||
private ZipEntry findComicInfoEntry(ZipFile zipFile) {
|
||||
@@ -371,15 +369,10 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
String lowerName = file.getName().toLowerCase();
|
||||
|
||||
// Non-archive fallback
|
||||
if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) {
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(file);
|
||||
|
||||
// CBZ path
|
||||
if (lowerName.endsWith(".cbz")) {
|
||||
if (type == ArchiveUtils.ArchiveType.ZIP) {
|
||||
try (ZipFile zipFile = new ZipFile(file)) {
|
||||
// Try front cover via ComicInfo
|
||||
ZipEntry coverEntry = findFrontCoverEntry(zipFile);
|
||||
@@ -408,7 +401,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CB7 path
|
||||
if (lowerName.endsWith(".cb7")) {
|
||||
if (type == ArchiveUtils.ArchiveType.SEVEN_ZIP) {
|
||||
try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) {
|
||||
// Try via ComicInfo.xml first
|
||||
SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ);
|
||||
@@ -462,8 +455,9 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
|
||||
// CBR path
|
||||
try (Archive archive = new Archive(file)) {
|
||||
try {
|
||||
if (type == ArchiveUtils.ArchiveType.RAR) {
|
||||
try (Archive archive = new Archive(file)) {
|
||||
try {
|
||||
|
||||
// Try via ComicInfo.xml first
|
||||
FileHeader comicInfo = findComicInfoHeader(archive);
|
||||
@@ -516,6 +510,7 @@ public class CbxMetadataExtractor implements FileMetadataExtractor {
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
}
|
||||
}
|
||||
|
||||
return generatePlaceholderCover(250, 350);
|
||||
}
|
||||
|
||||
+8
-6
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.github.junrar.Archive;
|
||||
import com.github.junrar.rarfile.FileHeader;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -54,12 +55,13 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
if (!shouldSaveMetadataToFile(file)) {
|
||||
return;
|
||||
}
|
||||
String fileName = file.getName().toLowerCase(Locale.ROOT);
|
||||
boolean isCbz = fileName.endsWith(".cbz");
|
||||
boolean isCbr = fileName.endsWith(".cbr");
|
||||
boolean isCb7 = fileName.endsWith(".cb7");
|
||||
|
||||
if (!isCbz && !isCbr && !isCb7) {
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(file);
|
||||
boolean isCbz = type == ArchiveUtils.ArchiveType.ZIP;
|
||||
boolean isCbr = type == ArchiveUtils.ArchiveType.RAR;
|
||||
boolean isCb7 = type == ArchiveUtils.ArchiveType.SEVEN_ZIP;
|
||||
|
||||
if (type == ArchiveUtils.ArchiveType.UNKNOWN) {
|
||||
log.warn("Unsupported file type for CBX writer: {}", file.getName());
|
||||
return;
|
||||
}
|
||||
@@ -583,4 +585,4 @@ public class CbxMetadataWriter implements MetadataWriter {
|
||||
log.warn("Failed to clean up temporary directory: {}", directory, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-5
@@ -6,6 +6,13 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.Library;
|
||||
import com.adityachandel.booklore.model.enums.OpdsSortOrder;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.adityachandel.booklore.util.RequestUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URLEncoder;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -602,12 +609,30 @@ public class OpdsFeedService {
|
||||
case EPUB -> "application/epub+zip";
|
||||
case FB2 -> "application/x-fictionbook+xml";
|
||||
case CBX -> {
|
||||
if (book.getArchiveType() != null) {
|
||||
yield switch (book.getArchiveType()) {
|
||||
case RAR -> "application/vnd.comicbook-rar";
|
||||
case ZIP -> "application/vnd.comicbook+zip";
|
||||
case SEVEN_ZIP -> "application/x-7z-compressed";
|
||||
default -> "application/vnd.comicbook+zip";
|
||||
};
|
||||
}
|
||||
|
||||
if (book.getFileName() != null) {
|
||||
String lower = book.getFileName().toLowerCase();
|
||||
if (lower.endsWith(".cbr")) yield "application/vnd.comicbook-rar";
|
||||
if (lower.endsWith(".cbz")) yield "application/vnd.comicbook+zip";
|
||||
if (lower.endsWith(".cb7")) yield "application/x-7z-compressed";
|
||||
if (lower.endsWith(".cbt")) yield "application/x-tar";
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(FileUtils.getBookFullPath(book)));
|
||||
yield switch (type) {
|
||||
case RAR -> "application/vnd.comicbook-rar";
|
||||
case ZIP -> "application/vnd.comicbook+zip";
|
||||
case SEVEN_ZIP -> "application/x-7z-compressed";
|
||||
default -> {
|
||||
String lower = book.getFileName().toLowerCase();
|
||||
if (lower.endsWith(".cbr")) yield "application/vnd.comicbook-rar";
|
||||
if (lower.endsWith(".cbz")) yield "application/vnd.comicbook+zip";
|
||||
if (lower.endsWith(".cb7")) yield "application/x-7z-compressed";
|
||||
if (lower.endsWith(".cbt")) yield "application/x-tar";
|
||||
yield "application/vnd.comicbook+zip";
|
||||
}
|
||||
};
|
||||
}
|
||||
yield "application/vnd.comicbook+zip";
|
||||
}
|
||||
|
||||
+14
-17
@@ -4,6 +4,7 @@ import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import com.github.junrar.Archive;
|
||||
@@ -125,15 +126,12 @@ public class CbxReaderService {
|
||||
}
|
||||
|
||||
private void extractCbxArchive(Path cbxPath, Path targetDir) throws IOException {
|
||||
String filename = cbxPath.getFileName().toString().toLowerCase();
|
||||
if (filename.endsWith(CBZ_EXTENSION)) {
|
||||
extractZipArchive(cbxPath, targetDir);
|
||||
} else if (filename.endsWith(CB7_EXTENSION)) {
|
||||
extract7zArchive(cbxPath, targetDir);
|
||||
} else if (filename.endsWith(CBR_EXTENSION)) {
|
||||
extractRarArchive(cbxPath, targetDir);
|
||||
} else {
|
||||
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
|
||||
switch (type) {
|
||||
case ZIP -> extractZipArchive(cbxPath, targetDir);
|
||||
case SEVEN_ZIP -> extract7zArchive(cbxPath, targetDir);
|
||||
case RAR -> extractRarArchive(cbxPath, targetDir);
|
||||
default -> throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,14 +354,13 @@ public class CbxReaderService {
|
||||
|
||||
private long estimateArchiveSize(Path cbxPath) {
|
||||
try {
|
||||
String name = cbxPath.getFileName().toString().toLowerCase();
|
||||
if (name.endsWith(CBZ_EXTENSION)) {
|
||||
return estimateCbzArchiveSize(cbxPath);
|
||||
} else if (name.endsWith(CB7_EXTENSION)) {
|
||||
return estimateCb7ArchiveSize(cbxPath);
|
||||
} else if (name.endsWith(CBR_EXTENSION)) {
|
||||
return estimateCbrArchiveSize(cbxPath);
|
||||
}
|
||||
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
|
||||
return switch (type) {
|
||||
case ZIP -> estimateCbzArchiveSize(cbxPath);
|
||||
case SEVEN_ZIP -> estimateCb7ArchiveSize(cbxPath);
|
||||
case RAR -> estimateCbrArchiveSize(cbxPath);
|
||||
default -> Long.MAX_VALUE;
|
||||
};
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to estimate archive size for {}", cbxPath, e);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import lombok.experimental.UtilityClass;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@Slf4j
|
||||
@UtilityClass
|
||||
public class ArchiveUtils {
|
||||
|
||||
public enum ArchiveType {
|
||||
ZIP,
|
||||
RAR,
|
||||
SEVEN_ZIP,
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
private static final byte[] ZIP_MAGIC = {0x50, 0x4B, 0x03, 0x04};
|
||||
private static final byte[] RAR_MAGIC = {0x52, 0x61, 0x72, 0x21, 0x1A, 0x07};
|
||||
private static final byte[] SEVEN_ZIP_MAGIC = {0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C};
|
||||
|
||||
public static ArchiveType detectArchiveType(File file) {
|
||||
if (file == null || !file.exists() || !file.isFile()) {
|
||||
return ArchiveType.UNKNOWN;
|
||||
}
|
||||
|
||||
try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
|
||||
byte[] buffer = new byte[8];
|
||||
int bytesRead = is.read(buffer);
|
||||
if (bytesRead < 4) {
|
||||
return detectArchiveTypeByExtension(file.getName());
|
||||
}
|
||||
|
||||
if (startsWith(buffer, ZIP_MAGIC)) {
|
||||
return ArchiveType.ZIP;
|
||||
}
|
||||
if (startsWith(buffer, RAR_MAGIC)) {
|
||||
return ArchiveType.RAR;
|
||||
}
|
||||
if (startsWith(buffer, SEVEN_ZIP_MAGIC)) {
|
||||
return ArchiveType.SEVEN_ZIP;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to detect archive type by content for file: {}", file.getAbsolutePath());
|
||||
}
|
||||
|
||||
return detectArchiveTypeByExtension(file.getName());
|
||||
}
|
||||
|
||||
public static ArchiveType detectArchiveTypeByExtension(String fileName) {
|
||||
if (fileName == null) {
|
||||
return ArchiveType.UNKNOWN;
|
||||
}
|
||||
String lower = fileName.toLowerCase();
|
||||
if (lower.endsWith(".cbz") || lower.endsWith(".zip")) {
|
||||
return ArchiveType.ZIP;
|
||||
}
|
||||
if (lower.endsWith(".cbr") || lower.endsWith(".rar")) {
|
||||
return ArchiveType.RAR;
|
||||
}
|
||||
if (lower.endsWith(".cb7") || lower.endsWith(".7z")) {
|
||||
return ArchiveType.SEVEN_ZIP;
|
||||
}
|
||||
return ArchiveType.UNKNOWN;
|
||||
}
|
||||
|
||||
private static boolean startsWith(byte[] buffer, byte[] magic) {
|
||||
if (buffer.length < magic.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < magic.length; i++) {
|
||||
if (buffer[i] != magic[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import lombok.experimental.UtilityClass;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -27,6 +28,13 @@ public class FileUtils {
|
||||
.replace("\\", "/");
|
||||
}
|
||||
|
||||
public String getBookFullPath(Book book) {
|
||||
return Path.of(book.getLibraryPath().getPath(), book.getFileSubPath(), book.getFileName())
|
||||
.normalize()
|
||||
.toString()
|
||||
.replace("\\", "/");
|
||||
}
|
||||
|
||||
public String getRelativeSubPath(String basePath, Path fullFilePath) {
|
||||
return Optional.ofNullable(Path.of(basePath)
|
||||
.relativize(fullFilePath)
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
ALTER TABLE book ADD COLUMN archive_type VARCHAR(255);
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CbxProcessorTest {
|
||||
|
||||
@Mock private BookRepository bookRepository;
|
||||
@Mock private BookAdditionalFileRepository bookAdditionalFileRepository;
|
||||
@Mock private BookCreatorService bookCreatorService;
|
||||
@Mock private BookMapper bookMapper;
|
||||
@Mock private FileService fileService;
|
||||
@Mock private MetadataMatchService metadataMatchService;
|
||||
@Mock private CbxMetadataExtractor cbxMetadataExtractor;
|
||||
|
||||
private CbxProcessor cbxProcessor;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
cbxProcessor = new CbxProcessor(
|
||||
bookRepository,
|
||||
bookAdditionalFileRepository,
|
||||
bookCreatorService,
|
||||
bookMapper,
|
||||
fileService,
|
||||
metadataMatchService,
|
||||
cbxMetadataExtractor
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateCover_ZipNamedAsCbr_ShouldExtractImage() throws IOException {
|
||||
// Create a ZIP file named .cbr
|
||||
File zipAsCbr = tempDir.resolve("mismatched.cbr").toFile();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipAsCbr))) {
|
||||
ZipEntry entry = new ZipEntry("cover.jpg");
|
||||
zos.putNextEntry(entry);
|
||||
BufferedImage image = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
|
||||
ImageIO.write(image, "jpg", zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(1L);
|
||||
bookEntity.setFileName(zipAsCbr.getName());
|
||||
bookEntity.setFileSubPath("");
|
||||
LibraryPathEntity libPath = new LibraryPathEntity();
|
||||
libPath.setPath(tempDir.toString());
|
||||
bookEntity.setLibraryPath(libPath);
|
||||
bookEntity.setMetadata(new BookMetadataEntity());
|
||||
|
||||
when(fileService.saveCoverImages(any(BufferedImage.class), eq(1L))).thenReturn(true);
|
||||
|
||||
cbxProcessor.generateCover(bookEntity);
|
||||
|
||||
verify(fileService).saveCoverImages(any(BufferedImage.class), eq(1L));
|
||||
}
|
||||
}
|
||||
+17
@@ -135,6 +135,23 @@ class CbxConversionServiceTest {
|
||||
verifyPageOrderInEpub(epubFile, 5);
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithZipNamedAsCbr_ShouldGenerateValidEpub() throws IOException, TemplateException, RarException {
|
||||
File zipAsCbr = new File(tempDir.toFile(), "fake.cbr");
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(zipAsCbr))) {
|
||||
BufferedImage testImage = createTestImage("Page 1", Color.RED);
|
||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry("page01.png");
|
||||
zipOut.putArchiveEntry(imageEntry);
|
||||
ImageIO.write(testImage, "png", zipOut);
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
File epubFile = cbxConversionService.convertCbxToEpub(zipAsCbr, tempDir.toFile(), testBookEntity, 85);
|
||||
|
||||
assertThat(epubFile).exists();
|
||||
verifyEpubStructure(epubFile);
|
||||
}
|
||||
|
||||
private File createTestCbzFile() throws IOException {
|
||||
File cbzFile = Files.createFile(tempDir.resolve("test-comic.cbz")).toFile();
|
||||
|
||||
|
||||
+24
@@ -173,6 +173,30 @@ class CbxMetadataExtractorTest {
|
||||
assertEquals("Some Book Title", md.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractMetadata_fromCbz_withCbrExtension_shouldWork() throws Exception {
|
||||
String xml = "<ComicInfo><Title>Mismatched Extension</Title></ComicInfo>";
|
||||
|
||||
File cbzAsCbr = createCbz("mismatched.cbr", new LinkedHashMap<>() {{
|
||||
put("ComicInfo.xml", xml.getBytes(StandardCharsets.UTF_8));
|
||||
}});
|
||||
|
||||
BookMetadata md = extractor.extractMetadata(cbzAsCbr);
|
||||
assertEquals("Mismatched Extension", md.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractCover_fromCbz_withCbrExtension_shouldWork() throws Exception {
|
||||
byte[] img = createTestImage(Color.RED);
|
||||
|
||||
File cbzAsCbr = createCbz("mismatched_cover.cbr", new LinkedHashMap<>() {{
|
||||
put("cover.jpg", img);
|
||||
}});
|
||||
|
||||
byte[] cover = extractor.extractCover(cbzAsCbr);
|
||||
assertArrayEquals(img, cover);
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
|
||||
private File createCbz(String name, Map<String, byte[]> entries) throws IOException {
|
||||
|
||||
+18
@@ -194,6 +194,24 @@ class CbxMetadataWriterTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveMetadataToFile_ZipNamedAsCbr_ShouldUpdateMetadata() throws Exception {
|
||||
File zipAsCbr = createCbz(tempDir.resolve("mismatched.cbr"), new String[]{"page1.jpg"});
|
||||
|
||||
BookMetadataEntity meta = new BookMetadataEntity();
|
||||
meta.setTitle("Mismatched Title");
|
||||
|
||||
writer.saveMetadataToFile(zipAsCbr, meta, null, new MetadataClearFlags());
|
||||
|
||||
try (ZipFile zip = new ZipFile(zipAsCbr)) {
|
||||
ZipEntry ci = zip.getEntry("ComicInfo.xml");
|
||||
assertNotNull(ci, "ComicInfo.xml should be present");
|
||||
Document doc = parseXml(zip.getInputStream(ci));
|
||||
assertEquals("Mismatched Title", text(doc, "Title"));
|
||||
assertNotNull(zip.getEntry("page1.jpg"));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------- helpers -------------
|
||||
|
||||
private static File createCbz(Path path, String[] imageNames) throws Exception {
|
||||
|
||||
+68
@@ -4,19 +4,28 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.config.security.userdetails.OpdsUserDetails;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.LibraryPath;
|
||||
import com.adityachandel.booklore.model.dto.OpdsUserV2;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.OpdsSortOrder;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -33,6 +42,9 @@ class OpdsFeedServiceMimeTypeTest {
|
||||
private OpdsFeedService opdsFeedService;
|
||||
private HttpServletRequest request;
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
authenticationService = mock(AuthenticationService.class);
|
||||
@@ -123,11 +135,67 @@ class OpdsFeedServiceMimeTypeTest {
|
||||
assertThat(xml).contains("type=\"application/x-fictionbook+xml\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMimeTypeForZipNamedAsCbr() throws IOException {
|
||||
// Create a ZIP file named .cbr
|
||||
File zipAsCbr = tempDir.resolve("mismatched.cbr").toFile();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipAsCbr))) {
|
||||
zos.putNextEntry(new ZipEntry("test.txt"));
|
||||
zos.write("hello".getBytes());
|
||||
zos.closeEntry();
|
||||
}
|
||||
|
||||
Book book = createBook(BookFileType.CBX, "mismatched.cbr");
|
||||
mockBooksPage(book);
|
||||
|
||||
String xml = opdsFeedService.generateCatalogFeed(request);
|
||||
|
||||
// Should detect as ZIP (application/vnd.comicbook+zip) despite .cbr extension
|
||||
assertThat(xml).contains("type=\"application/vnd.comicbook+zip\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMimeTypeForRarNamedAsCbz() throws IOException {
|
||||
// Create a RAR file named .cbz (fake RAR header)
|
||||
File rarAsCbz = tempDir.resolve("mismatched.cbz").toFile();
|
||||
try (FileOutputStream fos = new FileOutputStream(rarAsCbz)) {
|
||||
// RAR 5.0 magic number
|
||||
fos.write(new byte[]{0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00});
|
||||
}
|
||||
|
||||
Book book = createBook(BookFileType.CBX, "mismatched.cbz");
|
||||
mockBooksPage(book);
|
||||
|
||||
String xml = opdsFeedService.generateCatalogFeed(request);
|
||||
|
||||
// Should detect as RAR (application/vnd.comicbook-rar) despite .cbz extension
|
||||
assertThat(xml).contains("type=\"application/vnd.comicbook-rar\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMimeTypeFromCachedArchiveType() {
|
||||
Book book = createBook(BookFileType.CBX, "whatever.cbz");
|
||||
book.setArchiveType(ArchiveUtils.ArchiveType.RAR); // Simulate mismatched but cached type
|
||||
|
||||
mockBooksPage(book);
|
||||
|
||||
String xml = opdsFeedService.generateCatalogFeed(request);
|
||||
|
||||
// Should use cached type (RAR) even if filename is .cbz and no file exists (mocked logic)
|
||||
// Note: The logic in OpdsFeedService prioritizes cached type.
|
||||
// However, my test creates a real file in other tests, but here I can skip file creation
|
||||
// because the cached type check happens first.
|
||||
|
||||
assertThat(xml).contains("type=\"application/vnd.comicbook-rar\"");
|
||||
}
|
||||
|
||||
private Book createBook(BookFileType type, String fileName) {
|
||||
return Book.builder()
|
||||
.id(1L)
|
||||
.bookType(type)
|
||||
.fileName(fileName)
|
||||
.fileSubPath("")
|
||||
.libraryPath(LibraryPath.builder().path(tempDir.toString()).build())
|
||||
.addedOn(Instant.now())
|
||||
.metadata(BookMetadata.builder().title("Test Book").build())
|
||||
.build();
|
||||
|
||||
+15
-4
@@ -169,6 +169,18 @@ class CbxReaderServiceTest {
|
||||
"Page count should be exactly 130 (actual comic pages only)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvailablePages_ZipWithCbrExtension_shouldWork() throws IOException {
|
||||
Path zipAsCbrFile = tempDir.resolve("misnamed.cbr");
|
||||
createTestCbzWithMacOsFiles(zipAsCbrFile.toFile());
|
||||
|
||||
testBook.setFileName(zipAsCbrFile.getFileName().toString());
|
||||
|
||||
List<Integer> pages = service.getAvailablePages(bookId);
|
||||
|
||||
assertEquals(130, pages.size(), "Should correctly detect and extract misnamed ZIP as CBR");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAvailablePages_whenArchiveIsCorrupt_shouldThrowFileReadError() throws IOException {
|
||||
Path corruptCbz = tempDir.resolve("corrupt.cbz");
|
||||
@@ -176,15 +188,14 @@ class CbxReaderServiceTest {
|
||||
|
||||
testBook.setFileName(corruptCbz.getFileName().toString());
|
||||
testBook.getLibraryPath().setPath(tempDir.toString());
|
||||
|
||||
|
||||
APIException exception = assertThrows(APIException.class, () -> service.getAvailablePages(bookId));
|
||||
|
||||
assertNotEquals(ApiError.CACHE_TOO_LARGE.getMessage(), exception.getMessage(),
|
||||
|
||||
assertNotEquals(ApiError.CACHE_TOO_LARGE.getMessage(), exception.getMessage(),
|
||||
"Should not throw CACHE_TOO_LARGE for a corrupt file");
|
||||
assertTrue(exception.getMessage().startsWith("Error reading files from path"),
|
||||
"Should throw FILE_READ_ERROR (message starts with 'Error reading files from path'), actual: '" + exception.getMessage() + "'");
|
||||
}
|
||||
|
||||
private void createTestCbzWithMacOsFiles(File cbzFile) throws IOException {
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(cbzFile))) {
|
||||
for (int i = 1; i <= 130; i++) {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class ArchiveUtilsTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void detectArchiveType_ZipWithCbrExtension() throws IOException {
|
||||
File file = tempDir.resolve("test.cbr").toFile();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) {
|
||||
zos.putNextEntry(new ZipEntry("test.txt"));
|
||||
zos.write("hello".getBytes());
|
||||
zos.closeEntry();
|
||||
}
|
||||
|
||||
assertEquals(ArchiveUtils.ArchiveType.ZIP, ArchiveUtils.detectArchiveType(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectArchiveType_RarWithCbzExtension() throws IOException {
|
||||
File file = tempDir.resolve("test.cbz").toFile();
|
||||
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||
fos.write(new byte[]{0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00});
|
||||
}
|
||||
|
||||
assertEquals(ArchiveUtils.ArchiveType.RAR, ArchiveUtils.detectArchiveType(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectArchiveType_SevenZip() throws IOException {
|
||||
File file = tempDir.resolve("test.cb7").toFile();
|
||||
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||
// 7z magic number: 37 7A BC AF 27 1C
|
||||
fos.write(new byte[]{0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C});
|
||||
}
|
||||
|
||||
assertEquals(ArchiveUtils.ArchiveType.SEVEN_ZIP, ArchiveUtils.detectArchiveType(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detectArchiveType_FallbackToExtension() throws IOException {
|
||||
File file = tempDir.resolve("test.cbz").toFile();
|
||||
try (FileOutputStream fos = new FileOutputStream(file)) {
|
||||
fos.write(new byte[]{0, 0, 0, 0}); // Non-matching magic
|
||||
}
|
||||
|
||||
assertEquals(ArchiveUtils.ArchiveType.ZIP, ArchiveUtils.detectArchiveType(file));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user