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:
+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