chore: drop chapter cache service (#2773)
This commit is contained in:
@@ -55,16 +55,6 @@ public class CbxReaderService {
|
|||||||
.build();
|
.build();
|
||||||
|
|
||||||
private final ArchiveService archiveService;
|
private final ArchiveService archiveService;
|
||||||
private final ChapterCacheService chapterCacheService;
|
|
||||||
|
|
||||||
/** Single-threaded executor for background disk-cache population. */
|
|
||||||
private final ExecutorService cacheExecutor = Executors.newSingleThreadExecutor(r -> {
|
|
||||||
Thread t = new Thread(r, "cbx-cache-init");
|
|
||||||
t.setDaemon(true);
|
|
||||||
return t;
|
|
||||||
});
|
|
||||||
/** Tracks books whose async cache init has already been submitted. */
|
|
||||||
private final Set<String> cacheInitSubmitted = ConcurrentHashMap.newKeySet();
|
|
||||||
|
|
||||||
private record CachedArchiveMetadata(List<String> imageEntries, List<CbxPageDimension> pageDimensions, long lastModified) {
|
private record CachedArchiveMetadata(List<String> imageEntries, List<CbxPageDimension> pageDimensions, long lastModified) {
|
||||||
CachedArchiveMetadata {
|
CachedArchiveMetadata {
|
||||||
@@ -73,65 +63,6 @@ public class CbxReaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void initCache(Long bookId, String bookType) throws IOException {
|
|
||||||
Path cbxPath = getBookPath(bookId, bookType);
|
|
||||||
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
|
||||||
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
|
|
||||||
chapterCacheService.prepareCbxCache(cacheKey, cbxPath, metadata.imageEntries());
|
|
||||||
|
|
||||||
if (metadata.pageDimensions() == null) {
|
|
||||||
List<CbxPageDimension> dimensions = computeDimensionsFromDiskCache(cacheKey, metadata.imageEntries().size());
|
|
||||||
CachedArchiveMetadata updated = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
|
|
||||||
archiveCache.put(cbxPath.toString(), updated);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Submits a background task to extract all pages to the disk cache.
|
|
||||||
* This runs once per book/type combination and makes subsequent
|
|
||||||
* {@link #streamPageImage} calls hit Tier 2 (disk) instead of Tier 3
|
|
||||||
* (native extraction per request).
|
|
||||||
*/
|
|
||||||
private void submitBackgroundCacheInit(Long bookId, String bookType, long lastModified) {
|
|
||||||
String key = bookId + ":" + bookType + ":" + lastModified;
|
|
||||||
if (cacheInitSubmitted.add(key)) {
|
|
||||||
cacheExecutor.submit(() -> {
|
|
||||||
try {
|
|
||||||
initCache(bookId, bookType);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Background cache init failed for book {}: {}", bookId, e.getMessage());
|
|
||||||
cacheInitSubmitted.remove(key);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<CbxPageDimension> computeDimensionsFromDiskCache(String cacheKey, int pageCount) {
|
|
||||||
List<CbxPageDimension> dimensions = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= pageCount; i++) {
|
|
||||||
Path cachedPage = chapterCacheService.getCachedPage(cacheKey, i);
|
|
||||||
try (ImageInputStream iis = ImageIO.createImageInputStream(cachedPage.toFile())) {
|
|
||||||
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
|
|
||||||
if (readers.hasNext()) {
|
|
||||||
ImageReader reader = readers.next();
|
|
||||||
try {
|
|
||||||
reader.setInput(iis, true, true);
|
|
||||||
int width = reader.getWidth(0);
|
|
||||||
int height = reader.getHeight(0);
|
|
||||||
dimensions.add(CbxPageDimension.builder().pageNumber(i).width(width).height(height).wide(width > height).build());
|
|
||||||
continue;
|
|
||||||
} finally {
|
|
||||||
reader.dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Failed to read dimensions for cached page {}: {}", i, e.getMessage());
|
|
||||||
}
|
|
||||||
dimensions.add(CbxPageDimension.builder().pageNumber(i).width(0).height(0).wide(false).build());
|
|
||||||
}
|
|
||||||
return dimensions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Integer> getAvailablePages(Long bookId) {
|
public List<Integer> getAvailablePages(Long bookId) {
|
||||||
return getAvailablePages(bookId, null);
|
return getAvailablePages(bookId, null);
|
||||||
}
|
}
|
||||||
@@ -141,8 +72,6 @@ public class CbxReaderService {
|
|||||||
try {
|
try {
|
||||||
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
||||||
List<String> imageEntries = metadata.imageEntries();
|
List<String> imageEntries = metadata.imageEntries();
|
||||||
// Trigger background disk-cache population for faster subsequent page serving
|
|
||||||
submitBackgroundCacheInit(bookId, bookType, metadata.lastModified());
|
|
||||||
return IntStream.rangeClosed(1, imageEntries.size())
|
return IntStream.rangeClosed(1, imageEntries.size())
|
||||||
.boxed()
|
.boxed()
|
||||||
.toList();
|
.toList();
|
||||||
@@ -184,16 +113,6 @@ public class CbxReaderService {
|
|||||||
return metadata.pageDimensions();
|
return metadata.pageDimensions();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try disk cache first (fast, memory-safe)
|
|
||||||
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
|
|
||||||
if (chapterCacheService.hasPage(cacheKey, 1) && chapterCacheService.hasPage(cacheKey, metadata.imageEntries().size())) {
|
|
||||||
List<CbxPageDimension> dimensions = computeDimensionsFromDiskCache(cacheKey, metadata.imageEntries().size());
|
|
||||||
CachedArchiveMetadata updated = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
|
|
||||||
archiveCache.put(cbxPath.toString(), updated);
|
|
||||||
return dimensions;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Streaming: read only image headers, not full images
|
|
||||||
List<CbxPageDimension> dimensions = readDimensionsStreaming(cbxPath, metadata.imageEntries());
|
List<CbxPageDimension> dimensions = readDimensionsStreaming(cbxPath, metadata.imageEntries());
|
||||||
|
|
||||||
CachedArchiveMetadata updatedMetadata = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
|
CachedArchiveMetadata updatedMetadata = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
|
||||||
@@ -259,10 +178,6 @@ public class CbxReaderService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isZipPath(Path path) {
|
|
||||||
return ArchiveUtils.detectArchiveType(path) == ArchiveUtils.ArchiveType.ZIP;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String extractDisplayName(String entryPath) {
|
private String extractDisplayName(String entryPath) {
|
||||||
String fileName = baseName(entryPath);
|
String fileName = baseName(entryPath);
|
||||||
int lastDotIndex = fileName.lastIndexOf('.');
|
int lastDotIndex = fileName.lastIndexOf('.');
|
||||||
@@ -281,29 +196,10 @@ public class CbxReaderService {
|
|||||||
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
||||||
validatePageRequest(bookId, page, metadata.imageEntries());
|
validatePageRequest(bookId, page, metadata.imageEntries());
|
||||||
|
|
||||||
// Check L3 Disk Cache (extracted files)
|
|
||||||
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified());
|
|
||||||
if (chapterCacheService.hasPage(cacheKey, page)) {
|
|
||||||
Path cached = chapterCacheService.getCachedPage(cacheKey, page);
|
|
||||||
Files.copy(cached, outputStream);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to full extraction/stream (slowest)
|
|
||||||
String entryName = metadata.imageEntries().get(page - 1);
|
String entryName = metadata.imageEntries().get(page - 1);
|
||||||
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
|
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getCacheKey(Long bookId, String bookType, long lastModified) {
|
|
||||||
if (bookType != null) {
|
|
||||||
// Ensure we use the safe enum name to prevent path traversal
|
|
||||||
BookFileType type = BookFileType.fromName(bookType)
|
|
||||||
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
|
|
||||||
return bookId + "_" + type.name() + "_" + lastModified;
|
|
||||||
}
|
|
||||||
return bookId + "_" + lastModified;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path getBookPath(Long bookId, String bookType) {
|
private Path getBookPath(Long bookId, String bookType) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
if (bookType != null) {
|
if (bookType != null) {
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
package org.booklore.service.reader;
|
|
||||||
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
|
||||||
import org.booklore.config.AppProperties;
|
|
||||||
import org.booklore.exception.ApiError;
|
|
||||||
import org.booklore.service.ArchiveService;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.OutputStream;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Service for managing the on-disk extraction cache for reader chapters.
|
|
||||||
*/
|
|
||||||
@Slf4j
|
|
||||||
@Service
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class ChapterCacheService {
|
|
||||||
|
|
||||||
private static final long MTIME_TOLERANCE_MS = 2000;
|
|
||||||
|
|
||||||
private final AppProperties appProperties;
|
|
||||||
private final ArchiveService archiveService;
|
|
||||||
private final ConcurrentHashMap<String, ReentrantLock> cacheLocks = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ensures all pages of a CBX archive are extracted to the disk cache.
|
|
||||||
*/
|
|
||||||
public void prepareCbxCache(String cacheKey, Path cbxPath, List<String> entries) throws IOException {
|
|
||||||
ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, _ -> new ReentrantLock());
|
|
||||||
lock.lock();
|
|
||||||
try {
|
|
||||||
Path cacheDir = getCacheDir(cacheKey);
|
|
||||||
if (!Files.exists(cacheDir)) {
|
|
||||||
Files.createDirectories(cacheDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only extract if the cache is empty or stale
|
|
||||||
if (isCacheStale(cacheDir, cbxPath, entries.size())) {
|
|
||||||
log.info("Populating disk cache for {}: {} pages", cacheKey, entries.size());
|
|
||||||
|
|
||||||
for (int i = 0; i < entries.size(); i++) {
|
|
||||||
Path target = cacheDir.resolve("page_" + (i + 1) + ".jpg");
|
|
||||||
if (!Files.exists(target) || Files.size(target) == 0) {
|
|
||||||
String entryName = entries.get(i);
|
|
||||||
writeAtomically(target, out ->
|
|
||||||
archiveService.transferEntryTo(cbxPath, entryName, out));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark cache as fresh by setting its mtime to match the archive
|
|
||||||
Files.setLastModifiedTime(cacheDir, Files.getLastModifiedTime(cbxPath));
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
lock.unlock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public Path getCachedPage(String cacheKey, int pageNumber) {
|
|
||||||
return getCacheDir(cacheKey).resolve("page_" + pageNumber + ".jpg");
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean hasPage(String cacheKey, int pageNumber) {
|
|
||||||
Path pagePath = getCachedPage(cacheKey, pageNumber);
|
|
||||||
try {
|
|
||||||
return Files.exists(pagePath) && Files.size(pagePath) > 0;
|
|
||||||
} catch (IOException e) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Writes data to a temp file in the same directory, then atomically moves
|
|
||||||
* it to the target path. If the write fails, the partial temp file is
|
|
||||||
* cleaned up and the target is never touched.
|
|
||||||
*/
|
|
||||||
void writeAtomically(Path target, IOConsumer<OutputStream> writer) throws IOException {
|
|
||||||
Path tmp = Files.createTempFile(target.getParent(), target.getFileName().toString() + ".", ".tmp");
|
|
||||||
try {
|
|
||||||
try (OutputStream out = Files.newOutputStream(tmp)) {
|
|
||||||
writer.accept(out);
|
|
||||||
}
|
|
||||||
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
|
||||||
} finally {
|
|
||||||
Files.deleteIfExists(tmp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@FunctionalInterface
|
|
||||||
interface IOConsumer<T> {
|
|
||||||
void accept(T t) throws IOException;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Path getCacheDir(String cacheKey) {
|
|
||||||
if (cacheKey == null || cacheKey.contains("..") || cacheKey.contains("/") || cacheKey.contains("\\")) {
|
|
||||||
throw ApiError.INVALID_INPUT.createException("Invalid cache key: " + cacheKey);
|
|
||||||
}
|
|
||||||
return Paths.get(appProperties.getPathConfig(), "cache", "chapters", cacheKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isCacheStale(Path cacheDir, Path sourcePath, int expectedPages) throws IOException {
|
|
||||||
if (!Files.exists(cacheDir)) return true;
|
|
||||||
|
|
||||||
for (int i = 1; i <= expectedPages; i++) {
|
|
||||||
Path page = cacheDir.resolve("page_" + i + ".jpg");
|
|
||||||
if (!Files.exists(page) || Files.size(page) == 0) return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
long cacheMtime = Files.getLastModifiedTime(cacheDir).toMillis();
|
|
||||||
long sourceMtime = Files.getLastModifiedTime(sourcePath).toMillis();
|
|
||||||
return Math.abs(cacheMtime - sourceMtime) > MTIME_TOLERANCE_MS;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -19,7 +19,6 @@ import java.io.IOException;
|
|||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
@@ -39,7 +38,6 @@ public class PdfReaderService {
|
|||||||
private static final long MTIME_TOLERANCE_MS = 2000;
|
private static final long MTIME_TOLERANCE_MS = 2000;
|
||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final ChapterCacheService chapterCacheService;
|
|
||||||
private final Cache<String, CachedPdfMetadata> metadataCache = Caffeine.newBuilder()
|
private final Cache<String, CachedPdfMetadata> metadataCache = Caffeine.newBuilder()
|
||||||
.maximumSize(MAX_CACHE_ENTRIES)
|
.maximumSize(MAX_CACHE_ENTRIES)
|
||||||
.expireAfterAccess(Duration.ofMinutes(30))
|
.expireAfterAccess(Duration.ofMinutes(30))
|
||||||
@@ -47,41 +45,6 @@ public class PdfReaderService {
|
|||||||
|
|
||||||
private record CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {}
|
private record CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {}
|
||||||
|
|
||||||
public void initCache(Long bookId, String bookType) throws IOException {
|
|
||||||
Path pdfPath = getBookPath(bookId, bookType);
|
|
||||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
|
||||||
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified);
|
|
||||||
|
|
||||||
Path cacheDir = chapterCacheService.getCachedPage(cacheKey, 1).getParent();
|
|
||||||
if (!Files.exists(cacheDir)) {
|
|
||||||
Files.createDirectories(cacheDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
long cacheMtime = Files.getLastModifiedTime(cacheDir).toMillis();
|
|
||||||
boolean cacheEmpty;
|
|
||||||
try (var stream = Files.list(cacheDir)) {
|
|
||||||
cacheEmpty = stream.findAny().isEmpty();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cacheEmpty && Math.abs(cacheMtime - metadata.lastModified) <= MTIME_TOLERANCE_MS) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("Populating PDF disk cache for {}: {} pages", cacheKey, metadata.pageCount);
|
|
||||||
// PdfDocument is not thread-safe — render pages serially then cache
|
|
||||||
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
|
|
||||||
for (int i = 1; i <= metadata.pageCount; i++) {
|
|
||||||
Path target = chapterCacheService.getCachedPage(cacheKey, i);
|
|
||||||
if (!Files.exists(target) || Files.size(target) == 0) {
|
|
||||||
byte[] jpeg = doc.renderPageToBytes(i - 1, (int) DEFAULT_DPI, "jpeg");
|
|
||||||
writeAtomically(target, jpeg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Files.setLastModifiedTime(cacheDir, Files.getLastModifiedTime(pdfPath));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void getAvailablePages(Long bookId) {
|
public void getAvailablePages(Long bookId) {
|
||||||
getAvailablePages(bookId, null);
|
getAvailablePages(bookId, null);
|
||||||
}
|
}
|
||||||
@@ -120,20 +83,10 @@ public class PdfReaderService {
|
|||||||
public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException {
|
public void streamPageImage(Long bookId, String bookType, int page, OutputStream outputStream) throws IOException {
|
||||||
Path pdfPath = getBookPath(bookId, bookType);
|
Path pdfPath = getBookPath(bookId, bookType);
|
||||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||||
String cacheKey = getCacheKey(bookId, bookType, metadata.lastModified);
|
|
||||||
|
|
||||||
if (chapterCacheService.hasPage(cacheKey, page)) {
|
|
||||||
Files.copy(chapterCacheService.getCachedPage(cacheKey, page), outputStream);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
validatePageRequest(bookId, page, metadata.pageCount);
|
validatePageRequest(bookId, page, metadata.pageCount);
|
||||||
|
|
||||||
// Render, cache atomically, then stream
|
|
||||||
Path cached = chapterCacheService.getCachedPage(cacheKey, page);
|
|
||||||
Files.createDirectories(cached.getParent());
|
|
||||||
byte[] jpeg = renderPageToBytes(pdfPath, page);
|
byte[] jpeg = renderPageToBytes(pdfPath, page);
|
||||||
writeAtomically(cached, jpeg);
|
|
||||||
outputStream.write(jpeg);
|
outputStream.write(jpeg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,18 +204,4 @@ public class PdfReaderService {
|
|||||||
throw new IOException(e);
|
throw new IOException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Writes bytes to a temp file then atomically moves to the target path.
|
|
||||||
* If the write fails the partial temp file is cleaned up.
|
|
||||||
*/
|
|
||||||
private void writeAtomically(Path target, byte[] data) throws IOException {
|
|
||||||
Path tmp = Files.createTempFile(target.getParent(), target.getFileName().toString() + ".", ".tmp");
|
|
||||||
try {
|
|
||||||
Files.write(tmp, data);
|
|
||||||
Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
|
||||||
} finally {
|
|
||||||
Files.deleteIfExists(tmp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,8 @@ import org.booklore.service.metadata.writer.CbxMetadataWriter;
|
|||||||
import org.booklore.service.reader.CbxReaderService;
|
import org.booklore.service.reader.CbxReaderService;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.appsettings.AppSettingService;
|
import org.booklore.service.appsettings.AppSettingService;
|
||||||
import org.booklore.service.reader.ChapterCacheService;
|
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.condition.EnabledIf;
|
|
||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
@@ -66,13 +64,12 @@ class Rar5IntegrationTest {
|
|||||||
book.setId(99L);
|
book.setId(99L);
|
||||||
BookRepository mockRepo = Mockito.mock(BookRepository.class);
|
BookRepository mockRepo = Mockito.mock(BookRepository.class);
|
||||||
Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(Optional.of(book));
|
Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(Optional.of(book));
|
||||||
ChapterCacheService mockCache = Mockito.mock(ChapterCacheService.class);
|
|
||||||
|
|
||||||
try (var fileUtilsStatic = Mockito.mockStatic(FileUtils.class)) {
|
try (var fileUtilsStatic = Mockito.mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(book))
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(book))
|
||||||
.thenReturn(cbrCopy);
|
.thenReturn(cbrCopy);
|
||||||
|
|
||||||
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService(), mockCache);
|
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService());
|
||||||
List<Integer> pages = readerService.getAvailablePages(99L);
|
List<Integer> pages = readerService.getAvailablePages(99L);
|
||||||
|
|
||||||
assertThat(pages).hasSize(3);
|
assertThat(pages).hasSize(3);
|
||||||
@@ -89,7 +86,6 @@ class Rar5IntegrationTest {
|
|||||||
book.setId(99L);
|
book.setId(99L);
|
||||||
BookRepository mockRepo = Mockito.mock(BookRepository.class);
|
BookRepository mockRepo = Mockito.mock(BookRepository.class);
|
||||||
Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(Optional.of(book));
|
Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(Optional.of(book));
|
||||||
ChapterCacheService mockCache = Mockito.mock(ChapterCacheService.class);
|
|
||||||
|
|
||||||
try (
|
try (
|
||||||
var fileUtilsStatic = Mockito.mockStatic(FileUtils.class)
|
var fileUtilsStatic = Mockito.mockStatic(FileUtils.class)
|
||||||
@@ -97,7 +93,7 @@ class Rar5IntegrationTest {
|
|||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(book))
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(book))
|
||||||
.thenReturn(cbrCopy);
|
.thenReturn(cbrCopy);
|
||||||
|
|
||||||
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService(), mockCache);
|
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService());
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
readerService.streamPageImage(99L, 1, out);
|
readerService.streamPageImage(99L, 1, out);
|
||||||
|
|
||||||
|
|||||||
@@ -32,15 +32,9 @@ class CbxReaderServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
ArchiveService archiveService;
|
ArchiveService archiveService;
|
||||||
|
|
||||||
@Mock
|
|
||||||
ChapterCacheService chapterCacheService;
|
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
CbxReaderService cbxReaderService;
|
CbxReaderService cbxReaderService;
|
||||||
|
|
||||||
@Captor
|
|
||||||
ArgumentCaptor<Long> longCaptor;
|
|
||||||
|
|
||||||
BookEntity bookEntity;
|
BookEntity bookEntity;
|
||||||
Path cbzPath;
|
Path cbzPath;
|
||||||
|
|
||||||
@@ -69,8 +63,6 @@ class CbxReaderServiceTest {
|
|||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
||||||
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
||||||
|
|
||||||
cbxReaderService.initCache(1L, null);
|
|
||||||
|
|
||||||
List<Integer> pages = cbxReaderService.getAvailablePages(1L);
|
List<Integer> pages = cbxReaderService.getAvailablePages(1L);
|
||||||
assertEquals(List.of(1), pages);
|
assertEquals(List.of(1), pages);
|
||||||
}
|
}
|
||||||
@@ -90,8 +82,6 @@ class CbxReaderServiceTest {
|
|||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
||||||
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
||||||
|
|
||||||
cbxReaderService.initCache(1L, null);
|
|
||||||
|
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
cbxReaderService.streamPageImage(1L, 1, out);
|
cbxReaderService.streamPageImage(1L, 1, out);
|
||||||
assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray());
|
assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray());
|
||||||
@@ -109,8 +99,6 @@ class CbxReaderServiceTest {
|
|||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(cbzPath);
|
||||||
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
filesStatic.when(() -> Files.getLastModifiedTime(cbzPath)).thenReturn(FileTime.from(Instant.now()));
|
||||||
|
|
||||||
cbxReaderService.initCache(1L, null);
|
|
||||||
|
|
||||||
assertThrows(
|
assertThrows(
|
||||||
FileNotFoundException.class,
|
FileNotFoundException.class,
|
||||||
() -> cbxReaderService.streamPageImage(1L, 2, new ByteArrayOutputStream())
|
() -> cbxReaderService.streamPageImage(1L, 2, new ByteArrayOutputStream())
|
||||||
@@ -144,13 +132,4 @@ class CbxReaderServiceTest {
|
|||||||
);
|
);
|
||||||
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void testInitCache_InvalidBookType_Throws() {
|
|
||||||
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
|
||||||
APIException ex = assertThrows(APIException.class, () ->
|
|
||||||
cbxReaderService.initCache(1L, "../traversal")
|
|
||||||
);
|
|
||||||
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
package org.booklore.service.reader;
|
|
||||||
|
|
||||||
import org.booklore.config.AppProperties;
|
|
||||||
import org.booklore.service.ArchiveService;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.mockito.Mock;
|
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
|
||||||
|
|
||||||
import org.booklore.exception.APIException;
|
|
||||||
|
|
||||||
import java.nio.file.Path;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
|
||||||
class ChapterCacheServiceTest {
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private AppProperties appProperties;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private ArchiveService archiveService;
|
|
||||||
|
|
||||||
private ChapterCacheService chapterCacheService;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
chapterCacheService = new ChapterCacheService(appProperties, archiveService);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getCachedPage_withTraversal_throwsException() {
|
|
||||||
assertThrows(APIException.class, () ->
|
|
||||||
chapterCacheService.getCachedPage("../outside", 1)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getCachedPage_withPathSeparator_throwsException() {
|
|
||||||
assertThrows(APIException.class, () ->
|
|
||||||
chapterCacheService.getCachedPage("sub/folder", 1)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void hasPage_withTraversal_throwsException() {
|
|
||||||
assertThrows(APIException.class, () ->
|
|
||||||
chapterCacheService.hasPage("../outside", 1)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -31,20 +31,15 @@ class PdfReaderServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
private BookRepository bookRepository;
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
@Mock
|
|
||||||
private ChapterCacheService chapterCacheService;
|
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
private PdfReaderService pdfReaderService;
|
private PdfReaderService pdfReaderService;
|
||||||
|
|
||||||
private BookEntity bookEntity;
|
private BookEntity bookEntity;
|
||||||
private Path pdfPath;
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setup() {
|
void setup() {
|
||||||
bookEntity = new BookEntity();
|
bookEntity = new BookEntity();
|
||||||
bookEntity.setId(1L);
|
bookEntity.setId(1L);
|
||||||
pdfPath = Path.of("/tmp/test.pdf");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -55,13 +50,4 @@ class PdfReaderServiceTest {
|
|||||||
);
|
);
|
||||||
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void testInitCache_InvalidBookType_Throws() {
|
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
|
||||||
APIException ex = assertThrows(APIException.class, () ->
|
|
||||||
pdfReaderService.initCache(1L, "../traversal")
|
|
||||||
);
|
|
||||||
assertTrue(ex.getMessage().contains("Invalid book type"), "Expected INVALID_INPUT, got: " + ex.getMessage());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user