Implement cover size selection and regeneration
This commit is contained in:
committed by
Aditya Chandel
parent
bf87f030f8
commit
9e6640f27f
+6
-2
@@ -6,6 +6,8 @@ import com.adityachandel.booklore.service.AppSettingService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/settings")
|
||||
@@ -19,7 +21,9 @@ public class AppSettingController {
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
public void updateSetting(@RequestBody SettingRequest settingRequest) {
|
||||
appSettingService.updateSetting(settingRequest.getCategory(), settingRequest.getName(), settingRequest.getValue());
|
||||
public void updateSettings(@RequestBody List<SettingRequest> settingRequests) {
|
||||
for (SettingRequest settingRequest : settingRequests) {
|
||||
appSettingService.updateSetting(settingRequest.getName(), settingRequest.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -65,4 +65,16 @@ public class MetadataController {
|
||||
boolean isLocked = request.getIsLocked();
|
||||
return ResponseEntity.ok(bookMetadataService.updateFieldLockState(bookId, field, isLocked));
|
||||
}
|
||||
|
||||
@PostMapping("/regenerate-covers")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public void regenerateCovers() {
|
||||
bookMetadataService.regenerateCovers();
|
||||
}
|
||||
|
||||
@PostMapping("/{bookId}/regenerate-cover")
|
||||
@PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()")
|
||||
public void regenerateCovers(@PathVariable Long bookId) {
|
||||
bookMetadataService.regenerateCover(bookId);
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ public enum ApiError {
|
||||
METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"),
|
||||
FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"),
|
||||
INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"),
|
||||
METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata fields for book with ID: %d"),
|
||||
METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata"),
|
||||
USERNAME_ALREADY_TAKEN(HttpStatus.BAD_REQUEST, "Username already taken: %s"),
|
||||
USER_NOT_FOUND(HttpStatus.BAD_REQUEST, "User not found: %s"),
|
||||
CANNOT_DELETE_ADMIN(HttpStatus.FORBIDDEN, "Admin user cannot be deleted"),
|
||||
|
||||
+3
-29
@@ -11,40 +11,14 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AppSettings {
|
||||
private EpubSettings epub;
|
||||
private PdfSettings pdf;
|
||||
private ReaderSettings readerSettings;
|
||||
private CoverSettings coverSettings;
|
||||
private MetadataRefreshOptions metadataRefreshOptions;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class EpubSettings {
|
||||
private String theme;
|
||||
private String fontSize;
|
||||
private String font;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class PdfSettings {
|
||||
private String spread;
|
||||
private String zoom;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class ReaderSettings {
|
||||
private SettingScope pdfScope;
|
||||
private SettingScope epubScope;
|
||||
}
|
||||
|
||||
public enum SettingScope {
|
||||
global, individual
|
||||
public static class CoverSettings {
|
||||
private String resolution;
|
||||
}
|
||||
}
|
||||
|
||||
-1
@@ -6,7 +6,6 @@ import lombok.Setter;
|
||||
@Getter
|
||||
@Setter
|
||||
public class SettingRequest {
|
||||
private String category;
|
||||
private String name;
|
||||
private Object value;
|
||||
}
|
||||
|
||||
-5
@@ -3,8 +3,6 @@ package com.adityachandel.booklore.model.entity;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@Table(name = "app_settings")
|
||||
@Data
|
||||
@@ -14,9 +12,6 @@ public class AppSettingEntity {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "category", nullable = false)
|
||||
private String category;
|
||||
|
||||
@Column(name = "name", nullable = false)
|
||||
private String name;
|
||||
|
||||
|
||||
+1
-1
@@ -6,5 +6,5 @@ import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface AppSettingsRepository extends JpaRepository<AppSettingEntity, Long> {
|
||||
AppSettingEntity findByCategoryAndName(String category, String name);;
|
||||
AppSettingEntity findByName(String name);
|
||||
}
|
||||
|
||||
+59
-63
@@ -7,87 +7,83 @@ import com.adityachandel.booklore.repository.AppSettingsRepository;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
@RequiredArgsConstructor
|
||||
public class AppSettingService {
|
||||
|
||||
private final AppSettingsRepository appSettingsRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public static final String QUICK_BOOK_MATCH = "quick_book_match";
|
||||
public static final String COVER_IMAGE_RESOLUTION = "cover_image_resolution";
|
||||
|
||||
private volatile AppSettings appSettings;
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
public AppSettings getAppSettings() {
|
||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||
Map<String, Map<String, Object>> settingsMap = settings.stream()
|
||||
.collect(Collectors.groupingBy(AppSettingEntity::getCategory,
|
||||
Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal)));
|
||||
|
||||
AppSettings.AppSettingsBuilder appSettingsBuilder = AppSettings.builder();
|
||||
|
||||
if (settingsMap.containsKey("epub")) {
|
||||
Map<String, Object> epubSettings = settingsMap.get("epub");
|
||||
appSettingsBuilder.epub(AppSettings.EpubSettings.builder()
|
||||
.theme((String) epubSettings.get("theme"))
|
||||
.fontSize((String) epubSettings.get("fontSize"))
|
||||
.font((String) epubSettings.get("font"))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey("pdf")) {
|
||||
Map<String, Object> pdfSettings = settingsMap.get("pdf");
|
||||
appSettingsBuilder.pdf(AppSettings.PdfSettings.builder()
|
||||
.spread((String) pdfSettings.get("spread"))
|
||||
.zoom((String) pdfSettings.get("zoom"))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey("reader_setting")) {
|
||||
Map<String, Object> readerSetting = settingsMap.get("reader_setting");
|
||||
appSettingsBuilder.readerSettings(AppSettings.ReaderSettings.builder()
|
||||
.pdfScope(AppSettings.SettingScope.valueOf((String) readerSetting.get("pdf")))
|
||||
.epubScope(AppSettings.SettingScope.valueOf((String) readerSetting.get("epub")))
|
||||
.build());
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey("quick_book_match")) {
|
||||
Map<String, Object> quickBookMatch = settingsMap.get("quick_book_match");
|
||||
String quickBookMatchValue = (String) quickBookMatch.get("all_books");
|
||||
if (quickBookMatchValue != null) {
|
||||
try {
|
||||
MetadataRefreshOptions metadataRefreshOptions = objectMapper.readValue(quickBookMatchValue, MetadataRefreshOptions.class);
|
||||
appSettingsBuilder.metadataRefreshOptions(metadataRefreshOptions);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse quick_book_match settings", e);
|
||||
if (appSettings == null) {
|
||||
lock.lock();
|
||||
try {
|
||||
if (appSettings == null) {
|
||||
appSettings = buildAppSettings();
|
||||
}
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
return appSettingsBuilder.build();
|
||||
return appSettings;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateSetting(String category, String name, Object val) {
|
||||
AppSettingEntity setting = appSettingsRepository.findByCategoryAndName(category, name);
|
||||
if (setting != null) {
|
||||
if (category.equals("quick_book_match")) {
|
||||
try {
|
||||
String jsonString = objectMapper.writeValueAsString(val);
|
||||
setting.setVal(jsonString);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("Failed to serialize value: " + e.getMessage(), e);
|
||||
}
|
||||
} else {
|
||||
setting.setVal(val.toString());
|
||||
}
|
||||
appSettingsRepository.save(setting);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Setting not found for category: " + category + " and key: " + name);
|
||||
public void updateSetting(String name, Object val) {
|
||||
AppSettingEntity setting = appSettingsRepository.findByName(name);
|
||||
if (setting == null) {
|
||||
throw new IllegalArgumentException("Setting not found for name: " + name);
|
||||
}
|
||||
|
||||
setting.setVal(val.toString());
|
||||
appSettingsRepository.save(setting);
|
||||
refreshCache();
|
||||
}
|
||||
|
||||
private void refreshCache() {
|
||||
lock.lock();
|
||||
try {
|
||||
this.appSettings = buildAppSettings();
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private AppSettings buildAppSettings() {
|
||||
List<AppSettingEntity> settings = appSettingsRepository.findAll();
|
||||
Map<String, String> settingsMap = settings.stream().collect(Collectors.toMap(AppSettingEntity::getName, AppSettingEntity::getVal));
|
||||
|
||||
AppSettings.AppSettingsBuilder builder = AppSettings.builder();
|
||||
|
||||
if (settingsMap.containsKey(QUICK_BOOK_MATCH)) {
|
||||
try {
|
||||
MetadataRefreshOptions options = objectMapper.readValue(settingsMap.get(QUICK_BOOK_MATCH), MetadataRefreshOptions.class);
|
||||
builder.metadataRefreshOptions(options);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Failed to parse setting 'quick_book_match'", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsMap.containsKey(COVER_IMAGE_RESOLUTION)) {
|
||||
builder.coverSettings(AppSettings.CoverSettings.builder()
|
||||
.resolution(settingsMap.get(COVER_IMAGE_RESOLUTION))
|
||||
.build());
|
||||
}
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+46
@@ -17,6 +17,8 @@ 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.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.service.metadata.parser.BookParser;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -48,6 +50,8 @@ public class BookMetadataService {
|
||||
private final AppSettingService appSettingService;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
private final FileService fileService;
|
||||
private final PdfProcessor pdfProcessor;
|
||||
private final EpubProcessor epubProcessor;
|
||||
private final Map<MetadataProvider, BookParser> parserMap;
|
||||
|
||||
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
|
||||
@@ -395,4 +399,46 @@ public class BookMetadataService {
|
||||
bookMetadataRepository.save(metadata);
|
||||
return bookMetadataMapper.toBookMetadata(metadata, true);
|
||||
}
|
||||
|
||||
public void regenerateCover(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
if (bookEntity.getMetadata().getCoverLocked() != null && bookEntity.getMetadata().getCoverLocked()) {
|
||||
throw ApiError.METADATA_LOCKED.createException();
|
||||
} else {
|
||||
regenerateCoverForBook(bookEntity, "");
|
||||
}
|
||||
}
|
||||
|
||||
public void regenerateCovers() {
|
||||
Thread.startVirtualThread(() -> {
|
||||
List<BookEntity> books = bookRepository.findAll().stream()
|
||||
.filter(book -> book.getMetadata().getCoverLocked() == null || !book.getMetadata().getCoverLocked())
|
||||
.toList();
|
||||
int total = books.size();
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started regenerating covers for " + total + " books"));
|
||||
int[] current = {1};
|
||||
for (BookEntity book : books) {
|
||||
try {
|
||||
String progress = "(" + current[0] + "/" + total + ") ";
|
||||
regenerateCoverForBook(book, progress);
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage());
|
||||
}
|
||||
current[0]++;
|
||||
}
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished regenerating covers"));
|
||||
});
|
||||
}
|
||||
|
||||
private void regenerateCoverForBook(BookEntity book, String progress) {
|
||||
String title = book.getMetadata().getTitle();
|
||||
String message = progress + "Regenerating cover for: " + title;
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification(message));
|
||||
switch (book.getBookType()) {
|
||||
case PDF -> pdfProcessor.generateCover(book);
|
||||
case EPUB -> epubProcessor.generateCover(book);
|
||||
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException(book.getBookType());
|
||||
}
|
||||
log.info("{} Successfully regenerated cover for book ID {} ({})", progress, book.getId(), title);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,10 @@ import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.fileprocessor.EpubProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.PdfProcessor;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
@@ -15,6 +18,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -28,9 +32,12 @@ import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
@@ -46,6 +53,7 @@ public class BooksService {
|
||||
private final UserBookProgressRepository userBookProgressRepository;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
+82
-77
@@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
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;
|
||||
@@ -25,6 +26,7 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
@@ -42,6 +44,7 @@ public class EpubProcessor implements FileProcessor {
|
||||
private final BookCreatorService bookCreatorService;
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -61,30 +64,28 @@ public class EpubProcessor implements FileProcessor {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
protected Book processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.EPUB);
|
||||
try {
|
||||
io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
|
||||
|
||||
setBookMetadata(epub, bookEntity);
|
||||
processCover(epub, bookEntity);
|
||||
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error while processing file {}, error: {}", libraryFile.getFileName(), e.getMessage());
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
return bookMapper.toBook(bookEntity);
|
||||
}
|
||||
|
||||
private void processCover(io.documentnode.epub4j.domain.Book epub, BookEntity bookEntity) throws IOException {
|
||||
Resource coverImage = epub.getCoverImage();
|
||||
if (coverImage != null) {
|
||||
boolean success = saveCoverImage(coverImage, bookEntity.getId());
|
||||
if (success) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try {
|
||||
io.documentnode.epub4j.domain.Book epub = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
|
||||
Resource coverImage = epub.getCoverImage();
|
||||
boolean saved = saveCoverImage(coverImage, bookEntity.getId());
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return saved;
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for epub file {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Set<String> getAuthors(io.documentnode.epub4j.domain.Book book) {
|
||||
@@ -93,67 +94,71 @@ public class EpubProcessor implements FileProcessor {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void setBookMetadata(io.documentnode.epub4j.domain.Book book, BookEntity bookEntity) {
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
try {
|
||||
io.documentnode.epub4j.domain.Book book = new EpubReader().readEpub(new FileInputStream(FileUtils.getBookFullPath(bookEntity)));
|
||||
BookMetadataEntity bookMetadata = bookEntity.getMetadata();
|
||||
Metadata epubMetadata = book.getMetadata();
|
||||
if (epubMetadata != null) {
|
||||
bookMetadata.setTitle(epubMetadata.getFirstTitle());
|
||||
|
||||
if (epubMetadata != null) {
|
||||
bookMetadata.setTitle(epubMetadata.getFirstTitle());
|
||||
|
||||
if (epubMetadata.getDescriptions() != null && !epubMetadata.getDescriptions().isEmpty()) {
|
||||
bookMetadata.setDescription(epubMetadata.getDescriptions().getFirst());
|
||||
}
|
||||
|
||||
if (epubMetadata.getPublishers() != null && !epubMetadata.getPublishers().isEmpty()) {
|
||||
bookMetadata.setPublisher(epubMetadata.getPublishers().getFirst());
|
||||
}
|
||||
|
||||
List<String> identifiers = epubMetadata.getIdentifiers().stream()
|
||||
.map(Identifier::getValue)
|
||||
.toList();
|
||||
if (!identifiers.isEmpty()) {
|
||||
String isbn13 = identifiers.stream().filter(id -> id.length() == 13).findFirst().orElse(null);
|
||||
String isbn10 = identifiers.stream().filter(id -> id.length() == 10).findFirst().orElse(null);
|
||||
bookMetadata.setIsbn13(isbn13);
|
||||
bookMetadata.setIsbn10(isbn10);
|
||||
}
|
||||
|
||||
bookMetadata.setLanguage(epubMetadata.getLanguage() == null || epubMetadata.getLanguage().equalsIgnoreCase("UND") ? "en" : epubMetadata.getLanguage());
|
||||
|
||||
if (epubMetadata.getDates() != null && !epubMetadata.getDates().isEmpty()) {
|
||||
epubMetadata.getDates().stream()
|
||||
.findFirst()
|
||||
.ifPresent(publishedDate -> {
|
||||
String dateString = publishedDate.getValue();
|
||||
if (isValidLocalDate(dateString)) {
|
||||
LocalDate parsedDate = LocalDate.parse(dateString);
|
||||
bookMetadata.setPublishedDate(parsedDate);
|
||||
} else if (isValidOffsetDateTime(dateString)) {
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateString);
|
||||
bookMetadata.setPublishedDate(offsetDateTime.toLocalDate());
|
||||
} else {
|
||||
log.error("Unable to parse date: {}", dateString);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
|
||||
if (seriesName != null && !seriesName.isEmpty()) {
|
||||
bookMetadata.setSeriesName(seriesName);
|
||||
}
|
||||
|
||||
String seriesIndex = epubMetadata.getMetaAttribute("calibre:series_index");
|
||||
if (seriesIndex != null && !seriesIndex.isEmpty()) {
|
||||
try {
|
||||
double indexValue = Double.parseDouble(seriesIndex);
|
||||
bookMetadata.setSeriesNumber((int) indexValue);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Unable to parse series number: {}", seriesIndex);
|
||||
if (epubMetadata.getDescriptions() != null && !epubMetadata.getDescriptions().isEmpty()) {
|
||||
bookMetadata.setDescription(epubMetadata.getDescriptions().getFirst());
|
||||
}
|
||||
}
|
||||
|
||||
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
|
||||
bookCreatorService.addCategoriesToBook(epubMetadata.getSubjects(), bookEntity);
|
||||
if (epubMetadata.getPublishers() != null && !epubMetadata.getPublishers().isEmpty()) {
|
||||
bookMetadata.setPublisher(epubMetadata.getPublishers().getFirst());
|
||||
}
|
||||
|
||||
List<String> identifiers = epubMetadata.getIdentifiers().stream()
|
||||
.map(Identifier::getValue)
|
||||
.toList();
|
||||
if (!identifiers.isEmpty()) {
|
||||
String isbn13 = identifiers.stream().filter(id -> id.length() == 13).findFirst().orElse(null);
|
||||
String isbn10 = identifiers.stream().filter(id -> id.length() == 10).findFirst().orElse(null);
|
||||
bookMetadata.setIsbn13(isbn13);
|
||||
bookMetadata.setIsbn10(isbn10);
|
||||
}
|
||||
|
||||
bookMetadata.setLanguage(epubMetadata.getLanguage() == null || epubMetadata.getLanguage().equalsIgnoreCase("UND") ? "en" : epubMetadata.getLanguage());
|
||||
|
||||
if (epubMetadata.getDates() != null && !epubMetadata.getDates().isEmpty()) {
|
||||
epubMetadata.getDates().stream()
|
||||
.findFirst()
|
||||
.ifPresent(publishedDate -> {
|
||||
String dateString = publishedDate.getValue();
|
||||
if (isValidLocalDate(dateString)) {
|
||||
LocalDate parsedDate = LocalDate.parse(dateString);
|
||||
bookMetadata.setPublishedDate(parsedDate);
|
||||
} else if (isValidOffsetDateTime(dateString)) {
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateString);
|
||||
bookMetadata.setPublishedDate(offsetDateTime.toLocalDate());
|
||||
} else {
|
||||
log.error("Unable to parse date: {}", dateString);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
String seriesName = epubMetadata.getMetaAttribute("calibre:series");
|
||||
if (seriesName != null && !seriesName.isEmpty()) {
|
||||
bookMetadata.setSeriesName(seriesName);
|
||||
}
|
||||
|
||||
String seriesIndex = epubMetadata.getMetaAttribute("calibre:series_index");
|
||||
if (seriesIndex != null && !seriesIndex.isEmpty()) {
|
||||
try {
|
||||
double indexValue = Double.parseDouble(seriesIndex);
|
||||
bookMetadata.setSeriesNumber((int) indexValue);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("Unable to parse series number: {}", seriesIndex);
|
||||
}
|
||||
}
|
||||
|
||||
bookCreatorService.addAuthorsToBook(getAuthors(book), bookEntity);
|
||||
bookCreatorService.addCategoriesToBook(epubMetadata.getSubjects(), bookEntity);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error loading epub file {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-1
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.fileprocessor;
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.AppSettingService;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -26,6 +27,7 @@ import java.util.stream.Stream;
|
||||
public class FileProcessingUtils {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final AppSettingService appSettingService;
|
||||
|
||||
public void setBookCoverPath(long bookId, BookMetadataEntity bookMetadataEntity) {
|
||||
bookMetadataEntity.setThumbnail(appProperties.getPathConfig() + "/thumbs/" + bookId + "/f.jpg");
|
||||
@@ -34,7 +36,13 @@ public class FileProcessingUtils {
|
||||
|
||||
public boolean saveCoverImage(BufferedImage coverImage, long bookId) throws IOException {
|
||||
File coverDirectory = new File(appProperties.getPathConfig() + "/thumbs");
|
||||
BufferedImage resizedImage = resizeImage(coverImage, 250, 350);
|
||||
|
||||
String resolution = appSettingService.getAppSettings().getCoverSettings().getResolution();
|
||||
String[] split = resolution.split("x");
|
||||
int x = Integer.parseInt(split[0]);
|
||||
int y = Integer.parseInt(split[1]);
|
||||
|
||||
BufferedImage resizedImage = resizeImage(coverImage, x, y);
|
||||
File bookDirectory = new File(coverDirectory, String.valueOf(bookId));
|
||||
if (!bookDirectory.exists()) {
|
||||
if (!bookDirectory.mkdirs()) {
|
||||
|
||||
+32
-24
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
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;
|
||||
@@ -21,6 +22,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Optional;
|
||||
@@ -36,6 +38,7 @@ public class PdfProcessor implements FileProcessor {
|
||||
private final BookCreatorService bookCreatorService;
|
||||
private final BookMapper bookMapper;
|
||||
private final FileProcessingUtils fileProcessingUtils;
|
||||
private final BookMetadataRepository bookMetadataRepository;
|
||||
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
@@ -55,38 +58,43 @@ public class PdfProcessor implements FileProcessor {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
protected Book processNewFile(LibraryFile libraryFile) {
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
|
||||
try (PDDocument pdf = Loader.loadPDF(new File(FileUtils.getBookFullPath(bookEntity)))) {
|
||||
|
||||
setMetadata(pdf, bookEntity);
|
||||
processCover(pdf, bookEntity);
|
||||
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookEntity = bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
} catch (Exception e) {
|
||||
log.error("Error while processing file {}, error: {}", libraryFile.getFileName(), e.getMessage());
|
||||
if (generateCover(bookEntity)) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
}
|
||||
setMetadata(bookEntity);
|
||||
bookCreatorService.saveConnections(bookEntity);
|
||||
bookEntity = bookRepository.save(bookEntity);
|
||||
bookRepository.flush();
|
||||
return bookMapper.toBook(bookEntity);
|
||||
}
|
||||
|
||||
private void processCover(PDDocument document, BookEntity bookEntity) throws IOException {
|
||||
boolean success = generateCoverImageAndSave(bookEntity.getId(), document);
|
||||
if (success) {
|
||||
fileProcessingUtils.setBookCoverPath(bookEntity.getId(), bookEntity.getMetadata());
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try (PDDocument pdf = Loader.loadPDF(new File(FileUtils.getBookFullPath(bookEntity)))) {
|
||||
boolean saved = generateCoverImageAndSave(bookEntity.getId(), pdf);
|
||||
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
|
||||
bookMetadataRepository.save(bookEntity.getMetadata());
|
||||
return saved;
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for pdf file {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void setMetadata(PDDocument document, BookEntity bookEntity) {
|
||||
if (document.getDocumentInformation() == null) {
|
||||
log.warn("No document information found");
|
||||
} else {
|
||||
if (document.getDocumentInformation().getTitle() != null) {
|
||||
bookEntity.getMetadata().setTitle(document.getDocumentInformation().getTitle());
|
||||
}
|
||||
if (document.getDocumentInformation().getAuthor() != null) {
|
||||
Set<String> authors = getAuthors(document);
|
||||
bookCreatorService.addAuthorsToBook(authors, bookEntity);
|
||||
private void setMetadata(BookEntity bookEntity) {
|
||||
try (PDDocument pdf = Loader.loadPDF(new File(FileUtils.getBookFullPath(bookEntity)))) {
|
||||
if (pdf.getDocumentInformation() == null) {
|
||||
log.warn("No document information found");
|
||||
} else {
|
||||
if (pdf.getDocumentInformation().getTitle() != null) {
|
||||
bookEntity.getMetadata().setTitle(pdf.getDocumentInformation().getTitle());
|
||||
}
|
||||
if (pdf.getDocumentInformation().getAuthor() != null) {
|
||||
Set<String> authors = getAuthors(pdf);
|
||||
bookCreatorService.addAuthorsToBook(authors, bookEntity);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error loading pdf file {}, error: {}", bookEntity.getFileName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
ALTER TABLE app_settings
|
||||
DROP KEY category;
|
||||
|
||||
ALTER TABLE app_settings
|
||||
DROP COLUMN name;
|
||||
|
||||
ALTER TABLE app_settings
|
||||
RENAME COLUMN category TO name;
|
||||
|
||||
INSERT INTO app_settings (name, val)
|
||||
VALUES ('cover_image_resolution', '250x350');
|
||||
Reference in New Issue
Block a user