Feature: Add EPUB conversion support for CBX files to Kobo Sync (#1538)
* Feature/kobo sync cbx support (#3) * Feature: Add CBX syncing support to Kobo sync (#2) * feat: add cbx sync support * fix: phrasing of setting description to align with CBX terminology * fix: resolve issue with CBX setting persistence * fix: updated dev docker compose to align with Dockerfile * feat: add cbx files as allowed entitlements * fix: relax tomcat query characters for kobo sync * fix: remove hardcoded epub restrictions * fix: reduce image size and resolve relative content paths * fix: resolve issues with the image file encoding * feat: add rar and cb7 support * feat: bring generated epub more in line with epub standard * fix: resolve issues with extra metadata fields * fix: make css background colour white to improve e-ink performance * cleanup: code comments * feat: add cbx unit tests * fix: update zipfile to use builder pattern as current method is deprecated * fix: remove comments * fix: replace regex pattern to a simpler check * fix: remove unused imports * fix: update epub template to use standard language string * fix: missing line end on css * fix: remove duplicate query characters * fix: grammer issue * fix: resolve typo in the entitlement service test * fix: redundant imports and update long types * chore: update test descriptions for cbx conversion * fix: add check for larger images in archive files. unlikely to occur. * fix: merge temp dir logic for the book download * fix: update kobo entitlement to always report the format as epub3 * fix: implement suggested changes around javadocs and some edge cases to handle gracefully * chore: cleanup variable names to be clearer in download service * feat: change function to extract to disk instead of storing images in memory * fix: add temp file clean up into the conversion service * fix: add visual divider to seperate CBX and EPUB settings * fix: update lambdas to use method references * fix: reword setting description for cbx to epub sync --------- Co-authored-by: Aditya Chandel <8075870+adityachandelgit@users.noreply.github.com>
This commit is contained in:
co-authored by
Aditya Chandel
parent
e47046aa20
commit
dfb73d50d9
+114
@@ -0,0 +1,114 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.kobo.KoboBookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.KoboBookFormat;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.book.BookQueryService;
|
||||
import com.adityachandel.booklore.service.kobo.KoboCompatibilityService;
|
||||
import com.adityachandel.booklore.service.kobo.KoboEntitlementService;
|
||||
import com.adityachandel.booklore.util.kobo.KoboUrlBuilder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KoboEntitlementServiceTest {
|
||||
|
||||
@Mock
|
||||
private KoboUrlBuilder koboUrlBuilder;
|
||||
|
||||
@Mock
|
||||
private BookQueryService bookQueryService;
|
||||
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
|
||||
@Mock
|
||||
private KoboCompatibilityService koboCompatibilityService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboEntitlementService koboEntitlementService;
|
||||
|
||||
@Test
|
||||
void getMetadataForBook_shouldUseCompatibilityServiceFilter() {
|
||||
long bookId = 1L;
|
||||
String token = "test-token";
|
||||
|
||||
BookEntity cbxBook = createCbxBookEntity(bookId);
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(bookId)))
|
||||
.thenReturn(List.of(cbxBook));
|
||||
when(koboCompatibilityService.isBookSupportedForKobo(cbxBook))
|
||||
.thenReturn(true);
|
||||
when(koboUrlBuilder.downloadUrl(token, bookId))
|
||||
.thenReturn("http://test.com/download/" + bookId);
|
||||
when(appSettingService.getAppSettings())
|
||||
.thenReturn(createAppSettingsWithKoboSettings());
|
||||
|
||||
KoboBookMetadata result = koboEntitlementService.getMetadataForBook(bookId, token);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("Test CBX Book", result.getTitle());
|
||||
verify(koboCompatibilityService).isBookSupportedForKobo(cbxBook);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapToKoboMetadata_cbxBookWithConversionEnabled_shouldReturnEpubFormat() {
|
||||
long bookId = 1L;
|
||||
BookEntity cbxBook = createCbxBookEntity(bookId);
|
||||
String token = "test-token";
|
||||
|
||||
when(bookQueryService.findAllWithMetadataByIds(Set.of(bookId)))
|
||||
.thenReturn(List.of(cbxBook));
|
||||
when(koboCompatibilityService.isBookSupportedForKobo(cbxBook))
|
||||
.thenReturn(true);
|
||||
when(koboUrlBuilder.downloadUrl(token, cbxBook.getId()))
|
||||
.thenReturn("http://test.com/download/" + cbxBook.getId());
|
||||
when(appSettingService.getAppSettings())
|
||||
.thenReturn(createAppSettingsWithKoboSettings());
|
||||
|
||||
KoboBookMetadata result = koboEntitlementService.getMetadataForBook(bookId, token);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getDownloadUrls().size());
|
||||
assertEquals(KoboBookFormat.EPUB3.toString(), result.getDownloadUrls().get(0).getFormat());
|
||||
}
|
||||
|
||||
private BookEntity createCbxBookEntity(Long id) {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(id);
|
||||
book.setBookType(BookFileType.CBX);
|
||||
book.setFileSizeKb(1024L);
|
||||
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Test CBX Book");
|
||||
metadata.setDescription("A test CBX comic book");
|
||||
metadata.setBookId(id);
|
||||
book.setMetadata(metadata);
|
||||
|
||||
return book;
|
||||
}
|
||||
|
||||
private com.adityachandel.booklore.model.dto.settings.AppSettings createAppSettingsWithKoboSettings() {
|
||||
var appSettings = new com.adityachandel.booklore.model.dto.settings.AppSettings();
|
||||
KoboSettings koboSettings = KoboSettings.builder()
|
||||
.convertCbxToEpub(true)
|
||||
.conversionLimitInMbForCbx(50)
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(50)
|
||||
.build();
|
||||
appSettings.setKoboSettings(koboSettings);
|
||||
return appSettings;
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import freemarker.template.TemplateException;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("CBX Conversion Integration Test")
|
||||
class CbxConversionIntegrationTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private CbxConversionService conversionService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
conversionService = new CbxConversionService();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should successfully convert CBZ to EPUB with valid structure")
|
||||
void convertCbzToEpub_MainConversionTest() throws IOException, TemplateException, RarException {
|
||||
File testCbzFile = createTestComicCbzFile();
|
||||
BookEntity bookMetadata = createTestBookMetadata();
|
||||
|
||||
File epubFile = conversionService.convertCbxToEpub(testCbzFile, tempDir.toFile(), bookMetadata);
|
||||
|
||||
assertThat(epubFile)
|
||||
.exists()
|
||||
.hasExtension("epub");
|
||||
|
||||
assertThat(epubFile.length())
|
||||
.as("EPUB file should not be empty")
|
||||
.isGreaterThan(0);
|
||||
|
||||
verifyEpubContents(epubFile, bookMetadata);
|
||||
}
|
||||
|
||||
private File createTestComicCbzFile() throws IOException {
|
||||
File cbzFile = Files.createFile(tempDir.resolve("test-comic.cbz")).toFile();
|
||||
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(cbzFile))) {
|
||||
String[] pageNames = {"cover.jpg", "page01.png", "page02.jpg"};
|
||||
Color[] colors = {Color.RED, Color.GREEN, Color.BLUE};
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
BufferedImage pageImage = createComicPageImage(400, 600, colors[i], "Page " + (i + 1));
|
||||
|
||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry(pageNames[i]);
|
||||
zipOut.putArchiveEntry(imageEntry);
|
||||
|
||||
String format = pageNames[i].endsWith(".png") ? "png" : "jpg";
|
||||
ImageIO.write(pageImage, format, zipOut);
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
}
|
||||
|
||||
return cbzFile;
|
||||
}
|
||||
|
||||
private BufferedImage createComicPageImage(int width, int height, Color bgColor, String text) {
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
|
||||
g2d.setColor(bgColor);
|
||||
g2d.fillRect(0, 0, width, height);
|
||||
|
||||
g2d.setColor(Color.BLACK);
|
||||
g2d.setStroke(new BasicStroke(3));
|
||||
g2d.drawRect(10, 10, width - 20, height - 20);
|
||||
|
||||
g2d.setFont(new Font("Arial", Font.BOLD, 24));
|
||||
FontMetrics fm = g2d.getFontMetrics();
|
||||
int textWidth = fm.stringWidth(text);
|
||||
int textHeight = fm.getHeight();
|
||||
|
||||
g2d.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2);
|
||||
|
||||
g2d.dispose();
|
||||
return image;
|
||||
}
|
||||
|
||||
private BookEntity createTestBookMetadata() {
|
||||
BookEntity book = new BookEntity();
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
|
||||
metadata.setTitle("Amazing Comic Adventures");
|
||||
metadata.setLanguage("en");
|
||||
|
||||
book.setMetadata(metadata);
|
||||
return book;
|
||||
}
|
||||
|
||||
private void verifyEpubContents(File epubFile, BookEntity expectedMetadata) throws IOException {
|
||||
try (ZipFile zipFile = ZipFile.builder().setFile(epubFile).get()) {
|
||||
List<String> entryNames = Collections.list(zipFile.getEntries())
|
||||
.stream()
|
||||
.map(ZipArchiveEntry::getName)
|
||||
.toList();
|
||||
|
||||
assertThat(entryNames)
|
||||
.as("EPUB should contain required structure files")
|
||||
.contains(
|
||||
"mimetype",
|
||||
"META-INF/container.xml",
|
||||
"OEBPS/content.opf",
|
||||
"OEBPS/toc.ncx",
|
||||
"OEBPS/nav.xhtml",
|
||||
"OEBPS/Styles/stylesheet.css"
|
||||
);
|
||||
|
||||
verifyMimetypeEntry(zipFile);
|
||||
|
||||
long imageCount = entryNames.stream()
|
||||
.filter(name -> name.startsWith("OEBPS/Images/") && name.endsWith(".jpg"))
|
||||
.count();
|
||||
|
||||
long pageCount = entryNames.stream()
|
||||
.filter(name -> name.startsWith("OEBPS/Text/") && name.endsWith(".xhtml"))
|
||||
.count();
|
||||
|
||||
// Note: The EPUB contains 4 images because the conversion service duplicates the first image:
|
||||
// once as 'cover.jpg' (for the cover, referenced in the manifest but not in the spine)
|
||||
// and once as 'page-0001.jpg' (for the first comic page). Only 3 HTML pages are created,
|
||||
// one for each comic page image, since the cover image is not given its own HTML page.
|
||||
assertThat(imageCount)
|
||||
.as("Should have converted all comic pages to images")
|
||||
.isEqualTo(4);
|
||||
|
||||
assertThat(pageCount)
|
||||
.as("Should have created HTML page for each image (excluding cover)")
|
||||
.isEqualTo(3);
|
||||
|
||||
verifyContentOpf(zipFile, expectedMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyMimetypeEntry(ZipFile zipFile) throws IOException {
|
||||
ZipArchiveEntry mimetypeEntry = zipFile.getEntry("mimetype");
|
||||
|
||||
assertThat(mimetypeEntry)
|
||||
.as("Mimetype entry should exist")
|
||||
.isNotNull();
|
||||
|
||||
assertThat(mimetypeEntry.getMethod())
|
||||
.as("Mimetype should be stored uncompressed")
|
||||
.isEqualTo(ZipArchiveEntry.STORED);
|
||||
|
||||
try (InputStream stream = zipFile.getInputStream(mimetypeEntry)) {
|
||||
String content = new String(stream.readAllBytes());
|
||||
assertThat(content)
|
||||
.as("Mimetype content should be correct")
|
||||
.isEqualTo("application/epub+zip");
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyContentOpf(ZipFile zipFile, BookEntity expectedMetadata) throws IOException {
|
||||
ZipArchiveEntry contentOpfEntry = zipFile.getEntry("OEBPS/content.opf");
|
||||
|
||||
assertThat(contentOpfEntry)
|
||||
.as("Content.opf should exist")
|
||||
.isNotNull();
|
||||
|
||||
try (InputStream stream = zipFile.getInputStream(contentOpfEntry)) {
|
||||
String content = new String(stream.readAllBytes());
|
||||
|
||||
assertThat(content)
|
||||
.as("Content.opf should contain book title")
|
||||
.contains(expectedMetadata.getMetadata().getTitle());
|
||||
|
||||
assertThat(content)
|
||||
.as("Content.opf should contain language")
|
||||
.contains(expectedMetadata.getMetadata().getLanguage());
|
||||
|
||||
assertThat(content)
|
||||
.as("Content.opf should reference image files")
|
||||
.contains("media-type=\"image/jpeg\"");
|
||||
|
||||
assertThat(content)
|
||||
.as("Content.opf should reference HTML pages")
|
||||
.contains("media-type=\"application/xhtml+xml\"");
|
||||
|
||||
assertThat(content)
|
||||
.as("Content.opf should have spine entries")
|
||||
.contains("<spine")
|
||||
.contains("itemref");
|
||||
}
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import freemarker.template.TemplateException;
|
||||
import com.github.junrar.exception.RarException;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@DisplayName("CBX Conversion Service Tests")
|
||||
class CbxConversionServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private CbxConversionService cbxConversionService;
|
||||
private File testCbzFile;
|
||||
private BookEntity testBookEntity;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
cbxConversionService = new CbxConversionService();
|
||||
testCbzFile = createTestCbzFile();
|
||||
testBookEntity = createTestBookEntity();
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithValidCbzFile_ShouldGenerateValidEpub() throws IOException, TemplateException, RarException {
|
||||
File epubFile = cbxConversionService.convertCbxToEpub(testCbzFile, tempDir.toFile(), testBookEntity);
|
||||
|
||||
assertThat(epubFile).exists();
|
||||
assertThat(epubFile.getName()).endsWith(".epub");
|
||||
assertThat(epubFile.length()).isGreaterThan(0);
|
||||
|
||||
verifyEpubStructure(epubFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithNullCbxFile_ShouldThrowException() {
|
||||
assertThatThrownBy(() -> cbxConversionService.convertCbxToEpub(null, tempDir.toFile(), testBookEntity))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Invalid CBX file");
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithNonExistentFile_ShouldThrowException() {
|
||||
File nonExistentFile = new File(tempDir.toFile(), "non-existent.cbz");
|
||||
|
||||
assertThatThrownBy(() -> cbxConversionService.convertCbxToEpub(nonExistentFile, tempDir.toFile(), testBookEntity))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Invalid CBX file");
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithUnsupportedFileFormat_ShouldThrowException() throws IOException {
|
||||
File unsupportedFile = Files.createFile(tempDir.resolve("test.txt")).toFile();
|
||||
|
||||
assertThatThrownBy(() -> cbxConversionService.convertCbxToEpub(unsupportedFile, tempDir.toFile(), testBookEntity))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Unsupported file format");
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithNullTempDir_ShouldThrowException() {
|
||||
assertThatThrownBy(() -> cbxConversionService.convertCbxToEpub(testCbzFile, null, testBookEntity))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("Invalid temp directory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithEmptyCbzFile_ShouldThrowException() throws IOException {
|
||||
File emptyCbzFile = createEmptyCbzFile();
|
||||
|
||||
assertThatThrownBy(() -> cbxConversionService.convertCbxToEpub(emptyCbzFile, tempDir.toFile(), testBookEntity))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.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);
|
||||
|
||||
assertThat(epubFile).exists();
|
||||
verifyEpubStructure(epubFile);
|
||||
}
|
||||
|
||||
@Test
|
||||
void convertCbxToEpub_WithMultipleImages_ShouldPreservePageOrder() throws IOException, TemplateException, RarException {
|
||||
File multiPageCbzFile = createMultiPageCbzFile();
|
||||
|
||||
File epubFile = cbxConversionService.convertCbxToEpub(multiPageCbzFile, tempDir.toFile(), testBookEntity);
|
||||
|
||||
assertThat(epubFile).exists();
|
||||
verifyPageOrderInEpub(epubFile, 5);
|
||||
}
|
||||
|
||||
private File createTestCbzFile() throws IOException {
|
||||
File cbzFile = Files.createFile(tempDir.resolve("test-comic.cbz")).toFile();
|
||||
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(cbzFile))) {
|
||||
BufferedImage testImage = createTestImage("Page 1", Color.RED);
|
||||
|
||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry("page01.png");
|
||||
zipOut.putArchiveEntry(imageEntry);
|
||||
ImageIO.write(testImage, "png", zipOut);
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
return cbzFile;
|
||||
}
|
||||
|
||||
private File createEmptyCbzFile() throws IOException {
|
||||
File cbzFile = Files.createFile(tempDir.resolve("empty-comic.cbz")).toFile();
|
||||
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(cbzFile))) {
|
||||
ZipArchiveEntry textEntry = new ZipArchiveEntry("readme.txt");
|
||||
zipOut.putArchiveEntry(textEntry);
|
||||
zipOut.write("This is not an image".getBytes());
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
|
||||
return cbzFile;
|
||||
}
|
||||
|
||||
private File createMultiPageCbzFile() throws IOException {
|
||||
File cbzFile = Files.createFile(tempDir.resolve("multi-page-comic.cbz")).toFile();
|
||||
|
||||
try (ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(new FileOutputStream(cbzFile))) {
|
||||
Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.MAGENTA};
|
||||
|
||||
for (int i = 0; i < 5; i++) {
|
||||
BufferedImage testImage = createTestImage("Page " + (i + 1), colors[i]);
|
||||
|
||||
ZipArchiveEntry imageEntry = new ZipArchiveEntry(String.format("page%02d.png", i + 1));
|
||||
zipOut.putArchiveEntry(imageEntry);
|
||||
ImageIO.write(testImage, "png", zipOut);
|
||||
zipOut.closeArchiveEntry();
|
||||
}
|
||||
}
|
||||
|
||||
return cbzFile;
|
||||
}
|
||||
|
||||
private BufferedImage createTestImage(String text, Color backgroundColor) {
|
||||
BufferedImage image = new BufferedImage(200, 300, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
g2d.setColor(backgroundColor);
|
||||
g2d.fillRect(0, 0, 200, 300);
|
||||
|
||||
g2d.setColor(Color.BLACK);
|
||||
g2d.setFont(new Font("Arial", Font.BOLD, 16));
|
||||
g2d.drawString(text, 50, 150);
|
||||
|
||||
g2d.dispose();
|
||||
return image;
|
||||
}
|
||||
|
||||
private BookEntity createTestBookEntity() {
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
BookMetadataEntity metadata = new BookMetadataEntity();
|
||||
metadata.setTitle("Test Comic Book");
|
||||
metadata.setLanguage("en");
|
||||
bookEntity.setMetadata(metadata);
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
private void verifyEpubStructure(File epubFile) throws IOException {
|
||||
try (ZipFile zipFile = ZipFile.builder().setFile(epubFile).get()) {
|
||||
List<ZipArchiveEntry> entries = Collections.list(zipFile.getEntries());
|
||||
|
||||
assertThat(entries).extracting(ZipArchiveEntry::getName)
|
||||
.contains(
|
||||
"mimetype",
|
||||
"META-INF/container.xml",
|
||||
"OEBPS/content.opf",
|
||||
"OEBPS/toc.ncx",
|
||||
"OEBPS/nav.xhtml",
|
||||
"OEBPS/Styles/stylesheet.css"
|
||||
);
|
||||
|
||||
ZipArchiveEntry mimetypeEntry = zipFile.getEntry("mimetype");
|
||||
assertThat(mimetypeEntry).isNotNull();
|
||||
assertThat(mimetypeEntry.getMethod()).isEqualTo(ZipArchiveEntry.STORED);
|
||||
|
||||
try (InputStream mimetypeStream = zipFile.getInputStream(mimetypeEntry)) {
|
||||
String mimetypeContent = new String(mimetypeStream.readAllBytes());
|
||||
assertThat(mimetypeContent).isEqualTo("application/epub+zip");
|
||||
}
|
||||
|
||||
assertThat(entries).anyMatch(entry -> entry.getName().startsWith("OEBPS/Images/"));
|
||||
assertThat(entries).anyMatch(entry -> entry.getName().startsWith("OEBPS/Text/"));
|
||||
assertThat(entries).anyMatch(entry -> entry.getName().endsWith(".jpg"));
|
||||
assertThat(entries).anyMatch(entry -> entry.getName().endsWith(".xhtml"));
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyPageOrderInEpub(File epubFile, int expectedPageCount) throws IOException {
|
||||
try (ZipFile zipFile = ZipFile.builder().setFile(epubFile).get()) {
|
||||
List<ZipArchiveEntry> imageEntries = Collections.list(zipFile.getEntries()).stream()
|
||||
.filter(entry -> entry.getName().startsWith("OEBPS/Images/page-"))
|
||||
.sorted((e1, e2) -> e1.getName().compareTo(e2.getName()))
|
||||
.toList();
|
||||
|
||||
List<ZipArchiveEntry> htmlEntries = Collections.list(zipFile.getEntries()).stream()
|
||||
.filter(entry -> entry.getName().startsWith("OEBPS/Text/page-"))
|
||||
.sorted((e1, e2) -> e1.getName().compareTo(e2.getName()))
|
||||
.toList();
|
||||
|
||||
assertThat(imageEntries).hasSize(expectedPageCount);
|
||||
assertThat(htmlEntries).hasSize(expectedPageCount);
|
||||
|
||||
for (int i = 0; i < expectedPageCount; i++) {
|
||||
String expectedImageName = String.format("OEBPS/Images/page-%04d.jpg", i + 1);
|
||||
String expectedHtmlName = String.format("OEBPS/Text/page-%04d.xhtml", i + 1);
|
||||
|
||||
assertThat(imageEntries.get(i).getName()).isEqualTo(expectedImageName);
|
||||
assertThat(htmlEntries.get(i).getName()).isEqualTo(expectedHtmlName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package com.adityachandel.booklore.service.kobo;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@DisplayName("Kobo Compatibility Service Tests")
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KoboCompatibilityServiceTest {
|
||||
|
||||
@Mock
|
||||
private AppSettingService appSettingService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboCompatibilityService koboCompatibilityService;
|
||||
|
||||
private AppSettings appSettings;
|
||||
private KoboSettings koboSettings;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
koboSettings = KoboSettings.builder()
|
||||
.convertToKepub(false)
|
||||
.conversionLimitInMb(100)
|
||||
.convertCbxToEpub(false)
|
||||
.conversionLimitInMbForCbx(50)
|
||||
.build();
|
||||
|
||||
appSettings = new AppSettings();
|
||||
appSettings.setKoboSettings(koboSettings);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should always support EPUB files regardless of settings")
|
||||
void shouldAlwaysSupportEpubFiles() {
|
||||
BookEntity epubBook = createBookEntity(1L, BookFileType.EPUB, 1000L);
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(epubBook);
|
||||
|
||||
assertThat(isSupported).isTrue();
|
||||
verifyNoInteractions(appSettingService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should support CBX files when CBX conversion is enabled and within size limit")
|
||||
void shouldSupportCbxWhenConversionEnabledAndWithinSizeLimit() {
|
||||
BookEntity cbxBook = createBookEntity(1L, BookFileType.CBX, 1000L);
|
||||
koboSettings.setConvertCbxToEpub(true);
|
||||
koboSettings.setConversionLimitInMbForCbx(50);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(cbxBook);
|
||||
|
||||
assertThat(isSupported).isTrue();
|
||||
verify(appSettingService, atLeastOnce()).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not support CBX files when CBX conversion is disabled")
|
||||
void shouldNotSupportCbxWhenConversionDisabled() {
|
||||
BookEntity cbxBook = createBookEntity(1L, BookFileType.CBX, 1000L);
|
||||
koboSettings.setConvertCbxToEpub(false);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(cbxBook);
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not support CBX files when they exceed the size limit")
|
||||
void shouldNotSupportCbxWhenExceedsSizeLimit() {
|
||||
BookEntity largeCbxBook = createBookEntity(1L, BookFileType.CBX, 75_000L);
|
||||
koboSettings.setConvertCbxToEpub(true);
|
||||
koboSettings.setConversionLimitInMbForCbx(50);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(largeCbxBook);
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
verify(appSettingService, atLeastOnce()).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should support CBX files that exactly meet the size limit")
|
||||
void shouldSupportCbxAtExactSizeLimit() {
|
||||
BookEntity cbxBookAtLimit = createBookEntity(1L, BookFileType.CBX, 51_200L);
|
||||
koboSettings.setConvertCbxToEpub(true);
|
||||
koboSettings.setConversionLimitInMbForCbx(50);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(cbxBookAtLimit);
|
||||
|
||||
|
||||
assertThat(isSupported).isTrue();
|
||||
verify(appSettingService, atLeastOnce()).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not support CBX files when size limit check fails due to settings error")
|
||||
void shouldNotSupportCbxWhenSizeLimitCheckFails() {
|
||||
|
||||
BookEntity cbxBook = createBookEntity(1L, BookFileType.CBX, 1000L);
|
||||
koboSettings.setConvertCbxToEpub(true);
|
||||
// First call succeeds for conversion check, second call fails for size check
|
||||
when(appSettingService.getAppSettings())
|
||||
.thenReturn(appSettings)
|
||||
.thenThrow(new RuntimeException("Settings error"));
|
||||
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(cbxBook);
|
||||
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
verify(appSettingService, atLeastOnce()).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not support CBX files when Kobo settings are null")
|
||||
void shouldNotSupportCbxWhenSettingsAreNull() {
|
||||
|
||||
BookEntity cbxBook = createBookEntity(1L, BookFileType.CBX, 1000L);
|
||||
appSettings.setKoboSettings(null);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(cbxBook);
|
||||
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
verify(appSettingService, atLeastOnce()).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not support PDF files")
|
||||
void shouldNotSupportPdfFiles() {
|
||||
|
||||
BookEntity pdfBook = createBookEntity(1L, BookFileType.PDF, 1000L);
|
||||
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(pdfBook);
|
||||
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
verifyNoInteractions(appSettingService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle null book gracefully")
|
||||
void shouldHandleNullBookGracefully() {
|
||||
assertThatThrownBy(() -> koboCompatibilityService.isBookSupportedForKobo(null))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("Book cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle null book type gracefully")
|
||||
void shouldHandleNullBookTypeGracefully() {
|
||||
|
||||
BookEntity bookWithNullType = new BookEntity();
|
||||
bookWithNullType.setId(1L);
|
||||
bookWithNullType.setBookType(null);
|
||||
|
||||
|
||||
boolean isSupported = koboCompatibilityService.isBookSupportedForKobo(bookWithNullType);
|
||||
|
||||
|
||||
assertThat(isSupported).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return true when CBX conversion is enabled")
|
||||
void shouldReturnTrueWhenCbxConversionEnabled() {
|
||||
|
||||
koboSettings.setConvertCbxToEpub(true);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean isEnabled = koboCompatibilityService.isCbxConversionEnabled();
|
||||
|
||||
|
||||
assertThat(isEnabled).isTrue();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return false when CBX conversion is disabled")
|
||||
void shouldReturnFalseWhenCbxConversionDisabled() {
|
||||
|
||||
koboSettings.setConvertCbxToEpub(false);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean isEnabled = koboCompatibilityService.isCbxConversionEnabled();
|
||||
|
||||
|
||||
assertThat(isEnabled).isFalse();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle settings exception gracefully")
|
||||
void shouldHandleSettingsExceptionGracefully() {
|
||||
|
||||
when(appSettingService.getAppSettings()).thenThrow(new RuntimeException("Settings error"));
|
||||
|
||||
|
||||
boolean isEnabled = koboCompatibilityService.isCbxConversionEnabled();
|
||||
|
||||
|
||||
assertThat(isEnabled).isFalse();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should validate CBX file meets size limit")
|
||||
void shouldValidateCbxFileMeetsSizeLimit() {
|
||||
|
||||
BookEntity smallCbxBook = createBookEntity(1L, BookFileType.CBX, 1000L);
|
||||
koboSettings.setConversionLimitInMbForCbx(50);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean meetsLimit = koboCompatibilityService.meetsCbxConversionSizeLimit(smallCbxBook);
|
||||
|
||||
|
||||
assertThat(meetsLimit).isTrue();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should validate CBX file exceeds size limit")
|
||||
void shouldValidateCbxFileExceedsSizeLimit() {
|
||||
|
||||
BookEntity largeCbxBook = createBookEntity(1L, BookFileType.CBX, 100_000L);
|
||||
koboSettings.setConversionLimitInMbForCbx(50);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean meetsLimit = koboCompatibilityService.meetsCbxConversionSizeLimit(largeCbxBook);
|
||||
|
||||
|
||||
assertThat(meetsLimit).isFalse();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return false for size limit check on non-CBX book")
|
||||
void shouldReturnFalseForSizeLimitCheckOnNonCbxBook() {
|
||||
|
||||
BookEntity epubBook = createBookEntity(1L, BookFileType.EPUB, 1000L);
|
||||
|
||||
|
||||
boolean meetsLimit = koboCompatibilityService.meetsCbxConversionSizeLimit(epubBook);
|
||||
|
||||
|
||||
assertThat(meetsLimit).isFalse();
|
||||
verifyNoInteractions(appSettingService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle null file size gracefully")
|
||||
void shouldHandleNullFileSizeGracefully() {
|
||||
|
||||
BookEntity cbxBook = createBookEntity(1L, BookFileType.CBX, null);
|
||||
when(appSettingService.getAppSettings()).thenReturn(appSettings);
|
||||
|
||||
|
||||
boolean meetsLimit = koboCompatibilityService.meetsCbxConversionSizeLimit(cbxBook);
|
||||
|
||||
|
||||
assertThat(meetsLimit).isTrue();
|
||||
verify(appSettingService).getAppSettings();
|
||||
}
|
||||
|
||||
private BookEntity createBookEntity(Long id, BookFileType bookType, Long fileSizeKb) {
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(id);
|
||||
book.setBookType(bookType);
|
||||
book.setFileSizeKb(fileSizeKb);
|
||||
return book;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user