Revamp streaming PDF reader to render pages on demand (#2332)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+10
-4
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.controller;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.response.PdfBookInfo;
|
||||
import com.adityachandel.booklore.service.reader.PdfReaderService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -11,7 +12,6 @@ import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@@ -25,8 +25,14 @@ public class PdfReaderController {
|
||||
@Operation(summary = "List pages in a PDF book", description = "Retrieve a list of available page numbers for a PDF book.")
|
||||
@ApiResponse(responseCode = "200", description = "Page numbers returned successfully")
|
||||
@GetMapping("/{bookId}/pages")
|
||||
public List<Integer> listPages(
|
||||
@Parameter(description = "ID of the book") @PathVariable Long bookId) throws IOException {
|
||||
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return pdfReaderService.getAvailablePages(bookId);
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "Get book info for a PDF book", description = "Retrieve book information including page count and hierarchical outline/table of contents.")
|
||||
@ApiResponse(responseCode = "200", description = "Book info returned successfully")
|
||||
@GetMapping("/{bookId}/info")
|
||||
public PdfBookInfo getBookInfo(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
|
||||
return pdfReaderService.getBookInfo(bookId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,6 +195,9 @@ public class BookLoreUser {
|
||||
public static class NewPdfReaderSetting {
|
||||
private NewPdfPageSpread pageSpread;
|
||||
private NewPdfPageViewMode pageViewMode;
|
||||
private NewPdfBackgroundColor backgroundColor;
|
||||
private NewPdfPageFitMode fitMode;
|
||||
private NewPdfPageScrollMode scrollMode;
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
+4
-2
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.NewPdfPageViewMode;
|
||||
import com.adityachandel.booklore.model.enums.NewPdfPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.*;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -11,4 +10,7 @@ public class NewPdfViewerPreferences {
|
||||
private Long bookId;
|
||||
private NewPdfPageSpread pageSpread;
|
||||
private NewPdfPageViewMode pageViewMode;
|
||||
private NewPdfBackgroundColor backgroundColor;
|
||||
private NewPdfPageFitMode fitMode;
|
||||
private NewPdfPageScrollMode scrollMode;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PdfBookInfo {
|
||||
private int pageCount;
|
||||
private List<PdfOutlineItem> outline;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.adityachandel.booklore.model.dto.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PdfOutlineItem {
|
||||
private String title;
|
||||
private Integer pageNumber;
|
||||
private List<PdfOutlineItem> children;
|
||||
}
|
||||
+13
-2
@@ -1,7 +1,6 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import com.adityachandel.booklore.model.enums.NewPdfPageSpread;
|
||||
import com.adityachandel.booklore.model.enums.NewPdfPageViewMode;
|
||||
import com.adityachandel.booklore.model.enums.*;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -33,4 +32,16 @@ public class NewPdfViewerPreferencesEntity {
|
||||
@Column(name = "view_mode")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NewPdfPageViewMode pageViewMode;
|
||||
|
||||
@Column(name = "fit_mode")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NewPdfPageFitMode fitMode;
|
||||
|
||||
@Column(name = "scroll_mode")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NewPdfPageScrollMode scrollMode;
|
||||
|
||||
@Column(name = "background_color")
|
||||
@Enumerated(EnumType.STRING)
|
||||
private NewPdfBackgroundColor backgroundColor;
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum NewPdfBackgroundColor {
|
||||
GRAY,
|
||||
BLACK,
|
||||
WHITE
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum NewPdfPageFitMode {
|
||||
ACTUAL_SIZE,
|
||||
FIT_PAGE,
|
||||
FIT_WIDTH,
|
||||
FIT_HEIGHT,
|
||||
AUTO
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum NewPdfPageScrollMode {
|
||||
PAGINATED,
|
||||
INFINITE
|
||||
}
|
||||
@@ -3,14 +3,6 @@ package com.adityachandel.booklore.model.enums;
|
||||
import lombok.Getter;
|
||||
|
||||
public enum TaskType {
|
||||
CLEAR_PDF_CACHE(
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
"Clear PDF Cache",
|
||||
"Clears temporarily generated images used by the streaming PDF reader."
|
||||
),
|
||||
REFRESH_LIBRARY_METADATA(
|
||||
false,
|
||||
true,
|
||||
|
||||
@@ -164,6 +164,9 @@ public class BookService {
|
||||
.bookId(bookId)
|
||||
.pageViewMode(pdfPref.getPageViewMode())
|
||||
.pageSpread(pdfPref.getPageSpread())
|
||||
.fitMode(pdfPref.getFitMode())
|
||||
.scrollMode(pdfPref.getScrollMode())
|
||||
.backgroundColor(pdfPref.getBackgroundColor())
|
||||
.build()));
|
||||
} else if (bookType == BookFileType.CBX) {
|
||||
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
|
||||
+3
@@ -181,6 +181,9 @@ public class BookUpdateService {
|
||||
NewPdfViewerPreferences pdfSettings = settings.getNewPdfSettings();
|
||||
prefs.setPageSpread(pdfSettings.getPageSpread());
|
||||
prefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||
prefs.setFitMode(pdfSettings.getFitMode());
|
||||
prefs.setScrollMode(pdfSettings.getScrollMode());
|
||||
prefs.setBackgroundColor(pdfSettings.getBackgroundColor());
|
||||
newPdfViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
}
|
||||
|
||||
+178
-89
@@ -1,142 +1,231 @@
|
||||
package com.adityachandel.booklore.service.reader;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.response.PdfBookInfo;
|
||||
import com.adityachandel.booklore.model.dto.response.PdfOutlineItem;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
|
||||
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
|
||||
import org.apache.pdfbox.rendering.ImageType;
|
||||
import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PdfReaderService {
|
||||
|
||||
private static final String CACHE_INFO_FILENAME = ".cache-info";
|
||||
private static final Pattern NON_DIGIT_PATTERN = Pattern.compile("\\D+");
|
||||
private static final int MAX_CACHE_ENTRIES = 50;
|
||||
private static final float DEFAULT_DPI = 200f;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
private final FileService fileService;
|
||||
private final Map<String, CachedPdfMetadata> metadataCache = new ConcurrentHashMap<>();
|
||||
|
||||
public List<Integer> getAvailablePages(Long bookId) throws IOException {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
|
||||
private static class CachedPdfMetadata {
|
||||
final int pageCount;
|
||||
final long lastModified;
|
||||
final List<PdfOutlineItem> outline;
|
||||
volatile long lastAccessed;
|
||||
|
||||
Path pdfPath = Path.of(bookFullPath);
|
||||
Path cacheDir = Path.of(fileService.getPdfCachePath(), String.valueOf(bookId));
|
||||
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
|
||||
long maxCacheSizeBytes = appSettingService.getAppSettings().getPdfCacheSizeInMb() * 1024L * 1024L;
|
||||
long estimatedSize = Files.size(pdfPath);
|
||||
if (estimatedSize > maxCacheSizeBytes) {
|
||||
log.warn("Cache skipped: Estimated PDF size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
|
||||
throw ApiError.CACHE_TOO_LARGE.createException();
|
||||
CachedPdfMetadata(int pageCount, long lastModified, List<PdfOutlineItem> outline) {
|
||||
this.pageCount = pageCount;
|
||||
this.lastModified = lastModified;
|
||||
this.outline = outline;
|
||||
this.lastAccessed = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
public List<Integer> getAvailablePages(Long bookId) {
|
||||
Path pdfPath = getBookPath(bookId);
|
||||
try {
|
||||
if (needsCacheRefresh(pdfPath, cacheInfoPath)) {
|
||||
log.info("Invalidating cache for PDF book {}", bookId);
|
||||
if (Files.exists(cacheDir)) FileUtils.deleteDirectoryRecursively(cacheDir);
|
||||
Files.createDirectories(cacheDir);
|
||||
extractPdfPages(pdfPath, cacheDir);
|
||||
writeCacheInfo(pdfPath, cacheInfoPath);
|
||||
}
|
||||
|
||||
try (Stream<Path> stream = Files.list(cacheDir)) {
|
||||
return stream
|
||||
.filter(p -> p.toString().endsWith(".jpg"))
|
||||
.sorted()
|
||||
.map(p -> extractPageNumber(p.getFileName().toString()))
|
||||
.filter(p -> p != -1)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||
return IntStream.rangeClosed(1, metadata.pageCount)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to extract pages for book {}", bookId, e);
|
||||
throw new UncheckedIOException("Failed to extract pages from PDF for bookId: " + bookId, e);
|
||||
log.error("Failed to read PDF for book {}", bookId, e);
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to read PDF: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public PdfBookInfo getBookInfo(Long bookId) {
|
||||
Path pdfPath = getBookPath(bookId);
|
||||
try {
|
||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||
return PdfBookInfo.builder()
|
||||
.pageCount(metadata.pageCount)
|
||||
.outline(metadata.outline)
|
||||
.build();
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to read PDF for book {}", bookId, e);
|
||||
throw ApiError.FILE_READ_ERROR.createException("Failed to read PDF: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
|
||||
Path pagePath = Path.of(fileService.getPdfCachePath(), String.valueOf(bookId), String.format("%04d.jpg", page));
|
||||
if (!Files.exists(pagePath)) throw new FileNotFoundException("Page not found: " + page);
|
||||
try (InputStream in = Files.newInputStream(pagePath)) {
|
||||
try {
|
||||
in.transferTo(outputStream);
|
||||
} catch (IOException e) {
|
||||
log.error("Error streaming page {} of book {}", page, bookId, e);
|
||||
throw new UncheckedIOException("Failed to stream PDF page image for bookId: " + bookId, e);
|
||||
}
|
||||
Path pdfPath = getBookPath(bookId);
|
||||
CachedPdfMetadata metadata = getCachedMetadata(pdfPath);
|
||||
validatePageRequest(bookId, page, metadata.pageCount);
|
||||
renderPageToStream(pdfPath, page, outputStream);
|
||||
}
|
||||
|
||||
private Path getBookPath(Long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId)
|
||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
|
||||
return Path.of(bookFullPath);
|
||||
}
|
||||
|
||||
private void validatePageRequest(Long bookId, int page, int pageCount) throws FileNotFoundException {
|
||||
if (pageCount == 0) {
|
||||
throw new FileNotFoundException("No pages found for book: " + bookId);
|
||||
}
|
||||
if (page < 1 || page > pageCount) {
|
||||
throw new FileNotFoundException("Page " + page + " out of range [1-" + pageCount + "]");
|
||||
}
|
||||
}
|
||||
|
||||
private void extractPdfPages(Path pdfPath, Path targetDir) throws IOException {
|
||||
private CachedPdfMetadata getCachedMetadata(Path pdfPath) throws IOException {
|
||||
String cacheKey = pdfPath.toString();
|
||||
long currentModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||
CachedPdfMetadata cached = metadataCache.get(cacheKey);
|
||||
if (cached != null && cached.lastModified == currentModified) {
|
||||
cached.lastAccessed = System.currentTimeMillis();
|
||||
log.debug("Cache hit for PDF: {}", pdfPath.getFileName());
|
||||
return cached;
|
||||
}
|
||||
log.debug("Cache miss for PDF: {}, scanning...", pdfPath.getFileName());
|
||||
CachedPdfMetadata newMetadata = scanPdfMetadata(pdfPath);
|
||||
metadataCache.put(cacheKey, newMetadata);
|
||||
evictOldestCacheEntries();
|
||||
return newMetadata;
|
||||
}
|
||||
|
||||
private CachedPdfMetadata scanPdfMetadata(Path pdfPath) throws IOException {
|
||||
if (!Files.isReadable(pdfPath)) {
|
||||
throw new FileNotFoundException("PDF file is not readable: " + pdfPath);
|
||||
}
|
||||
long lastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile());
|
||||
PDDocument document = Loader.loadPDF(randomAccessRead)) {
|
||||
int pageCount = document.getNumberOfPages();
|
||||
List<PdfOutlineItem> outline = extractOutline(document);
|
||||
return new CachedPdfMetadata(pageCount, lastModified, outline);
|
||||
}
|
||||
}
|
||||
|
||||
private List<PdfOutlineItem> extractOutline(PDDocument document) {
|
||||
List<PdfOutlineItem> outline = new ArrayList<>();
|
||||
try {
|
||||
PDDocumentOutline documentOutline = document.getDocumentCatalog().getDocumentOutline();
|
||||
if (documentOutline != null) {
|
||||
PDOutlineItem item = documentOutline.getFirstChild();
|
||||
while (item != null) {
|
||||
PdfOutlineItem outlineItem = buildOutlineItem(document, item);
|
||||
if (outlineItem != null) {
|
||||
outline.add(outlineItem);
|
||||
}
|
||||
item = item.getNextSibling();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to extract PDF outline: {}", e.getMessage());
|
||||
}
|
||||
return outline;
|
||||
}
|
||||
|
||||
private PdfOutlineItem buildOutlineItem(PDDocument document, PDOutlineItem item) {
|
||||
try {
|
||||
String title = item.getTitle();
|
||||
if (title == null || title.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Integer pageNumber = null;
|
||||
try {
|
||||
PDPage page = item.findDestinationPage(document);
|
||||
if (page != null) {
|
||||
int pageIndex = document.getPages().indexOf(page);
|
||||
if (pageIndex >= 0) {
|
||||
pageNumber = pageIndex + 1;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to get page for outline item '{}': {}", title, e.getMessage());
|
||||
}
|
||||
|
||||
List<PdfOutlineItem> children = new ArrayList<>();
|
||||
PDOutlineItem child = item.getFirstChild();
|
||||
while (child != null) {
|
||||
PdfOutlineItem childItem = buildOutlineItem(document, child);
|
||||
if (childItem != null) {
|
||||
children.add(childItem);
|
||||
}
|
||||
child = child.getNextSibling();
|
||||
}
|
||||
|
||||
return PdfOutlineItem.builder()
|
||||
.title(title.trim())
|
||||
.pageNumber(pageNumber)
|
||||
.children(children.isEmpty() ? null : children)
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to process outline item: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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 cache entry: {}", key);
|
||||
});
|
||||
}
|
||||
|
||||
private void renderPageToStream(Path pdfPath, int page, OutputStream outputStream) throws IOException {
|
||||
try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfPath.toFile());
|
||||
PDDocument document = Loader.loadPDF(randomAccessRead)) {
|
||||
PDFRenderer renderer = new PDFRenderer(document);
|
||||
for (int i = 0; i < document.getNumberOfPages(); i++) {
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
image = renderer.renderImageWithDPI(i, 200, ImageType.RGB);
|
||||
Path outputFile = targetDir.resolve(String.format("%04d.jpg", i + 1));
|
||||
ImageIO.write(image, "JPEG", outputFile.toFile());
|
||||
} finally {
|
||||
if (image != null) {
|
||||
image.flush(); // Release native resources
|
||||
}
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
image = renderer.renderImageWithDPI(page - 1, DEFAULT_DPI, ImageType.RGB);
|
||||
ImageIO.write(image, "JPEG", outputStream);
|
||||
} finally {
|
||||
if (image != null) {
|
||||
image.flush();
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Failed to render PDF pages from {}", pdfPath, e);
|
||||
throw new UncheckedIOException("Error rendering PDF to images", e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean needsCacheRefresh(Path pdfPath, Path cacheInfoPath) throws IOException {
|
||||
if (!Files.exists(cacheInfoPath)) return true;
|
||||
|
||||
long currentLastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||
String recordedTimestamp = Files.readString(cacheInfoPath).trim();
|
||||
|
||||
try {
|
||||
long recordedLastModified = Long.parseLong(recordedTimestamp);
|
||||
return recordedLastModified != currentLastModified;
|
||||
} catch (NumberFormatException e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCacheInfo(Path pdfPath, Path cacheInfoPath) throws IOException {
|
||||
long lastModified = Files.getLastModifiedTime(pdfPath).toMillis();
|
||||
Files.writeString(cacheInfoPath, String.valueOf(lastModified), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
|
||||
}
|
||||
|
||||
private int extractPageNumber(String filename) {
|
||||
try {
|
||||
return Integer.parseInt(NON_DIGIT_PATTERN.matcher(filename).replaceAll(""));
|
||||
} catch (Exception e) {
|
||||
return -1;
|
||||
log.error("Failed to render PDF page {} from {}", page, pdfPath, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -107,6 +107,9 @@ public class DefaultUserSettingsProvider {
|
||||
return BookLoreUser.UserSettings.NewPdfReaderSetting.builder()
|
||||
.pageViewMode(NewPdfPageViewMode.SINGLE_PAGE)
|
||||
.pageSpread(NewPdfPageSpread.ODD)
|
||||
.fitMode(NewPdfPageFitMode.FIT_HEIGHT)
|
||||
.scrollMode(NewPdfPageScrollMode.PAGINATED)
|
||||
.backgroundColor(NewPdfBackgroundColor.WHITE)
|
||||
.build();
|
||||
}
|
||||
|
||||
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.model.enums.UserPermission;
|
||||
import com.adityachandel.booklore.task.TaskMetadataHelper;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Comparator;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Component
|
||||
@Slf4j
|
||||
public class ClearPdfCacheTask implements Task {
|
||||
|
||||
private FileService fileService;
|
||||
|
||||
@Override
|
||||
public void validatePermissions(BookLoreUser user, TaskCreateRequest request) {
|
||||
if (!UserPermission.CAN_ACCESS_TASK_MANAGER.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_ACCESS_TASK_MANAGER);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskCreateResponse execute(TaskCreateRequest request) {
|
||||
TaskCreateResponse.TaskCreateResponseBuilder builder = TaskCreateResponse.builder()
|
||||
.taskId(UUID.randomUUID().toString())
|
||||
.taskType(TaskType.CLEAR_PDF_CACHE);
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("{}: Task started", getTaskType());
|
||||
|
||||
try {
|
||||
fileService.clearCacheDirectory(fileService.getPdfCachePath());
|
||||
log.info("{}: Cache cleared", getTaskType());
|
||||
builder.status(TaskStatus.COMPLETED);
|
||||
} catch (Exception e) {
|
||||
log.error("{}: Error clearing cache", getTaskType(), e);
|
||||
builder.status(TaskStatus.FAILED);
|
||||
throw new RuntimeException("Failed to clear PDF cache", e);
|
||||
}
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("{}: Task completed. Duration: {} ms", getTaskType(), endTime - startTime);
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public TaskType getTaskType() {
|
||||
return TaskType.CLEAR_PDF_CACHE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMetadata() {
|
||||
return TaskMetadataHelper.getCacheSizeString(fileService.getPdfCachePath());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE new_pdf_viewer_preference
|
||||
ADD COLUMN fit_mode VARCHAR(16) NULL,
|
||||
ADD COLUMN scroll_mode VARCHAR(16) NULL,
|
||||
ADD COLUMN background_color VARCHAR(16) NULL;
|
||||
+8
-8
@@ -65,18 +65,18 @@ class TaskCronServiceTest {
|
||||
@Test
|
||||
void testGetAllEnabledCronConfigs_returnsList() {
|
||||
List<TaskCronConfigurationEntity> configs = List.of(
|
||||
buildEntity(TaskType.CLEAR_PDF_CACHE, "0 0 1 * * *", true)
|
||||
buildEntity(TaskType.CLEANUP_DELETED_BOOKS, "0 0 1 * * *", true)
|
||||
);
|
||||
when(repository.findByEnabledTrue()).thenReturn(configs);
|
||||
|
||||
List<TaskCronConfigurationEntity> result = service.getAllEnabledCronConfigs();
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(TaskType.CLEAR_PDF_CACHE, result.getFirst().getTaskType());
|
||||
assertEquals(TaskType.CLEANUP_DELETED_BOOKS, result.getFirst().getTaskType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCronConfigOrDefault_existingConfig() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", true);
|
||||
when(repository.findByTaskType(type)).thenReturn(Optional.of(entity));
|
||||
|
||||
@@ -88,7 +88,7 @@ class TaskCronServiceTest {
|
||||
|
||||
@Test
|
||||
void testGetCronConfigOrDefault_noConfig_returnsDefault() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
when(repository.findByTaskType(type)).thenReturn(Optional.empty());
|
||||
|
||||
CronConfig config = service.getCronConfigOrDefault(type);
|
||||
@@ -116,7 +116,7 @@ class TaskCronServiceTest {
|
||||
|
||||
@Test
|
||||
void testPatchCronConfig_updateExisting() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||
TaskCronConfigurationEntity entity = buildEntity(type, "0 0 1 * * *", false);
|
||||
|
||||
@@ -135,7 +135,7 @@ class TaskCronServiceTest {
|
||||
|
||||
@Test
|
||||
void testPatchCronConfig_createNew() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||
|
||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||
@@ -154,7 +154,7 @@ class TaskCronServiceTest {
|
||||
|
||||
@Test
|
||||
void testPatchCronConfig_invalidCronExpression_throws() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
BookLoreUser user = BookLoreUser.builder().id(10L).isDefaultPassword(false).build();
|
||||
|
||||
when(authService.getAuthenticatedUser()).thenReturn(user);
|
||||
@@ -223,7 +223,7 @@ class TaskCronServiceTest {
|
||||
|
||||
@Test
|
||||
void testValidateTaskTypeForCron_supported() {
|
||||
TaskType type = TaskType.CLEAR_PDF_CACHE;
|
||||
TaskType type = TaskType.CLEANUP_DELETED_BOOKS;
|
||||
assertDoesNotThrow(() -> {
|
||||
var method = TaskCronService.class.getDeclaredMethod("validateTaskTypeForCron", TaskType.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
+1
-1
@@ -264,7 +264,7 @@ class TaskHistoryServiceTest {
|
||||
List<TaskType> hiddenTypes = Arrays.asList(TaskType.values());
|
||||
TaskHistoryEntity dummyTask = TaskHistoryEntity.builder()
|
||||
.id("dummy")
|
||||
.type(TaskType.CLEAR_PDF_CACHE)
|
||||
.type(TaskType.CLEANUP_DELETED_BOOKS)
|
||||
.status(TaskStatus.FAILED)
|
||||
.progressPercentage(0)
|
||||
.createdAt(FIXED_TIME)
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ class TaskServiceTest {
|
||||
|
||||
@Test
|
||||
void testExecuteTaskThrowsForUnknownTaskType() {
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEAR_PDF_CACHE).triggeredByCron(false).build();
|
||||
TaskCreateRequest req = TaskCreateRequest.builder().taskType(TaskType.CLEANUP_DELETED_BOOKS).triggeredByCron(false).build();
|
||||
BookLoreUser user = new BookLoreUser();
|
||||
user.setId(1L);
|
||||
user.setUsername("user1");
|
||||
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package com.adityachandel.booklore.task.tasks;
|
||||
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.TaskCreateRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.TaskCreateResponse;
|
||||
import com.adityachandel.booklore.model.enums.TaskType;
|
||||
import com.adityachandel.booklore.task.TaskStatus;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ClearPdfCacheTaskTest {
|
||||
|
||||
@Mock
|
||||
private FileService fileService;
|
||||
|
||||
@InjectMocks
|
||||
private ClearPdfCacheTask clearPdfCacheTask;
|
||||
|
||||
private BookLoreUser user;
|
||||
private TaskCreateRequest request;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
user = BookLoreUser.builder()
|
||||
.permissions(new BookLoreUser.UserPermissions())
|
||||
.build();
|
||||
request = new TaskCreateRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatePermissions_shouldThrowException_whenUserCannotAccessTaskManager() {
|
||||
user.getPermissions().setCanAccessTaskManager(false);
|
||||
assertThrows(APIException.class, () -> clearPdfCacheTask.validatePermissions(user, request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void execute_shouldClearCache() {
|
||||
String cachePathStr = "/tmp/pdf-cache";
|
||||
when(fileService.getPdfCachePath()).thenReturn(cachePathStr);
|
||||
doNothing().when(fileService).clearCacheDirectory(cachePathStr);
|
||||
|
||||
TaskCreateResponse response = clearPdfCacheTask.execute(request);
|
||||
|
||||
assertEquals(TaskType.CLEAR_PDF_CACHE, response.getTaskType());
|
||||
assertEquals(TaskStatus.COMPLETED, response.getStatus());
|
||||
|
||||
verify(fileService).getPdfCachePath();
|
||||
verify(fileService).clearCacheDirectory(cachePathStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
void execute_shouldHandleException_whenClearCacheFails() {
|
||||
String cachePathStr = "/tmp/pdf-cache";
|
||||
when(fileService.getPdfCachePath()).thenReturn(cachePathStr);
|
||||
doThrow(new RuntimeException("Delete failed")).when(fileService).clearCacheDirectory(cachePathStr);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> clearPdfCacheTask.execute(request));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user