Implement support for comic book files (CBZ, CBR and CB7)

This commit is contained in:
aditya.chandel
2025-05-23 22:58:23 -06:00
committed by Aditya Chandel
parent 25ee510379
commit ff64362edb
56 changed files with 1617 additions and 141 deletions
+2
View File
@@ -67,6 +67,8 @@ dependencies {
// --- API Documentation ---
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.6'
implementation 'org.apache.commons:commons-compress:1.27.1'
implementation 'com.github.junrar:junrar:7.5.5'
}
hibernate {
@@ -0,0 +1,22 @@
package com.adityachandel.booklore.config;
import com.adityachandel.booklore.service.AppSettingService;
import jakarta.servlet.MultipartConfigElement;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement(AppSettingService appSettingService) {
MultipartConfigFactory factory = new MultipartConfigFactory();
long maxSizeMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
factory.setMaxFileSize(DataSize.ofMegabytes(maxSizeMb));
factory.setMaxRequestSize(DataSize.ofMegabytes(maxSizeMb));
return factory.createMultipartConfig();
}
}
@@ -51,7 +51,8 @@ public class SecurityConfig {
"/api/v1/settings",
"/api/v1/setup",
"/api/v1/setup/**",
"/api/v1/opds/*/cover.jpg"
"/api/v1/opds/*/cover.jpg",
"/api/v1/cbx/*/pages/*"
).permitAll()
.anyRequest().authenticated()
)
@@ -0,0 +1,29 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.CbxReaderService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/api/v1/cbx")
@RequiredArgsConstructor
public class CbxReaderController {
private final CbxReaderService cbxReaderService;
@GetMapping("/{bookId}/pages")
public List<Integer> listPages(@PathVariable Long bookId) {
return cbxReaderService.getAvailablePages(bookId);
}
@GetMapping("/{bookId}/pages/{pageNumber}")
public void getPage(@PathVariable Long bookId, @PathVariable int pageNumber, HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
cbxReaderService.streamPageImage(bookId, pageNumber, response.getOutputStream());
}
}
@@ -17,7 +17,8 @@ public enum ApiError {
IMAGE_NOT_FOUND(HttpStatus.NOT_FOUND, "Image not found or not readable"),
INVALID_FILE_FORMAT(HttpStatus.BAD_REQUEST, "Invalid file format, only pdf and epub are supported"),
LIBRARY_NOT_FOUND(HttpStatus.NOT_FOUND, "Library not found with ID: %d"),
FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: 100 MB"),
FILE_TOO_LARGE(HttpStatus.BAD_REQUEST, "File size exceeds the limit: %d MB"),
CACHE_TOO_LARGE(HttpStatus.BAD_REQUEST, "Book archive is too large to cache with current settings"),
DIRECTORY_CREATION_FAILED(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to create the directory: %s"),
INVALID_LIBRARY_PATH(HttpStatus.BAD_REQUEST, "Invalid library path"),
FILE_ALREADY_EXISTS(HttpStatus.CONFLICT, "File already exists"),
@@ -60,6 +60,10 @@ public class BookLoreUserTransformer {
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.EpubReaderSetting.class);
userSettings.setEpubReaderSetting(value);
}
case CBX_READER_SETTING -> {
var value = objectMapper.readValue(jsonValue, BookLoreUser.UserSettings.CbxReaderSetting.class);
userSettings.setCbxReaderSetting(value);
}
case SIDEBAR_LIBRARY_SORTING -> {
var value = objectMapper.readValue(jsonValue, SidebarSortOption.class);
userSettings.setSidebarLibrarySorting(value);
@@ -23,5 +23,6 @@ public class Book {
private BookMetadata metadata;
private PdfProgress pdfProgress;
private EpubProgress epubProgress;
private CbxProgress cbxProgress;
private List<Shelf> shelves;
}
@@ -1,6 +1,8 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
import com.adityachandel.booklore.model.enums.CbxPageSpread;
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import lombok.AllArgsConstructor;
import lombok.Builder;
@@ -36,6 +38,7 @@ public class BookLoreUser {
public PerBookSetting perBookSetting;
public PdfReaderSetting pdfReaderSetting;
public EpubReaderSetting epubReaderSetting;
public CbxReaderSetting cbxReaderSetting;
public SidebarSortOption sidebarLibrarySorting;
public SidebarSortOption sidebarShelfSorting;
@@ -50,7 +53,6 @@ public class BookLoreUser {
private String flow;
}
@Data
@Builder
@AllArgsConstructor
@@ -60,6 +62,15 @@ public class BookLoreUser {
private String pageZoom;
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public static class CbxReaderSetting {
private CbxPageSpread pageSpread;
private CbxPageViewMode pageViewMode;
}
@Data
@Builder
@AllArgsConstructor
@@ -67,6 +78,7 @@ public class BookLoreUser {
public static class PerBookSetting {
private GlobalOrIndividual pdf;
private GlobalOrIndividual epub;
private GlobalOrIndividual cbx;
public enum GlobalOrIndividual {
Global, Individual
@@ -8,4 +8,5 @@ import lombok.Data;
public class BookViewerSettings {
private PdfViewerPreferences pdfSettings;
private EpubViewerPreferences epubSettings;
private CbxViewerPreferences cbxSettings;
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.model.dto;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class CbxProgress {
@NotNull
Integer page;
@NotNull
Float percentage;
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.model.dto;
import com.adityachandel.booklore.model.enums.CbxPageSpread;
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class CbxViewerPreferences {
private Long bookId;
private CbxPageSpread pageSpread;
private CbxPageViewMode pageViewMode;
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.model.dto.request;
import com.adityachandel.booklore.model.dto.CbxProgress;
import com.adityachandel.booklore.model.dto.EpubProgress;
import com.adityachandel.booklore.model.dto.PdfProgress;
import jakarta.validation.constraints.AssertTrue;
@@ -12,9 +13,10 @@ public class ReadProgressRequest {
private Long bookId;
private EpubProgress epubProgress;
private PdfProgress pdfProgress;
private CbxProgress cbxProgress;
@AssertTrue(message = "Either epubProgress or pdfProgress must be provided")
public boolean isProgressValid() {
return epubProgress != null || pdfProgress != null;
return epubProgress != null || pdfProgress != null || cbxProgress != null;
}
}
@@ -5,16 +5,19 @@ import lombok.Getter;
@Getter
public enum AppSettingKey {
QUICK_BOOK_MATCH("quick_book_match", true),
OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true),
AUTO_BOOK_SEARCH("auto_book_search", false),
COVER_IMAGE_RESOLUTION("cover_image_resolution", false),
SIMILAR_BOOK_RECOMMENDATION("similar_book_recommendation", false),
UPLOAD_FILE_PATTERN("upload_file_pattern", false),
OPDS_SERVER_ENABLED("opds_server_enabled", false),
OIDC_ENABLED("oidc_enabled", false),
OIDC_PROVIDER_DETAILS("oidc_provider_details", true),
OIDC_AUTO_PROVISION_DETAILS("oidc_auto_provision_details", true),
SIDEBAR_LIBRARY_SORTING("sidebar_library_sorting", true),
SIDEBAR_SHELF_SORTING("sidebar_shelf_sorting", true);
CBX_CACHE_SIZE_IN_MB("cbx_cache_size_in_mb", false),
MAX_FILE_UPLOAD_SIZE_IN_MB("max_file_upload_size_in_mb", false);
private final String dbKey;
private final boolean isJson;
@@ -17,6 +17,8 @@ public class AppSettings {
private boolean similarBookRecommendation;
private boolean opdsServerEnabled;
private String uploadPattern;
private Integer cbxCacheSizeInMb;
private Integer maxFileUploadSizeInMb;
private boolean remoteAuthEnabled;
private boolean oidcEnabled;
@@ -7,6 +7,7 @@ public enum UserSettingKey {
PER_BOOK_SETTING("perBookSetting", true),
PDF_READER_SETTING("pdfReaderSetting", true),
EPUB_READER_SETTING("epubReaderSetting", true),
CBX_READER_SETTING("cbxReaderSetting", true),
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true);
@@ -0,0 +1,36 @@
package com.adityachandel.booklore.model.entity;
import com.adityachandel.booklore.model.enums.CbxPageSpread;
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "cbx_viewer_preference", uniqueConstraints = {
@UniqueConstraint(columnNames = {"user_id", "book_id"})
})
public class CbxViewerPreferencesEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id", nullable = false)
private Long userId;
@Column(name = "book_id", nullable = false)
private Long bookId;
@Column(name = "spread")
@Enumerated(EnumType.STRING)
private CbxPageSpread pageSpread;
@Column(name = "view_mode")
@Enumerated(EnumType.STRING)
private CbxPageViewMode pageViewMode;
}
@@ -40,4 +40,10 @@ public class UserBookProgressEntity {
@Column(name = "epub_progress_percent")
private Float epubProgressPercent;
@Column(name = "cbx_progress")
private Integer cbxProgress;
@Column(name = "cbx_progress_percent")
private Float cbxProgressPercent;
}
@@ -1,5 +1,5 @@
package com.adityachandel.booklore.model.enums;
public enum BookFileType {
PDF, EPUB
PDF, EPUB, CBX
}
@@ -0,0 +1,6 @@
package com.adityachandel.booklore.model.enums;
public enum CbxPageSpread {
EVEN,
ODD
}
@@ -0,0 +1,6 @@
package com.adityachandel.booklore.model.enums;
public enum CbxPageViewMode {
SINGLE_PAGE,
TWO_PAGE
}
@@ -0,0 +1,14 @@
package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface CbxViewerPreferencesRepository extends JpaRepository<CbxViewerPreferencesEntity, Long> {
Optional<CbxViewerPreferencesEntity> findByBookIdAndUserId(long bookId, Long id);
}
@@ -77,6 +77,8 @@ public class AppSettingService {
builder.similarBookRecommendation(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true")));
builder.opdsServerEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false")));
builder.oidcEnabled(Boolean.parseBoolean(getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false")));
builder.cbxCacheSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.CBX_CACHE_SIZE_IN_MB, "5120")));
builder.maxFileUploadSizeInMb(Integer.parseInt(getOrCreateSetting(AppSettingKey.MAX_FILE_UPLOAD_SIZE_IN_MB, "100")));
return builder.build();
}
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.mapper.BookMetadataMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.CbxProgress;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshOptions;
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
@@ -19,6 +20,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.service.metadata.parser.BookParser;
@@ -54,6 +56,7 @@ public class BookMetadataService {
private final FileService fileService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final Map<MetadataProvider, BookParser> parserMap;
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
@@ -438,9 +441,10 @@ public class BookMetadataService {
switch (book.getBookType()) {
case PDF -> pdfProcessor.generateCover(book);
case EPUB -> epubProcessor.generateCover(book);
case CBX -> cbxProcessor.generateCover(book);
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType());
}
log.info("{} Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
}
@Transactional
@@ -39,6 +39,7 @@ public class BooksService {
private final BookRepository bookRepository;
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
private final ShelfRepository shelfRepository;
private final FileService fileService;
private final BookMapper bookMapper;
@@ -67,6 +68,13 @@ public class BooksService {
.zoom(pdfPref.getZoom())
.spread(pdfPref.getSpread())
.build()));
} else if (bookEntity.getBookType() == BookFileType.CBX) {
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
.bookId(bookId)
.pageViewMode(cbxPref.getPageViewMode())
.pageSpread(cbxPref.getPageSpread())
.build()));
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
@@ -111,6 +119,22 @@ public class BooksService {
epubPrefs.setFlow(epubSettings.getFlow());
epubViewerPreferencesRepository.save(epubPrefs);
} else if (bookEntity.getBookType() == BookFileType.CBX) {
CbxViewerPreferencesEntity cbxPrefs = cbxViewerPreferencesRepository
.findByBookIdAndUserId(bookId, user.getId())
.orElseGet(() -> {
CbxViewerPreferencesEntity newPrefs = CbxViewerPreferencesEntity.builder()
.bookId(bookId)
.userId(user.getId())
.build();
return cbxViewerPreferencesRepository.save(newPrefs);
});
CbxViewerPreferences cbxSettings = bookViewerSettings.getCbxSettings();
cbxPrefs.setPageSpread(cbxSettings.getPageSpread());
cbxPrefs.setPageViewMode(cbxSettings.getPageViewMode());
cbxViewerPreferencesRepository.save(cbxPrefs);
} else {
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
}
@@ -137,6 +161,12 @@ public class BooksService {
.percentage(userProgress.getEpubProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.CBX) {
book.setCbxProgress(CbxProgress.builder()
.page(userProgress.getCbxProgress())
.percentage(userProgress.getCbxProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
if (!withDescription) {
@@ -180,6 +210,12 @@ public class BooksService {
.percentage(userProgress.getPdfProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.CBX) {
book.setCbxProgress(CbxProgress.builder()
.page(userProgress.getCbxProgress())
.percentage(userProgress.getCbxProgressPercent())
.build());
}
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
return book;
})
@@ -236,6 +272,9 @@ public class BooksService {
} else if (book.getBookType() == BookFileType.PDF && request.getPdfProgress() != null) {
userBookProgress.setPdfProgress(request.getPdfProgress().getPage());
userBookProgress.setPdfProgressPercent(request.getPdfProgress().getPercentage());
} else if (book.getBookType() == BookFileType.CBX && request.getCbxProgress() != null) {
userBookProgress.setCbxProgress(request.getCbxProgress().getPage());
userBookProgress.setCbxProgressPercent(request.getCbxProgress().getPercentage());
}
userBookProgressRepository.save(userBookProgress);
}
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class CbxMetadataExtractor implements UploadedFileMetadataExtractor {
@Override
public UploadedFileMetadata extractMetadata(String filePath) {
UploadedFileMetadata metadata = new UploadedFileMetadata();
String title = FilenameUtils.getBaseName(filePath);
metadata.setTitle(title);
return metadata;
}
}
@@ -0,0 +1,330 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository;
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;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.pdfbox.io.IOUtils;
import org.springframework.stereotype.Service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
@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 final BookRepository bookRepository;
private final AppSettingService appSettingService;
private final FileService fileService;
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);
try {
long maxCacheSizeBytes = mbToBytes(appSettingService.getAppSettings().getCbxCacheSizeInMb());
long estimatedSize = estimateArchiveSize(cbzPath);
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);
return List.of();
}
try (var stream = Files.list(cacheDir)) {
return stream
.filter(p -> p.toString().endsWith(".jpg"))
.sorted(Comparator.comparing(Path::getFileName))
.map(p -> extractPageNumber(p.getFileName().toString()))
.filter(p -> p != -1)
.collect(Collectors.toList());
} catch (IOException e) {
log.error("Failed to list pages for book {}", bookId, e);
return List.of();
}
}
public void streamPageImage(Long bookId, int page, OutputStream outputStream) throws IOException {
Path pagePath = Path.of(fileService.getCbxCachePath(), 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)) {
IOUtils.copy(in, outputStream);
}
}
private void extractCbxArchive(Path cbxPath, Path targetDir) throws IOException {
String filename = cbxPath.getFileName().toString().toLowerCase();
if (filename.endsWith(CBZ_EXTENSION)) {
extractZipArchive(cbxPath, targetDir);
} else if (filename.endsWith(CB7_EXTENSION)) {
extract7zArchive(cbxPath, targetDir);
} else if (filename.endsWith(CBR_EXTENSION)) {
extractRarArchive(cbxPath, targetDir);
} else {
throw new IOException("Unsupported archive format: " + cbxPath.getFileName());
}
}
private void extractZipArchive(Path cbzPath, Path targetDir) throws IOException {
try (InputStream fis = Files.newInputStream(cbzPath);
ZipInputStream zis = new ZipInputStream(fis)) {
ZipEntry entry;
int index = 1;
while ((entry = zis.getNextEntry()) != null) {
isImageFile(entry.getName());
if (!entry.isDirectory() && isImageFile(entry.getName())) {
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
}
zis.closeEntry();
}
}
}
private void extract7zArchive(Path cb7Path, Path targetDir) throws IOException {
try (SevenZFile sevenZFile = new SevenZFile(cb7Path.toFile())) {
SevenZArchiveEntry entry;
int index = 1;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (!entry.isDirectory() && isImageFile(entry.getName())) {
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
try (OutputStream out = Files.newOutputStream(target)) {
copySevenZEntry(sevenZFile, out, entry.getSize());
}
}
}
}
}
private void copySevenZEntry(SevenZFile sevenZFile, OutputStream out, long size) throws IOException {
byte[] buffer = new byte[8192];
long read = 0;
int count;
while (read < size && (count = sevenZFile.read(buffer, 0, (int) Math.min(buffer.length, size - read))) > 0) {
out.write(buffer, 0, count);
read += count;
}
}
private void extractRarArchive(Path cbrPath, Path targetDir) throws IOException {
try (Archive archive = new Archive(cbrPath.toFile())) {
List<FileHeader> headers = archive.getFileHeaders();
int index = 1;
for (FileHeader header : headers) {
if (!header.isDirectory() && isImageFile(header.getFileName())) {
Path target = targetDir.resolve(String.format("%04d.jpg", index++));
try (OutputStream out = Files.newOutputStream(target)) {
archive.extractFile(header, out);
}
}
}
} catch (Exception e) {
throw new IOException("Failed to extract CBR archive", e);
}
}
private boolean isImageFile(String name) {
String lower = name.toLowerCase().replace("\\", "/");
return lower.endsWith(".jpg") || lower.endsWith(".jpeg") || lower.endsWith(".png");
}
private int extractPageNumber(String filename) {
try {
return Integer.parseInt(filename.replaceAll("\\D+", ""));
} catch (Exception e) {
return -1;
}
}
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 {
String name = cbxPath.getFileName().toString().toLowerCase();
if (name.endsWith(CBZ_EXTENSION)) {
return estimateCbzArchiveSize(cbxPath);
} else if (name.endsWith(CB7_EXTENSION)) {
return estimateCb7ArchiveSize(cbxPath);
} else if (name.endsWith(CBR_EXTENSION)) {
return estimateCbrArchiveSize(cbxPath);
}
} catch (Exception e) {
log.warn("Failed to estimate archive size for {}", cbxPath, e);
}
return Long.MAX_VALUE;
}
private long estimateCbzArchiveSize(Path cbxPath) throws IOException {
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(cbxPath))) {
ZipEntry entry;
long total = 0;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory() && isImageFile(entry.getName())) {
total += entry.getCompressedSize();
}
}
return total;
}
}
private long estimateCb7ArchiveSize(Path cbxPath) throws IOException {
try (SevenZFile sevenZFile = new SevenZFile(cbxPath.toFile())) {
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;
}
}
@@ -1,17 +1,13 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import com.adityachandel.booklore.util.FileUtils;
import io.documentnode.epub4j.domain.Author;
import io.documentnode.epub4j.domain.Book;
import io.documentnode.epub4j.epub.EpubReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
@@ -20,21 +16,23 @@ import java.util.stream.Collectors;
@Slf4j
@Service
public class EpubMetadataExtractor implements BookFileMetadataExtractor {
public class EpubMetadataExtractor implements UploadedFileMetadataExtractor {
@Override
public UploadedFileMetadata extractMetadata(String filePath) {
UploadedFileMetadata metadata = new UploadedFileMetadata();
try (FileInputStream fis = new FileInputStream(filePath)) {
Book epubBook = new EpubReader().readEpub(fis);
Book epub = new EpubReader().readEpub(fis);
String title = epubBook.getTitle();
String title = epub.getTitle();
if (title != null && !title.isBlank()) {
metadata.setTitle(title);
} else {
metadata.setTitle(FilenameUtils.getBaseName(filePath));
}
List<Author> epubAuthors = epubBook.getMetadata().getAuthors();
List<Author> epubAuthors = epub.getMetadata().getAuthors();
if (!epubAuthors.isEmpty()) {
Set<String> authors = epubAuthors.stream()
.map(author -> author.getFirstname() + " " + author.getLastname())
@@ -3,13 +3,13 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
@@ -31,21 +31,24 @@ import java.util.Optional;
@Slf4j
public class FileUploadService {
private static final long MAX_FILE_SIZE = 100 * 1024 * 1024;
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String EPUB_MIME_TYPE = "application/epub+zip";
private static final String CBZ_MIME_TYPE = "application/x-cbz";
private static final String CBR_MIME_TYPE = "application/x-cbr";
private static final String CB7_MIME_TYPE = "application/x-cb7";
private final LibraryRepository libraryRepository;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final PdfMetadataExtractor pdfMetadataExtractor;
private final EpubMetadataExtractor epubMetadataExtractor;
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
validateFile(file);
Integer uploadSizeInMb = appSettingService.getAppSettings().getMaxFileUploadSizeInMb();
validateFile(file, uploadSizeInMb);
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
@@ -62,18 +65,12 @@ public class FileUploadService {
try {
file.transferTo(tempPath);
String fileType = Objects.requireNonNull(file.getContentType());
if (fileType.equalsIgnoreCase(PDF_MIME_TYPE)) {
metadata = pdfMetadataExtractor.extractMetadata(tempPath.toString());
} else if (fileType.equalsIgnoreCase(EPUB_MIME_TYPE)) {
metadata = epubMetadataExtractor.extractMetadata(tempPath.toString());
} else {
throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
}
metadata = extractMetadata(file, tempPath);
String title = Optional.ofNullable(metadata.getTitle()).orElse("").trim();
String authors = metadata.getAuthors() != null ? String.join(", ", metadata.getAuthors()) : "";
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
String relativePath = resolveUploadPath(uploadPattern, title, authors, file.getOriginalFilename());
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
@@ -100,13 +97,35 @@ public class FileUploadService {
}
}
private void validateFile(MultipartFile file) {
private UploadedFileMetadata extractMetadata(MultipartFile file, Path tempPath) throws IOException {
String fileType = Objects.requireNonNull(file.getContentType());
return switch (fileType.toLowerCase()) {
case PDF_MIME_TYPE -> pdfMetadataExtractor.extractMetadata(tempPath.toString());
case EPUB_MIME_TYPE -> epubMetadataExtractor.extractMetadata(tempPath.toString());
case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> new UploadedFileMetadata();
default -> throw ApiError.INVALID_FILE_FORMAT.createException("Unsupported file type.");
};
}
private boolean isSupportedContentType(String fileType) {
return PDF_MIME_TYPE.equals(fileType)
|| EPUB_MIME_TYPE.equals(fileType)
|| CBZ_MIME_TYPE.equals(fileType)
|| CBR_MIME_TYPE.equals(fileType)
|| CB7_MIME_TYPE.equals(fileType);
}
private boolean isFileTooLarge(MultipartFile file, int uploadSizeInMb) {
return file.getSize() > uploadSizeInMb * 1024L * 1024L;
}
private void validateFile(MultipartFile file, int uploadSizeInMb) {
String fileType = file.getContentType();
if (!PDF_MIME_TYPE.equals(fileType) && !EPUB_MIME_TYPE.equals(fileType)) {
if (!isSupportedContentType(fileType)) {
throw ApiError.INVALID_FILE_FORMAT.createException();
}
if (file.getSize() > MAX_FILE_SIZE) {
throw ApiError.FILE_TOO_LARGE.createException();
if (isFileTooLarge(file, uploadSizeInMb)) {
throw ApiError.FILE_TOO_LARGE.createException(uploadSizeInMb);
}
}
@@ -129,6 +148,7 @@ public class FileUploadService {
return switch (fileType) {
case PDF -> pdfProcessor.processFile(libraryFile, false);
case EPUB -> epubProcessor.processFile(libraryFile, false);
case CBX -> cbxProcessor.processFile(libraryFile, false);
};
}
@@ -160,6 +180,7 @@ public class FileUploadService {
return switch (fileType.toLowerCase()) {
case PDF_MIME_TYPE -> BookFileType.PDF;
case EPUB_MIME_TYPE -> BookFileType.EPUB;
case CBZ_MIME_TYPE, CBR_MIME_TYPE, CB7_MIME_TYPE -> BookFileType.CBX;
default -> null;
};
}
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.fileprocessor.CbxProcessor;
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
import com.adityachandel.booklore.util.FileUtils;
@@ -40,6 +41,7 @@ public class LibraryProcessingService {
private final NotificationService notificationService;
private final PdfProcessor pdfProcessor;
private final EpubProcessor epubProcessor;
private final CbxProcessor cbxProcessor;
private final BookRepository bookRepository;
private final EntityManager entityManager;
private final TransactionTemplate transactionTemplate;
@@ -138,8 +140,15 @@ public class LibraryProcessingService {
@Transactional
protected BookFileType getBookFileType(String fileName) {
if (fileName.endsWith(".pdf")) {
String lowerCaseName = fileName.toLowerCase();
if (lowerCaseName.endsWith(".pdf")) {
return BookFileType.PDF;
} else if (lowerCaseName.endsWith(".cbz")) {
return BookFileType.CBX;
} else if (lowerCaseName.endsWith(".cbr")) {
return BookFileType.CBX;
} else if (lowerCaseName.endsWith(".cb7")) {
return BookFileType.CBX;
} else {
return BookFileType.EPUB;
}
@@ -220,6 +229,8 @@ public class LibraryProcessingService {
return pdfProcessor.processFile(libraryFile, false);
} else if (libraryFile.getBookFileType() == BookFileType.EPUB) {
return epubProcessor.processFile(libraryFile, false);
} else if (libraryFile.getBookFileType() == BookFileType.CBX) {
return cbxProcessor.processFile(libraryFile, false);
}
return null;
}
@@ -239,12 +250,29 @@ public class LibraryProcessingService {
stream.filter(Files::isRegularFile)
.filter(file -> {
String fileName = file.getFileName().toString().toLowerCase();
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
return fileName.endsWith(".pdf") ||
fileName.endsWith(".epub") ||
fileName.endsWith(".cbz") ||
fileName.endsWith(".cbr") ||
fileName.endsWith(".cb7");
})
.forEach(fullFilePath -> {
BookFileType fileType = fullFilePath.getFileName().toString().toLowerCase().endsWith(".pdf")
? BookFileType.PDF
: BookFileType.EPUB;
String fileName = fullFilePath.getFileName().toString().toLowerCase();
BookFileType fileType;
if (fileName.endsWith(".pdf")) {
fileType = BookFileType.PDF;
} else if (fileName.endsWith(".epub")) {
fileType = BookFileType.EPUB;
} else if (fileName.endsWith(".cbz")) {
fileType = BookFileType.CBX;
} else if (fileName.endsWith(".cbr")) {
fileType = BookFileType.CBX;
} else if (fileName.endsWith(".cb7")) {
fileType = BookFileType.CBX;
} else {
return;
}
String relativePath = FileUtils.getRelativeSubPath(libraryPathEntity.getPath(), fullFilePath);
LibraryFile libraryFile = LibraryFile.builder()
.libraryEntity(libraryEntity)
@@ -2,6 +2,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
@@ -13,7 +14,7 @@ import java.util.Set;
@Slf4j
@Service
public class PdfMetadataExtractor implements BookFileMetadataExtractor {
public class PdfMetadataExtractor implements UploadedFileMetadataExtractor {
@Override
public UploadedFileMetadata extractMetadata(String filePath) {
@@ -24,6 +25,8 @@ public class PdfMetadataExtractor implements BookFileMetadataExtractor {
if (info != null) {
if (info.getTitle() != null && !info.getTitle().isBlank()) {
metadata.setTitle(info.getTitle());
} else {
metadata.setTitle(FilenameUtils.getBaseName(filePath));
}
if (info.getAuthor() != null && !info.getAuthor().isBlank()) {
metadata.setAuthors(Set.of(info.getAuthor().split(",")));
@@ -2,7 +2,7 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.UploadedFileMetadata;
public interface BookFileMetadataExtractor {
public interface UploadedFileMetadataExtractor {
UploadedFileMetadata extractMetadata(String filePath);
}
@@ -0,0 +1,209 @@
package com.adityachandel.booklore.service.fileprocessor;
import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookCreatorService;
import com.adityachandel.booklore.util.FileUtils;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.time.Instant;
import java.util.*;
@Slf4j
@Service
@AllArgsConstructor
public class CbxProcessor implements FileProcessor {
private final BookRepository bookRepository;
private final BookCreatorService bookCreatorService;
private final BookMapper bookMapper;
private final FileProcessingUtils fileProcessingUtils;
private final BookMetadataRepository bookMetadataRepository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public Book processFile(LibraryFile libraryFile, boolean forceProcess) {
File bookFile = new File(libraryFile.getFileName());
String fileName = bookFile.getName();
if (!forceProcess) {
Optional<BookEntity> bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
return bookOptional.map(bookMapper::toBook).orElseGet(() -> processNewFile(libraryFile));
} else {
return processNewFile(libraryFile);
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected Book processNewFile(LibraryFile libraryFile) {
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
if (generateCover(bookEntity)) {
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
}
setMetadata(bookEntity);
bookCreatorService.saveConnections(bookEntity);
bookEntity = bookRepository.save(bookEntity);
bookRepository.flush();
return bookMapper.toBook(bookEntity);
}
public boolean generateCover(BookEntity bookEntity) {
File file = new File(FileUtils.getBookFullPath(bookEntity));
try {
List<BufferedImage> images = extractImagesFromArchive(file);
if (images == null || images.isEmpty()) {
log.warn("No image entries found in archive: {}", file.getName());
return false;
}
BufferedImage coverImage = images.get(0);
boolean saved = fileProcessingUtils.saveCoverImage(coverImage, bookEntity.getId());
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
bookMetadataRepository.save(bookEntity.getMetadata());
return saved;
} catch (Exception e) {
log.error("Error generating cover from archive {}, error: {}", bookEntity.getFileName(), e.getMessage());
return false;
}
}
private List<BufferedImage> extractImagesFromArchive(File file) {
String name = file.getName().toLowerCase();
if (name.endsWith(".cbz")) {
return extractImagesFromZip(file);
} else if (name.endsWith(".cb7")) {
return extractImagesFrom7z(file);
} else if (name.endsWith(".cbr")) {
return extractImagesFromRar(file);
} else {
log.warn("Unsupported archive format: {}", name);
return List.of();
}
}
private List<BufferedImage> extractImagesFromRar(File file) {
List<BufferedImage> images = new ArrayList<>();
try (Archive archive = new Archive(file)) {
List<FileHeader> headers = archive.getFileHeaders();
headers.stream()
.filter(h -> {
if (h.isDirectory()) return false;
String fileName = h.getFileNameString().replace("\\", "/").toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".webp");
})
.sorted(Comparator.comparing(FileHeader::getFileNameString))
.forEach(header -> {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
archive.extractFile(header, baos);
byte[] imageData = baos.toByteArray();
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageData));
if (img != null) {
images.add(img);
}
} catch (Exception e) {
log.warn("Failed to read image from RAR entry {}: {}", header.getFileNameString(), e.getMessage());
}
});
} catch (Exception e) {
log.error("Error extracting images from RAR archive {}: {}", file.getName(), e.getMessage());
return List.of();
}
return images;
}
/**
* Extracts image entries from a ZIP archive (.cbz), sorted by entry name.
*/
private List<BufferedImage> extractImagesFromZip(File file) {
List<BufferedImage> images = new ArrayList<>();
try (ZipFile zipFile = new ZipFile(file)) {
List<? extends ZipArchiveEntry> imageEntries = Collections.list(zipFile.getEntries()).stream()
.filter(e -> !e.isDirectory())
.filter(e -> e.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)"))
.sorted(Comparator.comparing(ZipArchiveEntry::getName))
.toList();
for (ZipArchiveEntry entry : imageEntries) {
try (InputStream is = zipFile.getInputStream(entry)) {
BufferedImage img = ImageIO.read(is);
if (img != null) {
images.add(img);
}
} catch (Exception e) {
log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage());
}
}
return images;
} catch (Exception e) {
log.error("Error extracting images from ZIP archive {}: {}", file.getName(), e.getMessage());
return List.of();
}
}
private List<BufferedImage> extractImagesFrom7z(File file) {
List<BufferedImage> images = new ArrayList<>();
try (SevenZFile sevenZFile = new SevenZFile(file)) {
List<SevenZArchiveEntry> entries = new ArrayList<>();
SevenZArchiveEntry entry;
while ((entry = sevenZFile.getNextEntry()) != null) {
if (!entry.isDirectory() && entry.getName().matches("(?i).*\\.(jpg|jpeg|png|webp)")) {
entries.add(entry);
}
}
entries.sort(Comparator.comparing(SevenZArchiveEntry::getName));
for (SevenZArchiveEntry e : entries) {
try {
byte[] content = new byte[(int) e.getSize()];
int offset = 0;
while (offset < content.length) {
int bytesRead = sevenZFile.read(content, offset, content.length - offset);
if (bytesRead < 0) {
break;
}
offset += bytesRead;
}
BufferedImage img = ImageIO.read(new java.io.ByteArrayInputStream(content));
if (img != null) {
images.add(img);
}
} catch (Exception ex) {
log.warn("Failed to read image from 7z entry {}: {}", e.getName(), ex.getMessage());
}
}
} catch (Exception e) {
log.error("Error extracting images from 7z archive {}: {}", file.getName(), e.getMessage());
return List.of();
}
return images;
}
private void setMetadata(BookEntity bookEntity) {
String baseName = new File(bookEntity.getFileName()).getName();
String title = baseName.replaceAll("(?i)\\.cb[sz7]$", "").replaceAll("[_\\-]", " ").trim();
bookEntity.getMetadata().setTitle(truncate(title, 1000));
}
private String truncate(String input, int maxLength) {
if (input == null) return null;
return input.length() <= maxLength ? input : input.substring(0, maxLength);
}
}
@@ -91,23 +91,17 @@ public class AmazonBookParser implements BookParser {
Element link = item.select("a:containsOwn(" + type + ")").first();
if (link != null) {
bookLink = link.attr("href");
//log.info("{} link found: {}", type, bookLink);
break; // Take the first found link, whether Paperback or Hardcover
} else {
//log.info("No link containing '{}' found.", type);
break;
}
}
if (bookLink != null) {
return extractAsinFromUrl(bookLink);
} else {
String asin = item.attr("data-asin");
//log.info("No book link found, returning ASIN: {}", asin);
return asin;
return item.attr("data-asin");
}
}
private String extractAsinFromUrl(String url) {
// Extract the ASIN (book ID) from the URL, which will be the part after "/dp/"
String[] parts = url.split("/dp/");
if (parts.length > 1) {
String[] asinParts = parts[1].split("/");
@@ -184,7 +178,7 @@ public class AmazonBookParser implements BookParser {
if (titleElement != null) {
return titleElement.text();
}
log.error("Error fetching title: Element not found.");
log.warn("Failed to parse title: Element not found.");
return null;
}
@@ -193,7 +187,7 @@ public class AmazonBookParser implements BookParser {
if (subtitleElement != null) {
return subtitleElement.text();
}
log.debug("Error fetching subtitle: Element not found.");
log.warn("Failed to parse subtitle: Element not found.");
return null;
}
@@ -207,9 +201,9 @@ public class AmazonBookParser implements BookParser {
.map(Element::text)
.collect(Collectors.toSet());
}
log.error("Error fetching authors: Byline element not found.");
log.warn("Failed to parse authors: Byline element not found.");
} catch (Exception e) {
log.error("Error fetching authors: {}", e.getMessage());
log.warn("Failed to parse authors: {}", e.getMessage());
}
return Set.of();
}
@@ -224,7 +218,7 @@ public class AmazonBookParser implements BookParser {
}
return null;
} catch (Exception e) {
log.error("Error extracting description from the document", e);
log.warn("Failed to parse description: {}", e.getMessage());
}
return null;
}
@@ -235,9 +229,9 @@ public class AmazonBookParser implements BookParser {
if (isbn10Element != null) {
return isbn10Element.text();
}
log.debug("Error fetching ISBN-10: Element not found.");
log.warn("Failed to parse isbn10: Element not found.");
} catch (Exception e) {
log.debug("Error fetching ISBN-10: {}", e.getMessage());
log.warn("Failed to parse isbn10: {}", e.getMessage());
}
return null;
}
@@ -248,9 +242,9 @@ public class AmazonBookParser implements BookParser {
if (isbn13Element != null) {
return isbn13Element.text();
}
log.debug("Error fetching ISBN-13: Element not found.");
log.warn("Failed to parse isbn13: Element not found.");
} catch (Exception e) {
log.debug("Error fetching ISBN-13: {}", e.getMessage());
log.warn("Failed to parse isbn13: {}", e.getMessage());
}
return null;
}
@@ -271,10 +265,10 @@ public class AmazonBookParser implements BookParser {
}
}
} else {
log.warn("Error fetching publisher: Element 'detailBullets_feature_div' not found.");
log.warn("Failed to parse publisher: Element 'detailBullets_feature_div' not found.");
}
} catch (Exception e) {
log.warn("Error fetching publisher: {}", e.getMessage());
log.warn("Failed to parse publisher: {}", e.getMessage());
}
return null;
}
@@ -285,9 +279,9 @@ public class AmazonBookParser implements BookParser {
if (publicationDateElement != null) {
return parseAmazonDate(publicationDateElement.text());
}
log.warn("Error fetching publication date: Element not found.");
log.warn("Failed to parse publishedDate: Element not found.");
} catch (Exception e) {
log.warn("Error fetching publication date: {}", e.getMessage());
log.warn("Failed to parse publishedDate: {}", e.getMessage());
}
return null;
}
@@ -298,10 +292,10 @@ public class AmazonBookParser implements BookParser {
if (seriesNameElement != null) {
return seriesNameElement.text();
} else {
log.debug("Error fetching series name: Element not found.");
log.warn("Failed to parse seriesName: Element not found.");
}
} catch (Exception e) {
log.debug("Error fetching series name: {}", e.getMessage());
log.warn("Failed to parse seriesName: {}", e.getMessage());
}
return null;
}
@@ -316,10 +310,10 @@ public class AmazonBookParser implements BookParser {
return Float.parseFloat(parts[1]);
}
} else {
log.debug("Error fetching series number: Element not found.");
log.warn("Failed to parse seriesNumber: Element not found.");
}
} catch (Exception e) {
log.debug("Error fetching series number: {}", e.getMessage());
log.warn("Failed to parse seriesNumber: {}", e.getMessage());
}
return null;
}
@@ -334,10 +328,10 @@ public class AmazonBookParser implements BookParser {
return Integer.parseInt(parts[3]);
}
} else {
log.debug("Error fetching series total: Element not found.");
log.warn("Failed to parse seriesTotal: Element not found.");
}
} catch (Exception e) {
log.debug("Error fetching series total: {}", e.getMessage());
log.warn("Failed to parse seriesTotal: {}", e.getMessage());
}
return null;
}
@@ -348,9 +342,9 @@ public class AmazonBookParser implements BookParser {
if (languageElement != null) {
return languageElement.text();
}
log.warn("Error fetching language: Element not found.");
log.warn("Failed to parse language: Element not found.");
} catch (Exception e) {
log.warn("Error fetching language: {}", e.getMessage());
log.warn("Failed to parse language: {}", e.getMessage());
}
return null;
}
@@ -366,9 +360,9 @@ public class AmazonBookParser implements BookParser {
.map(c -> c.replace("(Books)", "").trim())
.collect(Collectors.toSet());
}
log.warn("Error fetching best seller categories: Element not found.");
log.warn("Failed to parse categories: Element not found.");
} catch (Exception e) {
log.warn("Error fetching best seller categories: {}", e.getMessage());
log.warn("Failed to parse categories: {}", e.getMessage());
}
return Set.of();
}
@@ -386,7 +380,7 @@ public class AmazonBookParser implements BookParser {
}
}
} catch (Exception e) {
log.warn("Error fetching rating", e);
log.warn("Failed to parse amazonRating: {}", e.getMessage());
}
return null;
}
@@ -405,7 +399,7 @@ public class AmazonBookParser implements BookParser {
}
}
} catch (Exception e) {
log.warn("Error fetching review count", e);
log.warn("Failed to parse amazonReviewCount: {}", e.getMessage());
}
return null;
}
@@ -416,9 +410,9 @@ public class AmazonBookParser implements BookParser {
if (imageElement != null) {
return imageElement.attr("src");
}
log.warn("Error fetching image URL: Image element not found.");
log.warn("Failed to parse thumbnail: Image element not found.");
} catch (Exception e) {
log.warn("Error fetching image URL: {}", e.getMessage());
log.warn("Failed to parse thumbnail: {}", e.getMessage());
}
return null;
}
@@ -432,7 +426,7 @@ public class AmazonBookParser implements BookParser {
String cleanedPageCount = pageCountText.replaceAll("[^\\d]", "");
return Integer.parseInt(cleanedPageCount);
} catch (NumberFormatException e) {
log.warn("Error parsing page count: {}", pageCountText, e);
log.warn("Error parsing page count: {}, error: {}", pageCountText, e.getMessage());
}
}
}
@@ -485,7 +479,7 @@ public class AmazonBookParser implements BookParser {
document.select("span.a-text-bold").tagName("b").removeAttr("class");
document.select("span.a-text-italic").tagName("i").removeAttr("class");
for (Element span : document.select("span.a-list-item")) {
span.unwrap(); // Removes the span and keeps its content
span.unwrap();
}
document.select("ol.a-ordered-list.a-vertical").tagName("ol").removeAttr("class");
document.select("ul.a-unordered-list.a-vertical").tagName("ul").removeAttr("class");
@@ -493,13 +487,10 @@ public class AmazonBookParser implements BookParser {
span.unwrap();
}
document.select("li").forEach(li -> {
// Remove <br> tags preceding the <li> (if any)
Element prev = li.previousElementSibling();
if (prev != null && "br".equals(prev.tagName())) {
prev.remove();
}
// Remove <br> tags following the <li> (if any)
Element next = li.nextElementSibling();
if (next != null && "br".equals(next.tagName())) {
next.remove();
@@ -510,7 +501,7 @@ public class AmazonBookParser implements BookParser {
.forEach(Element::remove);
return document.body().html();
} catch (Exception e) {
log.warn("Error cleaning html description", e);
log.warn("Error cleaning html description, Error: {}", e.getMessage());
}
return html;
}
@@ -9,6 +9,8 @@ import com.adityachandel.booklore.model.dto.settings.OidcAutoProvisionDetails;
import com.adityachandel.booklore.model.dto.settings.SidebarSortOption;
import com.adityachandel.booklore.model.dto.settings.UserSettingKey;
import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.enums.CbxPageSpread;
import com.adityachandel.booklore.model.enums.CbxPageViewMode;
import com.adityachandel.booklore.model.enums.ProvisioningMethod;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
@@ -179,6 +181,7 @@ public class UserProvisioningService {
addUserSetting(user, UserSettingKey.PER_BOOK_SETTING, buildDefaultPerBookSetting());
addUserSetting(user, UserSettingKey.PDF_READER_SETTING, buildDefaultPdfReaderSetting());
addUserSetting(user, UserSettingKey.EPUB_READER_SETTING, buildDefaultEpubReaderSetting());
addUserSetting(user, UserSettingKey.CBX_READER_SETTING, buildDefaultEpubReaderSetting());
addUserSetting(user, UserSettingKey.SIDEBAR_LIBRARY_SORTING, buildDefaultSidebarLibrarySorting());
addUserSetting(user, UserSettingKey.SIDEBAR_SHELF_SORTING, buildDefaultSidebarShelfSorting());
@@ -222,6 +225,13 @@ public class UserProvisioningService {
.build();
}
private BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
return BookLoreUser.UserSettings.CbxReaderSetting.builder()
.pageViewMode(CbxPageViewMode.SINGLE_PAGE)
.pageSpread(CbxPageSpread.ODD)
.build();
}
private Object buildDefaultSidebarLibrarySorting() {
return SidebarSortOption.builder()
.field("id")
@@ -118,6 +118,10 @@ public class FileService {
return appProperties.getPathConfig() + "/thumbs/" + bookId + "/";
}
public String getCbxCachePath() {
return appProperties.getPathConfig() + "/cbx_cache";
}
public String getMissingThumbnailPath() {
return appProperties.getPathConfig() + "/thumbs/missing/m.jpg";
}
@@ -3,9 +3,11 @@ package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.BookEntity;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.Optional;
@Slf4j
@@ -45,4 +47,14 @@ public class FileUtils {
return null;
}
}
public static void deleteDirectoryRecursively(Path path) throws IOException {
if (!Files.exists(path)) return;
try (var walk = Files.walk(path)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
}
}
@@ -14,9 +14,7 @@ app:
spring:
servlet:
multipart:
enabled: true
max-file-size: 100MB
max-request-size: 100MB
enabled: false
mvc:
async:
request-timeout: 600000
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS cbx_viewer_preference
(
id BIGINT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT NOT NULL,
book_id BIGINT NOT NULL,
spread VARCHAR(16) NULL,
view_mode VARCHAR(16) NULL,
UNIQUE (user_id, book_id)
);
@@ -0,0 +1,3 @@
ALTER TABLE user_book_progress
ADD COLUMN cbx_progress INT NULL,
ADD COLUMN cbx_progress_percent FLOAT NULL;