Ensure Booklore metadata changes are reflected on Kobo books (#2140)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-04 10:55:44 -07:00
committed by GitHub
co-authored by acx10
parent 3b3656c29b
commit 1ea9cbde3e
30 changed files with 981 additions and 436 deletions
@@ -6,7 +6,7 @@ import com.adityachandel.booklore.model.dto.kobo.KoboAuthentication;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper; import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper;
import com.adityachandel.booklore.model.dto.kobo.KoboResources; import com.adityachandel.booklore.model.dto.kobo.KoboResources;
import com.adityachandel.booklore.model.dto.kobo.KoboTestResponse; import com.adityachandel.booklore.model.dto.kobo.KoboTestResponse;
import com.adityachandel.booklore.service.*; import com.adityachandel.booklore.service.ShelfService;
import com.adityachandel.booklore.service.book.BookDownloadService; import com.adityachandel.booklore.service.book.BookDownloadService;
import com.adityachandel.booklore.service.book.BookService; import com.adityachandel.booklore.service.book.BookService;
import com.adityachandel.booklore.service.kobo.*; import com.adityachandel.booklore.service.kobo.*;
@@ -70,36 +70,58 @@ public class KoboController {
return koboLibrarySyncService.syncLibrary(user, token); return koboLibrarySyncService.syncLibrary(user, token);
} }
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a book.") @Operation(summary = "Get book thumbnail (versioned)", description = "Retrieve the thumbnail image for a local book with cache-busting version.")
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/false/image.jpg")
public ResponseEntity<Resource> getVersionedThumbnail(
@Parameter(description = "Book ID") @PathVariable String imageId,
@Parameter(description = "Cover version (timestamp)") @PathVariable String version,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height) {
return koboThumbnailService.getThumbnail(imageId);
}
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a Kobo store book.")
@ApiResponse(responseCode = "200", description = "Thumbnail returned successfully") @ApiResponse(responseCode = "200", description = "Thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg") @GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg")
public ResponseEntity<Resource> getThumbnail( public ResponseEntity<Resource> getThumbnail(
@Parameter(description = "Image ID") @PathVariable String imageId, @Parameter(description = "Image ID") @PathVariable String imageId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width, @Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height) { @Parameter(description = "Height of the thumbnail") @PathVariable int height) {
if (imageId.startsWith("BL-")) {
if (StringUtils.isNumeric(imageId)) { return koboThumbnailService.getThumbnail(imageId);
return koboThumbnailService.getThumbnail(Long.valueOf(imageId));
} else { } else {
String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/image.jpg", imageId, width, height); String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/false/image.jpg", imageId, width, height);
return koboServerProxy.proxyExternalUrl(cdnUrl); return koboServerProxy.proxyExternalUrl(cdnUrl);
} }
} }
@Operation(summary = "Get greyscale book thumbnail", description = "Retrieve a greyscale thumbnail image for a book.") @Operation(summary = "Get greyscale book thumbnail (versioned)", description = "Retrieve a greyscale thumbnail for a local book with cache-busting version.")
@ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully") @ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully")
@GetMapping("/v1/books/{bookId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg") @GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg")
public ResponseEntity<Resource> getGreyThumbnail( public ResponseEntity<Resource> getVersionedGreyThumbnail(
@Parameter(description = "Book ID") @PathVariable String bookId, @Parameter(description = "Book ID") @PathVariable String imageId,
@Parameter(description = "Cover version (timestamp)") @PathVariable String version,
@Parameter(description = "Width of the thumbnail") @PathVariable int width, @Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height, @Parameter(description = "Height of the thumbnail") @PathVariable int height,
@Parameter(description = "Quality of the thumbnail") @PathVariable int quality, @Parameter(description = "Quality of the thumbnail") @PathVariable int quality,
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) { @Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) {
return koboThumbnailService.getThumbnail(imageId);
}
if (StringUtils.isNumeric(bookId)) { @Operation(summary = "Get greyscale book thumbnail", description = "Retrieve a greyscale thumbnail image for a Kobo store book.")
return koboThumbnailService.getThumbnail(Long.valueOf(bookId)); @ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully")
@GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg")
public ResponseEntity<Resource> getGreyThumbnail(
@Parameter(description = "Image ID") @PathVariable String imageId,
@Parameter(description = "Width of the thumbnail") @PathVariable int width,
@Parameter(description = "Height of the thumbnail") @PathVariable int height,
@Parameter(description = "Quality of the thumbnail") @PathVariable int quality,
@Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) {
if (imageId.startsWith("BL-")) {
return koboThumbnailService.getThumbnail(imageId);
} else { } else {
String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/%d/%b/image.jpg", bookId, width, height, quality, isGreyscale); String cdnUrl = String.format("https://cdn.kobo.com/book-images/%s/%d/%d/%d/%b/image.jpg", imageId, width, height, quality, isGreyscale);
return koboServerProxy.proxyExternalUrl(cdnUrl); return koboServerProxy.proxyExternalUrl(cdnUrl);
} }
} }
@@ -107,16 +129,14 @@ public class KoboController {
@Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.") @Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.")
@ApiResponse(responseCode = "200", description = "Device authenticated successfully") @ApiResponse(responseCode = "200", description = "Device authenticated successfully")
@PostMapping("/v1/auth/device") @PostMapping("/v1/auth/device")
public ResponseEntity<KoboAuthentication> authenticateDevice( public ResponseEntity<KoboAuthentication> authenticateDevice(@Parameter(description = "Authentication request body") @RequestBody JsonNode body) {
@Parameter(description = "Authentication request body") @RequestBody JsonNode body) {
return koboDeviceAuthService.authenticateDevice(body); return koboDeviceAuthService.authenticateDevice(body);
} }
@Operation(summary = "Get book metadata", description = "Retrieve metadata for a book in the Kobo library.") @Operation(summary = "Get book metadata", description = "Retrieve metadata for a book in the Kobo library.")
@ApiResponse(responseCode = "200", description = "Metadata returned successfully") @ApiResponse(responseCode = "200", description = "Metadata returned successfully")
@GetMapping("/v1/library/{bookId}/metadata") @GetMapping("/v1/library/{bookId}/metadata")
public ResponseEntity<?> getBookMetadata( public ResponseEntity<?> getBookMetadata(@Parameter(description = "Book ID") @PathVariable String bookId) {
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) { if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(List.of(koboEntitlementService.getMetadataForBook(Long.parseLong(bookId), token))); return ResponseEntity.ok(List.of(koboEntitlementService.getMetadataForBook(Long.parseLong(bookId), token)));
} else { } else {
@@ -127,8 +147,7 @@ public class KoboController {
@Operation(summary = "Get reading state", description = "Retrieve the reading state for a book.") @Operation(summary = "Get reading state", description = "Retrieve the reading state for a book.")
@ApiResponse(responseCode = "200", description = "Reading state returned successfully") @ApiResponse(responseCode = "200", description = "Reading state returned successfully")
@GetMapping("/v1/library/{bookId}/state") @GetMapping("/v1/library/{bookId}/state")
public ResponseEntity<?> getState( public ResponseEntity<?> getState(@Parameter(description = "Book ID") @PathVariable String bookId) {
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) { if (StringUtils.isNumeric(bookId)) {
return ResponseEntity.ok(koboReadingStateService.getReadingState(bookId)); return ResponseEntity.ok(koboReadingStateService.getReadingState(bookId));
} else { } else {
@@ -152,8 +171,7 @@ public class KoboController {
@Operation(summary = "Get Kobo test analytics", description = "Get test analytics for Kobo.") @Operation(summary = "Get Kobo test analytics", description = "Get test analytics for Kobo.")
@ApiResponse(responseCode = "200", description = "Test analytics returned successfully") @ApiResponse(responseCode = "200", description = "Test analytics returned successfully")
@PostMapping("/v1/analytics/gettests") @PostMapping("/v1/analytics/gettests")
public ResponseEntity<?> getTests( public ResponseEntity<?> getTests(@Parameter(description = "Test analytics request body") @RequestBody Object body) {
@Parameter(description = "Test analytics request body") @RequestBody Object body) {
return ResponseEntity.ok(KoboTestResponse.builder() return ResponseEntity.ok(KoboTestResponse.builder()
.result("Success") .result("Success")
.testKey(RandomStringUtils.secure().nextAlphanumeric(24)) .testKey(RandomStringUtils.secure().nextAlphanumeric(24))
@@ -163,8 +181,7 @@ public class KoboController {
@Operation(summary = "Download Kobo book", description = "Download a book from the Kobo library.") @Operation(summary = "Download Kobo book", description = "Download a book from the Kobo library.")
@ApiResponse(responseCode = "200", description = "Book downloaded successfully") @ApiResponse(responseCode = "200", description = "Book downloaded successfully")
@GetMapping("/v1/books/{bookId}/download") @GetMapping("/v1/books/{bookId}/download")
public void downloadBook( public void downloadBook(@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) {
@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) {
if (StringUtils.isNumeric(bookId)) { if (StringUtils.isNumeric(bookId)) {
bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response); bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response);
} else { } else {
@@ -175,8 +192,7 @@ public class KoboController {
@Operation(summary = "Delete book from Kobo library", description = "Delete a book from the user's Kobo library.") @Operation(summary = "Delete book from Kobo library", description = "Delete a book from the user's Kobo library.")
@ApiResponse(responseCode = "200", description = "Book deleted successfully") @ApiResponse(responseCode = "200", description = "Book deleted successfully")
@DeleteMapping("/v1/library/{bookId}") @DeleteMapping("/v1/library/{bookId}")
public ResponseEntity<?> deleteBookFromLibrary( public ResponseEntity<?> deleteBookFromLibrary(@Parameter(description = "Book ID") @PathVariable String bookId) {
@Parameter(description = "Book ID") @PathVariable String bookId) {
if (StringUtils.isNumeric(bookId)) { if (StringUtils.isNumeric(bookId)) {
Shelf userKoboShelf = shelfService.getUserKoboShelf(); Shelf userKoboShelf = shelfService.getUserKoboShelf();
if (userKoboShelf != null) { if (userKoboShelf != null) {
@@ -19,7 +19,8 @@ public class BookEntitlement {
private ActivePeriod activePeriod; private ActivePeriod activePeriod;
@JsonProperty("IsRemoved") @JsonProperty("IsRemoved")
private boolean isRemoved; @Builder.Default
private Boolean removed = false;
private String status; private String status;
@@ -31,7 +32,7 @@ public class BookEntitlement {
@JsonProperty("IsHiddenFromArchive") @JsonProperty("IsHiddenFromArchive")
@Builder.Default @Builder.Default
private boolean isHiddenFromArchive = false; private boolean hiddenFromArchive = false;
private String id; private String id;
private String created; private String created;
@@ -39,7 +40,7 @@ public class BookEntitlement {
@JsonProperty("IsLocked") @JsonProperty("IsLocked")
@Builder.Default @Builder.Default
private boolean isLocked = false; private boolean locked = false;
@Builder.Default @Builder.Default
private String originCategory = "Imported"; private String originCategory = "Imported";
@@ -0,0 +1,19 @@
package com.adityachandel.booklore.model.dto.kobo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ChangedProductMetadata implements Entitlement {
private BookEntitlementContainer changedProductMetadata;
}
@@ -18,7 +18,6 @@ import java.util.Map;
@AllArgsConstructor @AllArgsConstructor
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
@Builder @Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class KoboBookMetadata { public class KoboBookMetadata {
private String crossRevisionId; private String crossRevisionId;
private String revisionId; private String revisionId;
@@ -29,13 +28,13 @@ public class KoboBookMetadata {
private String language = "en"; private String language = "en";
private String isbn; private String isbn;
private String genre; private String genre = "00000000-0000-0000-0000-000000000001";
private String slug; private String slug;
private String coverImageId; private String coverImageId;
@JsonProperty("IsSocialEnabled") @JsonProperty("IsSocialEnabled")
@Builder.Default @Builder.Default
private boolean isSocialEnabled = false; private boolean socialEnabled = true;
private String workId; private String workId;
@@ -44,14 +43,14 @@ public class KoboBookMetadata {
@JsonProperty("IsPreOrder") @JsonProperty("IsPreOrder")
@Builder.Default @Builder.Default
private boolean isPreOrder = false; private boolean preOrder = false;
@Builder.Default @Builder.Default
private List<ContributorRole> contributorRoles = new ArrayList<>(); private List<ContributorRole> contributorRoles = new ArrayList<>();
@JsonProperty("IsInternetArchive") @JsonProperty("IsInternetArchive")
@Builder.Default @Builder.Default
private boolean isInternetArchive = false; private boolean internetArchive = false;
private String entitlementId; private String entitlementId;
private String title; private String title;
@@ -81,7 +80,7 @@ public class KoboBookMetadata {
@JsonProperty("IsEligibleForKoboLove") @JsonProperty("IsEligibleForKoboLove")
@Builder.Default @Builder.Default
private boolean isEligibleForKoboLove = false; private boolean eligibleForKoboLove = false;
@Builder.Default @Builder.Default
private Map<String, String> phoneticPronunciations = Map.of(); private Map<String, String> phoneticPronunciations = Map.of();
@@ -43,6 +43,12 @@ public class BookEntity {
@OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) @OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private BookMetadataEntity metadata; private BookMetadataEntity metadata;
@Column(name = "metadata_updated_at")
private Instant metadataUpdatedAt;
@Column(name = "metadata_for_write_updated_at")
private Instant metadataForWriteUpdatedAt;
@ManyToOne @ManyToOne
@JoinColumn(name = "library_id", nullable = false) @JoinColumn(name = "library_id", nullable = false)
private LibraryEntity library; private LibraryEntity library;
@@ -60,6 +66,9 @@ public class BookEntity {
@Column(name = "current_hash", length = 128) @Column(name = "current_hash", length = 128)
private String currentHash; private String currentHash;
@Column(name = "book_cover_hash", length = 20)
private String bookCoverHash;
@Column(name = "deleted") @Column(name = "deleted")
@Builder.Default @Builder.Default
private Boolean deleted = Boolean.FALSE; private Boolean deleted = Boolean.FALSE;
@@ -4,6 +4,8 @@ package com.adityachandel.booklore.model.entity;
import jakarta.persistence.*; import jakarta.persistence.*;
import lombok.*; import lombok.*;
import java.time.Instant;
@Entity @Entity
@Table(name = "kobo_library_snapshot_book") @Table(name = "kobo_library_snapshot_book")
@Getter @Getter
@@ -24,6 +26,12 @@ public class KoboSnapshotBookEntity {
@Column(name = "book_id", nullable = false) @Column(name = "book_id", nullable = false)
private Long bookId; private Long bookId;
@Column(name = "file_hash")
private String fileHash;
@Column(name = "metadata_updated_at")
private Instant metadataUpdatedAt;
@Column(nullable = false) @Column(nullable = false)
@Builder.Default @Builder.Default
private boolean synced = false; private boolean synced = false;
@@ -21,6 +21,8 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpec
Optional<BookEntity> findByCurrentHash(String currentHash); Optional<BookEntity> findByCurrentHash(String currentHash);
Optional<BookEntity> findByBookCoverHash(String bookCoverHash);
@Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") @Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)")
Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId); Set<Long> findBookIdsByLibraryId(@Param("libraryId") long libraryId);
@@ -74,4 +74,40 @@ public interface KoboSnapshotBookRepository extends JpaRepository<KoboSnapshotBo
@Param("currSnapshotId") String currSnapshotId, @Param("currSnapshotId") String currSnapshotId,
Pageable pageable Pageable pageable
); );
@Query("""
SELECT curr
FROM KoboSnapshotBookEntity curr
JOIN KoboSnapshotBookEntity prev
ON curr.bookId = prev.bookId
WHERE curr.snapshot.id = :currSnapshotId
AND prev.snapshot.id = :prevSnapshotId
AND curr.fileHash = prev.fileHash
AND (curr.metadataUpdatedAt = prev.metadataUpdatedAt OR (curr.metadataUpdatedAt IS NULL AND prev.metadataUpdatedAt IS NULL))
""")
List<KoboSnapshotBookEntity> findUnchangedBooksBetweenSnapshots(
@Param("prevSnapshotId") String prevSnapshotId,
@Param("currSnapshotId") String currSnapshotId
);
@Query("""
SELECT curr
FROM KoboSnapshotBookEntity curr
JOIN KoboSnapshotBookEntity prev
ON curr.bookId = prev.bookId
WHERE curr.snapshot.id = :currSnapshotId
AND prev.snapshot.id = :prevSnapshotId
AND curr.synced = false
AND (
curr.fileHash <> prev.fileHash
OR (curr.metadataUpdatedAt <> prev.metadataUpdatedAt AND curr.metadataUpdatedAt IS NOT NULL AND prev.metadataUpdatedAt IS NOT NULL)
OR (curr.metadataUpdatedAt IS NOT NULL AND prev.metadataUpdatedAt IS NULL)
)
""")
Page<KoboSnapshotBookEntity> findChangedBooks(
@Param("prevSnapshotId") String prevSnapshotId,
@Param("currSnapshotId") String currSnapshotId,
Pageable pageable
);
} }
@@ -5,7 +5,6 @@ import com.adityachandel.booklore.model.dto.Book;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List; import java.util.List;
@@ -33,11 +32,6 @@ public class BookQueryService {
return bookRepository.findAllWithMetadataByIds(bookIds); return bookRepository.findAllWithMetadataByIds(bookIds);
} }
public List<BookEntity> findWithMetadataByIdsWithPagination(Set<Long> bookIds, int offset, int limit) {
Pageable pageable = PageRequest.of(offset / limit, limit);
return bookRepository.findWithMetadataByIdsWithPagination(bookIds, pageable);
}
public List<BookEntity> getAllFullBookEntities() { public List<BookEntity> getAllFullBookEntities() {
return bookRepository.findAllFullBooks(); return bookRepository.findAllFullBooks();
} }
@@ -288,6 +288,11 @@ public class BookService {
} }
} }
public Resource getBookCover(String coverHash) {
BookEntity bookEntity = bookRepository.findByBookCoverHash(coverHash).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(coverHash));
return getBookCover(bookEntity.getId());
}
public Resource getBackgroundImage() { public Resource getBackgroundImage() {
try { try {
BookLoreUser user = authenticationService.getAuthenticatedUser(); BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
import com.adityachandel.booklore.util.BookCoverUtils;
import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.FileUtils;
import com.github.junrar.Archive; import com.github.junrar.Archive;
@@ -25,7 +25,10 @@ import org.springframework.stereotype.Service;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.*; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*; import java.util.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -47,7 +50,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
BookCreatorService bookCreatorService, BookCreatorService bookCreatorService,
BookMapper bookMapper, BookMapper bookMapper,
FileService fileService, FileService fileService,
BookMetadataRepository bookMetadataRepository,
MetadataMatchService metadataMatchService, MetadataMatchService metadataMatchService,
CbxMetadataExtractor cbxMetadataExtractor) { CbxMetadataExtractor cbxMetadataExtractor) {
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
@@ -59,8 +61,8 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX); BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX);
if (generateCover(bookEntity)) { if (generateCover(bookEntity)) {
FileService.setBookCoverPath(bookEntity.getMetadata()); FileService.setBookCoverPath(bookEntity.getMetadata());
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
} }
extractAndSetMetadata(bookEntity); extractAndSetMetadata(bookEntity);
return bookEntity; return bookEntity;
} }
@@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
import com.adityachandel.booklore.util.BookCoverUtils;
import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.FileUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -32,19 +32,16 @@ import static com.adityachandel.booklore.util.FileService.truncate;
public class EpubProcessor extends AbstractFileProcessor implements BookFileProcessor { public class EpubProcessor extends AbstractFileProcessor implements BookFileProcessor {
private final EpubMetadataExtractor epubMetadataExtractor; private final EpubMetadataExtractor epubMetadataExtractor;
private final BookMetadataRepository bookMetadataRepository;
public EpubProcessor(BookRepository bookRepository, public EpubProcessor(BookRepository bookRepository,
BookAdditionalFileRepository bookAdditionalFileRepository, BookAdditionalFileRepository bookAdditionalFileRepository,
BookCreatorService bookCreatorService, BookCreatorService bookCreatorService,
BookMapper bookMapper, BookMapper bookMapper,
FileService fileService, FileService fileService,
BookMetadataRepository bookMetadataRepository,
MetadataMatchService metadataMatchService, MetadataMatchService metadataMatchService,
EpubMetadataExtractor epubMetadataExtractor) { EpubMetadataExtractor epubMetadataExtractor) {
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
this.epubMetadataExtractor = epubMetadataExtractor; this.epubMetadataExtractor = epubMetadataExtractor;
this.bookMetadataRepository = bookMetadataRepository;
} }
@Override @Override
@@ -53,6 +50,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc
setBookMetadata(bookEntity); setBookMetadata(bookEntity);
if (generateCover(bookEntity)) { if (generateCover(bookEntity)) {
FileService.setBookCoverPath(bookEntity.getMetadata()); FileService.setBookCoverPath(bookEntity.getMetadata());
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
} }
return bookEntity; return bookEntity;
} }
@@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.Fb2MetadataExtractor; import com.adityachandel.booklore.service.metadata.extractor.Fb2MetadataExtractor;
import com.adityachandel.booklore.util.BookCoverUtils;
import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.FileUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -38,7 +38,6 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce
BookCreatorService bookCreatorService, BookCreatorService bookCreatorService,
BookMapper bookMapper, BookMapper bookMapper,
FileService fileService, FileService fileService,
BookMetadataRepository bookMetadataRepository,
MetadataMatchService metadataMatchService, MetadataMatchService metadataMatchService,
Fb2MetadataExtractor fb2MetadataExtractor) { Fb2MetadataExtractor fb2MetadataExtractor) {
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
@@ -51,6 +50,7 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce
setBookMetadata(bookEntity); setBookMetadata(bookEntity);
if (generateCover(bookEntity)) { if (generateCover(bookEntity)) {
FileService.setBookCoverPath(bookEntity.getMetadata()); FileService.setBookCoverPath(bookEntity.getMetadata());
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
} }
return bookEntity; return bookEntity;
} }
@@ -6,11 +6,11 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.repository.BookAdditionalFileRepository; import com.adityachandel.booklore.repository.BookAdditionalFileRepository;
import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.book.BookCreatorService;
import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.MetadataMatchService;
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
import com.adityachandel.booklore.util.BookCoverUtils;
import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.FileUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -40,7 +40,6 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
BookCreatorService bookCreatorService, BookCreatorService bookCreatorService,
BookMapper bookMapper, BookMapper bookMapper,
FileService fileService, FileService fileService,
BookMetadataRepository bookMetadataRepository,
MetadataMatchService metadataMatchService, MetadataMatchService metadataMatchService,
PdfMetadataExtractor pdfMetadataExtractor) { PdfMetadataExtractor pdfMetadataExtractor) {
super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService);
@@ -52,6 +51,7 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF); BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.PDF);
if (generateCover(bookEntity)) { if (generateCover(bookEntity)) {
FileService.setBookCoverPath(bookEntity.getMetadata()); FileService.setBookCoverPath(bookEntity.getMetadata());
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
} }
extractAndSetMetadata(bookEntity); extractAndSetMetadata(bookEntity);
return bookEntity; return bookEntity;
@@ -127,7 +127,7 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce
if (StringUtils.isNotBlank(extracted.getGoodreadsId())) { if (StringUtils.isNotBlank(extracted.getGoodreadsId())) {
bookEntity.getMetadata().setGoodreadsId(extracted.getGoodreadsId()); bookEntity.getMetadata().setGoodreadsId(extracted.getGoodreadsId());
} }
if (StringUtils.isNotBlank(extracted.getComicvineId())){ if (StringUtils.isNotBlank(extracted.getComicvineId())) {
bookEntity.getMetadata().setComicvineId(extracted.getComicvineId()); bookEntity.getMetadata().setComicvineId(extracted.getComicvineId());
} }
if (StringUtils.isNotBlank(extracted.getIsbn10())) { if (StringUtils.isNotBlank(extracted.getIsbn10())) {
@@ -42,48 +42,58 @@ public class KoboEntitlementService {
private final AuthenticationService authenticationService; private final AuthenticationService authenticationService;
private final KoboReadingStateBuilder readingStateBuilder; private final KoboReadingStateBuilder readingStateBuilder;
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token, boolean removed) { public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds); List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
return books.stream() return books.stream()
.filter(koboCompatibilityService::isBookSupportedForKobo) .filter(koboCompatibilityService::isBookSupportedForKobo)
.map(book -> NewEntitlement.builder() .map(book -> NewEntitlement.builder()
.newEntitlement(BookEntitlementContainer.builder() .newEntitlement(BookEntitlementContainer.builder()
.bookEntitlement(buildBookEntitlement(book, removed)) .bookEntitlement(buildBookEntitlement(book, false))
.bookMetadata(mapToKoboMetadata(book, token)) .bookMetadata(mapToKoboMetadata(book, token))
.readingState(createInitialReadingState(book)) .readingState(getReadingStateForBook(book))
.build()) .build())
.build()) .build())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
public List<ChangedEntitlement> generateChangedEntitlements(Set<Long> bookIds, String token, boolean removed) { public List<? extends Entitlement> generateChangedEntitlements(Set<Long> bookIds, String token, boolean removed) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds); List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
if (removed) {
return books.stream() return books.stream()
.filter(koboCompatibilityService::isBookSupportedForKobo) .filter(koboCompatibilityService::isBookSupportedForKobo)
.map(book -> { .map(book -> {
KoboBookMetadata metadata; KoboBookMetadata metadata = KoboBookMetadata.builder()
if (removed) { .coverImageId(book.getBookCoverHash())
metadata = KoboBookMetadata.builder()
.coverImageId(String.valueOf(book.getId()))
.crossRevisionId(String.valueOf(book.getId())) .crossRevisionId(String.valueOf(book.getId()))
.entitlementId(String.valueOf(book.getId())) .entitlementId(String.valueOf(book.getId()))
.revisionId(String.valueOf(book.getId())) .revisionId(String.valueOf(book.getId()))
.workId(String.valueOf(book.getId())) .workId(String.valueOf(book.getId()))
.title(String.valueOf(book.getId())) .title(String.valueOf(book.getId()))
.build(); .build();
} else {
metadata = mapToKoboMetadata(book, token);
}
return ChangedEntitlement.builder() return ChangedEntitlement.builder()
.changedEntitlement(BookEntitlementContainer.builder() .changedEntitlement(BookEntitlementContainer.builder()
.bookEntitlement(buildBookEntitlement(book, true)) .bookEntitlement(buildBookEntitlement(book, removed))
.bookMetadata(metadata) .bookMetadata(metadata)
.build()) .build())
.build(); .build();
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
return books.stream()
.filter(bookEntity -> bookEntity.getBookType() == BookFileType.EPUB)
.map(book -> ChangedProductMetadata.builder()
.changedProductMetadata(BookEntitlementContainer.builder()
.bookEntitlement(buildBookEntitlement(book, false))
.bookMetadata(mapToKoboMetadata(book, token))
.build())
.build())
.collect(Collectors.toList());
}
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) { public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
OffsetDateTime now = getCurrentUtc(); OffsetDateTime now = getCurrentUtc();
@@ -118,7 +128,7 @@ public class KoboEntitlementService {
.build(); .build();
} }
private KoboReadingState createInitialReadingState(BookEntity book) { private KoboReadingState getReadingStateForBook(BookEntity book) {
OffsetDateTime now = getCurrentUtc(); OffsetDateTime now = getCurrentUtc();
String entitlementId = String.valueOf(book.getId()); String entitlementId = String.valueOf(book.getId());
@@ -163,7 +173,7 @@ public class KoboEntitlementService {
.activePeriod(BookEntitlement.ActivePeriod.builder() .activePeriod(BookEntitlement.ActivePeriod.builder()
.from(now.toString()) .from(now.toString())
.build()) .build())
.isRemoved(removed) .removed(removed)
.status("Active") .status("Active")
.crossRevisionId(String.valueOf(book.getId())) .crossRevisionId(String.valueOf(book.getId()))
.revisionId(String.valueOf(book.getId())) .revisionId(String.valueOf(book.getId()))
@@ -235,9 +245,9 @@ public class KoboEntitlementService {
.slug(metadata.getTitle() != null .slug(metadata.getTitle() != null
? NON_ALPHANUMERIC_LOWERCASE_PATTERN.matcher(metadata.getTitle().toLowerCase()).replaceAll("-") ? NON_ALPHANUMERIC_LOWERCASE_PATTERN.matcher(metadata.getTitle().toLowerCase()).replaceAll("-")
: null) : null)
.coverImageId(String.valueOf(metadata.getBookId())) .coverImageId(book.getBookCoverHash())
.workId(String.valueOf(book.getId())) .workId(String.valueOf(book.getId()))
.isPreOrder(false) .preOrder(false)
.contributorRoles(Collections.emptyList()) .contributorRoles(Collections.emptyList())
.entitlementId(String.valueOf(book.getId())) .entitlementId(String.valueOf(book.getId()))
.title(metadata.getTitle()) .title(metadata.getTitle())
@@ -1,17 +1,14 @@
package com.adityachandel.booklore.service.kobo; package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper; import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.*;
import com.adityachandel.booklore.model.entity.KoboDeletedBookProgressEntity;
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
import com.adityachandel.booklore.model.entity.ShelfEntity;
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
import com.adityachandel.booklore.model.enums.ShelfType; import com.adityachandel.booklore.model.enums.ShelfType;
import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository; import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import com.adityachandel.booklore.repository.KoboSnapshotBookRepository;
import com.adityachandel.booklore.repository.KoboLibrarySnapshotRepository; import com.adityachandel.booklore.repository.KoboLibrarySnapshotRepository;
import com.adityachandel.booklore.repository.KoboSnapshotBookRepository;
import com.adityachandel.booklore.repository.ShelfRepository;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
@@ -31,6 +28,7 @@ public class KoboLibrarySnapshotService {
private final BookEntityToKoboSnapshotBookMapper mapper; private final BookEntityToKoboSnapshotBookMapper mapper;
private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository; private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
private final KoboCompatibilityService koboCompatibilityService; private final KoboCompatibilityService koboCompatibilityService;
private final AuthenticationService authenticationService;
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Optional<KoboLibrarySnapshotEntity> findByIdAndUserId(String id, Long userId) { public Optional<KoboLibrarySnapshotEntity> findByIdAndUserId(String id, Long userId) {
@@ -64,13 +62,13 @@ public class KoboLibrarySnapshotService {
@Transactional @Transactional
public void updateSyncedStatusForExistingBooks(String previousSnapshotId, String currentSnapshotId) { public void updateSyncedStatusForExistingBooks(String previousSnapshotId, String currentSnapshotId) {
List<KoboSnapshotBookEntity> list = koboSnapshotBookRepository.findExistingBooksBetweenSnapshots(previousSnapshotId, currentSnapshotId); List<KoboSnapshotBookEntity> list = koboSnapshotBookRepository.findUnchangedBooksBetweenSnapshots(previousSnapshotId, currentSnapshotId);
List<Long> existingBooks = list.stream() List<Long> unchangedBooks = list.stream()
.map(KoboSnapshotBookEntity::getBookId) .map(KoboSnapshotBookEntity::getBookId)
.toList(); .toList();
if (!existingBooks.isEmpty()) { if (!unchangedBooks.isEmpty()) {
koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, existingBooks); koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, unchangedBooks);
} }
} }
@@ -110,6 +108,20 @@ public class KoboLibrarySnapshotService {
return page; return page;
} }
@Transactional
public Page<KoboSnapshotBookEntity> getChangedBooks(String previousSnapshotId, String currentSnapshotId, Pageable pageable) {
Page<KoboSnapshotBookEntity> page = koboSnapshotBookRepository.findChangedBooks(previousSnapshotId, currentSnapshotId, pageable);
List<Long> changedBookIds = page.getContent().stream()
.map(KoboSnapshotBookEntity::getBookId)
.toList();
if (!changedBookIds.isEmpty()) {
koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, changedBookIds);
}
return page;
}
private ShelfEntity getKoboShelf(Long userId) { private ShelfEntity getKoboShelf(Long userId) {
return shelfRepository return shelfRepository
.findByUserIdAndName(userId, ShelfType.KOBO.getName()) .findByUserIdAndName(userId, ShelfType.KOBO.getName())
@@ -127,16 +139,18 @@ public class KoboLibrarySnapshotService {
.map(book -> { .map(book -> {
KoboSnapshotBookEntity snapshotBook = mapper.toKoboSnapshotBook(book); KoboSnapshotBookEntity snapshotBook = mapper.toKoboSnapshotBook(book);
snapshotBook.setSnapshot(snapshot); snapshotBook.setSnapshot(snapshot);
snapshotBook.setFileHash(book.getCurrentHash());
snapshotBook.setMetadataUpdatedAt(book.getMetadataUpdatedAt());
return snapshotBook; return snapshotBook;
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private boolean isBookOwnedByUser(BookEntity book, Long userId) { private boolean isBookOwnedByUser(BookEntity book, Long userId) {
if (book == null || book.getLibrary() == null || book.getLibrary().getUsers() == null) { BookLoreUser user = authenticationService.getAuthenticatedUser();
return false; if (user.getPermissions().isAdmin()) {
return true;
} }
return book.getLibrary() return book.getLibrary()
.getUsers() .getUsers()
.stream() .stream()
@@ -53,6 +53,7 @@ public class KoboLibrarySyncService {
if (prevSnapshot.isPresent()) { if (prevSnapshot.isPresent()) {
int maxRemaining = 5; int maxRemaining = 5;
List<KoboSnapshotBookEntity> removedAll = new ArrayList<>(); List<KoboSnapshotBookEntity> removedAll = new ArrayList<>();
List<KoboSnapshotBookEntity> changedAll = new ArrayList<>();
koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.getId()); koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.getId());
@@ -61,34 +62,45 @@ public class KoboLibrarySyncService {
maxRemaining -= addedPage.getNumberOfElements(); maxRemaining -= addedPage.getNumberOfElements();
shouldContinueSync = addedPage.hasNext(); shouldContinueSync = addedPage.hasNext();
Page<KoboSnapshotBookEntity> removedPage = Page.empty(); Page<KoboSnapshotBookEntity> changedPage = Page.empty();
if (addedPage.isLast() && maxRemaining > 0) { if (addedPage.isLast() && maxRemaining > 0) {
changedPage = koboLibrarySnapshotService.getChangedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), PageRequest.of(0, maxRemaining));
changedAll.addAll(changedPage.getContent());
maxRemaining -= changedPage.getNumberOfElements();
shouldContinueSync = shouldContinueSync || changedPage.hasNext();
}
Page<KoboSnapshotBookEntity> removedPage = Page.empty();
if (changedPage.isLast() && maxRemaining > 0) {
removedPage = koboLibrarySnapshotService.getRemovedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), user.getId(), PageRequest.of(0, maxRemaining)); removedPage = koboLibrarySnapshotService.getRemovedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), user.getId(), PageRequest.of(0, maxRemaining));
removedAll.addAll(removedPage.getContent()); removedAll.addAll(removedPage.getContent());
shouldContinueSync = shouldContinueSync || removedPage.hasNext(); shouldContinueSync = shouldContinueSync || removedPage.hasNext();
} }
Set<Long> addedIds = addedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); Set<Long> addedIds = addedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
Set<Long> changedIds = changedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
Set<Long> removedIds = removedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); Set<Long> removedIds = removedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
entitlements.addAll(entitlementService.generateNewEntitlements(addedIds, token, false)); entitlements.addAll(entitlementService.generateNewEntitlements(addedIds, token));
entitlements.addAll(entitlementService.generateChangedEntitlements(changedIds, token, false));
entitlements.addAll(entitlementService.generateChangedEntitlements(removedIds, token, true)); entitlements.addAll(entitlementService.generateChangedEntitlements(removedIds, token, true));
if (!shouldContinueSync) { if (!shouldContinueSync) {
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId())); entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
} }
} else { } else {
int maxRemaining = 5; int maxRemaining = 5;
List<KoboSnapshotBookEntity> all = new ArrayList<>(); List<KoboSnapshotBookEntity> snapshotBookEntities = new ArrayList<>();
while (maxRemaining > 0) { while (maxRemaining > 0) {
var page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining)); Page<KoboSnapshotBookEntity> page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining));
all.addAll(page.getContent()); snapshotBookEntities.addAll(page.getContent());
maxRemaining -= page.getNumberOfElements(); maxRemaining -= page.getNumberOfElements();
shouldContinueSync = page.hasNext(); shouldContinueSync = page.hasNext();
if (!shouldContinueSync || page.getNumberOfElements() == 0) break; if (!shouldContinueSync || page.getNumberOfElements() == 0) break;
} }
Set<Long> ids = all.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); Set<Long> ids = snapshotBookEntities.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
entitlements.addAll(entitlementService.generateNewEntitlements(ids, token, false)); entitlements.addAll(entitlementService.generateNewEntitlements(ids, token));
if (!shouldContinueSync) { if (!shouldContinueSync) {
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId())); entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
@@ -92,15 +92,13 @@ public class KoboServerProxy {
String koboBaseUrl = "https://storeapi.kobo.com"; String koboBaseUrl = "https://storeapi.kobo.com";
String queryString = request.getQueryString(); String queryString = request.getQueryString();
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(koboBaseUrl) String uriString = koboBaseUrl + path;
.path(path);
if (queryString != null && !queryString.isBlank()) { if (queryString != null && !queryString.isBlank()) {
uriBuilder.query(queryString); uriString += "?" + queryString;
} }
URI uri = uriBuilder.build(true).toUri(); URI uri = URI.create(uriString);
log.info("Kobo proxy URL: {}", uri); log.debug("Kobo proxy URL: {}", uri);
String bodyString = body != null ? objectMapper.writeValueAsString(body) : "{}"; String bodyString = body != null ? objectMapper.writeValueAsString(body) : "{}";
HttpRequest.Builder builder = HttpRequest.newBuilder() HttpRequest.Builder builder = HttpRequest.newBuilder()
@@ -147,7 +145,7 @@ public class KoboServerProxy {
} }
} }
log.info("Kobo proxy response status: {}", response.statusCode()); log.debug("Kobo proxy response status: {}", response.statusCode());
return new ResponseEntity<>(responseBody, responseHeaders, HttpStatus.valueOf(response.statusCode())); return new ResponseEntity<>(responseBody, responseHeaders, HttpStatus.valueOf(response.statusCode()));
@@ -15,18 +15,16 @@ public class KoboThumbnailService {
private final BookService bookService; private final BookService bookService;
public ResponseEntity<Resource> getThumbnail(Long bookId) { public ResponseEntity<Resource> getThumbnail(String coverHash) {
return getThumbnailInternal(bookId); return getThumbnailInternal(coverHash);
} }
private ResponseEntity<Resource> getThumbnailInternal(Long bookId) { private ResponseEntity<Resource> getThumbnailInternal(String coverHash) {
Resource image = bookService.getBookCover(coverHash);
Resource image = bookService.getBookCover(bookId);
if (!isValidImage(image)) { if (!isValidImage(image)) {
log.warn("Thumbnail not found for bookId={}", bookId); log.warn("Thumbnail not found for bookId={}", coverHash);
return ResponseEntity.notFound().build(); return ResponseEntity.notFound().build();
} }
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "image/jpeg") .header(HttpHeaders.CONTENT_TYPE, "image/jpeg")
.body(image); .body(image);
@@ -0,0 +1,355 @@
package com.adityachandel.booklore.service.metadata;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMetadataMapper;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriter;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
import com.adityachandel.booklore.util.BookCoverUtils;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.time.Instant;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@Slf4j
@Service
@AllArgsConstructor
public class BookCoverService {
private static final int BATCH_SIZE = 100;
private final BookRepository bookRepository;
private final BookMetadataMapper bookMetadataMapper;
private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final FileService fileService;
private final BookFileProcessorRegistry processorRegistry;
private final BookQueryService bookQueryService;
private final CoverImageGenerator coverImageGenerator;
private final MetadataWriterFactory metadataWriterFactory;
private final TransactionTemplate transactionTemplate;
private record BookCoverInfo(Long id, String title) {
}
private record BookRegenerationInfo(Long id, String title, BookFileType bookType) {
}
public void generateCustomCover(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (isCoverLocked(bookEntity)) {
throw ApiError.METADATA_LOCKED.createException();
}
String title = bookEntity.getMetadata().getTitle();
String author = getAuthorNames(bookEntity);
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
fileService.createThumbnailFromBytes(bookId, coverBytes);
updateBookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
notifyBookCoverUpdate(bookEntity);
}
@Transactional
public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) {
fileService.createThumbnailFromFile(bookId, file);
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file));
}
@Transactional
public BookMetadata updateCoverImageFromUrl(Long bookId, String url) {
fileService.createThumbnailFromUrl(bookId, url);
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url));
}
public void updateCoverImageFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
validateCoverFile(file);
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes));
}
public void regenerateCover(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (isCoverLocked(bookEntity)) {
throw ApiError.METADATA_LOCKED.createException();
}
regenerateCoverForBook(bookEntity, "");
updateBookCoverMetadata(bookEntity);
bookRepository.save(bookEntity);
}
public void regenerateCoversForBooks(Set<Long> bookIds) {
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
}
public void regenerateCovers() {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
.filter(book -> !isCoverLocked(book))
.toList();
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books"));
int current = 1;
for (BookEntity book : books) {
try {
String progress = "(" + current + "/" + total + ") ";
regenerateCoverForBook(book, progress);
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage(), e);
}
current++;
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
}
});
}
private BookMetadata updateCover(Long bookId, BiConsumer<MetadataWriter, BookEntity> writerAction) {
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream()
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
updateBookCoverMetadata(bookEntity);
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
boolean saveToOriginalFile = settings.isSaveToOriginalFile();
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
metadataWriterFactory.getWriter(bookEntity.getBookType())
.ifPresent(writer -> {
writerAction.accept(writer, bookEntity);
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
bookEntity.setCurrentHash(newHash);
});
}
bookEntity.setMetadataUpdatedAt(Instant.now());
bookRepository.save(bookEntity);
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
}
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes) {
try {
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
int current = 1;
for (BookCoverInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes);
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
updateBookCoverMetadata(book);
bookRepository.save(book);
});
log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
} catch (Exception e) {
log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover update: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover update"));
}
}
private void processBulkCoverRegeneration(List<BookRegenerationInfo> books) {
try {
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
regenerateCoverForBookId(bookInfo);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
refreshedIds.add(bookInfo.id());
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
notifyBulkCoverUpdate(refreshedIds);
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
}
}
private void regenerateCoverForBook(BookEntity book, String progress) {
String title = book.getMetadata().getTitle();
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title));
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
boolean success = processor.generateCover(book);
if (success) {
Instant now = Instant.now();
book.getMetadata().setCoverUpdatedOn(now);
book.setBookCoverHash(BookCoverUtils.generateCoverHash());
}
log.info("{} regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success);
if (!success) {
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
}
}
private void regenerateCoverForBookId(BookRegenerationInfo bookInfo) {
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
processor.generateCover(book);
});
}
private void validateCoverFile(MultipartFile file) {
if (file.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Uploaded file is empty");
}
String contentType = file.getContentType();
if (contentType == null || (!contentType.toLowerCase().startsWith("image/jpeg") && !contentType.toLowerCase().startsWith("image/png"))) {
throw ApiError.INVALID_INPUT.createException("Only JPEG and PNG files are allowed");
}
long maxFileSize = 5L * 1024 * 1024;
if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(5);
}
}
private byte[] extractBytesFromMultipartFile(MultipartFile file) {
try {
return file.getBytes();
} catch (Exception e) {
log.error("Failed to read cover file: {}", e.getMessage());
throw new RuntimeException("Failed to read cover file", e);
}
}
private List<BookCoverInfo> getUnlockedBookCoverInfos(Set<Long> bookIds) {
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
.filter(book -> !isCoverLocked(book))
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
.toList();
}
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
.filter(book -> !isCoverLocked(book))
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType()))
.toList();
}
private boolean isCoverLocked(BookEntity book) {
return book.getMetadata().getCoverLocked() != null && book.getMetadata().getCoverLocked();
}
private String getAuthorNames(BookEntity bookEntity) {
if (bookEntity.getMetadata().getAuthors() != null && !bookEntity.getMetadata().getAuthors().isEmpty()) {
return bookEntity.getMetadata().getAuthors().stream()
.map(AuthorEntity::getName)
.collect(Collectors.joining(", "));
}
return null;
}
private void updateBookCoverMetadata(BookEntity bookEntity) {
Instant now = Instant.now();
bookEntity.setMetadataUpdatedAt(now);
bookEntity.getMetadata().setCoverUpdatedOn(now);
bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash());
}
private void notifyBookCoverUpdate(BookEntity bookEntity) {
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, List.of(Map.of(
"id", bookEntity.getId(),
"coverUpdatedOn", bookEntity.getMetadata().getCoverUpdatedOn()
)));
}
private void notifyBulkCoverUpdate(List<Long> refreshedIds) {
if (refreshedIds.isEmpty()) {
return;
}
List<Map<String, Object>> refreshedPatches = transactionTemplate.execute(status -> {
List<BookEntity> entities = bookQueryService.findAllWithMetadataByIds(new HashSet<>(refreshedIds));
if (entities == null || entities.isEmpty()) {
return List.<Map<String, Object>>of();
}
entities.forEach(e -> {
if (e.getMetadata() != null) {
e.getMetadata().getCoverUpdatedOn();
}
});
return entities.stream()
.map(e -> Map.<String, Object>of(
"id", e.getId(),
"coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn()
))
.toList();
});
if (refreshedPatches != null && !refreshedPatches.isEmpty()) {
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches);
}
}
private void pauseAfterBatchIfNeeded(int current, int total) {
if (current % BATCH_SIZE == 0 && current < total) {
try {
log.info("Processed {} items, pausing briefly before next batch...", current);
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Batch pause interrupted");
}
}
}
}
@@ -12,30 +12,19 @@ import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.request.BulkMetadataUpdateRequest; import com.adityachandel.booklore.model.dto.request.BulkMetadataUpdateRequest;
import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest; import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.Lock; import com.adityachandel.booklore.model.enums.Lock;
import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor; import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor;
import com.adityachandel.booklore.service.metadata.parser.BookParser; import com.adityachandel.booklore.service.metadata.parser.BookParser;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriter;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.FileUtils; import com.adityachandel.booklore.util.FileUtils;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -44,14 +33,8 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.time.Instant; import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Slf4j @Slf4j
@@ -59,49 +42,20 @@ import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
public class BookMetadataService { public class BookMetadataService {
private static final int BATCH_SIZE = 100;
private final BookRepository bookRepository; private final BookRepository bookRepository;
private final BookMapper bookMapper; private final BookMapper bookMapper;
private final BookMetadataMapper bookMetadataMapper; private final BookMetadataMapper bookMetadataMapper;
private final BookMetadataUpdater bookMetadataUpdater; private final BookMetadataUpdater bookMetadataUpdater;
private final NotificationService notificationService; private final NotificationService notificationService;
private final AppSettingService appSettingService;
private final BookMetadataRepository bookMetadataRepository; private final BookMetadataRepository bookMetadataRepository;
private final FileService fileService;
private final BookFileProcessorRegistry processorRegistry;
private final BookQueryService bookQueryService; private final BookQueryService bookQueryService;
private final Map<MetadataProvider, BookParser> parserMap; private final Map<MetadataProvider, BookParser> parserMap;
private final CbxMetadataExtractor cbxMetadataExtractor; private final CbxMetadataExtractor cbxMetadataExtractor;
private final MetadataWriterFactory metadataWriterFactory;
private final MetadataClearFlagsMapper metadataClearFlagsMapper; private final MetadataClearFlagsMapper metadataClearFlagsMapper;
private final org.springframework.transaction.PlatformTransactionManager transactionManager; private final BookCoverService bookCoverService;
private final CoverImageGenerator coverImageGenerator;
public void generateCustomCover(long bookId) { public void generateCustomCover(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); bookCoverService.generateCustomCover(bookId);
if (bookEntity.getMetadata().getCoverLocked() != null && bookEntity.getMetadata().getCoverLocked()) {
throw ApiError.METADATA_LOCKED.createException();
}
String title = bookEntity.getMetadata().getTitle();
String author = null;
if (bookEntity.getMetadata().getAuthors() != null && !bookEntity.getMetadata().getAuthors().isEmpty()) {
author = bookEntity.getMetadata().getAuthors().stream()
.map(AuthorEntity::getName)
.collect(Collectors.joining(", "));
}
byte[] coverBytes = coverImageGenerator.generateCover(title, author);
fileService.createThumbnailFromBytes(bookId, coverBytes);
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
bookRepository.save(bookEntity);
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, List.of(Map.of(
"id", bookId,
"coverUpdatedOn", bookEntity.getMetadata().getCoverUpdatedOn()
)));
} }
public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { public List<BookMetadata> getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) {
@@ -185,241 +139,28 @@ public class BookMetadataService {
@Transactional @Transactional
public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) {
fileService.createThumbnailFromFile(bookId, file); return bookCoverService.updateCoverImageFromFile(bookId, file);
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file));
}
public void updateCoverImageFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
validateCoverFile(file);
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() ->
processBulkCoverUpdate(unlockedBooks, coverImageBytes));
}
private void validateCoverFile(MultipartFile file) {
if (file.isEmpty()) {
throw ApiError.INVALID_INPUT.createException("Uploaded file is empty");
}
String contentType = file.getContentType();
if (contentType == null || (!contentType.toLowerCase().startsWith("image/jpeg") && !contentType.toLowerCase().startsWith("image/png"))) {
throw ApiError.INVALID_INPUT.createException("Only JPEG and PNG files are allowed");
}
long maxFileSize = 5L * 1024 * 1024;
if (file.getSize() > maxFileSize) {
throw ApiError.FILE_TOO_LARGE.createException(5);
}
}
private byte[] extractBytesFromMultipartFile(MultipartFile file) {
try {
return file.getBytes();
} catch (Exception e) {
log.error("Failed to read cover file: {}", e.getMessage());
throw new RuntimeException("Failed to read cover file", e);
}
}
private record BookCoverInfo(Long id, String title) {}
private List<BookCoverInfo> getUnlockedBookCoverInfos(Set<Long> bookIds) {
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
.filter(book -> !isCoverLocked(book))
.map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle()))
.toList();
}
private boolean isCoverLocked(BookEntity book) {
return book.getMetadata().getCoverLocked() != null && book.getMetadata().getCoverLocked();
}
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes) {
try {
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
int current = 1;
for (BookCoverInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes);
log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
} catch (Exception e) {
log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover update: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover update"));
}
} }
@Transactional @Transactional
public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { public BookMetadata updateCoverImageFromUrl(Long bookId, String url) {
fileService.createThumbnailFromUrl(bookId, url); return bookCoverService.updateCoverImageFromUrl(bookId, url);
return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url));
} }
private BookMetadata updateCover(Long bookId, BiConsumer<MetadataWriter, BookEntity> writerAction) { public void updateCoverImageFromFileForBooks(Set<Long> bookIds, MultipartFile file) {
BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId)).stream() bookCoverService.updateCoverImageFromFileForBooks(bookIds, file);
.findFirst()
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
bookEntity.getMetadata().setCoverUpdatedOn(Instant.now());
MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings();
boolean saveToOriginalFile = settings.isSaveToOriginalFile();
boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz();
if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) {
metadataWriterFactory.getWriter(bookEntity.getBookType())
.ifPresent(writer -> {
writerAction.accept(writer, bookEntity);
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
bookEntity.setCurrentHash(newHash);
});
}
bookRepository.save(bookEntity);
return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true);
} }
public void regenerateCover(long bookId) { public void regenerateCover(long bookId) {
BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); bookCoverService.regenerateCover(bookId);
if (bookEntity.getMetadata().getCoverLocked() != null && bookEntity.getMetadata().getCoverLocked()) {
throw ApiError.METADATA_LOCKED.createException();
} else {
regenerateCoverForBook(bookEntity, "");
} }
}
private record BookRegenerationInfo(Long id, String title, BookFileType bookType) {}
public void regenerateCoversForBooks(Set<Long> bookIds) { public void regenerateCoversForBooks(Set<Long> bookIds) {
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); bookCoverService.regenerateCoversForBooks(bookIds);
SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks));
}
private List<BookRegenerationInfo> getUnlockedBookRegenerationInfos(Set<Long> bookIds) {
return bookQueryService.findAllWithMetadataByIds(bookIds).stream()
.filter(book -> !isCoverLocked(book))
.map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType()))
.toList();
}
private void processBulkCoverRegeneration(List<BookRegenerationInfo> books) {
try {
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) {
try {
String progress = "(" + current + "/" + total + ") ";
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
regenerateCoverForBookId(bookInfo);
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title());
refreshedIds.add(bookInfo.id());
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e);
}
pauseAfterBatchIfNeeded(current, total);
current++;
}
List<Book> updatedBooks = new ArrayList<>();
if (!refreshedIds.isEmpty()) {
org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager);
List<java.util.Map<String, Object>> refreshedPatches = tx.execute(status -> {
List<BookEntity> entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds));
if (entities == null || entities.isEmpty()) return List.<java.util.Map<String, Object>>of();
entities.forEach(e -> {
if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn();
});
return entities.stream()
.map(e -> java.util.Map.<String, Object>of(
"id", e.getId(),
"coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn()
))
.toList();
});
if (refreshedPatches != null && !refreshedPatches.isEmpty()) {
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches);
}
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
}
}
private void pauseAfterBatchIfNeeded(int current, int total) {
if (current % BATCH_SIZE == 0 && current < total) {
try {
log.info("Processed {} items, pausing briefly before next batch...", current);
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Batch pause interrupted");
}
}
}
private void regenerateCoverForBookId(BookRegenerationInfo bookInfo) {
bookRepository.findById(bookInfo.id()).ifPresent(book -> {
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType());
processor.generateCover(book);
});
} }
public void regenerateCovers() { public void regenerateCovers() {
SecurityContextVirtualThread.runWithSecurityContext(() -> { bookCoverService.regenerateCovers();
try {
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
.filter(book -> !isCoverLocked(book))
.toList();
int total = books.size();
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books"));
int current = 1;
for (BookEntity book : books) {
try {
String progress = "(" + current + "/" + total + ") ";
regenerateCoverForBook(book, progress);
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage(), e);
}
current++;
}
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
}
});
}
private void regenerateCoverForBook(BookEntity book, String progress) {
String title = book.getMetadata().getTitle();
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title));
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType());
boolean success = processor.generateCover(book);
log.info("{}regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success);
if (!success) {
throw ApiError.FAILED_TO_REGENERATE_COVER.createException();
}
} }
public BookMetadata getComicInfoMetadata(long bookId) { public BookMetadata getComicInfoMetadata(long bookId) {
@@ -30,6 +30,7 @@ import org.springframework.util.StringUtils;
import java.io.File; import java.io.File;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.URI; import java.net.URI;
import java.time.Instant;
import java.util.*; import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Supplier; import java.util.function.Supplier;
@@ -102,8 +103,8 @@ public class BookMetadataUpdater {
updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail); updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail);
updateLocks(newMetadata, metadata); updateLocks(newMetadata, metadata);
bookEntity.setMetadataUpdatedAt(Instant.now());
bookRepository.save(bookEntity); bookRepository.save(bookEntity);
try { try {
Float score = metadataMatchService.calculateMatchScore(bookEntity); Float score = metadataMatchService.calculateMatchScore(bookEntity);
bookEntity.setMetadataMatchScore(score); bookEntity.setMetadataMatchScore(score);
@@ -122,7 +123,9 @@ public class BookMetadataUpdater {
File file = new File(bookEntity.getFullFilePath().toUri()); File file = new File(bookEntity.getFullFilePath().toUri());
writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags); writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags);
String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath());
bookEntity.setMetadataForWriteUpdatedAt(Instant.now());
bookEntity.setCurrentHash(newHash); bookEntity.setCurrentHash(newHash);
bookRepository.save(bookEntity);
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage()); log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage());
} }
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.util;
import lombok.experimental.UtilityClass;
import java.time.Instant;
import java.util.Random;
@UtilityClass
public class BookCoverUtils {
private static final String HASH_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String generateCoverHash() {
long timestamp = Instant.now().toEpochMilli();
Random random = new Random(timestamp);
StringBuilder hash = new StringBuilder(13);
hash.append("BL-");
for (int i = 0; i < 13; i++) {
hash.append(HASH_CHARS.charAt(random.nextInt(HASH_CHARS.length())));
}
return hash.toString();
}
}
@@ -43,10 +43,10 @@ public class KoboUrlBuilder {
log.info("Applied X-Forwarded-Port: {}", port); log.info("Applied X-Forwarded-Port: {}", port);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
builder.port(serverPort); builder.port(serverPort);
log.warn("Invalid X-Forwarded-Port header: {}", xfPort); log.debug("Invalid X-Forwarded-Port header: {}", xfPort);
} }
log.info("Final base URL: {}", builder.build().toUriString()); log.debug("Final base URL: {}", builder.build().toUriString());
return builder; return builder;
} }
@@ -0,0 +1,15 @@
ALTER TABLE book
ADD COLUMN IF NOT EXISTS metadata_updated_at TIMESTAMP;
ALTER TABLE book
ADD COLUMN IF NOT EXISTS metadata_for_write_updated_at TIMESTAMP;
ALTER TABLE kobo_library_snapshot_book
ADD COLUMN IF NOT EXISTS file_hash VARCHAR(255);
ALTER TABLE kobo_library_snapshot_book
ADD COLUMN IF NOT EXISTS metadata_updated_at TIMESTAMP;
ALTER TABLE book
ADD COLUMN IF NOT EXISTS book_cover_hash VARCHAR(20);
@@ -0,0 +1,7 @@
-- Assign all admin users to all libraries
INSERT IGNORE INTO user_library_mapping (user_id, library_id)
SELECT u.id, l.id
FROM users u
CROSS JOIN library l
INNER JOIN user_permissions up ON u.id = up.user_id
WHERE up.permission_admin = true;
@@ -1,6 +1,9 @@
package com.adityachandel.booklore.service.kobo; package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper; import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.BookLoreUser.UserPermissions;
import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity; import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
@@ -51,6 +54,9 @@ class KoboLibrarySnapshotServiceTest {
@Mock @Mock
private KoboCompatibilityService koboCompatibilityService; private KoboCompatibilityService koboCompatibilityService;
@Mock
private AuthenticationService authenticationService;
@InjectMocks @InjectMocks
private KoboLibrarySnapshotService service; private KoboLibrarySnapshotService service;
@@ -81,6 +87,15 @@ class KoboLibrarySnapshotServiceTest {
.id(202L) .id(202L)
.library(othersLibrary) .library(othersLibrary)
.build(); .build();
UserPermissions userPermissions = new UserPermissions();
userPermissions.setAdmin(false);
BookLoreUser mockUser = BookLoreUser.builder()
.id(owner.getId())
.permissions(userPermissions)
.build();
when(authenticationService.getAuthenticatedUser()).thenReturn(mockUser);
} }
@Test @Test
@@ -0,0 +1,258 @@
package com.adityachandel.booklore.service.metadata;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.mapper.BookMetadataMapper;
import com.adityachandel.booklore.model.dto.BookMetadata;
import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings;
import com.adityachandel.booklore.model.entity.AuthorEntity;
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.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.file.FileFingerprint;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriter;
import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory;
import com.adityachandel.booklore.util.FileService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.*;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.time.Instant;
import java.util.*;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
class BookCoverServiceTest {
@Mock private BookRepository bookRepository;
@Mock private BookMetadataMapper bookMetadataMapper;
@Mock private NotificationService notificationService;
@Mock private AppSettingService appSettingService;
@Mock private FileService fileService;
@Mock private BookFileProcessorRegistry processorRegistry;
@Mock private BookQueryService bookQueryService;
@Mock private CoverImageGenerator coverImageGenerator;
@Mock private MetadataWriterFactory metadataWriterFactory;
@Mock private TransactionTemplate transactionTemplate;
@InjectMocks private BookCoverService bookCoverService;
@Captor private ArgumentCaptor<Object> notificationCaptor;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
private BookEntity mockBookEntity(Long id, boolean coverLocked) {
BookMetadataEntity metadata = new BookMetadataEntity();
metadata.setTitle("Test Title");
metadata.setAuthors(Set.of(new AuthorEntity(1L, "Author Name", null)));
metadata.setCoverLocked(coverLocked);
BookEntity book = new BookEntity();
book.setId(id);
book.setMetadata(metadata);
book.setBookType(BookFileType.EPUB);
return book;
}
@Test
void generateCustomCover_success() {
BookEntity book = mockBookEntity(1L, false);
when(bookRepository.findById(1L)).thenReturn(Optional.of(book));
when(coverImageGenerator.generateCover(any(), any())).thenReturn(new byte[]{1,2,3});
doNothing().when(fileService).createThumbnailFromBytes(eq(1L), any());
when(bookRepository.save(any())).thenReturn(book);
bookCoverService.generateCustomCover(1L);
verify(fileService).createThumbnailFromBytes(eq(1L), any());
verify(bookRepository).save(book);
verify(notificationService).sendMessage(eq(Topic.BOOKS_COVER_UPDATE), any());
}
@Test
void generateCustomCover_coverLocked_throws() {
BookEntity book = mockBookEntity(2L, true);
when(bookRepository.findById(2L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> bookCoverService.generateCustomCover(2L))
.isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass());
}
@Test
void updateCoverImageFromFile_success() {
MultipartFile file = mock(MultipartFile.class);
BookEntity book = mockBookEntity(3L, false);
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
when(bookRepository.save(any())).thenReturn(book);
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
BookMetadata result = bookCoverService.updateCoverImageFromFile(3L, file);
verify(fileService).createThumbnailFromFile(3L, file);
assertThat(result).isNotNull();
}
@Test
void updateCoverImageFromUrl_success() {
String url = "http://test.com/cover.jpg";
BookEntity book = mockBookEntity(4L, false);
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
when(bookRepository.save(any())).thenReturn(book);
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
BookMetadata result = bookCoverService.updateCoverImageFromUrl(4L, url);
verify(fileService).createThumbnailFromUrl(4L, url);
assertThat(result).isNotNull();
}
@Test
void updateCoverImageFromFileForBooks_success() throws Exception {
try (MockedStatic<SecurityContextVirtualThread> ignored = mockStatic(SecurityContextVirtualThread.class)) {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(false);
when(file.getContentType()).thenReturn("image/jpeg");
doReturn(new byte[]{1,2,3}).when(file).getBytes();
BookEntity book = mockBookEntity(5L, false);
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
when(bookRepository.findById(5L)).thenReturn(Optional.of(book));
when(bookRepository.save(any())).thenReturn(book);
doNothing().when(fileService).createThumbnailFromBytes(eq(5L), any());
ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
});
bookCoverService.updateCoverImageFromFileForBooks(Set.of(5L), file);
ArgumentCaptor<Long> idCaptor = ArgumentCaptor.forClass(Long.class);
verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any());
assertThat(idCaptor.getValue()).isEqualTo(5L);
verify(bookRepository).save(any(BookEntity.class));
}
}
@Test
void updateCoverImageFromFileForBooks_invalidFile_throws() {
MultipartFile file = mock(MultipartFile.class);
when(file.isEmpty()).thenReturn(true);
assertThatThrownBy(() -> bookCoverService.updateCoverImageFromFileForBooks(Set.of(6L), file))
.isInstanceOf(ApiError.INVALID_INPUT.createException("dummy").getClass());
}
@Test
void regenerateCover_success() {
BookEntity book = mockBookEntity(7L, false);
when(bookRepository.findById(7L)).thenReturn(Optional.of(book));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
when(processor.generateCover(any())).thenReturn(true);
when(bookRepository.save(any())).thenReturn(book);
bookCoverService.regenerateCover(7L);
verify(processor).generateCover(book);
verify(bookRepository).save(book);
}
@Test
void regenerateCover_coverLocked_throws() {
BookEntity book = mockBookEntity(8L, true);
when(bookRepository.findById(8L)).thenReturn(Optional.of(book));
assertThatThrownBy(() -> bookCoverService.regenerateCover(8L))
.isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass());
}
@Test
void regenerateCoversForBooks_success() {
try (MockedStatic<SecurityContextVirtualThread> ignored = mockStatic(SecurityContextVirtualThread.class)) {
BookEntity book = mockBookEntity(9L, false);
when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
BookFileProcessor processor = mock(BookFileProcessor.class);
when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor);
when(processor.generateCover(any())).thenReturn(true);
when(bookRepository.findById(9L)).thenReturn(Optional.of(book));
when(bookRepository.save(any())).thenReturn(book);
ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class)))
.thenAnswer(invocation -> {
Runnable runnable = invocation.getArgument(0);
runnable.run();
return null;
});
bookCoverService.regenerateCoversForBooks(Set.of(9L));
ArgumentCaptor<BookEntity> bookCaptor = ArgumentCaptor.forClass(BookEntity.class);
verify(processor).generateCover(bookCaptor.capture());
assertThat(bookCaptor.getValue().getId()).isEqualTo(9L);
}
}
@Test
void updateCover_metadataPersistenceSettings_saveToOriginalFile() {
MultipartFile file = mock(MultipartFile.class);
BookEntity book = spy(mockBookEntity(10L, false));
doReturn(Path.of("/dummy/path")).when(book).getFullFilePath();
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
when(bookRepository.save(any())).thenReturn(book);
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false));
MetadataWriter writer = mock(MetadataWriter.class);
when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer));
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
try (MockedStatic<FileFingerprint> fingerprintMock = mockStatic(FileFingerprint.class)) {
fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash");
BookMetadata result = bookCoverService.updateCoverImageFromFile(10L, file);
verify(writer).replaceCoverImageFromUpload(book, file);
assertThat(result).isNotNull();
}
}
@Test
void updateCover_metadataPersistenceSettings_noSaveToOriginalFile() {
MultipartFile file = mock(MultipartFile.class);
BookEntity book = mockBookEntity(11L, false);
when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book));
when(bookRepository.save(any())).thenReturn(book);
when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(false, false));
when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata());
BookMetadata result = bookCoverService.updateCoverImageFromFile(11L, file);
verify(metadataWriterFactory, never()).getWriter(any());
assertThat(result).isNotNull();
}
private com.adityachandel.booklore.model.dto.settings.AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) {
MetadataPersistenceSettings settings = new MetadataPersistenceSettings();
settings.setSaveToOriginalFile(saveToOriginalFile);
settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz);
return new com.adityachandel.booklore.model.dto.settings.AppSettings() {
@Override
public MetadataPersistenceSettings getMetadataPersistenceSettings() {
return settings;
}
};
}
}
@@ -22,7 +22,7 @@
class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-10"> class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-10">
</p-progressSpinner> </p-progressSpinner>
} }
<div class="flex items-center gap-2 pt-4"> <div class="flex items-center gap-3 pt-3">
<p-button <p-button
icon="pi pi-refresh" icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)" (onClick)="regenerateCover(book.id)"
@@ -55,7 +55,7 @@
severity="info"> severity="info">
</p-button> </p-button>
<p-fileupload <p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined'" [chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload cover" pTooltip="Upload cover"
tooltipPosition="top" tooltipPosition="top"
[disabled]="book.metadata!['coverLocked']" [disabled]="book.metadata!['coverLocked']"
@@ -65,7 +65,6 @@
chooseIcon="pi pi-upload" chooseIcon="pi pi-upload"
accept="image/jpeg,image/png" accept="image/jpeg,image/png"
maxFileSize="5000000" maxFileSize="5000000"
chooseLabel=""
(onUpload)="onUpload($event)" (onUpload)="onUpload($event)"
(onError)="onUploadError($event)" (onError)="onUploadError($event)"
[auto]="true" [auto]="true"
@@ -53,6 +53,14 @@
border-left: 0px !important; border-left: 0px !important;
} }
::ng-deep p-fileupload .p-button-label {
display: none;
}
::ng-deep p-fileupload .p-button {
padding: 0.6rem 0.5rem;
}
label { label {
color: var(--text-color-secondary); color: var(--text-color-secondary);
white-space: nowrap; white-space: nowrap;