fix(readers): add chapter caching and improve page rendering (#514)
* fix(readers): add chapter caching and improve page rendering * fix(readers): simplify caching logic and remove unused methods in CbxReaderService and PdfReaderService # Conflicts: # booklore-api/src/main/java/org/booklore/controller/EpubReaderController.java
This commit is contained in:
@@ -42,22 +42,21 @@ public class EpubReaderController {
|
|||||||
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
|
@Operation(summary = "Get file from EPUB", description = "Retrieve a specific file from within the EPUB archive (HTML, CSS, images, fonts, etc.).")
|
||||||
@ApiResponse(responseCode = "200", description = "File content returned successfully")
|
@ApiResponse(responseCode = "200", description = "File content returned successfully")
|
||||||
@CheckBookAccess(bookIdParam = "bookId")
|
@CheckBookAccess(bookIdParam = "bookId")
|
||||||
@GetMapping("/{bookId}/file/**")
|
@GetMapping("/{bookId}/file/{*filePath}")
|
||||||
public void getFile(
|
public void getFile(
|
||||||
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
@Parameter(description = "ID of the book") @PathVariable Long bookId,
|
||||||
|
@PathVariable String filePath,
|
||||||
@Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType,
|
@Parameter(description = "Optional book type for alternative format (e.g., EPUB)") @RequestParam(required = false) String bookType,
|
||||||
HttpServletRequest request,
|
HttpServletRequest request,
|
||||||
HttpServletResponse response) throws IOException {
|
HttpServletResponse response) throws IOException {
|
||||||
|
|
||||||
String fullPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
|
String cleanPath = filePath.startsWith("/") ? filePath.substring(1) : filePath;
|
||||||
String prefix = "/api/v1/epub/" + bookId + "/file/";
|
cleanPath = URLDecoder.decode(cleanPath, StandardCharsets.UTF_8);
|
||||||
String filePath = fullPath.substring(prefix.length());
|
|
||||||
filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8);
|
|
||||||
|
|
||||||
String contentType = epubReaderService.getContentType(bookId, bookType, filePath);
|
String contentType = epubReaderService.getContentType(bookId, bookType, cleanPath);
|
||||||
response.setContentType(contentType);
|
response.setContentType(contentType);
|
||||||
|
|
||||||
long fileSize = epubReaderService.getFileSize(bookId, bookType, filePath);
|
long fileSize = epubReaderService.getFileSize(bookId, bookType, cleanPath);
|
||||||
if (fileSize > 0) {
|
if (fileSize > 0) {
|
||||||
response.setContentLengthLong(fileSize);
|
response.setContentLengthLong(fileSize);
|
||||||
}
|
}
|
||||||
@@ -71,10 +70,10 @@ public class EpubReaderController {
|
|||||||
// Defense in depth for untrusted EPUB resources. See Foliate's security guidance:
|
// Defense in depth for untrusted EPUB resources. See Foliate's security guidance:
|
||||||
// https://github.com/johnfactotum/foliate-js#security
|
// https://github.com/johnfactotum/foliate-js#security
|
||||||
response.setHeader("Content-Security-Policy", "script-src 'none'");
|
response.setHeader("Content-Security-Policy", "script-src 'none'");
|
||||||
response.setHeader("Cache-Control", "public, max-age=3600");
|
response.setHeader("Cache-Control", "private, max-age=3600");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
epubReaderService.streamFile(bookId, bookType, filePath, response.getOutputStream());
|
epubReaderService.streamFile(bookId, bookType, cleanPath, response.getOutputStream());
|
||||||
} catch (FileNotFoundException e) {
|
} catch (FileNotFoundException e) {
|
||||||
response.reset();
|
response.reset();
|
||||||
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
response.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||||
|
|||||||
@@ -27,6 +27,13 @@ public enum BookFileType {
|
|||||||
return extensions.contains(extension.toLowerCase());
|
return extensions.contains(extension.toLowerCase());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Optional<BookFileType> fromName(String name) {
|
||||||
|
if (name == null) return Optional.empty();
|
||||||
|
return Arrays.stream(values())
|
||||||
|
.filter(type -> type.name().equalsIgnoreCase(name))
|
||||||
|
.findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
public static Optional<BookFileType> fromExtension(String extension) {
|
public static Optional<BookFileType> fromExtension(String extension) {
|
||||||
String ext = extension.toLowerCase();
|
String ext = extension.toLowerCase();
|
||||||
return Arrays.stream(values())
|
return Arrays.stream(values())
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
|
|||||||
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
Optional<BookEntity> findByIdWithBookFiles(@Param("id") Long id);
|
Optional<BookEntity> findByIdWithBookFiles(@Param("id") Long id);
|
||||||
|
|
||||||
|
@EntityGraph(attributePaths = { "metadata", "bookFiles", "libraryPath", "library" })
|
||||||
|
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
|
Optional<BookEntity> findByIdForStreaming(@Param("id") Long id);
|
||||||
|
|
||||||
@EntityGraph(attributePaths = { "metadata", "metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags", "metadata.comicMetadata", "library" })
|
@EntityGraph(attributePaths = { "metadata", "metadata.authors", "metadata.categories", "metadata.moods", "metadata.tags", "metadata.comicMetadata", "library" })
|
||||||
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
|
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
|
||||||
Optional<BookEntity> findByIdWithMetadata(@Param("id") Long id);
|
Optional<BookEntity> findByIdWithMetadata(@Param("id") Long id);
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import com.github.gotson.nightcompress.Archive;
|
|||||||
import com.github.gotson.nightcompress.ArchiveEntry;
|
import com.github.gotson.nightcompress.ArchiveEntry;
|
||||||
import com.github.gotson.nightcompress.LibArchiveException;
|
import com.github.gotson.nightcompress.LibArchiveException;
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -15,22 +14,48 @@ 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.util.List;
|
import java.util.List;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
public class ArchiveService {
|
public class ArchiveService {
|
||||||
@PostConstruct
|
private static final int LOCK_STRIPE_COUNT = 256;
|
||||||
public void checkArchiveAvailable() {
|
private final ReentrantLock[] lockStripes = IntStream.range(0, LOCK_STRIPE_COUNT)
|
||||||
|
.mapToObj(ignored -> new ReentrantLock())
|
||||||
|
.toArray(ReentrantLock[]::new);
|
||||||
|
private volatile boolean available = safeCheckAvailable();
|
||||||
|
|
||||||
|
private static boolean safeCheckAvailable() {
|
||||||
try {
|
try {
|
||||||
// We want to check the version early because it allows for
|
return Archive.isAvailable();
|
||||||
// NightCompress to preload the libarchive library in a safe
|
|
||||||
// thread. Loading native libraries is not a thread safe operation.
|
|
||||||
if (!Archive.isAvailable()) {
|
|
||||||
log.warn("LibArchive is not available");
|
|
||||||
}
|
|
||||||
} catch (Throwable e) {
|
} catch (Throwable e) {
|
||||||
log.error("LibArchive could not be loaded", e);
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private ReentrantLock getFileLock(Path path) {
|
||||||
|
int hash = path.toAbsolutePath().normalize().toString().hashCode();
|
||||||
|
return lockStripes[Math.floorMod(hash, LOCK_STRIPE_COUNT)];
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void initLibArchive() {
|
||||||
|
// Log the availability result that was already determined at construction
|
||||||
|
// time. The @PostConstruct runs on the Spring startup thread which also
|
||||||
|
// ensures the native library is fully loaded before any concurrent HTTP
|
||||||
|
// request thread can call into it.
|
||||||
|
if (available) {
|
||||||
|
log.info("LibArchive loaded successfully");
|
||||||
|
} else {
|
||||||
|
log.error("LibArchive is not available – CBX/archive features will not work");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireAvailable() throws IOException {
|
||||||
|
if (!available) {
|
||||||
|
throw new IOException("LibArchive is not available – cannot process archive");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,23 +63,10 @@ public class ArchiveService {
|
|||||||
return Archive.isAvailable();
|
return Archive.isAvailable();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class Entry {
|
public record Entry(String name, long size) {}
|
||||||
private Entry() {}
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
private long size;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Entry getEntryFromArchiveEntry(ArchiveEntry archiveEntry) {
|
private Entry getEntryFromArchiveEntry(ArchiveEntry archiveEntry) {
|
||||||
Entry entry = new Entry();
|
return new Entry(archiveEntry.getName(), archiveEntry.getSize());
|
||||||
|
|
||||||
entry.name = archiveEntry.getName();
|
|
||||||
entry.size = archiveEntry.getSize();
|
|
||||||
|
|
||||||
return entry;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Entry> getEntries(Path path) throws IOException {
|
public List<Entry> getEntries(Path path) throws IOException {
|
||||||
@@ -62,12 +74,16 @@ public class ArchiveService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Stream<Entry> streamEntries(Path path) throws IOException {
|
public Stream<Entry> streamEntries(Path path) throws IOException {
|
||||||
|
requireAvailable();
|
||||||
|
ReentrantLock lock = getFileLock(path);
|
||||||
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
return Archive.getEntries(path)
|
List<ArchiveEntry> entries = Archive.getEntries(path);
|
||||||
.stream()
|
return entries.stream().map(this::getEntryFromArchiveEntry);
|
||||||
.map(this::getEntryFromArchiveEntry);
|
|
||||||
} catch (LibArchiveException e) {
|
} catch (LibArchiveException e) {
|
||||||
throw new IOException("Failed to read archive", e);
|
throw new IOException("Failed to read archive", e);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,25 +92,34 @@ public class ArchiveService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Stream<String> streamEntryNames(Path path) throws IOException {
|
public Stream<String> streamEntryNames(Path path) throws IOException {
|
||||||
|
requireAvailable();
|
||||||
|
ReentrantLock lock = getFileLock(path);
|
||||||
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
return Archive.getEntries(path)
|
List<ArchiveEntry> entries = Archive.getEntries(path);
|
||||||
.stream()
|
return entries.stream().map(ArchiveEntry::getName);
|
||||||
.map(ArchiveEntry::getName);
|
|
||||||
} catch (LibArchiveException e) {
|
} catch (LibArchiveException e) {
|
||||||
throw new IOException("Failed to read archive", e);
|
throw new IOException("Failed to read archive", e);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public long transferEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
|
public long transferEntryTo(Path path, String entryName, OutputStream outputStream) throws IOException {
|
||||||
|
requireAvailable();
|
||||||
// We cannot directly use the NightCompress `InputStream` as it is limited
|
// We cannot directly use the NightCompress `InputStream` as it is limited
|
||||||
// in its implementation and will cause fatal errors. Instead, we can use
|
// in its implementation and will cause fatal errors. Instead, we can use
|
||||||
// the `transferTo` on an output stream to copy data around.
|
// the `transferTo` on an output stream to copy data around.
|
||||||
|
ReentrantLock lock = getFileLock(path);
|
||||||
|
lock.lock();
|
||||||
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
|
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
|
||||||
if (inputStream != null) {
|
if (inputStream != null) {
|
||||||
return inputStream.transferTo(outputStream);
|
return inputStream.transferTo(outputStream);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
|
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new IOException("Entry not found in archive");
|
throw new IOException("Entry not found in archive");
|
||||||
@@ -111,12 +136,17 @@ public class ArchiveService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException {
|
public long extractEntryToPath(Path path, String entryName, Path outputPath) throws IOException {
|
||||||
|
requireAvailable();
|
||||||
|
ReentrantLock lock = getFileLock(path);
|
||||||
|
lock.lock();
|
||||||
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
|
try (InputStream inputStream = Archive.getInputStream(path, entryName)) {
|
||||||
if (inputStream != null) {
|
if (inputStream != null) {
|
||||||
return Files.copy(inputStream, outputPath);
|
return Files.copy(inputStream, outputPath);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
|
throw new IOException("Failed to extract from archive: " + e.getMessage(), e);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new IOException("Entry not found in archive");
|
throw new IOException("Entry not found in archive");
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ public class AppSettingService {
|
|||||||
if (sessionDurationStr != null && !sessionDurationStr.isBlank()) {
|
if (sessionDurationStr != null && !sessionDurationStr.isBlank()) {
|
||||||
try {
|
try {
|
||||||
builder.oidcSessionDurationHours(Integer.parseInt(sessionDurationStr));
|
builder.oidcSessionDurationHours(Integer.parseInt(sessionDurationStr));
|
||||||
} catch (NumberFormatException _) {
|
} catch (NumberFormatException ignored) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -187,20 +187,20 @@ public class CbxConversionService {
|
|||||||
List<Path> imagePaths = new ArrayList<>();
|
List<Path> imagePaths = new ArrayList<>();
|
||||||
|
|
||||||
for (ArchiveService.Entry entry : archiveService.getEntries(cbxFile.toPath())) {
|
for (ArchiveService.Entry entry : archiveService.getEntries(cbxFile.toPath())) {
|
||||||
if (!isImageFile(entry.getName())) {
|
if (!isImageFile(entry.name())) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
validateImageSize(entry.getName(), entry.getSize());
|
validateImageSize(entry.name(), entry.size());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.getName()));
|
Path outputPath = extractedImagesDir.resolve(extractFileName(entry.name()));
|
||||||
|
|
||||||
archiveService.extractEntryToPath(cbxFile.toPath(), entry.getName(), outputPath);
|
archiveService.extractEntryToPath(cbxFile.toPath(), entry.name(), outputPath);
|
||||||
|
|
||||||
imagePaths.add(outputPath);
|
imagePaths.add(outputPath);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Error extracting image {}: {}", entry.getName(), e.getMessage());
|
log.warn("Error extracting image {}: {}", entry.name(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package org.booklore.service.reader;
|
package org.booklore.service.reader;
|
||||||
|
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
|
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||||
|
import com.github.benmanes.caffeine.cache.RemovalCause;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.Setter;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.booklore.exception.ApiError;
|
import org.booklore.exception.ApiError;
|
||||||
import org.booklore.model.dto.response.CbxPageDimension;
|
import org.booklore.model.dto.response.CbxPageDimension;
|
||||||
@@ -17,19 +21,18 @@ import javax.imageio.ImageIO;
|
|||||||
import javax.imageio.ImageReader;
|
import javax.imageio.ImageReader;
|
||||||
import javax.imageio.stream.ImageInputStream;
|
import javax.imageio.stream.ImageInputStream;
|
||||||
import java.io.ByteArrayInputStream;
|
import java.io.ByteArrayInputStream;
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.FileNotFoundException;
|
import java.io.FileNotFoundException;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
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.time.Duration;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
import java.util.regex.Matcher;
|
import java.util.regex.Matcher;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
import java.util.zip.ZipFile;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -43,22 +46,73 @@ public class CbxReaderService {
|
|||||||
private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+");
|
private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+");
|
||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final Map<String, CachedArchiveMetadata> archiveCache = new ConcurrentHashMap<>();
|
private final Cache<String, CachedArchiveMetadata> archiveCache = Caffeine.newBuilder()
|
||||||
|
.maximumSize(MAX_CACHE_ENTRIES)
|
||||||
|
.expireAfterAccess(Duration.ofMinutes(30))
|
||||||
|
.build();
|
||||||
|
|
||||||
private final ArchiveService archiveService;
|
private final ArchiveService archiveService;
|
||||||
|
private final ChapterCacheService chapterCacheService;
|
||||||
|
|
||||||
private static class CachedArchiveMetadata {
|
// L1 Cache: Open ZipFile handles for active reading sessions (TTL 30m)
|
||||||
final List<String> imageEntries;
|
@Setter
|
||||||
final long lastModified;
|
private Cache<String, ZipFile> zipHandleCache = Caffeine.newBuilder()
|
||||||
volatile long lastAccessed;
|
.maximumSize(MAX_CACHE_ENTRIES)
|
||||||
|
.expireAfterAccess(Duration.ofMinutes(30))
|
||||||
|
.removalListener((String _, ZipFile value, RemovalCause _) -> {
|
||||||
|
try {
|
||||||
|
value.close();
|
||||||
|
} catch (IOException _) {
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.build();
|
||||||
|
|
||||||
CachedArchiveMetadata(List<String> imageEntries, long lastModified) {
|
private record CachedArchiveMetadata(List<String> imageEntries, List<CbxPageDimension> pageDimensions, long lastModified) {
|
||||||
this.imageEntries = List.copyOf(imageEntries);
|
CachedArchiveMetadata {
|
||||||
this.lastModified = lastModified;
|
imageEntries = List.copyOf(imageEntries);
|
||||||
this.lastAccessed = System.currentTimeMillis();
|
pageDimensions = pageDimensions != null ? List.copyOf(pageDimensions) : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
@@ -69,7 +123,7 @@ public class CbxReaderService {
|
|||||||
List<String> imageEntries = getImageEntriesFromArchiveCached(cbxPath);
|
List<String> imageEntries = getImageEntriesFromArchiveCached(cbxPath);
|
||||||
return IntStream.rangeClosed(1, imageEntries.size())
|
return IntStream.rangeClosed(1, imageEntries.size())
|
||||||
.boxed()
|
.boxed()
|
||||||
.collect(Collectors.toList());
|
.toList();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed to read archive for book {}", bookId, e);
|
log.error("Failed to read archive for book {}", bookId, e);
|
||||||
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
|
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
|
||||||
@@ -100,21 +154,25 @@ public class CbxReaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<CbxPageDimension> getPageDimensions(Long bookId) {
|
|
||||||
return getPageDimensions(bookId, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<CbxPageDimension> getPageDimensions(Long bookId, String bookType) {
|
public List<CbxPageDimension> getPageDimensions(Long bookId, String bookType) {
|
||||||
Path cbxPath = getBookPath(bookId, bookType);
|
Path cbxPath = getBookPath(bookId, bookType);
|
||||||
try {
|
try {
|
||||||
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
||||||
List<String> imageEntries = metadata.imageEntries;
|
if (metadata.pageDimensions() != null) {
|
||||||
|
return metadata.pageDimensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> imageEntries = metadata.imageEntries();
|
||||||
List<CbxPageDimension> dimensions = new ArrayList<>();
|
List<CbxPageDimension> dimensions = new ArrayList<>();
|
||||||
for (int i = 0; i < imageEntries.size(); i++) {
|
for (int i = 0; i < imageEntries.size(); i++) {
|
||||||
String entryName = imageEntries.get(i);
|
String entryName = imageEntries.get(i);
|
||||||
CbxPageDimension dim = readEntryDimension(cbxPath, entryName, i + 1);
|
CbxPageDimension dim = readEntryDimension(cbxPath, entryName, i + 1);
|
||||||
dimensions.add(dim);
|
dimensions.add(dim);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
CachedArchiveMetadata updatedMetadata = new CachedArchiveMetadata(metadata.imageEntries(), dimensions, metadata.lastModified());
|
||||||
|
archiveCache.put(cbxPath.toString(), updatedMetadata);
|
||||||
|
|
||||||
return dimensions;
|
return dimensions;
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed to read page dimensions for book {}", bookId, e);
|
log.error("Failed to read page dimensions for book {}", bookId, e);
|
||||||
@@ -124,15 +182,13 @@ public class CbxReaderService {
|
|||||||
|
|
||||||
private CbxPageDimension readEntryDimension(Path cbxPath, String entryName, int pageNumber) {
|
private CbxPageDimension readEntryDimension(Path cbxPath, String entryName, int pageNumber) {
|
||||||
try {
|
try {
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
byte[] imageBytes = archiveService.getEntryBytes(cbxPath, entryName);
|
||||||
archiveService.transferEntryTo(cbxPath, entryName, baos);
|
|
||||||
byte[] imageBytes = baos.toByteArray();
|
|
||||||
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageBytes))) {
|
try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageBytes))) {
|
||||||
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
|
Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
|
||||||
if (readers.hasNext()) {
|
if (readers.hasNext()) {
|
||||||
ImageReader reader = readers.next();
|
ImageReader reader = readers.next();
|
||||||
try {
|
try {
|
||||||
reader.setInput(iis);
|
reader.setInput(iis, true, true);
|
||||||
int width = reader.getWidth(0);
|
int width = reader.getWidth(0);
|
||||||
int height = reader.getHeight(0);
|
int height = reader.getHeight(0);
|
||||||
return CbxPageDimension.builder()
|
return CbxPageDimension.builder()
|
||||||
@@ -146,7 +202,7 @@ public class CbxReaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to read dimensions for page {} (entry: {}): {}", pageNumber, entryName, e.getMessage());
|
log.warn("Failed to read dimensions for page {} (entry: {}): {}", pageNumber, entryName, e.getMessage());
|
||||||
}
|
}
|
||||||
return CbxPageDimension.builder()
|
return CbxPageDimension.builder()
|
||||||
@@ -173,15 +229,68 @@ public class CbxReaderService {
|
|||||||
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 cbxPath = getBookPath(bookId, bookType);
|
Path cbxPath = getBookPath(bookId, bookType);
|
||||||
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
|
||||||
validatePageRequest(bookId, page, metadata.imageEntries);
|
validatePageRequest(bookId, page, metadata.imageEntries());
|
||||||
String entryName = metadata.imageEntries.get(page - 1);
|
|
||||||
|
// Tier 1: Check L1 Memory Map (OS File Cache) via open ZipFile
|
||||||
|
// This is the fastest path for ZIP/CBZ
|
||||||
|
try {
|
||||||
|
java.util.zip.ZipFile zip = getZipFile(cbxPath, metadata.lastModified());
|
||||||
|
if (zip != null) {
|
||||||
|
String entryName = metadata.imageEntries().get(page - 1);
|
||||||
|
java.util.zip.ZipEntry entry = zip.getEntry(entryName);
|
||||||
|
if (entry != null) {
|
||||||
|
try (InputStream is = zip.getInputStream(entry)) {
|
||||||
|
is.transferTo(outputStream);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.trace("L1 Zip cache miss or unsupported format for book {}: {}", bookId, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tier 2: 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tier 3: Fallback to full extraction/stream (slowest)
|
||||||
|
String entryName = metadata.imageEntries().get(page - 1);
|
||||||
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
|
archiveService.transferEntryTo(cbxPath, entryName, outputStream);
|
||||||
}
|
}
|
||||||
|
|
||||||
private Path getBookPath(Long bookId, String bookType) {
|
private ZipFile getZipFile(Path cbxPath, long lastModified) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
String cacheKey = cbxPath.toString() + ":" + lastModified;
|
||||||
|
return zipHandleCache.get(cacheKey, _ -> {
|
||||||
|
try {
|
||||||
|
if (cbxPath.toString().toLowerCase().endsWith(".cbz") || cbxPath.toString().toLowerCase().endsWith(".zip")) {
|
||||||
|
return new java.util.zip.ZipFile(cbxPath.toFile());
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("Failed to open ZipFile for {}: {}", cbxPath, e.getMessage());
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getCacheKey(Long bookId, String bookType, long lastModified) {
|
||||||
if (bookType != null) {
|
if (bookType != null) {
|
||||||
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
|
// 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) {
|
||||||
|
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
if (bookType != null) {
|
||||||
|
BookFileType requestedType = BookFileType.fromName(bookType)
|
||||||
|
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
|
||||||
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
||||||
.filter(bf -> bf.getBookType() == requestedType)
|
.filter(bf -> bf.getBookType() == requestedType)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
@@ -203,43 +312,26 @@ public class CbxReaderService {
|
|||||||
private CachedArchiveMetadata getCachedMetadata(Path cbxPath) throws IOException {
|
private CachedArchiveMetadata getCachedMetadata(Path cbxPath) throws IOException {
|
||||||
String cacheKey = cbxPath.toString();
|
String cacheKey = cbxPath.toString();
|
||||||
long currentModified = Files.getLastModifiedTime(cbxPath).toMillis();
|
long currentModified = Files.getLastModifiedTime(cbxPath).toMillis();
|
||||||
CachedArchiveMetadata cached = archiveCache.get(cacheKey);
|
CachedArchiveMetadata cached = archiveCache.getIfPresent(cacheKey);
|
||||||
if (cached != null && cached.lastModified == currentModified) {
|
if (cached != null && cached.lastModified() == currentModified) {
|
||||||
cached.lastAccessed = System.currentTimeMillis();
|
|
||||||
log.debug("Cache hit for archive: {}", cbxPath.getFileName());
|
log.debug("Cache hit for archive: {}", cbxPath.getFileName());
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
log.debug("Cache miss for archive: {}, scanning...", cbxPath.getFileName());
|
log.debug("Cache miss for archive: {}, scanning...", cbxPath.getFileName());
|
||||||
CachedArchiveMetadata newMetadata = scanArchiveMetadata(cbxPath);
|
CachedArchiveMetadata newMetadata = scanArchiveMetadata(cbxPath);
|
||||||
archiveCache.put(cacheKey, newMetadata);
|
archiveCache.put(cacheKey, newMetadata);
|
||||||
evictOldestCacheEntries();
|
|
||||||
return newMetadata;
|
return newMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> getImageEntriesFromArchiveCached(Path cbxPath) throws IOException {
|
private List<String> getImageEntriesFromArchiveCached(Path cbxPath) throws IOException {
|
||||||
return getCachedMetadata(cbxPath).imageEntries;
|
return getCachedMetadata(cbxPath).imageEntries();
|
||||||
}
|
|
||||||
|
|
||||||
private void evictOldestCacheEntries() {
|
|
||||||
if (archiveCache.size() <= MAX_CACHE_ENTRIES) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
List<String> keysToRemove = archiveCache.entrySet().stream()
|
|
||||||
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
|
|
||||||
.limit(archiveCache.size() - MAX_CACHE_ENTRIES)
|
|
||||||
.map(Map.Entry::getKey)
|
|
||||||
.toList();
|
|
||||||
keysToRemove.forEach(key -> {
|
|
||||||
archiveCache.remove(key);
|
|
||||||
log.debug("Evicted cache entry: {}", key);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private CachedArchiveMetadata scanArchiveMetadata(Path cbxPath) throws IOException {
|
private CachedArchiveMetadata scanArchiveMetadata(Path cbxPath) throws IOException {
|
||||||
long lastModified = Files.getLastModifiedTime(cbxPath).toMillis();
|
long lastModified = Files.getLastModifiedTime(cbxPath).toMillis();
|
||||||
|
|
||||||
List<String> entries = getImageEntries(cbxPath);
|
List<String> entries = getImageEntries(cbxPath);
|
||||||
return new CachedArchiveMetadata(entries, lastModified);
|
return new CachedArchiveMetadata(entries, null, lastModified);
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> getImageEntries(Path cbxPath) throws IOException {
|
private List<String> getImageEntries(Path cbxPath) throws IOException {
|
||||||
@@ -283,13 +375,10 @@ public class CbxReaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
String baseName = baseName(normalized).toLowerCase();
|
String baseName = baseName(normalized).toLowerCase();
|
||||||
if (baseName.startsWith("._") || baseName.startsWith(".")) {
|
if (baseName.startsWith("._") || !baseName.isEmpty() && baseName.charAt(0) == '.') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (SYSTEM_FILES.contains(baseName)) {
|
return !SYSTEM_FILES.contains(baseName);
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private String baseName(String path) {
|
private String baseName(String path) {
|
||||||
|
|||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package org.booklore.service.reader;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.booklore.config.AppProperties;
|
||||||
|
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.
|
||||||
|
* Extracts pages sequentially to avoid concurrent native libarchive access
|
||||||
|
* which can cause SIGSEGV / out-of-memory crashes in the native heap.
|
||||||
|
*/
|
||||||
|
public void prepareCbxCache(String cacheKey, Path cbxPath, List<String> entries) throws IOException {
|
||||||
|
ReentrantLock lock = cacheLocks.computeIfAbsent(cacheKey, ignored -> 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 org.booklore.exception.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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,8 +21,8 @@ import org.springframework.stereotype.Service;
|
|||||||
import java.io.*;
|
import java.io.*;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.time.Duration;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -33,76 +33,70 @@ public class EpubReaderService {
|
|||||||
|
|
||||||
private static final int MAX_CACHE_ENTRIES = 50;
|
private static final int MAX_CACHE_ENTRIES = 50;
|
||||||
|
|
||||||
private static final Map<String, String> CONTENT_TYPE_MAP = createContentTypeMap();
|
private static final Map<String, String> CONTENT_TYPE_MAP = Map.ofEntries(
|
||||||
|
Map.entry(".xhtml", "application/xhtml+xml"),
|
||||||
private static Map<String, String> createContentTypeMap() {
|
Map.entry(".html", "application/xhtml+xml"),
|
||||||
Map<String, String> map = new HashMap<>(32);
|
Map.entry(".htm", "application/xhtml+xml"),
|
||||||
map.put(".xhtml", "application/xhtml+xml");
|
Map.entry(".css", "text/css"),
|
||||||
map.put(".html", "application/xhtml+xml");
|
Map.entry(".js", "application/javascript"),
|
||||||
map.put(".htm", "application/xhtml+xml");
|
Map.entry(".jpg", "image/jpeg"),
|
||||||
map.put(".css", "text/css");
|
Map.entry(".jpeg", "image/jpeg"),
|
||||||
map.put(".js", "application/javascript");
|
Map.entry(".png", "image/png"),
|
||||||
map.put(".jpg", "image/jpeg");
|
Map.entry(".gif", "image/gif"),
|
||||||
map.put(".jpeg", "image/jpeg");
|
Map.entry(".svg", "image/svg+xml"),
|
||||||
map.put(".png", "image/png");
|
Map.entry(".webp", "image/webp"),
|
||||||
map.put(".gif", "image/gif");
|
Map.entry(".woff", "font/woff"),
|
||||||
map.put(".svg", "image/svg+xml");
|
Map.entry(".woff2", "font/woff2"),
|
||||||
map.put(".webp", "image/webp");
|
Map.entry(".ttf", "font/ttf"),
|
||||||
map.put(".woff", "font/woff");
|
Map.entry(".otf", "font/otf"),
|
||||||
map.put(".woff2", "font/woff2");
|
Map.entry(".eot", "application/vnd.ms-fontobject"),
|
||||||
map.put(".ttf", "font/ttf");
|
Map.entry(".xml", "application/xml"),
|
||||||
map.put(".otf", "font/otf");
|
Map.entry(".ncx", "application/x-dtbncx+xml"),
|
||||||
map.put(".eot", "application/vnd.ms-fontobject");
|
Map.entry(".smil", "application/smil+xml"),
|
||||||
map.put(".xml", "application/xml");
|
Map.entry(".mp3", "audio/mpeg"),
|
||||||
map.put(".ncx", "application/x-dtbncx+xml");
|
Map.entry(".mp4", "video/mp4"),
|
||||||
map.put(".smil", "application/smil+xml");
|
Map.entry(".m4a", "audio/mp4"),
|
||||||
map.put(".mp3", "audio/mpeg");
|
Map.entry(".m4b", "audio/mp4"),
|
||||||
map.put(".mp4", "video/mp4");
|
Map.entry(".aac", "audio/aac"),
|
||||||
map.put(".m4a", "audio/mp4");
|
Map.entry(".wav", "audio/wav"),
|
||||||
map.put(".m4b", "audio/mp4");
|
Map.entry(".flac", "audio/flac"),
|
||||||
map.put(".aac", "audio/aac");
|
Map.entry(".ogg", "audio/ogg"),
|
||||||
map.put(".wav", "audio/wav");
|
Map.entry(".webm", "video/webm"),
|
||||||
map.put(".flac", "audio/flac");
|
Map.entry(".avif", "image/avif"),
|
||||||
map.put(".ogg", "audio/ogg");
|
Map.entry(".opf", "application/oebps-package+xml")
|
||||||
map.put(".webm", "video/webm");
|
);
|
||||||
map.put(".avif", "image/avif");
|
|
||||||
map.put(".opf", "application/oebps-package+xml");
|
|
||||||
return Collections.unmodifiableMap(map);
|
|
||||||
}
|
|
||||||
|
|
||||||
private final BookRepository bookRepository;
|
private final BookRepository bookRepository;
|
||||||
private final Map<String, CachedEpubMetadata> metadataCache = new ConcurrentHashMap<>();
|
private final com.github.benmanes.caffeine.cache.Cache<String, CachedEpubMetadata> metadataCache = com.github.benmanes.caffeine.cache.Caffeine.newBuilder()
|
||||||
|
.maximumSize(MAX_CACHE_ENTRIES)
|
||||||
private static class CachedEpubMetadata {
|
.expireAfterAccess(Duration.ofMinutes(30))
|
||||||
final EpubBookInfo bookInfo;
|
.build();
|
||||||
final long lastModified;
|
|
||||||
final Set<String> validPaths;
|
|
||||||
final Map<String, EpubManifestItem> manifestByHref;
|
|
||||||
volatile long lastAccessed;
|
|
||||||
|
|
||||||
|
private record CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified,
|
||||||
|
Set<String> validPaths,
|
||||||
|
Map<String, EpubManifestItem> manifestByHref) {
|
||||||
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified) {
|
CachedEpubMetadata(EpubBookInfo bookInfo, long lastModified) {
|
||||||
this.bookInfo = bookInfo;
|
this(bookInfo, lastModified, buildValidPaths(bookInfo), buildManifestByHref(bookInfo));
|
||||||
this.lastModified = lastModified;
|
}
|
||||||
this.lastAccessed = System.currentTimeMillis();
|
|
||||||
|
|
||||||
|
private static Set<String> buildValidPaths(EpubBookInfo bookInfo) {
|
||||||
Set<String> paths = new HashSet<>(bookInfo.getManifest().size() + 2);
|
Set<String> paths = new HashSet<>(bookInfo.getManifest().size() + 2);
|
||||||
paths.add(CONTAINER_PATH);
|
paths.add(CONTAINER_PATH);
|
||||||
if (bookInfo.getContainerPath() != null) {
|
if (bookInfo.getContainerPath() != null) {
|
||||||
paths.add(bookInfo.getContainerPath());
|
paths.add(bookInfo.getContainerPath());
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, EpubManifestItem> byHref = new HashMap<>(bookInfo.getManifest().size());
|
|
||||||
for (EpubManifestItem item : bookInfo.getManifest()) {
|
for (EpubManifestItem item : bookInfo.getManifest()) {
|
||||||
paths.add(item.getHref());
|
paths.add(item.getHref());
|
||||||
byHref.put(item.getHref(), item);
|
|
||||||
}
|
}
|
||||||
|
return Collections.unmodifiableSet(paths);
|
||||||
this.validPaths = Collections.unmodifiableSet(paths);
|
|
||||||
this.manifestByHref = Collections.unmodifiableMap(byHref);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void touch() {
|
private static Map<String, EpubManifestItem> buildManifestByHref(EpubBookInfo bookInfo) {
|
||||||
this.lastAccessed = System.currentTimeMillis();
|
Map<String, EpubManifestItem> byHref = new HashMap<>(bookInfo.getManifest().size());
|
||||||
|
for (EpubManifestItem item : bookInfo.getManifest()) {
|
||||||
|
byHref.put(item.getHref(), item);
|
||||||
|
}
|
||||||
|
return Collections.unmodifiableMap(byHref);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +146,6 @@ public class EpubReaderService {
|
|||||||
Path epubPath = getBookPath(bookId, bookType);
|
Path epubPath = getBookPath(bookId, bookType);
|
||||||
try {
|
try {
|
||||||
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
|
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
|
||||||
metadata.touch();
|
|
||||||
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
|
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
|
||||||
EpubManifestItem item = metadata.manifestByHref.get(normalizedPath);
|
EpubManifestItem item = metadata.manifestByHref.get(normalizedPath);
|
||||||
return item != null ? item.getMediaType() : guessContentType(filePath);
|
return item != null ? item.getMediaType() : guessContentType(filePath);
|
||||||
@@ -169,7 +162,6 @@ public class EpubReaderService {
|
|||||||
Path epubPath = getBookPath(bookId, bookType);
|
Path epubPath = getBookPath(bookId, bookType);
|
||||||
try {
|
try {
|
||||||
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
|
CachedEpubMetadata metadata = getCachedMetadata(epubPath);
|
||||||
metadata.touch();
|
|
||||||
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
|
String normalizedPath = normalizePath(filePath, metadata.bookInfo.getRootPath());
|
||||||
|
|
||||||
// O(1) lookup instead of O(n) stream filter
|
// O(1) lookup instead of O(n) stream filter
|
||||||
@@ -181,7 +173,7 @@ public class EpubReaderService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Path getBookPath(Long bookId, String bookType) {
|
private Path getBookPath(Long bookId, String bookType) {
|
||||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
BookEntity bookEntity = bookRepository.findByIdForStreaming(bookId)
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
if (bookType != null) {
|
if (bookType != null) {
|
||||||
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
|
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
|
||||||
@@ -197,10 +189,9 @@ public class EpubReaderService {
|
|||||||
private CachedEpubMetadata getCachedMetadata(Path epubPath) throws IOException {
|
private CachedEpubMetadata getCachedMetadata(Path epubPath) throws IOException {
|
||||||
String cacheKey = epubPath.toString();
|
String cacheKey = epubPath.toString();
|
||||||
long currentModified = Files.getLastModifiedTime(epubPath).toMillis();
|
long currentModified = Files.getLastModifiedTime(epubPath).toMillis();
|
||||||
CachedEpubMetadata cached = metadataCache.get(cacheKey);
|
CachedEpubMetadata cached = metadataCache.getIfPresent(cacheKey);
|
||||||
|
|
||||||
if (cached != null && cached.lastModified == currentModified) {
|
if (cached != null && cached.lastModified() == currentModified) {
|
||||||
cached.lastAccessed = System.currentTimeMillis();
|
|
||||||
log.debug("Cache hit for EPUB: {}", epubPath.getFileName());
|
log.debug("Cache hit for EPUB: {}", epubPath.getFileName());
|
||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
@@ -208,25 +199,9 @@ public class EpubReaderService {
|
|||||||
log.debug("Cache miss for EPUB: {}, parsing...", epubPath.getFileName());
|
log.debug("Cache miss for EPUB: {}, parsing...", epubPath.getFileName());
|
||||||
CachedEpubMetadata newMetadata = parseEpubMetadata(epubPath, currentModified);
|
CachedEpubMetadata newMetadata = parseEpubMetadata(epubPath, currentModified);
|
||||||
metadataCache.put(cacheKey, newMetadata);
|
metadataCache.put(cacheKey, newMetadata);
|
||||||
evictOldestCacheEntries();
|
|
||||||
return newMetadata;
|
return newMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void evictOldestCacheEntries() {
|
|
||||||
if (metadataCache.size() <= MAX_CACHE_ENTRIES) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
List<String> keysToRemove = metadataCache.entrySet().stream()
|
|
||||||
.sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed))
|
|
||||||
.limit(metadataCache.size() - MAX_CACHE_ENTRIES)
|
|
||||||
.map(Map.Entry::getKey)
|
|
||||||
.toList();
|
|
||||||
keysToRemove.forEach(key -> {
|
|
||||||
metadataCache.remove(key);
|
|
||||||
log.debug("Evicted EPUB cache entry: {}", key);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException {
|
private CachedEpubMetadata parseEpubMetadata(Path epubPath, long lastModified) throws IOException {
|
||||||
try {
|
try {
|
||||||
Book book = new EpubReader().readEpubLazy(epubPath, "UTF-8");
|
Book book = new EpubReader().readEpubLazy(epubPath, "UTF-8");
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ 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.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
import com.github.benmanes.caffeine.cache.Cache;
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
@@ -35,23 +35,50 @@ public class PdfReaderService {
|
|||||||
|
|
||||||
private static final int MAX_CACHE_ENTRIES = 15;
|
private static final int MAX_CACHE_ENTRIES = 15;
|
||||||
private static final float DEFAULT_DPI = 200f;
|
private static final float DEFAULT_DPI = 200f;
|
||||||
|
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))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
private static class CachedPdfMetadata {
|
private record CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {}
|
||||||
final int pageCount;
|
|
||||||
final long lastModified;
|
|
||||||
final List<PdfOutlineItem> outline;
|
|
||||||
|
|
||||||
CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {
|
public void initCache(Long bookId, String bookType) throws IOException {
|
||||||
this.pageCount = pageCount;
|
Path pdfPath = getBookPath(bookId, bookType);
|
||||||
this.lastModified = lastModified;
|
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||||
this.outline = outline;
|
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) {
|
||||||
@@ -64,7 +91,7 @@ public class PdfReaderService {
|
|||||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||||
return IntStream.rangeClosed(1, metadata.pageCount)
|
return IntStream.rangeClosed(1, metadata.pageCount)
|
||||||
.boxed()
|
.boxed()
|
||||||
.collect(Collectors.toList());
|
.toList();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.error("Failed to read PDF for book {}", bookId, e);
|
log.error("Failed to read PDF for book {}", bookId, e);
|
||||||
throw ApiError.FILE_READ_ERROR.createException("Failed to read PDF: " + e.getMessage());
|
throw ApiError.FILE_READ_ERROR.createException("Failed to read PDF: " + e.getMessage());
|
||||||
@@ -92,15 +119,39 @@ 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);
|
||||||
renderPageToStream(pdfPath, page, outputStream);
|
|
||||||
|
// Render, cache atomically, then stream
|
||||||
|
Path cached = chapterCacheService.getCachedPage(cacheKey, page);
|
||||||
|
Files.createDirectories(cached.getParent());
|
||||||
|
byte[] jpeg = renderPageToBytes(pdfPath, page);
|
||||||
|
writeAtomically(cached, jpeg);
|
||||||
|
outputStream.write(jpeg);
|
||||||
|
}
|
||||||
|
|
||||||
|
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.findByIdWithBookFiles(bookId)
|
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
if (bookType != null) {
|
if (bookType != null) {
|
||||||
BookFileType requestedType = BookFileType.valueOf(bookType.toUpperCase());
|
BookFileType requestedType = BookFileType.fromName(bookType)
|
||||||
|
.orElseThrow(() -> ApiError.INVALID_INPUT.createException("Invalid book type: " + bookType));
|
||||||
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
BookFileEntity bookFile = bookEntity.getBookFiles().stream()
|
||||||
.filter(bf -> bf.getBookType() == requestedType)
|
.filter(bf -> bf.getBookType() == requestedType)
|
||||||
.findFirst()
|
.findFirst()
|
||||||
@@ -190,14 +241,27 @@ public class PdfReaderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
|
private byte[] renderPageToBytes(Path pdfPath, int page) throws IOException {
|
||||||
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
|
try (PdfDocument doc = PdfDocument.open(pdfPath)) {
|
||||||
// page is 1-based from the API, renderPageToBytes expects 0-based
|
// page is 1-based from the API, renderPageToBytes expects 0-based
|
||||||
byte[] jpeg = doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg");
|
return doc.renderPageToBytes(page - 1, (int) DEFAULT_DPI, "jpeg");
|
||||||
outputStream.write(jpeg);
|
} catch (Exception e) {
|
||||||
} catch (IOException e) {
|
|
||||||
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
|
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
|
||||||
throw 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,13 +60,14 @@ class Rar5IntegrationTest {
|
|||||||
BookEntity book = new BookEntity();
|
BookEntity book = new BookEntity();
|
||||||
book.setId(99L);
|
book.setId(99L);
|
||||||
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
||||||
org.mockito.Mockito.when(mockRepo.findByIdWithBookFiles(99L)).thenReturn(java.util.Optional.of(book));
|
org.mockito.Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(java.util.Optional.of(book));
|
||||||
|
org.booklore.service.reader.ChapterCacheService mockCache = org.mockito.Mockito.mock(org.booklore.service.reader.ChapterCacheService.class);
|
||||||
|
|
||||||
try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) {
|
try (var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
||||||
.thenReturn(cbrCopy);
|
.thenReturn(cbrCopy);
|
||||||
|
|
||||||
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService());
|
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService(), mockCache);
|
||||||
List<Integer> pages = readerService.getAvailablePages(99L);
|
List<Integer> pages = readerService.getAvailablePages(99L);
|
||||||
|
|
||||||
assertThat(pages).hasSize(3);
|
assertThat(pages).hasSize(3);
|
||||||
@@ -82,7 +83,8 @@ class Rar5IntegrationTest {
|
|||||||
BookEntity book = new BookEntity();
|
BookEntity book = new BookEntity();
|
||||||
book.setId(99L);
|
book.setId(99L);
|
||||||
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
BookRepository mockRepo = org.mockito.Mockito.mock(BookRepository.class);
|
||||||
org.mockito.Mockito.when(mockRepo.findByIdWithBookFiles(99L)).thenReturn(java.util.Optional.of(book));
|
org.mockito.Mockito.when(mockRepo.findByIdForStreaming(99L)).thenReturn(java.util.Optional.of(book));
|
||||||
|
org.booklore.service.reader.ChapterCacheService mockCache = org.mockito.Mockito.mock(org.booklore.service.reader.ChapterCacheService.class);
|
||||||
|
|
||||||
try (
|
try (
|
||||||
var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)
|
var fileUtilsStatic = org.mockito.Mockito.mockStatic(org.booklore.util.FileUtils.class)
|
||||||
@@ -90,7 +92,7 @@ class Rar5IntegrationTest {
|
|||||||
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
fileUtilsStatic.when(() -> org.booklore.util.FileUtils.getBookFullPath(book))
|
||||||
.thenReturn(cbrCopy);
|
.thenReturn(cbrCopy);
|
||||||
|
|
||||||
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService());
|
CbxReaderService readerService = new CbxReaderService(mockRepo, new ArchiveService(), mockCache);
|
||||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
readerService.streamPageImage(99L, 1, out);
|
readerService.streamPageImage(99L, 1, out);
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -101,7 +101,7 @@ class PdfMetadataExtractorTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void extractMetadata_minimalPdf_usesFilenameAsTitle() throws Exception {
|
void extractMetadata_minimalPdf_usesFilenameAsTitle() throws Exception {
|
||||||
File pdf = createPdf(_ -> {});
|
File pdf = createPdf(ignored -> {});
|
||||||
BookMetadata meta = extractor.extractMetadata(pdf);
|
BookMetadata meta = extractor.extractMetadata(pdf);
|
||||||
assertThat(meta.getTitle()).isEqualTo("test");
|
assertThat(meta.getTitle()).isEqualTo("test");
|
||||||
assertThat(meta.getPageCount()).isEqualTo(1);
|
assertThat(meta.getPageCount()).isEqualTo(1);
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package org.booklore.service.reader;
|
package org.booklore.service.reader;
|
||||||
|
|
||||||
|
import com.github.benmanes.caffeine.cache.Cache;
|
||||||
import org.booklore.exception.ApiError;
|
import org.booklore.exception.ApiError;
|
||||||
|
import org.booklore.exception.APIException;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.service.ArchiveService;
|
import org.booklore.service.ArchiveService;
|
||||||
|
import org.booklore.service.reader.ChapterCacheService;
|
||||||
import org.booklore.util.FileUtils;
|
import org.booklore.util.FileUtils;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
@@ -18,6 +21,7 @@ import java.nio.file.attribute.FileTime;
|
|||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
import java.util.zip.ZipFile;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.Mockito.*;
|
import static org.mockito.Mockito.*;
|
||||||
@@ -31,9 +35,15 @@ class CbxReaderServiceTest {
|
|||||||
@Mock
|
@Mock
|
||||||
ArchiveService archiveService;
|
ArchiveService archiveService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
ChapterCacheService chapterCacheService;
|
||||||
|
|
||||||
@InjectMocks
|
@InjectMocks
|
||||||
CbxReaderService cbxReaderService;
|
CbxReaderService cbxReaderService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
com.github.benmanes.caffeine.cache.Cache<String, java.util.zip.ZipFile> mockZipCache;
|
||||||
|
|
||||||
@Captor
|
@Captor
|
||||||
ArgumentCaptor<Long> longCaptor;
|
ArgumentCaptor<Long> longCaptor;
|
||||||
|
|
||||||
@@ -45,17 +55,21 @@ class CbxReaderServiceTest {
|
|||||||
bookEntity = new BookEntity();
|
bookEntity = new BookEntity();
|
||||||
bookEntity.setId(1L);
|
bookEntity.setId(1L);
|
||||||
cbzPath = Path.of("/tmp/test.cbz");
|
cbzPath = Path.of("/tmp/test.cbz");
|
||||||
|
// Manually inject the mock cache
|
||||||
|
cbxReaderService.setZipHandleCache(mockZipCache);
|
||||||
|
// Ensure zipHandleCache is mocked to return null on any key access
|
||||||
|
lenient().when(mockZipCache.get(anyString(), any())).thenReturn(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetAvailablePages_ThrowsOnMissingBook() {
|
void testGetAvailablePages_ThrowsOnMissingBook() {
|
||||||
when(bookRepository.findByIdWithBookFiles(2L)).thenReturn(Optional.empty());
|
when(bookRepository.findByIdForStreaming(2L)).thenReturn(Optional.empty());
|
||||||
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(), () -> cbxReaderService.getAvailablePages(2L));
|
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(), () -> cbxReaderService.getAvailablePages(2L));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetAvailablePages_Success() throws Exception {
|
void testGetAvailablePages_Success() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
||||||
|
|
||||||
try (
|
try (
|
||||||
@@ -65,6 +79,8 @@ 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);
|
||||||
}
|
}
|
||||||
@@ -72,7 +88,7 @@ class CbxReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamPageImage_Success() throws Exception {
|
void testStreamPageImage_Success() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
||||||
when(
|
when(
|
||||||
archiveService.transferEntryTo(eq(cbzPath), eq("1.jpg"), any())
|
archiveService.transferEntryTo(eq(cbzPath), eq("1.jpg"), any())
|
||||||
@@ -84,6 +100,8 @@ 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());
|
||||||
@@ -92,7 +110,7 @@ class CbxReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamPageImage_PageOutOfRange_Throws() throws Exception {
|
void testStreamPageImage_PageOutOfRange_Throws() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
||||||
try (
|
try (
|
||||||
MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class);
|
MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class);
|
||||||
@@ -101,6 +119,8 @@ 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())
|
||||||
@@ -110,7 +130,7 @@ class CbxReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamPageImage_EntryNotFound_Throws() throws Exception {
|
void testStreamPageImage_EntryNotFound_Throws() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
when(archiveService.streamEntryNames(cbzPath)).then((i) -> Stream.of("1.jpg"));
|
||||||
try (
|
try (
|
||||||
MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class);
|
MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class);
|
||||||
@@ -125,4 +145,22 @@ class CbxReaderServiceTest {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStreamPageImage_InvalidBookType_Throws() {
|
||||||
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
APIException ex = assertThrows(APIException.class, () ->
|
||||||
|
cbxReaderService.streamPageImage(1L, "../traversal", 1, new ByteArrayOutputStream())
|
||||||
|
);
|
||||||
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
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)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -91,7 +91,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetBookInfo_Success() throws Exception {
|
void testGetBookInfo_Success() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -114,7 +114,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetBookInfo_BookNotFound() {
|
void testGetBookInfo_BookNotFound() {
|
||||||
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
|
when(bookRepository.findByIdForStreaming(999L)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
|
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
|
||||||
() -> epubReaderService.getBookInfo(999L));
|
() -> epubReaderService.getBookInfo(999L));
|
||||||
@@ -122,7 +122,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetBookInfo_CacheHit() throws Exception {
|
void testGetBookInfo_CacheHit() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -140,7 +140,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamFile_Success() throws Exception {
|
void testStreamFile_Success() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -167,7 +167,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamFile_FileNotFound() throws Exception {
|
void testStreamFile_FileNotFound() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -185,7 +185,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamFile_PathTraversalBlocked() throws Exception {
|
void testStreamFile_PathTraversalBlocked() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -203,7 +203,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamFile_ContainerXmlAllowed() throws Exception {
|
void testStreamFile_ContainerXmlAllowed() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -223,7 +223,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetContentType_FromManifest() throws Exception {
|
void testGetContentType_FromManifest() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -246,7 +246,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetContentType_Fallback() throws Exception {
|
void testGetContentType_Fallback() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -266,7 +266,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetFileSize_FromManifest() throws Exception {
|
void testGetFileSize_FromManifest() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -288,7 +288,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testGetFileSize_NotFound() throws Exception {
|
void testGetFileSize_NotFound() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -301,7 +301,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testSpineOrder() throws Exception {
|
void testSpineOrder() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -321,7 +321,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testTocParsing() throws Exception {
|
void testTocParsing() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -342,7 +342,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testManifestProperties() throws Exception {
|
void testManifestProperties() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
@@ -365,7 +365,7 @@ class EpubReaderServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testStreamFile_LeadingSlashHandled() throws Exception {
|
void testStreamFile_LeadingSlashHandled() throws Exception {
|
||||||
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
when(bookRepository.findByIdForStreaming(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
|
||||||
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
try (MockedStatic<FileUtils> fileUtilsStatic = mockStatic(FileUtils.class)) {
|
||||||
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
fileUtilsStatic.when(() -> FileUtils.getBookFullPath(bookEntity)).thenReturn(epubPath);
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package org.booklore.service.reader;
|
||||||
|
|
||||||
|
import org.booklore.exception.APIException;
|
||||||
|
import org.booklore.exception.ApiError;
|
||||||
|
import org.booklore.model.entity.BookEntity;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.util.FileUtils;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockedStatic;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.attribute.FileTime;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class PdfReaderServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private BookRepository bookRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private ChapterCacheService chapterCacheService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private PdfReaderService pdfReaderService;
|
||||||
|
|
||||||
|
private BookEntity bookEntity;
|
||||||
|
private Path pdfPath;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() {
|
||||||
|
bookEntity = new BookEntity();
|
||||||
|
bookEntity.setId(1L);
|
||||||
|
pdfPath = Path.of("/tmp/test.pdf");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStreamPageImage_InvalidBookType_Throws() {
|
||||||
|
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
|
||||||
|
APIException ex = assertThrows(APIException.class, () ->
|
||||||
|
pdfReaderService.streamPageImage(1L, "../traversal", 1, new ByteArrayOutputStream())
|
||||||
|
);
|
||||||
|
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