Stream CBZ contents directly from the archive instead of unzipping and caching files (#2229)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-10 10:41:34 -07:00
committed by GitHub
co-authored by acx10
parent af07110f4c
commit 4543381814
25 changed files with 550 additions and 779 deletions
@@ -16,7 +16,9 @@ public class ImageCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.startsWith("/api/v1/media/book/") && (uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover"))) {
if (uri.startsWith("/api/v1/media/book/") &&
(uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover") ||
uri.contains("/pdf/pages/") || uri.contains("/cbx/pages/"))) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600_000));
}
@@ -4,7 +4,6 @@ import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.bookdrop.BookDropService;
import com.adityachandel.booklore.service.reader.CbxReaderService;
import com.adityachandel.booklore.service.reader.PdfReaderService;
import com.adityachandel.booklore.service.IconService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@@ -21,9 +20,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
@AllArgsConstructor
@@ -31,27 +27,22 @@ import java.util.regex.Pattern;
@RequestMapping("/api/v1/media")
public class BookMediaController {
private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\x00-\\x7F]");
private final BookService bookService;
private final PdfReaderService pdfReaderService;
private final CbxReaderService cbxReaderService;
private final BookDropService bookDropService;
private final IconService iconService;
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@GetMapping("/book/{bookId}/thumbnail")
public ResponseEntity<Resource> getBookThumbnail(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
public ResponseEntity<Resource> getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
}
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
@GetMapping("/book/{bookId}/cover")
public ResponseEntity<Resource> getBookCover(
@Parameter(description = "ID of the book") @PathVariable long bookId) {
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookCover(bookId));
}
@@ -80,8 +71,7 @@ public class BookMediaController {
@Operation(summary = "Get bookdrop cover", description = "Retrieve the cover image for a specific bookdrop file.")
@ApiResponse(responseCode = "200", description = "Bookdrop cover returned successfully")
@GetMapping("/bookdrop/{bookdropId}/cover")
public ResponseEntity<Resource> getBookdropCover(
@Parameter(description = "ID of the bookdrop file") @PathVariable long bookdropId) {
public ResponseEntity<Resource> getBookdropCover(@Parameter(description = "ID of the bookdrop file") @PathVariable long bookdropId) {
Resource file = bookDropService.getBookdropCover(bookdropId);
String contentDisposition = "inline; filename=\"cover.jpg\"; filename*=UTF-8''cover.jpg";
return (file != null)
@@ -24,8 +24,7 @@ public class CbxReaderController {
@Operation(summary = "List pages in a CBX book", description = "Retrieve a list of available page numbers for a CBX 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) {
public List<Integer> listPages(@Parameter(description = "ID of the book") @PathVariable Long bookId) {
return cbxReaderService.getAvailablePages(bookId);
}
}
@@ -30,7 +30,6 @@ public enum AppSettingKey {
COVER_CROPPING_SETTINGS ("cover_cropping_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
AUTO_BOOK_SEARCH ("auto_book_search", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
SIMILAR_BOOK_RECOMMENDATION ("similar_book_recommendation", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
CBX_CACHE_SIZE_IN_MB ("cbx_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
PDF_CACHE_SIZE_IN_MB ("pdf_cache_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
MAX_FILE_UPLOAD_SIZE_IN_MB ("max_file_upload_size_in_mb", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
TELEMETRY_ENABLED ("telemetryEnabled", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_GLOBAL_PREFERENCES)),
@@ -19,7 +19,6 @@ public class AppSettings {
private boolean similarBookRecommendation;
private boolean opdsServerEnabled;
private String uploadPattern;
private Integer cbxCacheSizeInMb;
private Integer pdfCacheSizeInMb;
private Integer maxFileUploadSizeInMb;
private boolean remoteAuthEnabled;
@@ -3,15 +3,6 @@ package com.adityachandel.booklore.model.enums;
import lombok.Getter;
public enum TaskType {
CLEAR_CBX_CACHE(
false,
false,
true,
false,
"Clear CBX Cache",
"Clears temporarily extracted comic book files used by the reader."
),
CLEAR_PDF_CACHE(
false,
false,
@@ -134,7 +134,6 @@ public class AppSettingService {
builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
builder.telemetryEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.TELEMETRY_ENABLED, "true")));
builder.cbxCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
builder.pdfCacheSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.PDF_CACHE_SIZE_IN_MB, "5120")));
builder.maxFileUploadSizeInMb(Integer.parseInt(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
builder.metadataDownloadOnBookdrop(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.METADATA_DOWNLOAD_ON_BOOKDROP, "true")));
@@ -3,12 +3,8 @@ package com.adityachandel.booklore.service.reader;
import com.adityachandel.booklore.exception.ApiError;
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.ArchiveUtils;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils;
import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -23,222 +19,326 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Comparator;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.IntStream;
@Slf4j
@Service
@RequiredArgsConstructor
public class CbxReaderService {
private static final String CACHE_INFO_FILENAME = ".cache-info";
private static final String CBZ_EXTENSION = ".cbz";
private static final String CBR_EXTENSION = ".cbr";
private static final String CB7_EXTENSION = ".cb7";
private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"};
private static final Charset[] ENCODINGS_TO_TRY = {
StandardCharsets.UTF_8,
Charset.forName("Shift_JIS"),
StandardCharsets.ISO_8859_1,
Charset.forName("CP437"),
Charset.forName("MS932")
};
private static final int MAX_CACHE_ENTRIES = 50;
private static final int BUFFER_SIZE = 8192;
private static final Pattern NUMERIC_PATTERN = Pattern.compile("(\\d+)|(\\D+)");
private static final Set<String> SYSTEM_FILES = Set.of(".ds_store", "thumbs.db", "desktop.ini");
private final BookRepository bookRepository;
private final AppSettingService appSettingService;
private final FileService fileService;
private final Map<String, CachedArchiveMetadata> archiveCache = new ConcurrentHashMap<>();
private static class CachedArchiveMetadata {
final List<String> imageEntries;
final long lastModified;
final Charset successfulEncoding;
volatile long lastAccessed;
CachedArchiveMetadata(List<String> imageEntries, long lastModified, Charset successfulEncoding) {
this.imageEntries = List.copyOf(imageEntries);
this.lastModified = lastModified;
this.successfulEncoding = successfulEncoding;
this.lastAccessed = System.currentTimeMillis();
}
}
public List<Integer> getAvailablePages(Long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
String bookFullPath = FileUtils.getBookFullPath(bookEntity);
Path cbzPath = Path.of(bookFullPath);
Path cacheDir = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId));
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
Path cbxPath = getBookPath(bookId);
try {
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
long estimatedSize = estimateArchiveSize(cbzPath);
if (estimatedSize == -1) {
long fileSize = Files.size(cbzPath);
if (fileSize > maxCacheSizeBytes) {
log.warn("Cache skipped: Physical file size {} exceeds max cache size {} (Estimation failed)", fileSize, maxCacheSizeBytes);
throw ApiError.CACHE_TOO_LARGE.createException();
}
} else if (estimatedSize > maxCacheSizeBytes) {
log.warn("Cache skipped: Estimated archive size {} exceeds max cache size {}", estimatedSize, maxCacheSizeBytes);
throw ApiError.CACHE_TOO_LARGE.createException();
}
enforceCacheLimit();
if (needsCacheRefresh(cbzPath, cacheInfoPath)) {
log.info("Invalidating cache for book {}", bookId);
if (Files.exists(cacheDir)) FileUtils.deleteDirectoryRecursively(cacheDir);
Files.createDirectories(cacheDir);
extractCbxArchive(cbzPath, cacheDir);
writeCacheInfo(cbzPath, cacheInfoPath);
if (!Files.exists(cacheDir)) {
log.warn("Cache for book {} was deleted during enforcement. Re-extracting.", bookId);
Files.createDirectories(cacheDir);
extractCbxArchive(cbzPath, cacheDir);
writeCacheInfo(cbzPath, cacheInfoPath);
}
}
} catch (IOException e) {
log.error("Failed to cache CBZ for book {}", bookId, e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
}
try (var stream = Files.list(cacheDir)) {
List<Path> imageFiles = stream
.filter(p -> isImageFile(p.getFileName().toString()))
.sorted(Comparator.comparing(Path::getFileName))
.toList();
return java.util.stream.IntStream.rangeClosed(1, imageFiles.size())
List<String> imageEntries = getImageEntriesFromArchiveCached(cbxPath);
return IntStream.rangeClosed(1, imageEntries.size())
.boxed()
.collect(Collectors.toList());
} catch (IOException e) {
log.error("Failed to list pages for book {}", bookId, e);
return List.of();
log.error("Failed to read archive for book {}", bookId, e);
throw ApiError.FILE_READ_ERROR.createException("Failed to read archive: " + e.getMessage());
}
}
public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
Path bookDir = Path.of(fileService.getCbxCachePath(), String.valueOf(bookId));
List<Path> images;
try (Stream<Path> files = Files.list(bookDir)) {
images = files
.filter(p -> isImageFile(p.getFileName().toString()))
.sorted(Comparator.comparing(p -> p.getFileName().toString()))
.toList();
}
if (images.isEmpty()) {
Path cbxPath = getBookPath(bookId);
CachedArchiveMetadata metadata = getCachedMetadata(cbxPath);
validatePageRequest(bookId, page, metadata.imageEntries);
String entryName = metadata.imageEntries.get(page - 1);
streamEntryFromArchive(cbxPath, entryName, outputStream, metadata.successfulEncoding);
}
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, List<String> imageEntries) throws FileNotFoundException {
if (imageEntries.isEmpty()) {
throw new FileNotFoundException("No image files found for book: " + bookId);
}
if (page < 1 || page > images.size()) {
throw new FileNotFoundException("Page out of range: " + page);
}
Path pagePath = images.get(page - 1);
try (InputStream in = Files.newInputStream(pagePath)) {
IOUtils.copy(in, outputStream);
if (page < 1 || page > imageEntries.size()) {
throw new FileNotFoundException("Page " + page + " out of range [1-" + imageEntries.size() + "]");
}
}
private void extractCbxArchive(Path cbxPath, Path targetDir) throws IOException {
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
switch (type) {
case ZIP -> extractZipArchive(cbxPath, targetDir);
case SEVEN_ZIP -> extract7zArchive(cbxPath, targetDir);
case RAR -> extractRarArchive(cbxPath, targetDir);
default -> throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
private CachedArchiveMetadata getCachedMetadata(Path cbxPath) throws IOException {
String cacheKey = cbxPath.toString();
long currentModified = Files.getLastModifiedTime(cbxPath).toMillis();
CachedArchiveMetadata cached = archiveCache.get(cacheKey);
if (cached != null && cached.lastModified == currentModified) {
cached.lastAccessed = System.currentTimeMillis();
log.debug("Cache hit for archive: {}", cbxPath.getFileName());
return cached;
}
log.debug("Cache miss for archive: {}, scanning...", cbxPath.getFileName());
CachedArchiveMetadata newMetadata = scanArchiveMetadata(cbxPath);
archiveCache.put(cacheKey, newMetadata);
evictOldestCacheEntries();
return newMetadata;
}
private List<String> getImageEntriesFromArchiveCached(Path cbxPath) throws IOException {
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 {
String filename = cbxPath.getFileName().toString().toLowerCase();
long lastModified = Files.getLastModifiedTime(cbxPath).toMillis();
if (filename.endsWith(CBZ_EXTENSION)) {
return scanZipMetadata(cbxPath, lastModified);
} else if (filename.endsWith(CB7_EXTENSION)) {
List<String> entries = getImageEntriesFrom7z(cbxPath);
return new CachedArchiveMetadata(entries, lastModified, null);
} else if (filename.endsWith(CBR_EXTENSION)) {
List<String> entries = getImageEntriesFromRar(cbxPath);
return new CachedArchiveMetadata(entries, lastModified, null);
} else {
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
}
}
private void extractZipArchive(Path cbzPath, Path targetDir) throws IOException {
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
private void streamEntryFromArchive(Path cbxPath, String entryName, OutputStream outputStream, Charset cachedEncoding) throws IOException {
String filename = cbxPath.getFileName().toString().toLowerCase();
if (filename.endsWith(CBZ_EXTENSION)) {
streamEntryFromZip(cbxPath, entryName, outputStream, cachedEncoding);
} else if (filename.endsWith(CB7_EXTENSION)) {
streamEntryFrom7z(cbxPath, entryName, outputStream);
} else if (filename.endsWith(CBR_EXTENSION)) {
streamEntryFromRar(cbxPath, entryName, outputStream);
} else {
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
}
}
for (String encoding : encodingsToTry) {
Charset charset = Charset.forName(encoding);
private CachedArchiveMetadata scanZipMetadata(Path cbxPath, long lastModified) throws IOException {
String cacheKey = cbxPath.toString();
CachedArchiveMetadata oldCache = archiveCache.get(cacheKey);
if (oldCache != null && oldCache.successfulEncoding != null) {
try {
// Fast path: Try reading from Central Directory only
if (extractZipWithEncoding(cbzPath, targetDir, charset, true)) return;
List<String> entries = getImageEntriesFromZipWithEncoding(cbxPath, oldCache.successfulEncoding, true);
return new CachedArchiveMetadata(entries, lastModified, oldCache.successfulEncoding);
} catch (Exception e) {
log.debug("Fast path failed for encoding {}: {}", encoding, e.getMessage());
}
try {
// Slow path: Fallback to scanning local file headers
if (extractZipWithEncoding(cbzPath, targetDir, charset, false)) return;
} catch (Exception e) {
log.debug("Slow path failed for encoding {}: {}", encoding, e.getMessage());
log.debug("Cached encoding {} failed, trying others", oldCache.successfulEncoding);
}
}
throw new IOException("Unable to extract ZIP archive with any supported encoding");
for (Charset encoding : ENCODINGS_TO_TRY) {
try {
List<String> entries = getImageEntriesFromZipWithEncoding(cbxPath, encoding, true);
return new CachedArchiveMetadata(entries, lastModified, encoding);
} catch (Exception e) {
log.debug("ZIP fast path failed for encoding {}: {}", encoding, e.getMessage());
}
try {
List<String> entries = getImageEntriesFromZipWithEncoding(cbxPath, encoding, false);
return new CachedArchiveMetadata(entries, lastModified, encoding);
} catch (Exception e) {
log.debug("ZIP slow path failed for encoding {}: {}", encoding, e.getMessage());
}
}
throw new IOException("Unable to read ZIP archive with any supported encoding");
}
private boolean extractZipWithEncoding(Path cbzPath, Path targetDir, Charset charset, boolean useFastPath) throws IOException {
private List<String> getImageEntriesFromZipWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException {
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
org.apache.commons.compress.archivers.zip.ZipFile.builder()
.setPath(cbzPath)
.setPath(cbxPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(useFastPath)
.get()) {
var entries = zipFile.getEntries();
boolean foundImages = false;
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
List<String> entries = new ArrayList<>();
Enumeration<ZipArchiveEntry> enumeration = zipFile.getEntries();
while (enumeration.hasMoreElements()) {
ZipArchiveEntry entry = enumeration.nextElement();
if (!entry.isDirectory() && isImageFile(entry.getName())) {
String fileName = extractFileNameFromPath(entry.getName());
Path target = targetDir.resolve(fileName);
try (InputStream in = zipFile.getInputStream(entry)) {
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
foundImages = true;
}
entries.add(entry.getName());
}
}
return foundImages;
sortNaturally(entries);
return entries;
}
}
private void extract7zArchive(Path cb7Path, Path targetDir) throws IOException {
try (SevenZFile sevenZFile = SevenZFile.builder().setPath(cb7Path).get()) {
private void streamEntryFromZip(Path cbxPath, String entryName, OutputStream outputStream, Charset cachedEncoding) throws IOException {
if (cachedEncoding != null) {
if (streamEntryFromZipWithEncoding(cbxPath, entryName, outputStream, cachedEncoding, true)) {
return;
}
if (streamEntryFromZipWithEncoding(cbxPath, entryName, outputStream, cachedEncoding, false)) {
return;
}
}
for (Charset encoding : ENCODINGS_TO_TRY) {
if (encoding.equals(cachedEncoding)) continue;
try {
if (streamEntryFromZipWithEncoding(cbxPath, entryName, outputStream, encoding, true)) {
return;
}
} catch (Exception e) {
log.debug("ZIP stream fast path failed for encoding {}: {}", encoding, e.getMessage());
}
try {
if (streamEntryFromZipWithEncoding(cbxPath, entryName, outputStream, encoding, false)) {
return;
}
} catch (Exception e) {
log.debug("ZIP stream slow path failed for encoding {}: {}", encoding, e.getMessage());
}
}
throw new IOException("Unable to find entry in ZIP archive: " + entryName);
}
private boolean streamEntryFromZipWithEncoding(Path cbxPath, String entryName, OutputStream outputStream, Charset charset, boolean useFastPath) throws IOException {
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
org.apache.commons.compress.archivers.zip.ZipFile.builder()
.setPath(cbxPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(useFastPath)
.get()) {
ZipArchiveEntry entry = zipFile.getEntry(entryName);
if (entry != null) {
try (InputStream in = zipFile.getInputStream(entry)) {
IOUtils.copy(in, outputStream);
}
return true;
}
}
return false;
}
private List<String> getImageEntriesFrom7z(Path cbxPath) throws IOException {
List<String> entries = new ArrayList<>();
try (SevenZFile sevenZFile = SevenZFile.builder().setPath(cbxPath).get()) {
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (!entry.isDirectory() && isImageFile(entry.getName())) {
String fileName = extractFileNameFromPath(entry.getName());
Path target = targetDir.resolve(fileName);
try (OutputStream out = Files.newOutputStream(target)) {
copySevenZEntry(sevenZFile, out, entry.getSize());
}
entries.add(entry.getName());
}
}
}
sortNaturally(entries);
return entries;
}
private void streamEntryFrom7z(Path cbxPath, String entryName, OutputStream outputStream) throws IOException {
try (SevenZFile sevenZFile = SevenZFile.builder().setPath(cbxPath).get()) {
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (entry.getName().equals(entryName)) {
copySevenZEntry(sevenZFile, outputStream, entry.getSize());
return;
}
}
}
throw new FileNotFoundException("Entry not found in 7z archive: " + entryName);
}
private void copySevenZEntry(SevenZFile sevenZFile, OutputStream out, long size) throws IOException {
byte[] buffer = new byte[8192];
byte[] buffer = new byte[BUFFER_SIZE];
long remaining = size;
while (remaining > 0) {
int toRead = (int) Math.min(buffer.length, remaining);
int read = sevenZFile.read(buffer, 0, toRead);
if (read == -1) break;
if (read == -1) {
break;
}
out.write(buffer, 0, read);
remaining -= read;
}
}
private void extractRarArchive(Path cbrPath, Path targetDir) throws IOException {
try (Archive archive = new Archive(cbrPath.toFile())) {
List<FileHeader> headers = archive.getFileHeaders();
for (FileHeader header : headers) {
private List<String> getImageEntriesFromRar(Path cbxPath) throws IOException {
List<String> entries = new ArrayList<>();
try (Archive archive = new Archive(cbxPath.toFile())) {
for (FileHeader header : archive.getFileHeaders()) {
if (!header.isDirectory() && isImageFile(header.getFileName())) {
String fileName = extractFileNameFromPath(header.getFileName());
Path target = targetDir.resolve(fileName);
try (OutputStream out = Files.newOutputStream(target)) {
archive.extractFile(header, out);
}
entries.add(header.getFileName());
}
}
} catch (Exception e) {
throw new IOException("Failed to extract CBR archive", e);
throw new IOException("Failed to read RAR archive: " + e.getMessage(), e);
}
sortNaturally(entries);
return entries;
}
private String extractFileNameFromPath(String fullPath) {
String normalizedPath = fullPath.replace("\\", "/");
int lastSlash = normalizedPath.lastIndexOf('/');
return lastSlash >= 0 ? normalizedPath.substring(lastSlash + 1) : normalizedPath;
private void streamEntryFromRar(Path cbxPath, String entryName, OutputStream outputStream) throws IOException {
try (Archive archive = new Archive(cbxPath.toFile())) {
for (FileHeader header : archive.getFileHeaders()) {
if (header.getFileName().equals(entryName)) {
archive.extractFile(header, outputStream);
return;
}
}
} catch (Exception e) {
throw new IOException("Failed to extract from RAR archive: " + e.getMessage(), e);
}
throw new FileNotFoundException("Entry not found in RAR archive: " + entryName);
}
private boolean isImageFile(String name) {
if (!isContentEntry(name)) {
return false;
}
String lower = name.toLowerCase().replace("\\", "/");
String lower = name.toLowerCase().replace('\\', '/');
for (String extension : SUPPORTED_IMAGE_EXTENSIONS) {
if (lower.endsWith(extension)) {
return true;
@@ -248,197 +348,50 @@ public class CbxReaderService {
}
private boolean isContentEntry(String name) {
if (name == null) return false;
String norm = name.replace('\\', '/');
if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false;
String[] parts = norm.split("/");
for (String part : parts) {
if ("__MACOSX".equalsIgnoreCase(part)) return false;
if (name == null || name.isEmpty()) {
return false;
}
String normalized = name.replace('\\', '/');
if (normalized.startsWith("__MACOSX/") || normalized.contains("/__MACOSX/")) {
return false;
}
String baseName = baseName(normalized).toLowerCase();
if (baseName.startsWith("._") || baseName.startsWith(".")) {
return false;
}
if (SYSTEM_FILES.contains(baseName)) {
return false;
}
String base = baseName(norm);
if (base.startsWith("._")) return false;
if (base.startsWith(".")) return false;
if (".ds_store".equalsIgnoreCase(base)) return false;
return true;
}
private String baseName(String path) {
if (path == null) return null;
if (path == null || path.isEmpty()) {
return "";
}
int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
return slash >= 0 ? path.substring(slash + 1) : path;
}
private boolean needsCacheRefresh(Path cbzPath, Path cacheInfoPath) throws IOException {
if (!Files.exists(cacheInfoPath)) return true;
long currentLastModified = Files.getLastModifiedTime(cbzPath).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 cbzPath, Path cacheInfoPath) throws IOException {
long lastModified = Files.getLastModifiedTime(cbzPath).toMillis();
Files.writeString(cacheInfoPath, String.valueOf(lastModified), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
private void enforceCacheLimit() {
try {
Path cacheRoot = Path.of(fileService.getCbxCachePath());
if (!Files.exists(cacheRoot) || !Files.isDirectory(cacheRoot)) {
return;
}
long totalSize = 0L;
List<Path> cacheDirs;
try (Stream<Path> stream = Files.list(cacheRoot)) {
cacheDirs = stream.filter(Files::isDirectory).collect(Collectors.toList());
}
for (Path dir : cacheDirs) {
totalSize += getDirectorySize(dir);
}
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
while (totalSize > maxCacheSizeBytes && !cacheDirs.isEmpty()) {
Path leastRecentlyReadDir = cacheDirs.stream()
.min(Comparator.comparingLong(this::getLastReadTime))
.orElse(null);
long sizeFreed = getDirectorySize(leastRecentlyReadDir);
FileUtils.deleteDirectoryRecursively(leastRecentlyReadDir);
cacheDirs.remove(leastRecentlyReadDir);
totalSize -= sizeFreed;
log.info("Deleted cache directory {} to enforce cache size limit", leastRecentlyReadDir);
}
} catch (IOException e) {
log.error("Error enforcing cache size limit", e);
}
}
private long getLastReadTime(Path cacheDir) {
Path cacheInfoPath = cacheDir.resolve(CACHE_INFO_FILENAME);
if (!Files.exists(cacheInfoPath)) {
return Long.MIN_VALUE;
}
try {
String content = Files.readString(cacheInfoPath).trim();
return Long.parseLong(content);
} catch (Exception e) {
return Long.MIN_VALUE;
}
}
private long getDirectorySize(Path dir) {
try (Stream<Path> paths = Files.walk(dir)) {
return paths
.filter(Files::isRegularFile)
.mapToLong(p -> {
try {
return Files.size(p);
} catch (IOException e) {
return 0L;
}
})
.sum();
} catch (IOException e) {
return 0L;
}
}
private long estimateArchiveSize(Path cbxPath) {
try {
ArchiveUtils.ArchiveType type = ArchiveUtils.detectArchiveType(cbxPath.toFile());
return switch (type) {
case ZIP -> estimateCbzArchiveSize(cbxPath);
case SEVEN_ZIP -> estimateCb7ArchiveSize(cbxPath);
case RAR -> estimateCbrArchiveSize(cbxPath);
default -> Long.MAX_VALUE;
};
} catch (Exception e) {
log.warn("Failed to estimate archive size for {}", cbxPath, e);
}
return -1;
}
private long estimateCbzArchiveSize(Path cbxPath) throws IOException {
String[] encodingsToTry = {"UTF-8", "Shift_JIS", "ISO-8859-1", "CP437", "MS932"};
for (String encoding : encodingsToTry) {
Charset charset = Charset.forName(encoding);
try {
long size = estimateCbzWithEncoding(cbxPath, charset, true);
if (size > 0) return size;
} catch (Exception e) {
log.debug("Fast path estimation failed for encoding {}: {}", encoding, e.getMessage());
}
try {
long size = estimateCbzWithEncoding(cbxPath, charset, false);
if (size > 0) return size;
} catch (Exception e) {
log.debug("Slow path estimation failed for encoding {}: {}", encoding, e.getMessage());
}
}
log.warn("Unable to estimate archive size for {} with any supported encoding", cbxPath);
return -1;
}
private long estimateCbzWithEncoding(Path cbxPath, Charset charset, boolean useFastPath) throws IOException {
try (org.apache.commons.compress.archivers.zip.ZipFile zipFile =
org.apache.commons.compress.archivers.zip.ZipFile.builder()
.setPath(cbxPath)
.setCharset(charset)
.setUseUnicodeExtraFields(true)
.setIgnoreLocalFileHeader(useFastPath)
.get()) {
long total = 0;
var entries = zipFile.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
if (!entry.isDirectory() && isImageFile(entry.getName())) {
long size = entry.getSize();
total += (size >= 0) ? size : entry.getCompressedSize();
private void sortNaturally(List<String> entries) {
entries.sort((s1, s2) -> {
Matcher m1 = NUMERIC_PATTERN.matcher(s1);
Matcher m2 = NUMERIC_PATTERN.matcher(s2);
while (m1.find() && m2.find()) {
String part1 = m1.group();
String part2 = m2.group();
if (part1.matches("\\d+") && part2.matches("\\d+")) {
int cmp = Integer.compare(
Integer.parseInt(part1),
Integer.parseInt(part2)
);
if (cmp != 0) return cmp;
} else {
int cmp = part1.compareToIgnoreCase(part2);
if (cmp != 0) return cmp;
}
}
return total > 0 ? total : -1;
}
}
private long estimateCb7ArchiveSize(Path cbxPath) throws IOException {
try (SevenZFile sevenZFile = SevenZFile.builder().setPath(cbxPath).get()) {
SevenZArchiveEntry entry;
long total = 0;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (!entry.isDirectory() && isImageFile(entry.getName())) {
total += entry.getSize();
}
}
return total;
}
}
private long estimateCbrArchiveSize(Path cbxPath) throws IOException, RarException {
try (Archive archive = new Archive(cbxPath.toFile())) {
long total = 0;
for (FileHeader header : archive.getFileHeaders()) {
if (!header.isDirectory() && isImageFile(header.getFileName())) {
total += header.getFullUnpackSize();
}
}
return total;
}
}
private long mbToBytes(int mb) {
return mb * 1024L * 1024L;
return s1.compareToIgnoreCase(s2);
});
}
}
@@ -4,14 +4,6 @@ import lombok.Getter;
public enum TaskType {
CLEAR_CBX_CACHE(
false,
false,
true,
false,
"Clear CBX Cache",
"Clears temporarily extracted comic book files used by the reader."
),
CLEAR_PDF_CACHE(
false,
false,
@@ -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 ClearCbxCacheTask 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_CBX_CACHE);
long startTime = System.currentTimeMillis();
log.info("{}: Task started", getTaskType());
try {
fileService.clearCacheDirectory(fileService.getCbxCachePath());
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 CBX 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_CBX_CACHE;
}
@Override
public String getMetadata() {
return TaskMetadataHelper.getCacheSizeString(fileService.getCbxCachePath());
}
}
@@ -8,9 +8,6 @@ import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
@@ -103,10 +100,6 @@ public class FileService {
return Paths.get(appProperties.getPathConfig(), "metadata_backup", String.valueOf(bookId)).toString();
}
public String getCbxCachePath() {
return Paths.get(appProperties.getPathConfig(), "cbx_cache").toString();
}
public String getPdfCachePath() {
return Paths.get(appProperties.getPathConfig(), "pdf_cache").toString();
}
@@ -161,7 +154,7 @@ public class FileService {
log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage());
return null;
}
log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)");
return null;
}
@@ -373,7 +366,7 @@ public class FileService {
boolean isExtremelyTall = settings.isVerticalCroppingEnabled() && heightToWidthRatio > threshold;
if (isExtremelyTall) {
int croppedHeight = (int) (width * TARGET_COVER_ASPECT_RATIO);
log.debug("Cropping tall image: {}x{} (ratio {}) -> {}x{}, smartCrop={}",
log.debug("Cropping tall image: {}x{} (ratio {}) -> {}x{}, smartCrop={}",
width, height, String.format("%.2f", heightToWidthRatio), width, croppedHeight, smartCrop);
return cropFromTop(image, width, croppedHeight, smartCrop);
}
@@ -381,7 +374,7 @@ public class FileService {
boolean isExtremelyWide = settings.isHorizontalCroppingEnabled() && widthToHeightRatio > threshold;
if (isExtremelyWide) {
int croppedWidth = (int) (height / TARGET_COVER_ASPECT_RATIO);
log.debug("Cropping wide image: {}x{} (ratio {}) -> {}x{}, smartCrop={}",
log.debug("Cropping wide image: {}x{} (ratio {}) -> {}x{}, smartCrop={}",
width, height, String.format("%.2f", widthToHeightRatio), croppedWidth, height, smartCrop);
return cropFromLeft(image, croppedWidth, height, smartCrop);
}
@@ -395,7 +388,7 @@ public class FileService {
int contentStartY = findContentStartY(image);
int margin = (int) (targetHeight * SMART_CROP_MARGIN_PERCENT);
startY = Math.max(0, contentStartY - margin);
int maxStartY = image.getHeight() - targetHeight;
startY = Math.min(startY, maxStartY);
}
@@ -408,7 +401,7 @@ public class FileService {
int contentStartX = findContentStartX(image);
int margin = (int) (targetWidth * SMART_CROP_MARGIN_PERCENT);
startX = Math.max(0, contentStartX - margin);
int maxStartX = image.getWidth() - targetWidth;
startX = Math.min(startX, maxStartX);
}
@@ -457,8 +450,8 @@ public class FileService {
int r1 = (rgb1 >> 16) & 0xFF, g1 = (rgb1 >> 8) & 0xFF, b1 = rgb1 & 0xFF;
int r2 = (rgb2 >> 16) & 0xFF, g2 = (rgb2 >> 8) & 0xFF, b2 = rgb2 & 0xFF;
return Math.abs(r1 - r2) <= SMART_CROP_COLOR_TOLERANCE
&& Math.abs(g1 - g2) <= SMART_CROP_COLOR_TOLERANCE
&& Math.abs(b1 - b2) <= SMART_CROP_COLOR_TOLERANCE;
&& Math.abs(g1 - g2) <= SMART_CROP_COLOR_TOLERANCE
&& Math.abs(b1 - b2) <= SMART_CROP_COLOR_TOLERANCE;
}
public static void setBookCoverPath(BookMetadataEntity bookMetadataEntity) {