Introduce a new eBook reader with support for EPUB, MOBI, AZW3, and FB2 formats (#2258)
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
+3
-6
@@ -102,8 +102,7 @@ public class BookController {
|
||||
@ApiResponse(responseCode = "200", description = "Book content returned successfully")
|
||||
@GetMapping("/{bookId}/content")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
|
||||
public ResponseEntity<ByteArrayResource> getBookContent(@Parameter(description = "ID of the book") @PathVariable long bookId) throws IOException {
|
||||
return bookService.getBookContent(bookId);
|
||||
}
|
||||
|
||||
@@ -115,8 +114,7 @@ public class BookController {
|
||||
@GetMapping("/{bookId}/download")
|
||||
@PreAuthorize("@securityUtil.canDownload() or @securityUtil.isAdmin()")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<Resource> downloadBook(
|
||||
@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
public ResponseEntity<Resource> downloadBook(@Parameter(description = "ID of the book to download") @PathVariable("bookId") Long bookId) {
|
||||
return bookService.downloadBook(bookId);
|
||||
}
|
||||
|
||||
@@ -124,8 +122,7 @@ public class BookController {
|
||||
@ApiResponse(responseCode = "200", description = "Viewer settings returned successfully")
|
||||
@GetMapping("/{bookId}/viewer-setting")
|
||||
@CheckBookAccess(bookIdParam = "bookId")
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(
|
||||
@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
public ResponseEntity<BookViewerSettings> getBookViewerSettings(@Parameter(description = "ID of the book") @PathVariable long bookId) {
|
||||
return ResponseEntity.ok(bookService.getBookViewerSetting(bookId));
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -49,6 +49,7 @@ public class BookLoreUserTransformer {
|
||||
case PER_BOOK_SETTING -> userSettings.setPerBookSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PerBookSetting.class));
|
||||
case PDF_READER_SETTING -> userSettings.setPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.PdfReaderSetting.class));
|
||||
case EPUB_READER_SETTING -> userSettings.setEpubReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EpubReaderSetting.class));
|
||||
case EBOOK_READER_SETTING -> userSettings.setEbookReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.EbookReaderSetting.class));
|
||||
case CBX_READER_SETTING -> userSettings.setCbxReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.CbxReaderSetting.class));
|
||||
case NEW_PDF_READER_SETTING -> userSettings.setNewPdfReaderSetting(objectMapper.readValue(value, BookLoreUser.UserSettings.NewPdfReaderSetting.class));
|
||||
case SIDEBAR_LIBRARY_SORTING -> userSettings.setSidebarLibrarySorting(objectMapper.readValue(value, SidebarSortOption.class));
|
||||
|
||||
@@ -63,6 +63,7 @@ public class BookLoreUser {
|
||||
public PdfReaderSetting pdfReaderSetting;
|
||||
public NewPdfReaderSetting newPdfReaderSetting;
|
||||
public EpubReaderSetting epubReaderSetting;
|
||||
public EbookReaderSetting ebookReaderSetting;
|
||||
public CbxReaderSetting cbxReaderSetting;
|
||||
public SidebarSortOption sidebarLibrarySorting;
|
||||
public SidebarSortOption sidebarShelfSorting;
|
||||
@@ -107,6 +108,7 @@ public class BookLoreUser {
|
||||
private Float coverSize;
|
||||
@JsonAlias("seriesCollapse")
|
||||
private Boolean seriesCollapsed;
|
||||
private Boolean overlayBookType;
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -129,6 +131,7 @@ public class BookLoreUser {
|
||||
private String view;
|
||||
@JsonAlias("seriesCollapse")
|
||||
private Boolean seriesCollapsed;
|
||||
private Boolean overlayBookType;
|
||||
}
|
||||
|
||||
@Data
|
||||
@@ -145,6 +148,25 @@ public class BookLoreUser {
|
||||
private String spread;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public static class EbookReaderSetting {
|
||||
private String fontFamily;
|
||||
private Integer fontSize;
|
||||
private Float gap;
|
||||
private Boolean hyphenate;
|
||||
private Boolean isDark;
|
||||
private Boolean justify;
|
||||
private Float lineHeight;
|
||||
private Integer maxBlockSize;
|
||||
private Integer maxColumnCount;
|
||||
private Integer maxInlineSize;
|
||||
private String theme;
|
||||
private String flow;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@AllArgsConstructor
|
||||
|
||||
+1
-1
@@ -8,6 +8,6 @@ import lombok.Data;
|
||||
public class BookViewerSettings {
|
||||
private PdfViewerPreferences pdfSettings;
|
||||
private NewPdfViewerPreferences newPdfSettings;
|
||||
private EpubViewerPreferences epubSettings;
|
||||
private EbookViewerPreferences ebookSettings;
|
||||
private CbxViewerPreferences cbxSettings;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.adityachandel.booklore.model.dto;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class EbookViewerPreferences {
|
||||
private Long bookId;
|
||||
private Long userId;
|
||||
private String fontFamily;
|
||||
private Integer fontSize;
|
||||
private Float gap;
|
||||
private Boolean hyphenate;
|
||||
private Boolean isDark;
|
||||
private Boolean justify;
|
||||
private Float lineHeight;
|
||||
private Integer maxBlockSize;
|
||||
private Integer maxColumnCount;
|
||||
private Integer maxInlineSize;
|
||||
private String theme;
|
||||
private String flow;
|
||||
}
|
||||
|
||||
+1
@@ -9,6 +9,7 @@ import lombok.Data;
|
||||
public class EpubProgress {
|
||||
@NotNull
|
||||
String cfi;
|
||||
String href;
|
||||
@NotNull
|
||||
Float percentage;
|
||||
}
|
||||
|
||||
+3
-1
@@ -24,7 +24,9 @@ public class MetadataPersistenceSettings {
|
||||
private FormatSettings cbx;
|
||||
|
||||
public boolean isAnyFormatEnabled() {
|
||||
return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled()));
|
||||
return (epub != null && epub.isEnabled())
|
||||
|| (pdf != null && pdf.isEnabled())
|
||||
|| (cbx != null && cbx.isEnabled());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -8,6 +8,7 @@ public enum UserSettingKey {
|
||||
PDF_READER_SETTING("pdfReaderSetting", true),
|
||||
NEW_PDF_READER_SETTING("newPdfReaderSetting", true),
|
||||
EPUB_READER_SETTING("epubReaderSetting", true),
|
||||
EBOOK_READER_SETTING("ebookReaderSetting", true),
|
||||
CBX_READER_SETTING("cbxReaderSetting", true),
|
||||
SIDEBAR_LIBRARY_SORTING("sidebarLibrarySorting", true),
|
||||
SIDEBAR_SHELF_SORTING("sidebarShelfSorting", true),
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.adityachandel.booklore.model.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Table(name = "ebook_viewer_preference", uniqueConstraints = {
|
||||
@UniqueConstraint(columnNames = {"user_id", "book_id"})
|
||||
})
|
||||
public class EbookViewerPreferenceEntity {
|
||||
|
||||
@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 = "font_family", nullable = false)
|
||||
private String fontFamily;
|
||||
|
||||
@Column(name = "font_size", nullable = false)
|
||||
private Integer fontSize;
|
||||
|
||||
@Column(name = "gap", nullable = false)
|
||||
private Float gap;
|
||||
|
||||
@Column(name = "hyphenate", nullable = false)
|
||||
private Boolean hyphenate;
|
||||
|
||||
@Column(name = "is_dark", nullable = false)
|
||||
private Boolean isDark;
|
||||
|
||||
@Column(name = "justify", nullable = false)
|
||||
private Boolean justify;
|
||||
|
||||
@Column(name = "line_height", nullable = false)
|
||||
private Float lineHeight;
|
||||
|
||||
@Column(name = "max_block_size", nullable = false)
|
||||
private Integer maxBlockSize;
|
||||
|
||||
@Column(name = "max_column_count", nullable = false)
|
||||
private Integer maxColumnCount;
|
||||
|
||||
@Column(name = "max_inline_size", nullable = false)
|
||||
private Integer maxInlineSize;
|
||||
|
||||
@Column(name = "theme", nullable = false)
|
||||
private String theme;
|
||||
|
||||
@Column(name = "flow", nullable = false)
|
||||
private String flow;
|
||||
}
|
||||
|
||||
+3
@@ -39,6 +39,9 @@ public class UserBookProgressEntity {
|
||||
@Column(name = "epub_progress", length = 1000)
|
||||
private String epubProgress;
|
||||
|
||||
@Column(name = "epub_progress_href", length = 1000)
|
||||
private String epubProgressHref;
|
||||
|
||||
@Column(name = "epub_progress_percent")
|
||||
private Float epubProgressPercent;
|
||||
|
||||
|
||||
+3
@@ -14,6 +14,9 @@ public enum BookFileExtension {
|
||||
CBZ("cbz", BookFileType.CBX),
|
||||
CBR("cbr", BookFileType.CBX),
|
||||
CB7("cb7", BookFileType.CBX),
|
||||
MOBI("mobi", BookFileType.MOBI),
|
||||
AZW3("azw3", BookFileType.AZW3),
|
||||
AZW("azw", BookFileType.AZW3),
|
||||
FB2("fb2", BookFileType.FB2);
|
||||
|
||||
private final String extension;
|
||||
|
||||
@@ -12,7 +12,9 @@ public enum BookFileType {
|
||||
PDF(Set.of("pdf")),
|
||||
EPUB(Set.of("epub")),
|
||||
CBX(Set.of("cbz", "cbr", "cb7")),
|
||||
FB2(Set.of("fb2"));
|
||||
FB2(Set.of("fb2")),
|
||||
MOBI(Set.of("mobi")),
|
||||
AZW3(Set.of("azw3", "azw"));
|
||||
|
||||
private final Set<String> extensions;
|
||||
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.adityachandel.booklore.repository;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.EbookViewerPreferenceEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface EbookViewerPreferenceRepository extends JpaRepository<EbookViewerPreferenceEntity, Long> {
|
||||
|
||||
Optional<EbookViewerPreferenceEntity> findByBookIdAndUserId(Long bookId, Long userId);
|
||||
|
||||
}
|
||||
|
||||
+28
-102
@@ -4,30 +4,25 @@ import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.entity.NewPdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.core.io.*;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.UrlResource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -41,7 +36,6 @@ import java.net.MalformedURLException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -52,7 +46,6 @@ public class BookService {
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
private final FileService fileService;
|
||||
@@ -64,46 +57,9 @@ public class BookService {
|
||||
private final BookDownloadService bookDownloadService;
|
||||
private final MonitoringRegistrationService monitoringRegistrationService;
|
||||
private final BookUpdateService bookUpdateService;
|
||||
private final EbookViewerPreferenceRepository ebookViewerPreferencesRepository;
|
||||
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
}
|
||||
|
||||
public List<Book> getBookDTOs(boolean includeDescription) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
boolean isAdmin = user.getPermissions().isAdmin();
|
||||
@@ -125,7 +81,7 @@ public class BookService {
|
||||
);
|
||||
|
||||
books.forEach(book -> {
|
||||
enrichBookWithProgress(book, progressMap.get(book.getId()));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(book.getId()));
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
});
|
||||
|
||||
@@ -144,7 +100,7 @@ public class BookService {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
if (!withDescription) book.getMetadata().setDescription(null);
|
||||
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
@@ -158,46 +114,8 @@ public class BookService {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
book.setLastReadTime(userProgress.getLastReadTime());
|
||||
|
||||
if (userProgress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(userProgress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
bookEntity.getBookFiles().iterator().forEachRemaining(bookFile -> {
|
||||
if (bookFile.getBookType() == BookFileType.PDF) {
|
||||
book.setPdfProgress(PdfProgress.builder()
|
||||
.page(userProgress.getPdfProgress())
|
||||
.percentage(userProgress.getPdfProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
if (bookFile.getBookType() == BookFileType.EPUB) {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(userProgress.getEpubProgress())
|
||||
.percentage(userProgress.getEpubProgressPercent())
|
||||
.build());
|
||||
if (userProgress.getKoreaderProgressPercent() != null) {
|
||||
if (book.getKoreaderProgress() == null) {
|
||||
book.setKoreaderProgress(KoProgress.builder().build());
|
||||
}
|
||||
book.getKoreaderProgress().setPercentage(userProgress.getKoreaderProgressPercent() * 100);
|
||||
}
|
||||
}
|
||||
|
||||
if (bookFile.getBookType() == BookFileType.CBX) {
|
||||
book.setCbxProgress(CbxProgress.builder()
|
||||
.page(userProgress.getCbxProgress())
|
||||
.percentage(userProgress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
});
|
||||
|
||||
BookProgressUtil.enrichBookWithProgress(book, userProgress);
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
book.setReadStatus(userProgress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(userProgress.getReadStatus()));
|
||||
book.setDateFinished(userProgress.getDateFinished());
|
||||
book.setPersonalRating(userProgress.getPersonalRating());
|
||||
|
||||
if (!withDescription) {
|
||||
book.getMetadata().setDescription(null);
|
||||
@@ -206,26 +124,35 @@ public class BookService {
|
||||
return book;
|
||||
}
|
||||
|
||||
|
||||
public BookViewerSettings getBookViewerSetting(long bookId) {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
BookViewerSettings.BookViewerSettingsBuilder settingsBuilder = BookViewerSettings.builder();
|
||||
BookFileEntity bookFileEntity = bookEntity.getPrimaryBookFile();
|
||||
|
||||
if (bookFileEntity.getBookType() == BookFileType.EPUB) {
|
||||
epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(epubPref -> settingsBuilder.epubSettings(EpubViewerPreferences.builder()
|
||||
BookFileType bookType = bookEntity.getPrimaryBookFile().getBookType();
|
||||
if (bookType == BookFileType.EPUB || bookType == BookFileType.FB2
|
||||
|| bookType == BookFileType.MOBI
|
||||
|| bookType == BookFileType.AZW3) {
|
||||
ebookViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(epubPref -> settingsBuilder.ebookSettings(EbookViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
.font(epubPref.getFont())
|
||||
.userId(user.getId())
|
||||
.fontFamily(epubPref.getFontFamily())
|
||||
.fontSize(epubPref.getFontSize())
|
||||
.gap(epubPref.getGap())
|
||||
.hyphenate(epubPref.getHyphenate())
|
||||
.isDark(epubPref.getIsDark())
|
||||
.justify(epubPref.getJustify())
|
||||
.lineHeight(epubPref.getLineHeight())
|
||||
.maxBlockSize(epubPref.getMaxBlockSize())
|
||||
.maxColumnCount(epubPref.getMaxColumnCount())
|
||||
.maxInlineSize(epubPref.getMaxInlineSize())
|
||||
.theme(epubPref.getTheme())
|
||||
.flow(epubPref.getFlow())
|
||||
.spread(epubPref.getSpread())
|
||||
.letterSpacing(epubPref.getLetterSpacing())
|
||||
.lineHeight(epubPref.getLineHeight())
|
||||
.build()));
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.PDF) {
|
||||
} else if (bookType == BookFileType.PDF) {
|
||||
pdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(pdfPref -> settingsBuilder.pdfSettings(PdfViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
@@ -238,7 +165,7 @@ public class BookService {
|
||||
.pageViewMode(pdfPref.getPageViewMode())
|
||||
.pageSpread(pdfPref.getPageSpread())
|
||||
.build()));
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.CBX) {
|
||||
} else if (bookType == BookFileType.CBX) {
|
||||
cbxViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.ifPresent(cbxPref -> settingsBuilder.cbxSettings(CbxViewerPreferences.builder()
|
||||
.bookId(bookId)
|
||||
@@ -318,7 +245,6 @@ public class BookService {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
|
||||
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
|
||||
|
||||
+329
-298
@@ -1,64 +1,46 @@
|
||||
package com.adityachandel.booklore.service.book;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.service.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.BookViewerSettings;
|
||||
import com.adityachandel.booklore.model.dto.CbxViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.EpubViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.NewPdfViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.PdfViewerPreferences;
|
||||
import com.adityachandel.booklore.model.dto.Shelf;
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
|
||||
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
|
||||
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
|
||||
import com.adityachandel.booklore.model.dto.response.BookStatusUpdateResponse;
|
||||
import com.adityachandel.booklore.model.dto.response.PersonalRatingUpdateResponse;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookFileEntity;
|
||||
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
|
||||
import com.adityachandel.booklore.model.entity.CbxViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.EpubViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.NewPdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.PdfViewerPreferencesEntity;
|
||||
import com.adityachandel.booklore.model.entity.ShelfEntity;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.entity.*;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
import com.adityachandel.booklore.model.enums.ResetProgressType;
|
||||
import com.adityachandel.booklore.model.enums.UserPermission;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.CbxViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.EpubViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.NewPdfViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.PdfViewerPreferencesRepository;
|
||||
import com.adityachandel.booklore.repository.ShelfRepository;
|
||||
import com.adityachandel.booklore.repository.UserBookProgressRepository;
|
||||
import com.adityachandel.booklore.repository.UserRepository;
|
||||
import com.adityachandel.booklore.repository.*;
|
||||
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
|
||||
import com.adityachandel.booklore.service.user.UserProgressService;
|
||||
import com.adityachandel.booklore.util.BookProgressUtil;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.EnumUtils;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@AllArgsConstructor
|
||||
@Service
|
||||
public class BookUpdateService {
|
||||
|
||||
private static final float READING_THRESHOLD = 0.5f;
|
||||
private static final float COMPLETED_THRESHOLD = 99.5f;
|
||||
|
||||
private final BookRepository bookRepository;
|
||||
private final PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
private final EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private final CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
private final NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
private final ShelfRepository shelfRepository;
|
||||
@@ -69,132 +51,41 @@ public class BookUpdateService {
|
||||
private final BookQueryService bookQueryService;
|
||||
private final UserProgressService userProgressService;
|
||||
private final KoboReadingStateService koboReadingStateService;
|
||||
private final EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
public void updateBookViewerSetting(long bookId, BookViewerSettings bookViewerSettings) {
|
||||
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookFileEntity bookFileEntity = bookEntity.getPrimaryBookFile();
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if (bookFileEntity.getBookType() == BookFileType.PDF) {
|
||||
if (bookViewerSettings.getPdfSettings() != null) {
|
||||
PdfViewerPreferencesEntity pdfPrefs = pdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
PdfViewerPreferencesEntity newPrefs = PdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return pdfViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
PdfViewerPreferences pdfSettings = bookViewerSettings.getPdfSettings();
|
||||
pdfPrefs.setZoom(pdfSettings.getZoom());
|
||||
pdfPrefs.setSpread(pdfSettings.getSpread());
|
||||
pdfViewerPreferencesRepository.save(pdfPrefs);
|
||||
}
|
||||
if (bookViewerSettings.getNewPdfSettings() != null) {
|
||||
NewPdfViewerPreferencesEntity pdfPrefs = newPdfViewerPreferencesRepository.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
NewPdfViewerPreferencesEntity entity = NewPdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return newPdfViewerPreferencesRepository.save(entity);
|
||||
});
|
||||
NewPdfViewerPreferences pdfSettings = bookViewerSettings.getNewPdfSettings();
|
||||
pdfPrefs.setPageSpread(pdfSettings.getPageSpread());
|
||||
pdfPrefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||
newPdfViewerPreferencesRepository.save(pdfPrefs);
|
||||
}
|
||||
} else if (bookFileEntity.getBookType() == BookFileType.EPUB) {
|
||||
EpubViewerPreferencesEntity epubPrefs = epubViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, user.getId())
|
||||
.orElseGet(() -> {
|
||||
EpubViewerPreferencesEntity newPrefs = EpubViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(user.getId())
|
||||
.build();
|
||||
return epubViewerPreferencesRepository.save(newPrefs);
|
||||
});
|
||||
|
||||
EpubViewerPreferences epubSettings = bookViewerSettings.getEpubSettings();
|
||||
epubPrefs.setFont(epubSettings.getFont());
|
||||
epubPrefs.setFontSize(epubSettings.getFontSize());
|
||||
epubPrefs.setTheme(epubSettings.getTheme());
|
||||
epubPrefs.setFlow(epubSettings.getFlow());
|
||||
epubPrefs.setSpread(epubSettings.getSpread());
|
||||
epubPrefs.setLetterSpacing(epubSettings.getLetterSpacing());
|
||||
epubPrefs.setLineHeight(epubSettings.getLineHeight());
|
||||
epubViewerPreferencesRepository.save(epubPrefs);
|
||||
|
||||
} else if (bookFileEntity.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());
|
||||
cbxPrefs.setFitMode(cbxSettings.getFitMode());
|
||||
cbxPrefs.setScrollMode(cbxSettings.getScrollMode());
|
||||
cbxPrefs.setBackgroundColor(cbxSettings.getBackgroundColor());
|
||||
cbxViewerPreferencesRepository.save(cbxPrefs);
|
||||
|
||||
} else {
|
||||
if (book.getPrimaryBookFile().getBookType() == null) {
|
||||
throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
switch (book.getPrimaryBookFile().getBookType()) {
|
||||
case PDF -> updatePdfViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
case CBX -> updateCbxViewerSettings(bookId, user.getId(), bookViewerSettings);
|
||||
default -> throw ApiError.UNSUPPORTED_BOOK_TYPE.createException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void updateReadProgress(ReadProgressRequest request) {
|
||||
BookEntity book = bookRepository.findByIdWithBookFiles(request.getBookId()).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(request.getBookId()));
|
||||
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
UserBookProgressEntity progress = userBookProgressRepository
|
||||
.findByUserIdAndBookId(user.getId(), book.getId())
|
||||
.orElseGet(UserBookProgressEntity::new);
|
||||
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId())
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(user.getId());
|
||||
progress.setUser(userEntity);
|
||||
|
||||
progress.setBook(book);
|
||||
progress.setLastReadTime(Instant.now());
|
||||
|
||||
Float percentage = null;
|
||||
BookFileEntity bookFileEntity = book.getPrimaryBookFile();
|
||||
switch (bookFileEntity.getBookType()) {
|
||||
case EPUB -> {
|
||||
if (request.getEpubProgress() != null) {
|
||||
progress.setEpubProgress(request.getEpubProgress().getCfi());
|
||||
percentage = request.getEpubProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
case PDF -> {
|
||||
if (request.getPdfProgress() != null) {
|
||||
progress.setPdfProgress(request.getPdfProgress().getPage());
|
||||
percentage = request.getPdfProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
case CBX -> {
|
||||
if (request.getCbxProgress() != null) {
|
||||
progress.setCbxProgress(request.getCbxProgress().getPage());
|
||||
percentage = request.getCbxProgress().getPercentage();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Float percentage = updateProgressByBookType(progress, book.getPrimaryBookFile().getBookType(), request);
|
||||
if (percentage != null) {
|
||||
progress.setReadStatus(getStatus(percentage));
|
||||
setProgressPercent(progress, bookFileEntity.getBookType(), percentage);
|
||||
progress.setReadStatus(calculateReadStatus(percentage));
|
||||
setProgressPercent(progress, book.getPrimaryBookFile().getBookType(), percentage);
|
||||
}
|
||||
|
||||
if (request.getDateFinished() != null) {
|
||||
progress.setDateFinished(request.getDateFinished());
|
||||
}
|
||||
@@ -205,161 +96,280 @@ public class BookUpdateService {
|
||||
@Transactional
|
||||
public List<BookStatusUpdateResponse> updateReadStatus(List<Long> bookIds, String status) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if(bookIds.size() > 1 && !UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS);
|
||||
}
|
||||
validateBulkOperationPermission(bookIds, user, UserPermission.CAN_BULK_RESET_BOOK_READ_STATUS);
|
||||
|
||||
ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status);
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
Instant now = Instant.now();
|
||||
Instant dateFinished = readStatus == ReadStatus.READ ? now : null;
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdateReadStatus(user.getId(), new ArrayList<>(existingProgressBookIds), readStatus, now, dateFinished);
|
||||
}
|
||||
updateExistingProgress(user.getId(), existingProgressBookIds, readStatus, now, dateFinished);
|
||||
createNewProgress(user.getId(), bookIds, existingProgressBookIds, readStatus, now, dateFinished);
|
||||
|
||||
Set<Long> newProgressBookIds = bookIds.stream()
|
||||
.filter(id -> !existingProgressBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (!newProgressBookIds.isEmpty()) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(userEntity);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setReadStatus(readStatus);
|
||||
progress.setReadStatusModifiedTime(now);
|
||||
progress.setDateFinished(dateFinished);
|
||||
return progress;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(readStatus)
|
||||
.readStatusModifiedTime(now)
|
||||
.dateFinished(dateFinished)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildStatusUpdateResponses(bookIds, readStatus, now, dateFinished);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<BookStatusUpdateResponse> resetProgress(List<Long> bookIds, ResetProgressType type) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
if(bookIds.size() > 1 && type == ResetProgressType.BOOKLORE && !UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS);
|
||||
}
|
||||
|
||||
if(bookIds.size() > 1 && type == ResetProgressType.KOREADER && !UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS);
|
||||
}
|
||||
validateResetPermission(bookIds, user, type);
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
if (type == ResetProgressType.BOOKLORE) {
|
||||
userBookProgressRepository.bulkResetBookloreProgress(user.getId(), new ArrayList<>(existingProgressBookIds), now);
|
||||
} else if (type == ResetProgressType.KOREADER) {
|
||||
userBookProgressRepository.bulkResetKoreaderProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
|
||||
} else if (type == ResetProgressType.KOBO) {
|
||||
userBookProgressRepository.bulkResetKoboProgress(user.getId(), new ArrayList<>(existingProgressBookIds));
|
||||
existingProgressBookIds.forEach(koboReadingStateService::deleteReadingState);
|
||||
}
|
||||
performReset(user.getId(), existingProgressBookIds, type, now);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(null)
|
||||
.readStatusModifiedTime(existingProgressBookIds.contains(bookId) ? now : null)
|
||||
.dateFinished(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildResetResponses(bookIds, existingProgressBookIds, now);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PersonalRatingUpdateResponse> updatePersonalRating(List<Long> bookIds, Integer rating) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), rating);
|
||||
}
|
||||
|
||||
Set<Long> newProgressBookIds = bookIds.stream()
|
||||
.filter(id -> !existingProgressBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
createProgressForRating(user.getId(), bookIds, existingProgressBookIds, rating);
|
||||
|
||||
if (!newProgressBookIds.isEmpty()) {
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> new UsernameNotFoundException("User not found"));
|
||||
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(userEntity);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setPersonalRating(rating);
|
||||
return progress;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(rating)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildRatingUpdateResponses(bookIds, rating);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PersonalRatingUpdateResponse> resetPersonalRating(List<Long> bookIds) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
|
||||
Set<Long> existingProgressBookIds = validateBooksAndGetExistingProgress(user.getId(), bookIds);
|
||||
|
||||
if (!existingProgressBookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdatePersonalRating(user.getId(), new ArrayList<>(existingProgressBookIds), null);
|
||||
}
|
||||
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return buildRatingUpdateResponses(bookIds, null);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<Book> assignShelvesToBooks(Set<Long> bookIds, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
BookLoreUserEntity userEntity = userRepository.findById(user.getId()).orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(user.getId()));
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(user.getId());
|
||||
|
||||
Set<Long> userShelfIds = userEntity.getShelves().stream().map(ShelfEntity::getId).collect(Collectors.toSet());
|
||||
validateShelfOwnership(userEntity, shelfIdsToAssign, shelfIdsToUnassign);
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
|
||||
updateBookShelves(bookEntities, shelvesToAssign, shelfIdsToUnassign);
|
||||
bookRepository.saveAll(bookEntities);
|
||||
|
||||
return buildBooksWithProgress(bookEntities, user.getId());
|
||||
}
|
||||
|
||||
private void updatePdfViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
if (settings.getPdfSettings() != null) {
|
||||
PdfViewerPreferencesEntity prefs = findOrCreatePdfPreferences(bookId, userId);
|
||||
PdfViewerPreferences pdfSettings = settings.getPdfSettings();
|
||||
prefs.setZoom(pdfSettings.getZoom());
|
||||
prefs.setSpread(pdfSettings.getSpread());
|
||||
pdfViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
|
||||
if (settings.getNewPdfSettings() != null) {
|
||||
NewPdfViewerPreferencesEntity prefs = findOrCreateNewPdfPreferences(bookId, userId);
|
||||
NewPdfViewerPreferences pdfSettings = settings.getNewPdfSettings();
|
||||
prefs.setPageSpread(pdfSettings.getPageSpread());
|
||||
prefs.setPageViewMode(pdfSettings.getPageViewMode());
|
||||
newPdfViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateEbookViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
EbookViewerPreferenceEntity prefs = findOrCreateEbookPreferences(bookId, userId);
|
||||
EbookViewerPreferences epubSettings = settings.getEbookSettings();
|
||||
|
||||
prefs.setUserId(userId);
|
||||
prefs.setBookId(bookId);
|
||||
prefs.setFontFamily(epubSettings.getFontFamily());
|
||||
prefs.setFontSize(epubSettings.getFontSize());
|
||||
prefs.setGap(epubSettings.getGap());
|
||||
prefs.setHyphenate(epubSettings.getHyphenate());
|
||||
prefs.setIsDark(epubSettings.getIsDark());
|
||||
prefs.setJustify(epubSettings.getJustify());
|
||||
prefs.setLineHeight(epubSettings.getLineHeight());
|
||||
prefs.setMaxBlockSize(epubSettings.getMaxBlockSize());
|
||||
prefs.setMaxColumnCount(epubSettings.getMaxColumnCount());
|
||||
prefs.setMaxInlineSize(epubSettings.getMaxInlineSize());
|
||||
prefs.setTheme(epubSettings.getTheme());
|
||||
prefs.setFlow(epubSettings.getFlow());
|
||||
|
||||
ebookViewerPreferenceRepository.save(prefs);
|
||||
}
|
||||
|
||||
private void updateCbxViewerSettings(long bookId, Long userId, BookViewerSettings settings) {
|
||||
CbxViewerPreferencesEntity prefs = findOrCreateCbxPreferences(bookId, userId);
|
||||
CbxViewerPreferences cbxSettings = settings.getCbxSettings();
|
||||
|
||||
prefs.setPageSpread(cbxSettings.getPageSpread());
|
||||
prefs.setPageViewMode(cbxSettings.getPageViewMode());
|
||||
prefs.setFitMode(cbxSettings.getFitMode());
|
||||
prefs.setScrollMode(cbxSettings.getScrollMode());
|
||||
prefs.setBackgroundColor(cbxSettings.getBackgroundColor());
|
||||
|
||||
cbxViewerPreferencesRepository.save(prefs);
|
||||
}
|
||||
|
||||
private PdfViewerPreferencesEntity findOrCreatePdfPreferences(long bookId, Long userId) {
|
||||
return pdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> pdfViewerPreferencesRepository.save(
|
||||
PdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private NewPdfViewerPreferencesEntity findOrCreateNewPdfPreferences(long bookId, Long userId) {
|
||||
return newPdfViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> newPdfViewerPreferencesRepository.save(
|
||||
NewPdfViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private EbookViewerPreferenceEntity findOrCreateEbookPreferences(long bookId, Long userId) {
|
||||
return ebookViewerPreferenceRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> ebookViewerPreferenceRepository.save(
|
||||
EbookViewerPreferenceEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private CbxViewerPreferencesEntity findOrCreateCbxPreferences(long bookId, Long userId) {
|
||||
return cbxViewerPreferencesRepository
|
||||
.findByBookIdAndUserId(bookId, userId)
|
||||
.orElseGet(() -> cbxViewerPreferencesRepository.save(
|
||||
CbxViewerPreferencesEntity.builder()
|
||||
.bookId(bookId)
|
||||
.userId(userId)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
private Float updateProgressByBookType(UserBookProgressEntity progress, BookFileType bookType, ReadProgressRequest request) {
|
||||
return switch (bookType) {
|
||||
case EPUB, FB2, MOBI, AZW3 -> updateEbookProgress(progress, request.getEpubProgress());
|
||||
case PDF -> updatePdfProgress(progress, request.getPdfProgress());
|
||||
case CBX -> updateCbxProgress(progress, request.getCbxProgress());
|
||||
};
|
||||
}
|
||||
|
||||
private Float updateEbookProgress(UserBookProgressEntity progress, EpubProgress epubProgress) {
|
||||
if (epubProgress == null) return null;
|
||||
progress.setEpubProgress(epubProgress.getCfi());
|
||||
progress.setEpubProgressHref(epubProgress.getHref());
|
||||
return epubProgress.getPercentage();
|
||||
}
|
||||
|
||||
private Float updatePdfProgress(UserBookProgressEntity progress, PdfProgress pdfProgress) {
|
||||
if (pdfProgress == null) return null;
|
||||
progress.setPdfProgress(pdfProgress.getPage());
|
||||
return pdfProgress.getPercentage();
|
||||
}
|
||||
|
||||
private Float updateCbxProgress(UserBookProgressEntity progress, CbxProgress cbxProgress) {
|
||||
if (cbxProgress == null) return null;
|
||||
progress.setCbxProgress(cbxProgress.getPage());
|
||||
return cbxProgress.getPercentage();
|
||||
}
|
||||
|
||||
private void updateExistingProgress(Long userId, Set<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
if (!bookIds.isEmpty()) {
|
||||
userBookProgressRepository.bulkUpdateReadStatus(userId, new ArrayList<>(bookIds), status, now, dateFinished);
|
||||
}
|
||||
}
|
||||
|
||||
private void createNewProgress(Long userId, List<Long> allBookIds, Set<Long> existingBookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
Set<Long> newProgressBookIds = allBookIds.stream()
|
||||
.filter(id -> !existingBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (newProgressBookIds.isEmpty()) return;
|
||||
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(userId);
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> createProgressEntity(userEntity, bookId, status, now, dateFinished))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
private UserBookProgressEntity createProgressEntity(BookLoreUserEntity user, Long bookId, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(user);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setReadStatus(status);
|
||||
progress.setReadStatusModifiedTime(now);
|
||||
progress.setDateFinished(dateFinished);
|
||||
return progress;
|
||||
}
|
||||
|
||||
private void performReset(Long userId, Set<Long> bookIds, ResetProgressType type, Instant now) {
|
||||
List<Long> bookIdList = new ArrayList<>(bookIds);
|
||||
|
||||
switch (type) {
|
||||
case BOOKLORE -> userBookProgressRepository.bulkResetBookloreProgress(userId, bookIdList, now);
|
||||
case KOREADER -> userBookProgressRepository.bulkResetKoreaderProgress(userId, bookIdList);
|
||||
case KOBO -> {
|
||||
userBookProgressRepository.bulkResetKoboProgress(userId, bookIdList);
|
||||
bookIds.forEach(koboReadingStateService::deleteReadingState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createProgressForRating(Long userId, List<Long> allBookIds, Set<Long> existingBookIds, Integer rating) {
|
||||
Set<Long> newProgressBookIds = allBookIds.stream()
|
||||
.filter(id -> !existingBookIds.contains(id))
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (newProgressBookIds.isEmpty()) return;
|
||||
|
||||
BookLoreUserEntity userEntity = findUserOrThrow(userId);
|
||||
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
|
||||
.map(bookId -> createProgressEntityWithRating(userEntity, bookId, rating))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
userBookProgressRepository.saveAll(newProgressEntities);
|
||||
}
|
||||
|
||||
private UserBookProgressEntity createProgressEntityWithRating(BookLoreUserEntity user, Long bookId, Integer rating) {
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setUser(user);
|
||||
|
||||
BookEntity bookEntity = new BookEntity();
|
||||
bookEntity.setId(bookId);
|
||||
progress.setBook(bookEntity);
|
||||
|
||||
progress.setPersonalRating(rating);
|
||||
return progress;
|
||||
}
|
||||
|
||||
private void validateShelfOwnership(BookLoreUserEntity user, Set<Long> shelfIdsToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
Set<Long> userShelfIds = user.getShelves().stream()
|
||||
.map(ShelfEntity::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (!userShelfIds.containsAll(shelfIdsToAssign)) {
|
||||
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot assign shelves that do not belong to the user.");
|
||||
@@ -367,25 +377,53 @@ public class BookUpdateService {
|
||||
if (!userShelfIds.containsAll(shelfIdsToUnassign)) {
|
||||
throw ApiError.GENERIC_UNAUTHORIZED.createException("Cannot unassign shelves that do not belong to the user.");
|
||||
}
|
||||
}
|
||||
|
||||
List<BookEntity> bookEntities = bookQueryService.findAllWithMetadataByIds(bookIds);
|
||||
List<ShelfEntity> shelvesToAssign = shelfRepository.findAllById(shelfIdsToAssign);
|
||||
for (BookEntity bookEntity : bookEntities) {
|
||||
bookEntity.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
bookEntity.getShelves().addAll(shelvesToAssign);
|
||||
private void updateBookShelves(List<BookEntity> books, List<ShelfEntity> shelvesToAssign, Set<Long> shelfIdsToUnassign) {
|
||||
for (BookEntity book : books) {
|
||||
book.getShelves().removeIf(shelf -> shelfIdsToUnassign.contains(shelf.getId()));
|
||||
book.getShelves().addAll(shelvesToAssign);
|
||||
}
|
||||
bookRepository.saveAll(bookEntities);
|
||||
}
|
||||
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(
|
||||
user.getId(), bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet()));
|
||||
private List<Book> buildBooksWithProgress(List<BookEntity> bookEntities, Long userId) {
|
||||
Set<Long> bookIds = bookEntities.stream().map(BookEntity::getId).collect(Collectors.toSet());
|
||||
Map<Long, UserBookProgressEntity> progressMap = userProgressService.fetchUserProgress(userId, bookIds);
|
||||
|
||||
return bookEntities.stream().map(bookEntity -> {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}).collect(Collectors.toList());
|
||||
return bookEntities.stream()
|
||||
.map(bookEntity -> buildBook(bookEntity, userId, progressMap))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Book buildBook(BookEntity bookEntity, Long userId, Map<Long, UserBookProgressEntity> progressMap) {
|
||||
Book book = bookMapper.toBook(bookEntity);
|
||||
book.setShelves(filterShelvesByUserId(book.getShelves(), userId));
|
||||
book.setFilePath(FileUtils.getBookFullPath(bookEntity));
|
||||
BookProgressUtil.enrichBookWithProgress(book, progressMap.get(bookEntity.getId()));
|
||||
return book;
|
||||
}
|
||||
|
||||
private BookLoreUserEntity findUserOrThrow(Long userId) {
|
||||
return userRepository.findById(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
}
|
||||
|
||||
private void validateBulkOperationPermission(List<Long> bookIds, BookLoreUser user, UserPermission permission) {
|
||||
if (bookIds.size() > 1 && !permission.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateResetPermission(List<Long> bookIds, BookLoreUser user, ResetProgressType type) {
|
||||
if (bookIds.size() <= 1) return;
|
||||
UserPermission permission = switch (type) {
|
||||
case BOOKLORE -> UserPermission.CAN_BULK_RESET_BOOKLORE_READ_PROGRESS;
|
||||
case KOREADER -> UserPermission.CAN_BULK_RESET_KOREADER_READ_PROGRESS;
|
||||
default -> null;
|
||||
};
|
||||
if (permission != null && !permission.isGranted(user.getPermissions())) {
|
||||
throw ApiError.PERMISSION_DENIED.createException(permission);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Long> validateBooksAndGetExistingProgress(Long userId, List<Long> bookIds) {
|
||||
@@ -399,54 +437,47 @@ public class BookUpdateService {
|
||||
|
||||
private void setProgressPercent(UserBookProgressEntity progress, BookFileType type, Float percentage) {
|
||||
switch (type) {
|
||||
case EPUB -> progress.setEpubProgressPercent(percentage);
|
||||
case EPUB, FB2, MOBI, AZW3 -> progress.setEpubProgressPercent(percentage);
|
||||
case PDF -> progress.setPdfProgressPercent(percentage);
|
||||
case CBX -> progress.setCbxProgressPercent(percentage);
|
||||
}
|
||||
}
|
||||
|
||||
private ReadStatus getStatus(Float percentage) {
|
||||
if (percentage >= 99.5f) return ReadStatus.READ;
|
||||
if (percentage > 0.5f) return ReadStatus.READING;
|
||||
private ReadStatus calculateReadStatus(Float percentage) {
|
||||
if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ;
|
||||
if (percentage > READING_THRESHOLD) return ReadStatus.READING;
|
||||
return ReadStatus.UNREAD;
|
||||
}
|
||||
|
||||
private void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
private List<BookStatusUpdateResponse> buildStatusUpdateResponses(List<Long> bookIds, ReadStatus status, Instant now, Instant dateFinished) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(status)
|
||||
.readStatusModifiedTime(now)
|
||||
.dateFinished(dateFinished)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(com.adityachandel.booklore.model.dto.progress.KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
private List<BookStatusUpdateResponse> buildResetResponses(List<Long> bookIds, Set<Long> existingBookIds, Instant now) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> BookStatusUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.readStatus(null)
|
||||
.readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null)
|
||||
.dateFinished(null)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
switch (book.getBookType()) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(com.adityachandel.booklore.model.dto.progress.EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(com.adityachandel.booklore.model.dto.progress.KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case PDF -> book.setPdfProgress(com.adityachandel.booklore.model.dto.progress.PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(com.adityachandel.booklore.model.dto.progress.CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
private List<PersonalRatingUpdateResponse> buildRatingUpdateResponses(List<Long> bookIds, Integer rating) {
|
||||
return bookIds.stream()
|
||||
.map(bookId -> PersonalRatingUpdateResponse.builder()
|
||||
.bookId(bookId)
|
||||
.personalRating(rating)
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
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.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.Azw3MetadataExtractor;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class Azw3Processor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final Azw3MetadataExtractor azw3MetadataExtractor;
|
||||
|
||||
public Azw3Processor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService,
|
||||
Azw3MetadataExtractor azw3MetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.azw3MetadataExtractor = azw3MetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookFileType fileType = determineFileType(libraryFile.getFileName());
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, fileType);
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try {
|
||||
File azw3File = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
byte[] coverData = azw3MetadataExtractor.extractCover(azw3File);
|
||||
|
||||
if (coverData == null || coverData.length == 0) {
|
||||
log.warn("No cover image found in AZW3 '{}'", bookEntity.getPrimaryBookFile());
|
||||
return false;
|
||||
}
|
||||
|
||||
return saveCoverImage(coverData, bookEntity.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for AZW3 '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.AZW3);
|
||||
}
|
||||
|
||||
private BookFileType determineFileType(String fileName) {
|
||||
return BookFileType.AZW3;
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
BookMetadata azw3Metadata = azw3MetadataExtractor.extractMetadata(bookFile);
|
||||
if (azw3Metadata == null) return;
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
metadata.setTitle(truncate(azw3Metadata.getTitle(), 1000));
|
||||
metadata.setSubtitle(truncate(azw3Metadata.getSubtitle(), 1000));
|
||||
metadata.setDescription(truncate(azw3Metadata.getDescription(), 2000));
|
||||
metadata.setPublisher(truncate(azw3Metadata.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(azw3Metadata.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(azw3Metadata.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(azw3Metadata.getSeriesNumber());
|
||||
metadata.setSeriesTotal(azw3Metadata.getSeriesTotal());
|
||||
metadata.setIsbn13(truncate(azw3Metadata.getIsbn13(), 64));
|
||||
metadata.setIsbn10(truncate(azw3Metadata.getIsbn10(), 64));
|
||||
metadata.setPageCount(azw3Metadata.getPageCount());
|
||||
|
||||
String lang = azw3Metadata.getLanguage();
|
||||
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||
|
||||
metadata.setAsin(truncate(azw3Metadata.getAsin(), 20));
|
||||
metadata.setAmazonRating(azw3Metadata.getAmazonRating());
|
||||
metadata.setAmazonReviewCount(azw3Metadata.getAmazonReviewCount());
|
||||
metadata.setGoodreadsId(truncate(azw3Metadata.getGoodreadsId(), 100));
|
||||
metadata.setGoodreadsRating(azw3Metadata.getGoodreadsRating());
|
||||
metadata.setGoodreadsReviewCount(azw3Metadata.getGoodreadsReviewCount());
|
||||
metadata.setHardcoverId(truncate(azw3Metadata.getHardcoverId(), 100));
|
||||
metadata.setHardcoverRating(azw3Metadata.getHardcoverRating());
|
||||
metadata.setHardcoverReviewCount(azw3Metadata.getHardcoverReviewCount());
|
||||
metadata.setGoogleId(truncate(azw3Metadata.getGoogleId(), 100));
|
||||
metadata.setComicvineId(truncate(azw3Metadata.getComicvineId(), 100));
|
||||
metadata.setRanobedbId(truncate(azw3Metadata.getRanobedbId(), 100));
|
||||
metadata.setRanobedbRating(azw3Metadata.getRanobedbRating());
|
||||
|
||||
bookCreatorService.addAuthorsToBook(azw3Metadata.getAuthors(), bookEntity);
|
||||
|
||||
if (azw3Metadata.getCategories() != null) {
|
||||
Set<String> validSubjects = azw3Metadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.collect(Collectors.toSet());
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
|
||||
BufferedImage originalImage = FileService.readImage(coverData);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for AZW3");
|
||||
return false;
|
||||
}
|
||||
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package com.adityachandel.booklore.service.fileprocessor;
|
||||
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
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.BookAdditionalFileRepository;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.service.book.BookCreatorService;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataMatchService;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.MobiMetadataExtractor;
|
||||
import com.adityachandel.booklore.util.BookCoverUtils;
|
||||
import com.adityachandel.booklore.util.FileService;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.util.FileService.truncate;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MobiProcessor extends AbstractFileProcessor implements BookFileProcessor {
|
||||
|
||||
private final MobiMetadataExtractor mobiMetadataExtractor;
|
||||
|
||||
public MobiProcessor(BookRepository bookRepository,
|
||||
BookAdditionalFileRepository bookAdditionalFileRepository,
|
||||
BookCreatorService bookCreatorService,
|
||||
BookMapper bookMapper,
|
||||
FileService fileService,
|
||||
MetadataMatchService metadataMatchService,
|
||||
MobiMetadataExtractor mobiMetadataExtractor) {
|
||||
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
|
||||
this.mobiMetadataExtractor = mobiMetadataExtractor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookEntity processNewFile(LibraryFile libraryFile) {
|
||||
BookFileType fileType = determineFileType(libraryFile.getFileName());
|
||||
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, fileType);
|
||||
setBookMetadata(bookEntity);
|
||||
if (generateCover(bookEntity)) {
|
||||
FileService.setBookCoverPath(bookEntity.getMetadata());
|
||||
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
|
||||
}
|
||||
return bookEntity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean generateCover(BookEntity bookEntity) {
|
||||
try {
|
||||
File mobiFile = new File(FileUtils.getBookFullPath(bookEntity));
|
||||
byte[] coverData = mobiMetadataExtractor.extractCover(mobiFile);
|
||||
|
||||
if (coverData == null || coverData.length == 0) {
|
||||
log.warn("No cover image found in MOBI '{}'", bookEntity.getPrimaryBookFile().getFileName());
|
||||
return false;
|
||||
}
|
||||
|
||||
return saveCoverImage(coverData, bookEntity.getId());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("Error generating cover for MOBI '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BookFileType> getSupportedTypes() {
|
||||
return List.of(BookFileType.MOBI);
|
||||
}
|
||||
|
||||
private BookFileType determineFileType(String fileName) {
|
||||
String lowerCase = fileName.toLowerCase();
|
||||
return BookFileType.MOBI;
|
||||
}
|
||||
|
||||
private void setBookMetadata(BookEntity bookEntity) {
|
||||
File bookFile = new File(bookEntity.getFullFilePath().toUri());
|
||||
BookMetadata mobiMetadata = mobiMetadataExtractor.extractMetadata(bookFile);
|
||||
if (mobiMetadata == null) return;
|
||||
|
||||
BookMetadataEntity metadata = bookEntity.getMetadata();
|
||||
|
||||
metadata.setTitle(truncate(mobiMetadata.getTitle(), 1000));
|
||||
metadata.setSubtitle(truncate(mobiMetadata.getSubtitle(), 1000));
|
||||
metadata.setDescription(truncate(mobiMetadata.getDescription(), 2000));
|
||||
metadata.setPublisher(truncate(mobiMetadata.getPublisher(), 1000));
|
||||
metadata.setPublishedDate(mobiMetadata.getPublishedDate());
|
||||
metadata.setSeriesName(truncate(mobiMetadata.getSeriesName(), 1000));
|
||||
metadata.setSeriesNumber(mobiMetadata.getSeriesNumber());
|
||||
metadata.setSeriesTotal(mobiMetadata.getSeriesTotal());
|
||||
metadata.setIsbn13(truncate(mobiMetadata.getIsbn13(), 64));
|
||||
metadata.setIsbn10(truncate(mobiMetadata.getIsbn10(), 64));
|
||||
metadata.setPageCount(mobiMetadata.getPageCount());
|
||||
|
||||
String lang = mobiMetadata.getLanguage();
|
||||
metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000));
|
||||
|
||||
metadata.setAsin(truncate(mobiMetadata.getAsin(), 20));
|
||||
metadata.setAmazonRating(mobiMetadata.getAmazonRating());
|
||||
metadata.setAmazonReviewCount(mobiMetadata.getAmazonReviewCount());
|
||||
metadata.setGoodreadsId(truncate(mobiMetadata.getGoodreadsId(), 100));
|
||||
metadata.setGoodreadsRating(mobiMetadata.getGoodreadsRating());
|
||||
metadata.setGoodreadsReviewCount(mobiMetadata.getGoodreadsReviewCount());
|
||||
metadata.setHardcoverId(truncate(mobiMetadata.getHardcoverId(), 100));
|
||||
metadata.setHardcoverRating(mobiMetadata.getHardcoverRating());
|
||||
metadata.setHardcoverReviewCount(mobiMetadata.getHardcoverReviewCount());
|
||||
metadata.setGoogleId(truncate(mobiMetadata.getGoogleId(), 100));
|
||||
metadata.setComicvineId(truncate(mobiMetadata.getComicvineId(), 100));
|
||||
metadata.setRanobedbId(truncate(mobiMetadata.getRanobedbId(), 100));
|
||||
metadata.setRanobedbRating(mobiMetadata.getRanobedbRating());
|
||||
|
||||
bookCreatorService.addAuthorsToBook(mobiMetadata.getAuthors(), bookEntity);
|
||||
|
||||
if (mobiMetadata.getCategories() != null) {
|
||||
Set<String> validSubjects = mobiMetadata.getCategories().stream()
|
||||
.filter(s -> s != null && !s.isBlank() && s.length() <= 100 && !s.contains("\n") && !s.contains("\r") && !s.contains(" "))
|
||||
.collect(Collectors.toSet());
|
||||
bookCreatorService.addCategoriesToBook(validSubjects, bookEntity);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception {
|
||||
BufferedImage originalImage = FileService.readImage(coverData);
|
||||
if (originalImage == null) {
|
||||
log.warn("Failed to decode cover image for MOBI");
|
||||
return false;
|
||||
}
|
||||
|
||||
return fileService.saveCoverImages(originalImage, bookId);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-8
@@ -562,23 +562,23 @@ public class MetadataRefreshService {
|
||||
return metadata;
|
||||
}
|
||||
|
||||
protected <T> T resolveField(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor) {
|
||||
protected <T > T resolveField(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor) {
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, extractor, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected Integer resolveFieldAsInteger(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, Integer> fieldValueExtractor) {
|
||||
protected Integer resolveFieldAsInteger (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, Integer > fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected String resolveFieldAsString(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor) {
|
||||
protected String resolveFieldAsString (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractor fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, Objects::nonNull);
|
||||
}
|
||||
|
||||
protected Set<String> resolveFieldAsList(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
protected Set<String> resolveFieldAsList (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
|
||||
return resolveFieldWithProviders(metadataMap, fieldProvider, fieldValueExtractor::extract, (value) -> value != null && !value.isEmpty());
|
||||
}
|
||||
|
||||
private <T> T resolveFieldWithProviders(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function<BookMetadata, T> extractor, Predicate<T> isValidValue) {
|
||||
private <T > T resolveFieldWithProviders(Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, Function < BookMetadata, T > extractor, Predicate < T > isValidValue) {
|
||||
if (fieldProvider == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -599,7 +599,7 @@ public class MetadataRefreshService {
|
||||
return null;
|
||||
}
|
||||
|
||||
Set<String> getAllCategories(Map<MetadataProvider, BookMetadata> metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor) {
|
||||
Set<String> getAllCategories (Map < MetadataProvider, BookMetadata > metadataMap, MetadataRefreshOptions.FieldProvider fieldProvider, FieldValueExtractorList fieldValueExtractor){
|
||||
Set<String> uniqueCategories = new HashSet<>();
|
||||
if (fieldProvider == null) {
|
||||
return uniqueCategories;
|
||||
@@ -624,7 +624,7 @@ public class MetadataRefreshService {
|
||||
return uniqueCategories;
|
||||
}
|
||||
|
||||
protected Set<Long> getBookEntities(MetadataRefreshRequest request) {
|
||||
protected Set<Long> getBookEntities (MetadataRefreshRequest request){
|
||||
MetadataRefreshRequest.RefreshType refreshType = request.getRefreshType();
|
||||
if (refreshType != MetadataRefreshRequest.RefreshType.LIBRARY && refreshType != MetadataRefreshRequest.RefreshType.BOOKS) {
|
||||
throw ApiError.INVALID_REFRESH_TYPE.createException();
|
||||
@@ -638,4 +638,3 @@ public class MetadataRefreshService {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class Azw3MetadataExtractor extends MobiBaseMetadataExtractor {
|
||||
|
||||
private static final long KF8_BOUNDARY = 0xFFFFFFFF;
|
||||
|
||||
@Override
|
||||
protected String getFormatName() {
|
||||
return "AZW3";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void processFormatSpecificHeader(RandomAccessFile raf, PalmDBRecord record0, MobiHeader header, int headerLength) throws IOException {
|
||||
// For KF8 (AZW3), check for KF8 boundary and resource index
|
||||
if (header.isKF8 && headerLength >= 232) {
|
||||
raf.seek(record0.offset + 16 + 192);
|
||||
long kf8Boundary = readInt(raf) & 0xFFFFFFFFL;
|
||||
if (kf8Boundary == KF8_BOUNDARY) {
|
||||
log.debug("KF8 boundary found at expected location");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -16,6 +16,8 @@ public class MetadataExtractorFactory {
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final CbxMetadataExtractor cbxMetadataExtractor;
|
||||
private final Fb2MetadataExtractor fb2MetadataExtractor;
|
||||
private final MobiMetadataExtractor mobiMetadataExtractor;
|
||||
private final Azw3MetadataExtractor azw3MetadataExtractor;
|
||||
|
||||
public BookMetadata extractMetadata(BookFileType bookFileType, File file) {
|
||||
return switch (bookFileType) {
|
||||
@@ -23,6 +25,8 @@ public class MetadataExtractorFactory {
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBX -> cbxMetadataExtractor.extractMetadata(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3 -> azw3MetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -32,6 +36,8 @@ public class MetadataExtractorFactory {
|
||||
case EPUB -> epubMetadataExtractor.extractMetadata(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractMetadata(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractMetadata(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractMetadata(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractMetadata(file);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +47,8 @@ public class MetadataExtractorFactory {
|
||||
case PDF -> pdfMetadataExtractor.extractCover(file);
|
||||
case CBZ, CBR, CB7 -> cbxMetadataExtractor.extractCover(file);
|
||||
case FB2 -> fb2MetadataExtractor.extractCover(file);
|
||||
case MOBI -> mobiMetadataExtractor.extractCover(file);
|
||||
case AZW3, AZW -> azw3MetadataExtractor.extractCover(file);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+430
@@ -0,0 +1,430 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.util.*;
|
||||
|
||||
@Slf4j
|
||||
public abstract class MobiBaseMetadataExtractor implements FileMetadataExtractor {
|
||||
|
||||
// EXTH record types
|
||||
protected static final int EXTH_AUTHOR = 100;
|
||||
protected static final int EXTH_PUBLISHER = 101;
|
||||
protected static final int EXTH_DESCRIPTION = 103;
|
||||
protected static final int EXTH_ISBN = 104;
|
||||
protected static final int EXTH_SUBJECT = 105;
|
||||
protected static final int EXTH_PUBLISHED_DATE = 106;
|
||||
protected static final int EXTH_LANGUAGE = 524;
|
||||
protected static final int EXTH_COVER_OFFSET = 201;
|
||||
protected static final int EXTH_THUMB_OFFSET = 202;
|
||||
protected static final int EXTH_ASIN = 113;
|
||||
|
||||
protected abstract String getFormatName();
|
||||
|
||||
@Override
|
||||
public byte[] extractCover(File file) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
|
||||
PalmDB palmDB = readPalmDB(raf);
|
||||
if (palmDB == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MobiHeader mobiHeader = readMobiHeader(raf, palmDB);
|
||||
if (mobiHeader == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Try to get cover from EXTH
|
||||
Integer coverIndex = mobiHeader.exthRecords.get(EXTH_COVER_OFFSET);
|
||||
if (coverIndex == null) {
|
||||
coverIndex = mobiHeader.exthRecords.get(EXTH_THUMB_OFFSET);
|
||||
}
|
||||
|
||||
if (coverIndex != null) {
|
||||
int imageRecordIndex = mobiHeader.firstImageIndex + coverIndex;
|
||||
if (imageRecordIndex < palmDB.records.size()) {
|
||||
return extractImageFromRecord(raf, palmDB.records.get(imageRecordIndex));
|
||||
}
|
||||
}
|
||||
|
||||
// Try first image
|
||||
if (mobiHeader.firstImageIndex > 0 && mobiHeader.firstImageIndex < palmDB.records.size()) {
|
||||
return extractImageFromRecord(raf, palmDB.records.get(mobiHeader.firstImageIndex));
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to extract cover from {}: {}", getFormatName(), file.getName(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BookMetadata extractMetadata(File file) {
|
||||
try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
|
||||
PalmDB palmDB = readPalmDB(raf);
|
||||
if (palmDB == null) {
|
||||
log.warn("Failed to read PalmDB header from: {}", file.getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
MobiHeader mobiHeader = readMobiHeader(raf, palmDB);
|
||||
if (mobiHeader == null) {
|
||||
log.warn("Failed to read {} header from: {}", getFormatName(), file.getName());
|
||||
return null;
|
||||
}
|
||||
|
||||
BookMetadata.BookMetadataBuilder builder = BookMetadata.builder();
|
||||
Set<String> authors = new HashSet<>();
|
||||
Set<String> categories = new HashSet<>();
|
||||
|
||||
// Extract title
|
||||
if (StringUtils.isNotBlank(mobiHeader.title)) {
|
||||
builder.title(mobiHeader.title);
|
||||
}
|
||||
|
||||
// Extract metadata from EXTH records
|
||||
for (var entry : mobiHeader.exthData.entrySet()) {
|
||||
int recordType = entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
if (StringUtils.isBlank(value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (recordType) {
|
||||
case EXTH_AUTHOR -> authors.add(value.trim());
|
||||
case EXTH_PUBLISHER -> builder.publisher(value.trim());
|
||||
case EXTH_DESCRIPTION -> builder.description(value.trim());
|
||||
case EXTH_ISBN -> {
|
||||
String isbn = value.replaceAll("[^0-9Xx]", "");
|
||||
if (isbn.length() == 13) {
|
||||
builder.isbn13(isbn);
|
||||
} else if (isbn.length() == 10) {
|
||||
builder.isbn10(isbn);
|
||||
}
|
||||
}
|
||||
case EXTH_SUBJECT -> {
|
||||
for (String category : value.split("[;,]")) {
|
||||
String trimmed = category.trim();
|
||||
if (StringUtils.isNotBlank(trimmed)) {
|
||||
categories.add(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
case EXTH_PUBLISHED_DATE -> {
|
||||
LocalDate date = parseDate(value.trim());
|
||||
if (date != null) {
|
||||
builder.publishedDate(date);
|
||||
}
|
||||
}
|
||||
case EXTH_LANGUAGE -> builder.language(value.trim());
|
||||
case EXTH_ASIN -> builder.asin(value.trim());
|
||||
}
|
||||
}
|
||||
|
||||
builder.authors(authors);
|
||||
builder.categories(categories);
|
||||
|
||||
return builder.build();
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to extract metadata from {}: {}", getFormatName(), file.getName(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected PalmDB readPalmDB(RandomAccessFile raf) throws IOException {
|
||||
if (raf.length() < 78) {
|
||||
log.debug("File too small for PalmDB");
|
||||
return null;
|
||||
}
|
||||
|
||||
PalmDB palmDB = new PalmDB();
|
||||
|
||||
// Read database name
|
||||
raf.seek(0);
|
||||
byte[] nameBytes = new byte[32];
|
||||
raf.readFully(nameBytes);
|
||||
int nameLen = 0;
|
||||
for (int i = 0; i < nameBytes.length; i++) {
|
||||
if (nameBytes[i] == 0) {
|
||||
nameLen = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
palmDB.name = new String(nameBytes, 0, nameLen, StandardCharsets.ISO_8859_1);
|
||||
|
||||
// Read number of records
|
||||
raf.seek(76);
|
||||
palmDB.numRecords = readShort(raf);
|
||||
|
||||
log.debug("PalmDB: name={}, records={}", palmDB.name, palmDB.numRecords);
|
||||
|
||||
if (palmDB.numRecords <= 0 || palmDB.numRecords > 10000) {
|
||||
log.debug("Invalid number of records: {}", palmDB.numRecords);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read record list
|
||||
raf.seek(78);
|
||||
for (int i = 0; i < palmDB.numRecords; i++) {
|
||||
PalmDBRecord record = new PalmDBRecord();
|
||||
record.offset = readInt(raf);
|
||||
record.attributes = raf.read();
|
||||
record.id = readThreeBytes(raf);
|
||||
palmDB.records.add(record);
|
||||
}
|
||||
|
||||
// Calculate record sizes
|
||||
for (int i = 0; i < palmDB.records.size(); i++) {
|
||||
PalmDBRecord record = palmDB.records.get(i);
|
||||
if (i < palmDB.records.size() - 1) {
|
||||
record.size = palmDB.records.get(i + 1).offset - record.offset;
|
||||
} else {
|
||||
record.size = (int) (raf.length() - record.offset);
|
||||
}
|
||||
}
|
||||
|
||||
return palmDB;
|
||||
}
|
||||
|
||||
protected MobiHeader readMobiHeader(RandomAccessFile raf, PalmDB palmDB) throws IOException {
|
||||
if (palmDB.records.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
PalmDBRecord record0 = palmDB.records.get(0);
|
||||
raf.seek(record0.offset);
|
||||
|
||||
MobiHeader header = new MobiHeader();
|
||||
|
||||
// Read PalmDOC header
|
||||
int compression = readShort(raf);
|
||||
raf.skipBytes(2);
|
||||
int textLength = readInt(raf);
|
||||
int recordCount = readShort(raf);
|
||||
int recordSize = readShort(raf);
|
||||
int encryptionType = readShort(raf);
|
||||
raf.skipBytes(2);
|
||||
|
||||
log.debug("PalmDOC: compression={}, textLength={}, recordCount={}, recordSize={}",
|
||||
compression, textLength, recordCount, recordSize);
|
||||
|
||||
// Check for MOBI header
|
||||
raf.seek(record0.offset + 16);
|
||||
byte[] identifier = new byte[4];
|
||||
raf.readFully(identifier);
|
||||
String identifierStr = new String(identifier, StandardCharsets.US_ASCII);
|
||||
|
||||
log.debug("Header identifier: {}", identifierStr);
|
||||
|
||||
if (!identifierStr.equals("MOBI")) {
|
||||
log.debug("No MOBI/KF8 header found");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read MOBI header
|
||||
raf.seek(record0.offset + 20);
|
||||
int headerLength = readInt(raf);
|
||||
int mobiType = readInt(raf);
|
||||
int textEncoding = readInt(raf);
|
||||
|
||||
log.debug("{}: headerLength={}, type={}, encoding={}", getFormatName(), headerLength, mobiType, textEncoding);
|
||||
|
||||
// Check if this is KF8 (AZW3) format
|
||||
header.isKF8 = (mobiType == 2);
|
||||
if (header.isKF8) {
|
||||
log.debug("Detected KF8 (AZW3) format");
|
||||
}
|
||||
|
||||
// Process format-specific logic
|
||||
processFormatSpecificHeader(raf, record0, header, headerLength);
|
||||
|
||||
// Determine charset
|
||||
Charset charset = textEncoding == 65001 ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1;
|
||||
header.charset = charset;
|
||||
|
||||
// Skip to full name offset/length
|
||||
raf.seek(record0.offset + 16 + 68);
|
||||
int fullNameOffset = readInt(raf);
|
||||
int fullNameLength = readInt(raf);
|
||||
|
||||
log.debug("Full name: offset={}, length={}", fullNameOffset, fullNameLength);
|
||||
|
||||
// Read title
|
||||
if (fullNameLength > 0 && fullNameLength < 10000) {
|
||||
raf.seek(record0.offset + fullNameOffset);
|
||||
byte[] titleBytes = new byte[fullNameLength];
|
||||
raf.readFully(titleBytes);
|
||||
header.title = new String(titleBytes, charset).trim();
|
||||
log.debug("Title: {}", header.title);
|
||||
}
|
||||
|
||||
// Read first image index
|
||||
raf.seek(record0.offset + 16 + 92);
|
||||
header.firstImageIndex = readInt(raf);
|
||||
|
||||
log.debug("First image index: {}", header.firstImageIndex);
|
||||
|
||||
// Check for EXTH header
|
||||
raf.seek(record0.offset + 16 + 112);
|
||||
int exthFlags = readInt(raf);
|
||||
|
||||
log.debug("EXTH flags: 0x{}", Integer.toHexString(exthFlags));
|
||||
|
||||
if ((exthFlags & 0x40) != 0) {
|
||||
long exthOffset = record0.offset + 16 + headerLength;
|
||||
raf.seek(exthOffset);
|
||||
|
||||
byte[] exthIdentifier = new byte[4];
|
||||
raf.readFully(exthIdentifier);
|
||||
String exthStr = new String(exthIdentifier, StandardCharsets.US_ASCII);
|
||||
|
||||
log.debug("EXTH identifier: {}", exthStr);
|
||||
|
||||
if (exthStr.equals("EXTH")) {
|
||||
readExthRecords(raf, header, charset);
|
||||
}
|
||||
}
|
||||
|
||||
return header;
|
||||
}
|
||||
|
||||
protected void processFormatSpecificHeader(RandomAccessFile raf, PalmDBRecord record0,
|
||||
MobiHeader header, int headerLength) throws IOException {
|
||||
// Override in subclasses for format-specific processing
|
||||
}
|
||||
|
||||
protected void readExthRecords(RandomAccessFile raf, MobiHeader header, Charset charset) throws IOException {
|
||||
long exthStart = raf.getFilePointer() - 4;
|
||||
|
||||
int headerLength = readInt(raf);
|
||||
int recordCount = readInt(raf);
|
||||
|
||||
log.debug("EXTH: headerLength={}, recordCount={}", headerLength, recordCount);
|
||||
|
||||
for (int i = 0; i < recordCount && i < 500; i++) {
|
||||
int recordType = readInt(raf);
|
||||
int recordLength = readInt(raf);
|
||||
|
||||
if (recordLength < 8 || recordLength > 100000) {
|
||||
log.warn("Invalid EXTH record length: {}", recordLength);
|
||||
break;
|
||||
}
|
||||
|
||||
int dataLength = recordLength - 8;
|
||||
byte[] data = new byte[dataLength];
|
||||
raf.readFully(data);
|
||||
|
||||
if (recordType == EXTH_COVER_OFFSET || recordType == EXTH_THUMB_OFFSET) {
|
||||
if (dataLength >= 4) {
|
||||
int value = ((data[0] & 0xFF) << 24) | ((data[1] & 0xFF) << 16) |
|
||||
((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
|
||||
header.exthRecords.put(recordType, value);
|
||||
log.debug("EXTH record {} (int): {}", recordType, value);
|
||||
}
|
||||
} else {
|
||||
String value = new String(data, charset).trim();
|
||||
value = value.replace("\0", "");
|
||||
if (!value.isEmpty()) {
|
||||
header.exthData.put(recordType, value);
|
||||
log.debug("EXTH record {} (string): {}", recordType,
|
||||
value.length() > 100 ? value.substring(0, 100) + "..." : value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected byte[] extractImageFromRecord(RandomAccessFile raf, PalmDBRecord record) throws IOException {
|
||||
if (record.size <= 0 || record.size > 10_000_000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
raf.seek(record.offset);
|
||||
byte[] data = new byte[record.size];
|
||||
raf.readFully(data);
|
||||
|
||||
// Check for image magic bytes
|
||||
if (data.length > 4) {
|
||||
if ((data[0] == (byte) 0xFF && data[1] == (byte) 0xD8) || // JPEG
|
||||
(data[0] == (byte) 0x89 && data[1] == (byte) 0x50 &&
|
||||
data[2] == (byte) 0x4E && data[3] == (byte) 0x47) || // PNG
|
||||
(data[0] == (byte) 0x47 && data[1] == (byte) 0x49 &&
|
||||
data[2] == (byte) 0x46)) { // GIF
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected LocalDate parseDate(String dateString) {
|
||||
if (StringUtils.isBlank(dateString)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
if (dateString.matches("\\d{4}-\\d{2}-\\d{2}")) {
|
||||
return LocalDate.parse(dateString);
|
||||
}
|
||||
|
||||
if (dateString.matches("\\d{4}")) {
|
||||
return LocalDate.of(Integer.parseInt(dateString), 1, 1);
|
||||
}
|
||||
|
||||
if (dateString.matches("\\d{4}/\\d{2}/\\d{2}")) {
|
||||
String[] parts = dateString.split("/");
|
||||
return LocalDate.of(Integer.parseInt(parts[0]),
|
||||
Integer.parseInt(parts[1]),
|
||||
Integer.parseInt(parts[2]));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Failed to parse date: {}", dateString, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected int readInt(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 24) | (raf.read() << 16) | (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected int readShort(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected int readThreeBytes(RandomAccessFile raf) throws IOException {
|
||||
return (raf.read() << 16) | (raf.read() << 8) | raf.read();
|
||||
}
|
||||
|
||||
protected static class PalmDB {
|
||||
String name;
|
||||
int numRecords;
|
||||
List<PalmDBRecord> records = new ArrayList<>();
|
||||
}
|
||||
|
||||
protected static class PalmDBRecord {
|
||||
int offset;
|
||||
int attributes;
|
||||
int id;
|
||||
int size;
|
||||
}
|
||||
|
||||
protected static class MobiHeader {
|
||||
String title;
|
||||
int firstImageIndex = -1;
|
||||
boolean isKF8 = false;
|
||||
Charset charset = StandardCharsets.UTF_8;
|
||||
Map<Integer, String> exthData = new HashMap<>();
|
||||
Map<Integer, Integer> exthRecords = new HashMap<>();
|
||||
}
|
||||
}
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.adityachandel.booklore.service.metadata.extractor;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MobiMetadataExtractor extends MobiBaseMetadataExtractor {
|
||||
|
||||
@Override
|
||||
protected String getFormatName() {
|
||||
return "MOBI";
|
||||
}
|
||||
}
|
||||
+10
-9
@@ -8,18 +8,17 @@ import com.adityachandel.booklore.model.enums.OpdsSortOrder;
|
||||
import com.adityachandel.booklore.service.MagicShelfService;
|
||||
import com.adityachandel.booklore.util.ArchiveUtils;
|
||||
import com.adityachandel.booklore.util.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -381,7 +380,7 @@ public class OpdsFeedService {
|
||||
int size = Math.min(parseLongParam(request, "size", (long) DEFAULT_PAGE_SIZE).intValue(), MAX_PAGE_SIZE);
|
||||
|
||||
Page<Book> booksPage = opdsBookService.getRecentBooksPage(userId, page - 1, size);
|
||||
|
||||
|
||||
// Apply user's preferred sort order
|
||||
booksPage = opdsBookService.applySortOrder(booksPage, sortOrder);
|
||||
|
||||
@@ -621,6 +620,8 @@ public class OpdsFeedService {
|
||||
}
|
||||
yield "application/x-fictionbook+xml";
|
||||
}
|
||||
case MOBI -> "application/x-mobipocket-ebook";
|
||||
case AZW3 -> "application/vnd.amazon.ebook";
|
||||
case CBX -> {
|
||||
if (book.getArchiveType() != null) {
|
||||
yield switch (book.getArchiveType()) {
|
||||
@@ -674,9 +675,9 @@ public class OpdsFeedService {
|
||||
private Set<Long> parseShelfIds(HttpServletRequest request) {
|
||||
String shelfIdParam = request.getParameter("shelfId");
|
||||
String shelfIdsParam = request.getParameter("shelfIds");
|
||||
|
||||
|
||||
Set<Long> shelfIds = new HashSet<>();
|
||||
|
||||
|
||||
// Support both single shelfId and comma-separated shelfIds
|
||||
if (shelfIdParam != null && !shelfIdParam.isBlank()) {
|
||||
try {
|
||||
@@ -685,7 +686,7 @@ public class OpdsFeedService {
|
||||
log.warn("Invalid shelfId parameter: {}", shelfIdParam);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (shelfIdsParam != null && !shelfIdsParam.isBlank()) {
|
||||
for (String id : shelfIdsParam.split(",")) {
|
||||
try {
|
||||
@@ -695,7 +696,7 @@ public class OpdsFeedService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return shelfIds.isEmpty() ? null : shelfIds;
|
||||
}
|
||||
|
||||
|
||||
+19
@@ -24,6 +24,7 @@ public class DefaultUserSettingsProvider {
|
||||
defaultSettings.put(UserSettingKey.PER_BOOK_SETTING, this::buildDefaultPerBookSetting);
|
||||
defaultSettings.put(UserSettingKey.PDF_READER_SETTING, this::buildDefaultPdfReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.EPUB_READER_SETTING, this::buildDefaultEpubReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.EBOOK_READER_SETTING, this::buildDefaultEbookReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.CBX_READER_SETTING, this::buildDefaultCbxReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.NEW_PDF_READER_SETTING, this::buildDefaultNewPdfReaderSetting);
|
||||
defaultSettings.put(UserSettingKey.SIDEBAR_LIBRARY_SORTING, this::buildDefaultSidebarLibrarySorting);
|
||||
@@ -75,6 +76,23 @@ public class DefaultUserSettingsProvider {
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookLoreUser.UserSettings.EbookReaderSetting buildDefaultEbookReaderSetting() {
|
||||
return BookLoreUser.UserSettings.EbookReaderSetting.builder()
|
||||
.fontFamily("serif")
|
||||
.fontSize(16)
|
||||
.gap(0.05f)
|
||||
.hyphenate(false)
|
||||
.isDark(false)
|
||||
.justify(false)
|
||||
.lineHeight(1.5f)
|
||||
.maxBlockSize(1440)
|
||||
.maxColumnCount(2)
|
||||
.maxInlineSize(720)
|
||||
.theme("gray")
|
||||
.flow("paginated")
|
||||
.build();
|
||||
}
|
||||
|
||||
private BookLoreUser.UserSettings.CbxReaderSetting buildDefaultCbxReaderSetting() {
|
||||
return BookLoreUser.UserSettings.CbxReaderSetting.builder()
|
||||
.pageViewMode(CbxPageViewMode.SINGLE_PAGE)
|
||||
@@ -112,6 +130,7 @@ public class DefaultUserSettingsProvider {
|
||||
.view("GRID")
|
||||
.coverSize(1.0F)
|
||||
.seriesCollapsed(false)
|
||||
.overlayBookType(true)
|
||||
.build())
|
||||
.overrides(null)
|
||||
.build();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.adityachandel.booklore.util;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.*;
|
||||
import com.adityachandel.booklore.model.dto.progress.*;
|
||||
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.enums.ReadStatus;
|
||||
|
||||
public class BookProgressUtil {
|
||||
|
||||
public static void setBookProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress.getKoboProgressPercent() != null) {
|
||||
book.setKoboProgress(KoboProgress.builder()
|
||||
.percentage(progress.getKoboProgressPercent())
|
||||
.build());
|
||||
}
|
||||
|
||||
BookFileType type = book.getBookType();
|
||||
if (type == null) return;
|
||||
|
||||
switch (type) {
|
||||
case EPUB -> {
|
||||
book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.href(progress.getEpubProgressHref())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
book.setKoreaderProgress(KoProgress.builder()
|
||||
.percentage(progress.getKoreaderProgressPercent() != null ? progress.getKoreaderProgressPercent() * 100 : null)
|
||||
.build());
|
||||
}
|
||||
case FB2, MOBI, AZW3 -> book.setEpubProgress(EpubProgress.builder()
|
||||
.cfi(progress.getEpubProgress())
|
||||
.href(progress.getEpubProgressHref())
|
||||
.percentage(progress.getEpubProgressPercent())
|
||||
.build());
|
||||
case PDF -> book.setPdfProgress(PdfProgress.builder()
|
||||
.page(progress.getPdfProgress())
|
||||
.percentage(progress.getPdfProgressPercent())
|
||||
.build());
|
||||
case CBX -> book.setCbxProgress(CbxProgress.builder()
|
||||
.page(progress.getCbxProgress())
|
||||
.percentage(progress.getCbxProgressPercent())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
public static void enrichBookWithProgress(Book book, UserBookProgressEntity progress) {
|
||||
if (progress != null) {
|
||||
setBookProgress(book, progress);
|
||||
book.setLastReadTime(progress.getLastReadTime());
|
||||
book.setReadStatus(progress.getReadStatus() == null ? String.valueOf(ReadStatus.UNSET) : String.valueOf(progress.getReadStatus()));
|
||||
book.setDateFinished(progress.getDateFinished());
|
||||
book.setPersonalRating(progress.getPersonalRating());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
CREATE TABLE IF NOT EXISTS ebook_viewer_preference
|
||||
(
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
book_id BIGINT NOT NULL,
|
||||
font_family VARCHAR(128) NULL,
|
||||
font_size INT NULL,
|
||||
gap FLOAT NULL,
|
||||
hyphenate BOOLEAN NULL,
|
||||
is_dark BOOLEAN NULL,
|
||||
justify BOOLEAN NULL,
|
||||
line_height FLOAT NULL,
|
||||
max_block_size INT NULL,
|
||||
max_column_count INT NULL,
|
||||
max_inline_size INT NULL,
|
||||
theme VARCHAR(64) NULL,
|
||||
flow VARCHAR(32) NULL,
|
||||
UNIQUE (user_id, book_id),
|
||||
CONSTRAINT fk_ebook_viewer_preference_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_ebook_viewer_preference_book FOREIGN KEY (book_id) REFERENCES book (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
ALTER TABLE user_book_progress
|
||||
ADD COLUMN IF NOT EXISTS epub_progress_href VARCHAR(1000);
|
||||
@@ -38,7 +38,7 @@ class BookServiceDeleteTests {
|
||||
void setUp() {
|
||||
BookRepository bookRepository = Mockito.mock(BookRepository.class);
|
||||
PdfViewerPreferencesRepository pdfViewerPreferencesRepository = Mockito.mock(PdfViewerPreferencesRepository.class);
|
||||
EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class);
|
||||
EbookViewerPreferenceRepository ebookViewerPreferenceRepository = Mockito.mock(EbookViewerPreferenceRepository.class);
|
||||
CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class);
|
||||
NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class);
|
||||
FileService fileService = Mockito.mock(FileService.class);
|
||||
@@ -54,7 +54,6 @@ class BookServiceDeleteTests {
|
||||
bookService = new BookService(
|
||||
bookRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
epubViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
fileService,
|
||||
@@ -65,7 +64,8 @@ class BookServiceDeleteTests {
|
||||
userProgressService,
|
||||
bookDownloadService,
|
||||
monitoringRegistrationService,
|
||||
bookUpdateService
|
||||
bookUpdateService,
|
||||
ebookViewerPreferenceRepository
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+28
-7
@@ -20,6 +20,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
@@ -38,7 +39,7 @@ import java.util.Set;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class)
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BookServiceTest {
|
||||
|
||||
@Mock
|
||||
@@ -46,7 +47,7 @@ class BookServiceTest {
|
||||
@Mock
|
||||
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
private EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
@Mock
|
||||
private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock
|
||||
@@ -170,15 +171,35 @@ class BookServiceTest {
|
||||
primaryFile.setBookType(BookFileType.EPUB);
|
||||
entity.setBookFiles(List.of(primaryFile));
|
||||
when(bookRepository.findByIdWithBookFiles(4L)).thenReturn(Optional.of(entity));
|
||||
EpubViewerPreferencesEntity epubPref = new EpubViewerPreferencesEntity();
|
||||
epubPref.setFont("Arial");
|
||||
when(epubViewerPreferencesRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
|
||||
EbookViewerPreferenceEntity epubPref = new EbookViewerPreferenceEntity();
|
||||
epubPref.setFontFamily("Arial");
|
||||
epubPref.setFontSize(16);
|
||||
epubPref.setGap(0.2f);
|
||||
epubPref.setHyphenate(true);
|
||||
epubPref.setIsDark(false);
|
||||
epubPref.setJustify(true);
|
||||
epubPref.setLineHeight(1.5f);
|
||||
epubPref.setMaxBlockSize(800);
|
||||
epubPref.setMaxColumnCount(2);
|
||||
epubPref.setMaxInlineSize(1200);
|
||||
epubPref.setTheme("light");
|
||||
when(ebookViewerPreferenceRepository.findByBookIdAndUserId(4L, testUser.getId())).thenReturn(Optional.of(epubPref));
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
|
||||
BookViewerSettings settings = bookService.getBookViewerSetting(4L);
|
||||
|
||||
assertNotNull(settings.getEpubSettings());
|
||||
assertEquals("Arial", settings.getEpubSettings().getFont());
|
||||
assertNotNull(settings.getEbookSettings());
|
||||
assertEquals("Arial", settings.getEbookSettings().getFontFamily());
|
||||
assertEquals(16, settings.getEbookSettings().getFontSize());
|
||||
assertEquals(0.2f, settings.getEbookSettings().getGap());
|
||||
assertTrue(settings.getEbookSettings().getHyphenate());
|
||||
assertFalse(settings.getEbookSettings().getIsDark());
|
||||
assertTrue(settings.getEbookSettings().getJustify());
|
||||
assertEquals(1.5f, settings.getEbookSettings().getLineHeight());
|
||||
assertEquals(800, settings.getEbookSettings().getMaxBlockSize());
|
||||
assertEquals(2, settings.getEbookSettings().getMaxColumnCount());
|
||||
assertEquals(1200, settings.getEbookSettings().getMaxInlineSize());
|
||||
assertEquals("light", settings.getEbookSettings().getTheme());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+33
-23
@@ -34,8 +34,6 @@ class BookUpdateServiceTest {
|
||||
@Mock
|
||||
private PdfViewerPreferencesRepository pdfViewerPreferencesRepository;
|
||||
@Mock
|
||||
private EpubViewerPreferencesRepository epubViewerPreferencesRepository;
|
||||
@Mock
|
||||
private CbxViewerPreferencesRepository cbxViewerPreferencesRepository;
|
||||
@Mock
|
||||
private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository;
|
||||
@@ -55,6 +53,8 @@ class BookUpdateServiceTest {
|
||||
private UserProgressService userProgressService;
|
||||
@Mock
|
||||
private KoboReadingStateService koboReadingStateService;
|
||||
@Mock
|
||||
private EbookViewerPreferenceRepository ebookViewerPreferenceRepository;
|
||||
|
||||
@InjectMocks
|
||||
private BookUpdateService bookUpdateService;
|
||||
@@ -65,7 +65,6 @@ class BookUpdateServiceTest {
|
||||
bookUpdateService = new BookUpdateService(
|
||||
bookRepository,
|
||||
pdfViewerPreferencesRepository,
|
||||
epubViewerPreferencesRepository,
|
||||
cbxViewerPreferencesRepository,
|
||||
newPdfViewerPreferencesRepository,
|
||||
shelfRepository,
|
||||
@@ -75,7 +74,8 @@ class BookUpdateServiceTest {
|
||||
authenticationService,
|
||||
bookQueryService,
|
||||
userProgressService,
|
||||
koboReadingStateService
|
||||
koboReadingStateService,
|
||||
ebookViewerPreferenceRepository
|
||||
);
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ class BookUpdateServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateBookViewerSetting_epub_shouldUpdateEpubPrefs() {
|
||||
void updateBookViewerSetting_epub_shouldUpdateEpubPrefsV2() {
|
||||
long bookId = 1L;
|
||||
BookEntity book = new BookEntity();
|
||||
book.setId(bookId);
|
||||
@@ -123,30 +123,40 @@ class BookUpdateServiceTest {
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
|
||||
when(user.getId()).thenReturn(2L);
|
||||
|
||||
EpubViewerPreferencesEntity epubPrefs = new EpubViewerPreferencesEntity();
|
||||
when(epubViewerPreferencesRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
|
||||
EbookViewerPreferenceEntity epubPrefs = new EbookViewerPreferenceEntity();
|
||||
when(ebookViewerPreferenceRepository.findByBookIdAndUserId(bookId, 2L)).thenReturn(Optional.of(epubPrefs));
|
||||
BookViewerSettings settings = BookViewerSettings.builder()
|
||||
.epubSettings(EpubViewerPreferences.builder()
|
||||
.font("font")
|
||||
.fontSize(12)
|
||||
.theme("theme")
|
||||
.flow("flow")
|
||||
.spread("spread")
|
||||
.letterSpacing(1.2f)
|
||||
.lineHeight(1.3f)
|
||||
.ebookSettings(EbookViewerPreferences.builder()
|
||||
.fontFamily("serif")
|
||||
.fontSize(18)
|
||||
.gap(0.1f)
|
||||
.hyphenate(true)
|
||||
.isDark(true)
|
||||
.justify(true)
|
||||
.lineHeight(1.7f)
|
||||
.maxBlockSize(800)
|
||||
.maxColumnCount(3)
|
||||
.maxInlineSize(1200)
|
||||
.theme("dark")
|
||||
.flow("paginated")
|
||||
.build())
|
||||
.build();
|
||||
|
||||
bookUpdateService.updateBookViewerSetting(bookId, settings);
|
||||
|
||||
verify(epubViewerPreferencesRepository).save(epubPrefs);
|
||||
assertEquals("font", epubPrefs.getFont());
|
||||
assertEquals(12, epubPrefs.getFontSize());
|
||||
assertEquals("theme", epubPrefs.getTheme());
|
||||
assertEquals("flow", epubPrefs.getFlow());
|
||||
assertEquals("spread", epubPrefs.getSpread());
|
||||
assertEquals(1.2f, epubPrefs.getLetterSpacing());
|
||||
assertEquals(1.3f, epubPrefs.getLineHeight());
|
||||
verify(ebookViewerPreferenceRepository).save(epubPrefs);
|
||||
assertEquals("serif", epubPrefs.getFontFamily());
|
||||
assertEquals(18, epubPrefs.getFontSize());
|
||||
assertEquals(0.1f, epubPrefs.getGap());
|
||||
assertTrue(epubPrefs.getHyphenate());
|
||||
assertTrue(epubPrefs.getIsDark());
|
||||
assertTrue(epubPrefs.getJustify());
|
||||
assertEquals(1.7f, epubPrefs.getLineHeight());
|
||||
assertEquals(800, epubPrefs.getMaxBlockSize());
|
||||
assertEquals(3, epubPrefs.getMaxColumnCount());
|
||||
assertEquals(1200, epubPrefs.getMaxInlineSize());
|
||||
assertEquals("dark", epubPrefs.getTheme());
|
||||
assertEquals("paginated", epubPrefs.getFlow());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user