diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java index 9aec66ba7..ca2a04b05 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/KoboController.java @@ -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.KoboResources; 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.BookService; import com.adityachandel.booklore.service.kobo.*; @@ -70,36 +70,58 @@ public class KoboController { 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 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") @GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/false/image.jpg") public ResponseEntity getThumbnail( @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) { - - if (StringUtils.isNumeric(imageId)) { - return koboThumbnailService.getThumbnail(Long.valueOf(imageId)); + if (imageId.startsWith("BL-")) { + return koboThumbnailService.getThumbnail(imageId); } 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); } } - @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") - @GetMapping("/v1/books/{bookId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg") - public ResponseEntity getGreyThumbnail( - @Parameter(description = "Book ID") @PathVariable String bookId, + @GetMapping("/v1/books/{imageId}/{version}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg") + public ResponseEntity getVersionedGreyThumbnail( + @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, @Parameter(description = "Quality of the thumbnail") @PathVariable int quality, @Parameter(description = "Is greyscale") @PathVariable boolean isGreyscale) { + return koboThumbnailService.getThumbnail(imageId); + } - if (StringUtils.isNumeric(bookId)) { - return koboThumbnailService.getThumbnail(Long.valueOf(bookId)); + @Operation(summary = "Get greyscale book thumbnail", description = "Retrieve a greyscale thumbnail image for a Kobo store book.") + @ApiResponse(responseCode = "200", description = "Greyscale thumbnail returned successfully") + @GetMapping("/v1/books/{imageId}/thumbnail/{width}/{height}/{quality}/{isGreyscale}/image.jpg") + public ResponseEntity 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 { - 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); } } @@ -107,16 +129,14 @@ public class KoboController { @Operation(summary = "Authenticate Kobo device", description = "Authenticate a Kobo device.") @ApiResponse(responseCode = "200", description = "Device authenticated successfully") @PostMapping("/v1/auth/device") - public ResponseEntity authenticateDevice( - @Parameter(description = "Authentication request body") @RequestBody JsonNode body) { + public ResponseEntity authenticateDevice(@Parameter(description = "Authentication request body") @RequestBody JsonNode body) { return koboDeviceAuthService.authenticateDevice(body); } @Operation(summary = "Get book metadata", description = "Retrieve metadata for a book in the Kobo library.") @ApiResponse(responseCode = "200", description = "Metadata returned successfully") @GetMapping("/v1/library/{bookId}/metadata") - public ResponseEntity getBookMetadata( - @Parameter(description = "Book ID") @PathVariable String bookId) { + public ResponseEntity getBookMetadata(@Parameter(description = "Book ID") @PathVariable String bookId) { if (StringUtils.isNumeric(bookId)) { return ResponseEntity.ok(List.of(koboEntitlementService.getMetadataForBook(Long.parseLong(bookId), token))); } else { @@ -127,8 +147,7 @@ public class KoboController { @Operation(summary = "Get reading state", description = "Retrieve the reading state for a book.") @ApiResponse(responseCode = "200", description = "Reading state returned successfully") @GetMapping("/v1/library/{bookId}/state") - public ResponseEntity getState( - @Parameter(description = "Book ID") @PathVariable String bookId) { + public ResponseEntity getState(@Parameter(description = "Book ID") @PathVariable String bookId) { if (StringUtils.isNumeric(bookId)) { return ResponseEntity.ok(koboReadingStateService.getReadingState(bookId)); } else { @@ -152,8 +171,7 @@ public class KoboController { @Operation(summary = "Get Kobo test analytics", description = "Get test analytics for Kobo.") @ApiResponse(responseCode = "200", description = "Test analytics returned successfully") @PostMapping("/v1/analytics/gettests") - public ResponseEntity getTests( - @Parameter(description = "Test analytics request body") @RequestBody Object body) { + public ResponseEntity getTests(@Parameter(description = "Test analytics request body") @RequestBody Object body) { return ResponseEntity.ok(KoboTestResponse.builder() .result("Success") .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.") @ApiResponse(responseCode = "200", description = "Book downloaded successfully") @GetMapping("/v1/books/{bookId}/download") - public void downloadBook( - @Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) { + public void downloadBook(@Parameter(description = "Book ID") @PathVariable String bookId, HttpServletResponse response) { if (StringUtils.isNumeric(bookId)) { bookDownloadService.downloadKoboBook(Long.parseLong(bookId), response); } 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.") @ApiResponse(responseCode = "200", description = "Book deleted successfully") @DeleteMapping("/v1/library/{bookId}") - public ResponseEntity deleteBookFromLibrary( - @Parameter(description = "Book ID") @PathVariable String bookId) { + public ResponseEntity deleteBookFromLibrary(@Parameter(description = "Book ID") @PathVariable String bookId) { if (StringUtils.isNumeric(bookId)) { Shelf userKoboShelf = shelfService.getUserKoboShelf(); if (userKoboShelf != null) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/BookEntitlement.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/BookEntitlement.java index 2267d1e36..6fc9a35e5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/BookEntitlement.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/BookEntitlement.java @@ -19,7 +19,8 @@ public class BookEntitlement { private ActivePeriod activePeriod; @JsonProperty("IsRemoved") - private boolean isRemoved; + @Builder.Default + private Boolean removed = false; private String status; @@ -31,7 +32,7 @@ public class BookEntitlement { @JsonProperty("IsHiddenFromArchive") @Builder.Default - private boolean isHiddenFromArchive = false; + private boolean hiddenFromArchive = false; private String id; private String created; @@ -39,7 +40,7 @@ public class BookEntitlement { @JsonProperty("IsLocked") @Builder.Default - private boolean isLocked = false; + private boolean locked = false; @Builder.Default private String originCategory = "Imported"; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/ChangedProductMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/ChangedProductMetadata.java new file mode 100644 index 000000000..ec16bf26d --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/ChangedProductMetadata.java @@ -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; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java index 2b4776878..1d560f645 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java @@ -18,7 +18,6 @@ import java.util.Map; @AllArgsConstructor @JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) @Builder -@JsonInclude(JsonInclude.Include.NON_NULL) public class KoboBookMetadata { private String crossRevisionId; private String revisionId; @@ -29,13 +28,13 @@ public class KoboBookMetadata { private String language = "en"; private String isbn; - private String genre; + private String genre = "00000000-0000-0000-0000-000000000001"; private String slug; private String coverImageId; @JsonProperty("IsSocialEnabled") @Builder.Default - private boolean isSocialEnabled = false; + private boolean socialEnabled = true; private String workId; @@ -44,14 +43,14 @@ public class KoboBookMetadata { @JsonProperty("IsPreOrder") @Builder.Default - private boolean isPreOrder = false; + private boolean preOrder = false; @Builder.Default private List contributorRoles = new ArrayList<>(); @JsonProperty("IsInternetArchive") @Builder.Default - private boolean isInternetArchive = false; + private boolean internetArchive = false; private String entitlementId; private String title; @@ -81,7 +80,7 @@ public class KoboBookMetadata { @JsonProperty("IsEligibleForKoboLove") @Builder.Default - private boolean isEligibleForKoboLove = false; + private boolean eligibleForKoboLove = false; @Builder.Default private Map phoneticPronunciations = Map.of(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java index a7936f865..1ac7c9546 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/BookEntity.java @@ -43,6 +43,12 @@ public class BookEntity { @OneToOne(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) private BookMetadataEntity metadata; + @Column(name = "metadata_updated_at") + private Instant metadataUpdatedAt; + + @Column(name = "metadata_for_write_updated_at") + private Instant metadataForWriteUpdatedAt; + @ManyToOne @JoinColumn(name = "library_id", nullable = false) private LibraryEntity library; @@ -60,6 +66,9 @@ public class BookEntity { @Column(name = "current_hash", length = 128) private String currentHash; + @Column(name = "book_cover_hash", length = 20) + private String bookCoverHash; + @Column(name = "deleted") @Builder.Default private Boolean deleted = Boolean.FALSE; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/KoboSnapshotBookEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/KoboSnapshotBookEntity.java index b3ae88ad4..e006fc54f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/KoboSnapshotBookEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/KoboSnapshotBookEntity.java @@ -4,6 +4,8 @@ package com.adityachandel.booklore.model.entity; import jakarta.persistence.*; import lombok.*; +import java.time.Instant; + @Entity @Table(name = "kobo_library_snapshot_book") @Getter @@ -24,6 +26,12 @@ public class KoboSnapshotBookEntity { @Column(name = "book_id", nullable = false) private Long bookId; + @Column(name = "file_hash") + private String fileHash; + + @Column(name = "metadata_updated_at") + private Instant metadataUpdatedAt; + @Column(nullable = false) @Builder.Default private boolean synced = false; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index ed7d3a2c3..f063b20da 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -21,6 +21,8 @@ public interface BookRepository extends JpaRepository, JpaSpec Optional findByCurrentHash(String currentHash); + Optional findByBookCoverHash(String bookCoverHash); + @Query("SELECT b.id FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") Set findBookIdsByLibraryId(@Param("libraryId") long libraryId); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/KoboSnapshotBookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/KoboSnapshotBookRepository.java index fbf3927fe..61e256a39 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/KoboSnapshotBookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/KoboSnapshotBookRepository.java @@ -22,15 +22,15 @@ public interface KoboSnapshotBookRepository extends JpaRepository bookIds); @Query(""" - SELECT curr - FROM KoboSnapshotBookEntity curr - WHERE curr.snapshot.id = :currSnapshotId - AND curr.bookId IN ( - SELECT prev.bookId - FROM KoboSnapshotBookEntity prev - WHERE prev.snapshot.id = :prevSnapshotId - ) - """) + SELECT curr + FROM KoboSnapshotBookEntity curr + WHERE curr.snapshot.id = :currSnapshotId + AND curr.bookId IN ( + SELECT prev.bookId + FROM KoboSnapshotBookEntity prev + WHERE prev.snapshot.id = :prevSnapshotId + ) + """) List findExistingBooksBetweenSnapshots( @Param("prevSnapshotId") String prevSnapshotId, @Param("currSnapshotId") String currSnapshotId @@ -55,23 +55,59 @@ public interface KoboSnapshotBookRepository extends JpaRepository findRemovedBooks( @Param("prevSnapshotId") String prevSnapshotId, @Param("currSnapshotId") String currSnapshotId, 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 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 findChangedBooks( + @Param("prevSnapshotId") String prevSnapshotId, + @Param("currSnapshotId") String currSnapshotId, + Pageable pageable + ); + } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookQueryService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookQueryService.java index 558f67886..71228ffb1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookQueryService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookQueryService.java @@ -5,7 +5,6 @@ import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.repository.BookRepository; import lombok.RequiredArgsConstructor; -import org.springframework.data.domain.*; import org.springframework.stereotype.Service; import java.util.List; @@ -33,11 +32,6 @@ public class BookQueryService { return bookRepository.findAllWithMetadataByIds(bookIds); } - public List findWithMetadataByIdsWithPagination(Set bookIds, int offset, int limit) { - Pageable pageable = PageRequest.of(offset / limit, limit); - return bookRepository.findWithMetadataByIdsWithPagination(bookIds, pageable); - } - public List getAllFullBookEntities() { return bookRepository.findAllFullBooks(); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java index b0f1562aa..0e3e71d5c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/book/BookService.java @@ -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() { try { BookLoreUser user = authenticationService.getAuthenticatedUser(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index cd0dcbcfe..2f4b6f9ac 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; 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.extractor.CbxMetadataExtractor; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import com.github.junrar.Archive; @@ -25,7 +25,10 @@ import org.springframework.stereotype.Service; import javax.imageio.ImageIO; 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.regex.Pattern; @@ -47,8 +50,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, - BookMetadataRepository bookMetadataRepository, - MetadataMatchService metadataMatchService, + MetadataMatchService metadataMatchService, CbxMetadataExtractor cbxMetadataExtractor) { super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); this.cbxMetadataExtractor = cbxMetadataExtractor; @@ -59,8 +61,8 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.CBX); if (generateCover(bookEntity)) { FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); } - extractAndSetMetadata(bookEntity); return bookEntity; } @@ -117,8 +119,8 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce .setUseUnicodeExtraFields(true) .setIgnoreLocalFileHeader(true) .get()) { - Optional image = findAndReadFirstImage(zipFile); - if (image.isPresent()) return image; + Optional image = findAndReadFirstImage(zipFile); + if (image.isPresent()) return image; } catch (Exception e) { log.debug("Fast path failed for ZIP extraction: {}", e.getMessage()); } @@ -236,7 +238,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce // Fallback to filename-derived title setMetadata(bookEntity); } - } + } private void setMetadata(BookEntity bookEntity) { String baseName = new File(bookEntity.getFileName()).getName(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index 50d3235b4..a4384c203 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import lombok.extern.slf4j.Slf4j; @@ -32,19 +32,16 @@ import static com.adityachandel.booklore.util.FileService.truncate; public class EpubProcessor extends AbstractFileProcessor implements BookFileProcessor { private final EpubMetadataExtractor epubMetadataExtractor; - private final BookMetadataRepository bookMetadataRepository; public EpubProcessor(BookRepository bookRepository, BookAdditionalFileRepository bookAdditionalFileRepository, BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, - BookMetadataRepository bookMetadataRepository, MetadataMatchService metadataMatchService, EpubMetadataExtractor epubMetadataExtractor) { super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); this.epubMetadataExtractor = epubMetadataExtractor; - this.bookMetadataRepository = bookMetadataRepository; } @Override @@ -53,6 +50,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc setBookMetadata(bookEntity); if (generateCover(bookEntity)) { FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); } return bookEntity; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java index aa258b818..09c58f3c4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java @@ -7,11 +7,11 @@ import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.extractor.Fb2MetadataExtractor; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import lombok.extern.slf4j.Slf4j; @@ -38,7 +38,6 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, - BookMetadataRepository bookMetadataRepository, MetadataMatchService metadataMatchService, Fb2MetadataExtractor fb2MetadataExtractor) { super(bookRepository, bookAdditionalFileRepository, bookCreatorService, bookMapper, fileService, metadataMatchService); @@ -51,6 +50,7 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce setBookMetadata(bookEntity); if (generateCover(bookEntity)) { FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); } return bookEntity; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java index dfd6f09fb..0b41f7e7f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/PdfProcessor.java @@ -6,11 +6,11 @@ import com.adityachandel.booklore.model.dto.settings.LibraryFile; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.repository.BookAdditionalFileRepository; -import com.adityachandel.booklore.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.book.BookCreatorService; import com.adityachandel.booklore.service.metadata.MetadataMatchService; import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.FileUtils; import lombok.extern.slf4j.Slf4j; @@ -40,7 +40,6 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce BookCreatorService bookCreatorService, BookMapper bookMapper, FileService fileService, - BookMetadataRepository bookMetadataRepository, MetadataMatchService metadataMatchService, PdfMetadataExtractor pdfMetadataExtractor) { 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); if (generateCover(bookEntity)) { FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); } extractAndSetMetadata(bookEntity); return bookEntity; @@ -127,7 +127,7 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce if (StringUtils.isNotBlank(extracted.getGoodreadsId())) { bookEntity.getMetadata().setGoodreadsId(extracted.getGoodreadsId()); } - if (StringUtils.isNotBlank(extracted.getComicvineId())){ + if (StringUtils.isNotBlank(extracted.getComicvineId())) { bookEntity.getMetadata().setComicvineId(extracted.getComicvineId()); } if (StringUtils.isNotBlank(extracted.getIsbn10())) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java index a3c4ac8fb..c78e5b472 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboEntitlementService.java @@ -42,65 +42,75 @@ public class KoboEntitlementService { private final AuthenticationService authenticationService; private final KoboReadingStateBuilder readingStateBuilder; - public List generateNewEntitlements(Set bookIds, String token, boolean removed) { + public List generateNewEntitlements(Set bookIds, String token) { List books = bookQueryService.findAllWithMetadataByIds(bookIds); return books.stream() .filter(koboCompatibilityService::isBookSupportedForKobo) .map(book -> NewEntitlement.builder() .newEntitlement(BookEntitlementContainer.builder() - .bookEntitlement(buildBookEntitlement(book, removed)) + .bookEntitlement(buildBookEntitlement(book, false)) .bookMetadata(mapToKoboMetadata(book, token)) - .readingState(createInitialReadingState(book)) + .readingState(getReadingStateForBook(book)) .build()) .build()) .collect(Collectors.toList()); } - public List generateChangedEntitlements(Set bookIds, String token, boolean removed) { + public List generateChangedEntitlements(Set bookIds, String token, boolean removed) { + List books = bookQueryService.findAllWithMetadataByIds(bookIds); - return books.stream() - .filter(koboCompatibilityService::isBookSupportedForKobo) - .map(book -> { - KoboBookMetadata metadata; - if (removed) { - metadata = KoboBookMetadata.builder() - .coverImageId(String.valueOf(book.getId())) + + + if (removed) { + return books.stream() + .filter(koboCompatibilityService::isBookSupportedForKobo) + .map(book -> { + KoboBookMetadata metadata = KoboBookMetadata.builder() + .coverImageId(book.getBookCoverHash()) .crossRevisionId(String.valueOf(book.getId())) .entitlementId(String.valueOf(book.getId())) .revisionId(String.valueOf(book.getId())) .workId(String.valueOf(book.getId())) .title(String.valueOf(book.getId())) .build(); - } else { - metadata = mapToKoboMetadata(book, token); - } - return ChangedEntitlement.builder() - .changedEntitlement(BookEntitlementContainer.builder() - .bookEntitlement(buildBookEntitlement(book, true)) - .bookMetadata(metadata) - .build()) - .build(); - }) + + return ChangedEntitlement.builder() + .changedEntitlement(BookEntitlementContainer.builder() + .bookEntitlement(buildBookEntitlement(book, removed)) + .bookMetadata(metadata) + .build()) + .build(); + }) + .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 generateChangedReadingStates(List progressEntries) { OffsetDateTime now = getCurrentUtc(); String timestamp = now.toString(); - + return progressEntries.stream() .map(progress -> buildChangedReadingState(progress, timestamp, now)) .toList(); } - + private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) { String entitlementId = String.valueOf(progress.getBook().getId()); - + KoboReadingState.CurrentBookmark bookmark = progress.getKoboProgressPercent() != null ? readingStateBuilder.buildBookmarkFromProgress(progress, now) : readingStateBuilder.buildEmptyBookmark(now); - + KoboReadingState readingState = KoboReadingState.builder() .entitlementId(entitlementId) .created(timestamp) @@ -110,7 +120,7 @@ public class KoboEntitlementService { .currentBookmark(bookmark) .statistics(KoboReadingState.Statistics.builder().lastModified(timestamp).build()) .build(); - + return ChangedReadingState.builder() .changedReadingState(ChangedReadingState.WrappedReadingState.builder() .readingState(readingState) @@ -118,24 +128,24 @@ public class KoboEntitlementService { .build(); } - private KoboReadingState createInitialReadingState(BookEntity book) { + private KoboReadingState getReadingStateForBook(BookEntity book) { OffsetDateTime now = getCurrentUtc(); String entitlementId = String.valueOf(book.getId()); - + KoboReadingState existingState = readingStateRepository.findByEntitlementId(entitlementId) .map(readingStateMapper::toDto) .orElse(null); - + Optional userProgress = progressRepository .findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId()); - + KoboReadingState.CurrentBookmark bookmark = existingState != null && existingState.getCurrentBookmark() != null ? existingState.getCurrentBookmark() : userProgress - .filter(progress -> progress.getKoboProgressPercent() != null) - .map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now)) - .orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now)); - + .filter(progress -> progress.getKoboProgressPercent() != null) + .map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now)) + .orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now)); + KoboReadingState.StatusInfo statusInfo = userProgress .map(progress -> readingStateBuilder.buildStatusInfoFromProgress(progress, now.toString())) .orElseGet(() -> KoboReadingState.StatusInfo.builder() @@ -163,7 +173,7 @@ public class KoboEntitlementService { .activePeriod(BookEntitlement.ActivePeriod.builder() .from(now.toString()) .build()) - .isRemoved(removed) + .removed(removed) .status("Active") .crossRevisionId(String.valueOf(book.getId())) .revisionId(String.valueOf(book.getId())) @@ -211,10 +221,10 @@ public class KoboEntitlementService { KoboBookFormat bookFormat = KoboBookFormat.EPUB3; KoboSettings koboSettings = appSettingService.getAppSettings().getKoboSettings(); - + boolean isEpubFile = book.getBookType() == BookFileType.EPUB; boolean isCbxFile = book.getBookType() == BookFileType.CBX; - + if (koboSettings != null) { if (isEpubFile && koboSettings.isConvertToKepub()) { bookFormat = KoboBookFormat.KEPUB; @@ -235,9 +245,9 @@ public class KoboEntitlementService { .slug(metadata.getTitle() != null ? NON_ALPHANUMERIC_LOWERCASE_PATTERN.matcher(metadata.getTitle().toLowerCase()).replaceAll("-") : null) - .coverImageId(String.valueOf(metadata.getBookId())) + .coverImageId(book.getBookCoverHash()) .workId(String.valueOf(book.getId())) - .isPreOrder(false) + .preOrder(false) .contributorRoles(Collections.emptyList()) .entitlementId(String.valueOf(book.getId())) .title(metadata.getTitle()) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotService.java index 10bc4b850..bd1d425a2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotService.java @@ -1,17 +1,14 @@ package com.adityachandel.booklore.service.kobo; +import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.mapper.BookEntityToKoboSnapshotBookMapper; -import com.adityachandel.booklore.model.entity.BookEntity; -import com.adityachandel.booklore.model.entity.BookLoreUserEntity; -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.dto.BookLoreUser; +import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.ShelfType; 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.KoboSnapshotBookRepository; +import com.adityachandel.booklore.repository.ShelfRepository; import lombok.AllArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -31,6 +28,7 @@ public class KoboLibrarySnapshotService { private final BookEntityToKoboSnapshotBookMapper mapper; private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository; private final KoboCompatibilityService koboCompatibilityService; + private final AuthenticationService authenticationService; @Transactional(readOnly = true) public Optional findByIdAndUserId(String id, Long userId) { @@ -64,13 +62,13 @@ public class KoboLibrarySnapshotService { @Transactional public void updateSyncedStatusForExistingBooks(String previousSnapshotId, String currentSnapshotId) { - List list = koboSnapshotBookRepository.findExistingBooksBetweenSnapshots(previousSnapshotId, currentSnapshotId); - List existingBooks = list.stream() + List list = koboSnapshotBookRepository.findUnchangedBooksBetweenSnapshots(previousSnapshotId, currentSnapshotId); + List unchangedBooks = list.stream() .map(KoboSnapshotBookEntity::getBookId) .toList(); - if (!existingBooks.isEmpty()) { - koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, existingBooks); + if (!unchangedBooks.isEmpty()) { + koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, unchangedBooks); } } @@ -110,6 +108,20 @@ public class KoboLibrarySnapshotService { return page; } + @Transactional + public Page getChangedBooks(String previousSnapshotId, String currentSnapshotId, Pageable pageable) { + Page page = koboSnapshotBookRepository.findChangedBooks(previousSnapshotId, currentSnapshotId, pageable); + List changedBookIds = page.getContent().stream() + .map(KoboSnapshotBookEntity::getBookId) + .toList(); + + if (!changedBookIds.isEmpty()) { + koboSnapshotBookRepository.markBooksSynced(currentSnapshotId, changedBookIds); + } + + return page; + } + private ShelfEntity getKoboShelf(Long userId) { return shelfRepository .findByUserIdAndName(userId, ShelfType.KOBO.getName()) @@ -127,16 +139,18 @@ public class KoboLibrarySnapshotService { .map(book -> { KoboSnapshotBookEntity snapshotBook = mapper.toKoboSnapshotBook(book); snapshotBook.setSnapshot(snapshot); + snapshotBook.setFileHash(book.getCurrentHash()); + snapshotBook.setMetadataUpdatedAt(book.getMetadataUpdatedAt()); return snapshotBook; }) .collect(Collectors.toList()); } private boolean isBookOwnedByUser(BookEntity book, Long userId) { - if (book == null || book.getLibrary() == null || book.getLibrary().getUsers() == null) { - return false; + BookLoreUser user = authenticationService.getAuthenticatedUser(); + if (user.getPermissions().isAdmin()) { + return true; } - return book.getLibrary() .getUsers() .stream() @@ -148,4 +162,4 @@ public class KoboLibrarySnapshotService { koboLibrarySnapshotRepository.deleteById(id); } -} +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySyncService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySyncService.java index 8a8539262..a572f6326 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySyncService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboLibrarySyncService.java @@ -53,6 +53,7 @@ public class KoboLibrarySyncService { if (prevSnapshot.isPresent()) { int maxRemaining = 5; List removedAll = new ArrayList<>(); + List changedAll = new ArrayList<>(); koboLibrarySnapshotService.updateSyncedStatusForExistingBooks(prevSnapshot.get().getId(), currSnapshot.getId()); @@ -61,35 +62,46 @@ public class KoboLibrarySyncService { maxRemaining -= addedPage.getNumberOfElements(); shouldContinueSync = addedPage.hasNext(); - Page removedPage = Page.empty(); + Page changedPage = Page.empty(); 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 removedPage = Page.empty(); + if (changedPage.isLast() && maxRemaining > 0) { removedPage = koboLibrarySnapshotService.getRemovedBooks(prevSnapshot.get().getId(), currSnapshot.getId(), user.getId(), PageRequest.of(0, maxRemaining)); removedAll.addAll(removedPage.getContent()); shouldContinueSync = shouldContinueSync || removedPage.hasNext(); } Set addedIds = addedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); + Set changedIds = changedAll.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); Set 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)); - + + if (!shouldContinueSync) { entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId())); } } else { int maxRemaining = 5; - List all = new ArrayList<>(); + List snapshotBookEntities = new ArrayList<>(); while (maxRemaining > 0) { - var page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining)); - all.addAll(page.getContent()); + Page page = koboLibrarySnapshotService.getUnsyncedBooks(currSnapshot.getId(), PageRequest.of(0, maxRemaining)); + snapshotBookEntities.addAll(page.getContent()); maxRemaining -= page.getNumberOfElements(); shouldContinueSync = page.hasNext(); if (!shouldContinueSync || page.getNumberOfElements() == 0) break; } - Set ids = all.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); - entitlements.addAll(entitlementService.generateNewEntitlements(ids, token, false)); - + Set ids = snapshotBookEntities.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet()); + entitlements.addAll(entitlementService.generateNewEntitlements(ids, token)); + if (!shouldContinueSync) { entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId())); } @@ -146,7 +158,7 @@ public class KoboLibrarySyncService { } private List syncReadingStatesToKobo(Long userId, String snapshotId) { - List booksNeedingSync = + List booksNeedingSync = userBookProgressRepository.findAllBooksNeedingKoboSync(userId, snapshotId); if (booksNeedingSync.isEmpty()) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboServerProxy.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboServerProxy.java index 96530c379..79bb66b9c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboServerProxy.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboServerProxy.java @@ -92,15 +92,13 @@ public class KoboServerProxy { String koboBaseUrl = "https://storeapi.kobo.com"; String queryString = request.getQueryString(); - UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(koboBaseUrl) - .path(path); - + String uriString = koboBaseUrl + path; if (queryString != null && !queryString.isBlank()) { - uriBuilder.query(queryString); + uriString += "?" + queryString; } - URI uri = uriBuilder.build(true).toUri(); - log.info("Kobo proxy URL: {}", uri); + URI uri = URI.create(uriString); + log.debug("Kobo proxy URL: {}", uri); String bodyString = body != null ? objectMapper.writeValueAsString(body) : "{}"; 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())); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboThumbnailService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboThumbnailService.java index 91bfb5c9b..763c9b2cb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboThumbnailService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboThumbnailService.java @@ -15,18 +15,16 @@ public class KoboThumbnailService { private final BookService bookService; - public ResponseEntity getThumbnail(Long bookId) { - return getThumbnailInternal(bookId); + public ResponseEntity getThumbnail(String coverHash) { + return getThumbnailInternal(coverHash); } - private ResponseEntity getThumbnailInternal(Long bookId) { - - Resource image = bookService.getBookCover(bookId); + private ResponseEntity getThumbnailInternal(String coverHash) { + Resource image = bookService.getBookCover(coverHash); 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.ok() .header(HttpHeaders.CONTENT_TYPE, "image/jpeg") .body(image); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java new file mode 100644 index 000000000..58ac16c6b --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookCoverService.java @@ -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 bookIds, MultipartFile file) { + validateCoverFile(file); + byte[] coverImageBytes = extractBytesFromMultipartFile(file); + List 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 bookIds) { + List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); + SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); + } + + public void regenerateCovers() { + SecurityContextVirtualThread.runWithSecurityContext(() -> { + try { + List 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 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 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 books) { + try { + int total = books.size(); + notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)")); + + int current = 1; + List 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 getUnlockedBookCoverInfos(Set bookIds) { + return bookQueryService.findAllWithMetadataByIds(bookIds).stream() + .filter(book -> !isCoverLocked(book)) + .map(book -> new BookCoverInfo(book.getId(), book.getMetadata().getTitle())) + .toList(); + } + + private List getUnlockedBookRegenerationInfos(Set 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 refreshedIds) { + if (refreshedIds.isEmpty()) { + return; + } + + List> refreshedPatches = transactionTemplate.execute(status -> { + List entities = bookQueryService.findAllWithMetadataByIds(new HashSet<>(refreshedIds)); + if (entities == null || entities.isEmpty()) { + return List.>of(); + } + + entities.forEach(e -> { + if (e.getMetadata() != null) { + e.getMetadata().getCoverUpdatedOn(); + } + }); + + return entities.stream() + .map(e -> Map.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"); + } + } + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java index 1c95ba632..0b85d4b1f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataService.java @@ -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.FetchMetadataRequest; 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.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.Lock; 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.repository.BookMetadataRepository; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.book.BookQueryService; import com.adityachandel.booklore.service.NotificationService; -import com.adityachandel.booklore.service.appsettings.AppSettingService; -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.book.BookQueryService; import com.adityachandel.booklore.service.metadata.extractor.CbxMetadataExtractor; 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.SecurityContextVirtualThread; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -44,14 +33,8 @@ import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.lang.reflect.Method; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; +import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.function.BiConsumer; import java.util.stream.Collectors; @Slf4j @@ -59,49 +42,20 @@ import java.util.stream.Collectors; @AllArgsConstructor public class BookMetadataService { - private static final int BATCH_SIZE = 100; - private final BookRepository bookRepository; private final BookMapper bookMapper; private final BookMetadataMapper bookMetadataMapper; private final BookMetadataUpdater bookMetadataUpdater; private final NotificationService notificationService; - private final AppSettingService appSettingService; private final BookMetadataRepository bookMetadataRepository; - private final FileService fileService; - private final BookFileProcessorRegistry processorRegistry; private final BookQueryService bookQueryService; private final Map parserMap; private final CbxMetadataExtractor cbxMetadataExtractor; - private final MetadataWriterFactory metadataWriterFactory; private final MetadataClearFlagsMapper metadataClearFlagsMapper; - private final org.springframework.transaction.PlatformTransactionManager transactionManager; - private final CoverImageGenerator coverImageGenerator; + private final BookCoverService bookCoverService; public void generateCustomCover(long bookId) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - if (bookEntity.getMetadata().getCoverLocked() != null && bookEntity.getMetadata().getCoverLocked()) { - throw ApiError.METADATA_LOCKED.createException(); - } - - 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() - ))); + bookCoverService.generateCustomCover(bookId); } public List getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { @@ -185,241 +139,28 @@ public class BookMetadataService { @Transactional public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { - fileService.createThumbnailFromFile(bookId, file); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); - } - - public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { - validateCoverFile(file); - byte[] coverImageBytes = extractBytesFromMultipartFile(file); - List 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 getUnlockedBookCoverInfos(Set 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 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")); - } + return bookCoverService.updateCoverImageFromFile(bookId, file); } @Transactional public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { - fileService.createThumbnailFromUrl(bookId, url); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + return bookCoverService.updateCoverImageFromUrl(bookId, url); } - private BookMetadata updateCover(Long bookId, BiConsumer writerAction) { - BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(java.util.Collections.singleton(bookId)).stream() - .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 updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { + bookCoverService.updateCoverImageFromFileForBooks(bookIds, file); } public void regenerateCover(long bookId) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - if (bookEntity.getMetadata().getCoverLocked() != null && bookEntity.getMetadata().getCoverLocked()) { - throw ApiError.METADATA_LOCKED.createException(); - } else { - regenerateCoverForBook(bookEntity, ""); - } + bookCoverService.regenerateCover(bookId); } - private record BookRegenerationInfo(Long id, String title, BookFileType bookType) {} - public void regenerateCoversForBooks(Set bookIds) { - List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); - SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); - } - - private List getUnlockedBookRegenerationInfos(Set 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 books) { - try { - int total = books.size(); - notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)")); - - int current = 1; - List 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 updatedBooks = new ArrayList<>(); - if (!refreshedIds.isEmpty()) { - org.springframework.transaction.support.TransactionTemplate tx = new org.springframework.transaction.support.TransactionTemplate(transactionManager); - - List> refreshedPatches = tx.execute(status -> { - List entities = bookQueryService.findAllWithMetadataByIds(new java.util.HashSet<>(refreshedIds)); - if (entities == null || entities.isEmpty()) return List.>of(); - - entities.forEach(e -> { - if (e.getMetadata() != null) e.getMetadata().getCoverUpdatedOn(); - }); - - return entities.stream() - .map(e -> java.util.Map.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); - }); + bookCoverService.regenerateCoversForBooks(bookIds); } public void regenerateCovers() { - SecurityContextVirtualThread.runWithSecurityContext(() -> { - try { - List 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(); - } - + bookCoverService.regenerateCovers(); } public BookMetadata getComicInfoMetadata(long bookId) { diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java index 55e950012..29c4165d4 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdater.java @@ -30,6 +30,7 @@ import org.springframework.util.StringUtils; import java.io.File; import java.net.InetAddress; import java.net.URI; +import java.time.Instant; import java.util.*; import java.util.function.Consumer; import java.util.function.Supplier; @@ -102,8 +103,8 @@ public class BookMetadataUpdater { updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail); updateLocks(newMetadata, metadata); + bookEntity.setMetadataUpdatedAt(Instant.now()); bookRepository.save(bookEntity); - try { Float score = metadataMatchService.calculateMatchScore(bookEntity); bookEntity.setMetadataMatchScore(score); @@ -122,7 +123,9 @@ public class BookMetadataUpdater { File file = new File(bookEntity.getFullFilePath().toUri()); writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags); String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); + bookEntity.setMetadataForWriteUpdatedAt(Instant.now()); bookEntity.setCurrentHash(newHash); + bookRepository.save(bookEntity); } catch (Exception e) { log.warn("Failed to write metadata for book ID {}: {}", bookId, e.getMessage()); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/BookCoverUtils.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookCoverUtils.java new file mode 100644 index 000000000..d09b7ef7e --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/BookCoverUtils.java @@ -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(); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java b/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java index 52c63dbae..00ad1ae56 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/util/kobo/KoboUrlBuilder.java @@ -43,10 +43,10 @@ public class KoboUrlBuilder { log.info("Applied X-Forwarded-Port: {}", port); } catch (NumberFormatException e) { 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; } diff --git a/booklore-api/src/main/resources/db/migration/V83__Add_metadata_and_kobo_book_columns.sql b/booklore-api/src/main/resources/db/migration/V83__Add_metadata_and_kobo_book_columns.sql new file mode 100644 index 000000000..a6558cdaa --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V83__Add_metadata_and_kobo_book_columns.sql @@ -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); + diff --git a/booklore-api/src/main/resources/db/migration/V84__Assign_admin_users_to_all_libraries.sql b/booklore-api/src/main/resources/db/migration/V84__Assign_admin_users_to_all_libraries.sql new file mode 100644 index 000000000..a75975836 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V84__Assign_admin_users_to_all_libraries.sql @@ -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; \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotServiceTest.java index 15d11c47b..fa968e485 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboLibrarySnapshotServiceTest.java @@ -1,6 +1,9 @@ package com.adityachandel.booklore.service.kobo; +import com.adityachandel.booklore.config.security.service.AuthenticationService; 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.BookLoreUserEntity; import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity; @@ -51,6 +54,9 @@ class KoboLibrarySnapshotServiceTest { @Mock private KoboCompatibilityService koboCompatibilityService; + @Mock + private AuthenticationService authenticationService; + @InjectMocks private KoboLibrarySnapshotService service; @@ -81,6 +87,15 @@ class KoboLibrarySnapshotServiceTest { .id(202L) .library(othersLibrary) .build(); + + UserPermissions userPermissions = new UserPermissions(); + userPermissions.setAdmin(false); + + BookLoreUser mockUser = BookLoreUser.builder() + .id(owner.getId()) + .permissions(userPermissions) + .build(); + when(authenticationService.getAuthenticatedUser()).thenReturn(mockUser); } @Test diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java new file mode 100644 index 000000000..7c1e41db1 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java @@ -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 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 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 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 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 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 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; + } + }; + } +} + diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html index 11cab7dcb..13c2a2f4f 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html @@ -22,7 +22,7 @@ class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-10"> } -
+