fix(archive): infer archive type via Magic Numbers instead of filename (#79)

* chore(deps): bump actions/setup-node from 6.2.0 to 6.3.0 (#1)

Dependabot couldn't find the original pull request head commit, ea510f40fc1855aa17a782e05b0d30547e84955e.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump docker/setup-buildx-action from 3.12.0 to 4.0.0 (#2)

Dependabot couldn't find the original pull request head commit, faed6bf8a712c5fc793fa628157de25d97888131.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump docker/build-push-action from 6.19.2 to 7.0.0 (#3)

Dependabot couldn't find the original pull request head commit, f110823720b6dd773df014ba288a126d8837fe28.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump docker/login-action from 3.7.0 to 4.0.0 (#6)

Dependabot couldn't find the original pull request head commit, 9a8d7a1daf5afff06bb35e36607c3da9aa730e21.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix(archive): infer archive type via Magic Numbers instead of filename

* fix(archive): improve archive type detection and improve logging for cover image retrieval

---------

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
brios
2026-04-22 17:26:30 -04:00
committed by Zach Yale
co-authored by dependabot[bot]
parent dc1fa74af7
commit 3c0b5c0c9c
8 changed files with 48 additions and 73 deletions
@@ -104,7 +104,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
image.flush(); // Release resources after processing
}
} else {
log.warn("Could not find cover image in CBZ file '{}'", bookFile.getFileName());
log.warn("Could not find cover image in '{}' archive", bookFile.getFileName());
}
} catch (Exception e) {
log.error("Error generating cover for '{}': {}", bookFile.getFileName(), e.getMessage());
@@ -166,7 +166,8 @@ public class CbxConversionService {
throw new IllegalArgumentException("Invalid CBX file: " + cbxFile);
}
if (!isSupportedCbxFormat(cbxFile.getName())) {
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxFile);
if (type == ArchiveUtils.ArchiveType.UNKNOWN) {
throw new IllegalArgumentException("Unsupported file format: " + cbxFile.getName() +
". Supported formats: CBZ, CBR, CB7");
}
@@ -694,14 +695,4 @@ public class CbxConversionService {
return crc32.getValue();
}
public boolean isSupportedCbxFormat(String fileName) {
if (fileName == null) {
return false;
}
String lowerName = fileName.toLowerCase();
return lowerName.endsWith(".cbz") ||
lowerName.endsWith(".cbr") ||
lowerName.endsWith(".cb7");
}
}
@@ -673,22 +673,15 @@ public class OpdsFeedService {
if (hasValidFilePath(bookFile)) {
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(new File(bookFile.getFilePath()));
// We only trust detection if it found something definite (not UNKNOWN)
if (type != ArchiveUtils.ArchiveType.UNKNOWN) {
yield switch (type) {
case RAR -> "application/vnd.comicbook-rar";
case ZIP -> "application/vnd.comicbook+zip";
case SEVEN_ZIP -> "application/x-7z-compressed";
default -> "application/vnd.comicbook+zip"; // Should not happen given the if check
default -> "application/vnd.comicbook+zip";
};
}
}
String lower = bookFile.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";
}
case AUDIOBOOK -> {
@@ -14,6 +14,7 @@ import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.repository.BookRepository;
import org.booklore.util.ArchiveUtils;
import org.booklore.util.FileUtils;
import org.booklore.util.UnrarHelper;
import org.springframework.stereotype.Service;
@@ -38,9 +39,6 @@ import java.util.stream.IntStream;
@RequiredArgsConstructor
public class CbxReaderService {
private static final String CBZ_EXTENSION = ".cbz";
private static final String CBR_EXTENSION = ".cbr";
private static final String CB7_EXTENSION = ".cb7";
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"};
private static final Charset[] ENCODINGS_TO_TRY = {
StandardCharsets.UTF_8,
@@ -195,19 +193,20 @@ public class CbxReaderService {
}
private CachedArchiveMetadata scanArchiveMetadata(Path cbxPath) throws IOException {
String filename = cbxPath.getFileName().toString().toLowerCase();
long lastModified = Files.getLastModifiedTime(cbxPath).toMillis();
if (filename.endsWith(CBZ_EXTENSION)) {
return scanZipMetadata(cbxPath, lastModified);
} else if (filename.endsWith(CB7_EXTENSION)) {
List<String> entries = getImageEntriesFrom7z(cbxPath);
return new CachedArchiveMetadata(entries, lastModified, null, false);
} else if (filename.endsWith(CBR_EXTENSION)) {
List<String> entries = getImageEntriesFromRar(cbxPath);
return new CachedArchiveMetadata(entries, lastModified, null, false);
} else {
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
}
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
return switch (type) {
case ZIP -> scanZipMetadata(cbxPath, lastModified);
case SEVEN_ZIP -> {
List<String> entries = getImageEntriesFrom7z(cbxPath);
yield new CachedArchiveMetadata(entries, lastModified, null, false);
}
case RAR -> {
List<String> entries = getImageEntriesFromRar(cbxPath);
yield new CachedArchiveMetadata(entries, lastModified, null, false);
}
default -> throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
};
}
private CachedArchiveMetadata scanZipMetadata(Path cbxPath, long lastModified) throws IOException {
@@ -316,15 +315,12 @@ public class CbxReaderService {
private void streamEntryFromArchive(Path cbxPath, String entryName, OutputStream outputStream, CachedArchiveMetadata metadata) throws IOException {
String filename = cbxPath.getFileName().toString().toLowerCase();
if (filename.endsWith(CBZ_EXTENSION)) {
streamEntryFromZip(cbxPath, entryName, outputStream, metadata);
} else if (filename.endsWith(CB7_EXTENSION)) {
streamEntryFrom7z(cbxPath, entryName, outputStream);
} else if (filename.endsWith(CBR_EXTENSION)) {
streamEntryFromRar(cbxPath, entryName, outputStream);
} else {
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
switch (type) {
case ZIP -> streamEntryFromZip(cbxPath, entryName, outputStream, metadata);
case SEVEN_ZIP -> streamEntryFrom7z(cbxPath, entryName, outputStream);
case RAR -> streamEntryFromRar(cbxPath, entryName, outputStream);
default -> throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
}
}
@@ -93,30 +93,6 @@ class CbxConversionServiceTest {
.hasMessageContaining("No valid images found");
}
@Test
void isSupportedCbxFormat_WithSupportedFiles_ShouldReturnTrue() {
assertThat(cbxConversionService.isSupportedCbxFormat("test.cbz")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("test.CBZ")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("path/to/test.cbz")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("test.cbr")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("test.CBR")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("path/to/test.cbr")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("test.cb7")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("test.CB7")).isTrue();
assertThat(cbxConversionService.isSupportedCbxFormat("path/to/test.cb7")).isTrue();
}
@Test
void isSupportedCbxFormat_WithUnsupportedFormats_ShouldReturnFalse() {
assertThat(cbxConversionService.isSupportedCbxFormat("test.zip")).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat("test.pdf")).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat("test.epub")).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat("test.txt")).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat("test")).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat(null)).isFalse();
assertThat(cbxConversionService.isSupportedCbxFormat("")).isFalse();
}
@Test
void convertCbxToEpub_WithNullBookEntity_ShouldUseDefaultMetadata() throws IOException, TemplateException, RarException {
File epubFile = cbxConversionService.convertCbxToEpub(testCbzFile, tempDir.toFile(), null,85);
@@ -105,7 +105,12 @@ class OpdsFeedServiceMimeTypeTest {
}
@Test
void testMimeTypeForCbr() {
void testMimeTypeForCbr() throws IOException {
File rarFile = tempDir.resolve("comic.cbr").toFile();
try (FileOutputStream fos = new FileOutputStream(rarFile)) {
// RAR 4.x magic bytes
fos.write(new byte[]{0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00});
}
Book book = createBook(BookFileType.CBX, "comic.cbr");
mockBooksPage(book);
String xml = opdsFeedService.generateCatalogFeed(request);
@@ -113,7 +118,12 @@ class OpdsFeedServiceMimeTypeTest {
}
@Test
void testMimeTypeForCb7() {
void testMimeTypeForCb7() throws IOException {
File sevenZFile = tempDir.resolve("comic.cb7").toFile();
try (FileOutputStream fos = new FileOutputStream(sevenZFile)) {
// 7z magic bytes
fos.write(new byte[]{0x37, 0x7A, (byte) 0xBC, (byte) 0xAF, 0x27, 0x1C});
}
Book book = createBook(BookFileType.CBX, "comic.cb7");
mockBooksPage(book);
String xml = opdsFeedService.generateCatalogFeed(request);
@@ -122,10 +132,12 @@ class OpdsFeedServiceMimeTypeTest {
@Test
void testMimeTypeForCbt() {
// CBT is TAR-based; ArchiveUtils has no TAR magic byte detection,
// so an unrecognised archive defaults to the CBX fallback mime type.
Book book = createBook(BookFileType.CBX, "comic.cbt");
mockBooksPage(book);
String xml = opdsFeedService.generateCatalogFeed(request);
assertThat(xml).contains("type=\"application/x-tar\"");
assertThat(xml).contains("type=\"application/vnd.comicbook+zip\"");
}
@Test
@@ -495,10 +495,11 @@ class OpdsFeedServiceTest {
var method = OpdsFeedService.class.getDeclaredMethod("fileMimeType", BookFile.class);
method.setAccessible(true);
// The reliable path: archive type is cached during indexing
BookFile bookFile = BookFile.builder()
.bookType(BookFileType.CBX)
.fileName("comic.cbr")
.archiveType(ArchiveUtils.ArchiveType.UNKNOWN)
.archiveType(ArchiveUtils.ArchiveType.RAR)
.build();
String mimeType = (String) method.invoke(opdsFeedService, bookFile);
+7 -1
View File
@@ -1,6 +1,12 @@
services:
backend:
image: gradle:9.3.1-jdk25-alpine
build:
context: .
dockerfile_inline: |
FROM linuxserver/unrar:7.1.10 AS unrar-layer
FROM gradle:9.3.1-jdk25-alpine
RUN apk add --no-cache libstdc++ libgcc
COPY --from=unrar-layer /usr/bin/unrar-alpine /usr/local/bin/unrar
command: sh -c "cd /booklore-api && ./gradlew bootRun"
ports:
- "${BACKEND_PORT:-6060}:6060"