From d38271de9ce7196994aad8d30e5548dcbf2d5098 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Thu, 5 Feb 2026 13:33:08 -0700 Subject: [PATCH] Audiobook enhancement (#2611) * Audiobook enhancement * Fix choppy virtual scroller with mixed audiobook/ebook cards by using uniform heights * Fix audiobook cover regeneration for combined books and improve error messages * Fix cover extraction when attaching audiobook files during rescan * Set audiobookCoverUpdatedOn for cache busting when generating cover * Add support for regenerating covers from specific book files * Fix Continue Reading/Listening scrollers to filter by actual progress instead of primary file type * Show ebook cover and open ebook reader in Continue Reading scroller for combined books * Prevent read status from being downgraded when saving audiobook progress * Fix BookCoverServiceTest to match updated regenerateCover method signature --------- Co-authored-by: acx10 --- .../org/booklore/config/BookParserConfig.java | 5 +- .../controller/BookCoverController.java | 40 ++ .../controller/BookMediaController.java | 14 + .../controller/LibraryController.java | 9 + .../AudioFileChapterListConverter.java | 45 ++ .../java/org/booklore/exception/ApiError.java | 4 +- .../java/org/booklore/mapper/BookMapper.java | 57 +- .../org/booklore/mapper/v2/BookMapperV2.java | 60 ++- .../controller/MobileBookController.java | 10 + .../mobile/dto/MobileBookSummary.java | 2 + .../mobile/mapper/MobileBookMapper.java | 20 + .../mobile/service/MobileBookService.java | 37 +- .../MobileBookSpecification.java | 21 + .../booklore/model/MetadataClearFlags.java | 3 + .../booklore/model/dto/AudiobookMetadata.java | 33 ++ .../org/booklore/model/dto/BookMetadata.java | 15 + .../java/org/booklore/model/dto/Library.java | 1 + .../model/dto/request/CoverFetchRequest.java | 2 +- .../dto/request/CreateLibraryRequest.java | 1 + .../settings/MetadataPersistenceSettings.java | 4 +- .../settings/MetadataProviderSettings.java | 7 + .../org/booklore/model/entity/BookEntity.java | 3 + .../booklore/model/entity/BookFileEntity.java | 48 +- .../model/entity/BookMetadataEntity.java | 54 ++ .../booklore/model/entity/LibraryEntity.java | 4 + .../model/enums/MetadataProvider.java | 2 +- .../repository/BookMetadataRepository.java | 5 + .../booklore/repository/BookRepository.java | 14 +- .../booklore/service/book/BookService.java | 26 + .../service/bookdrop/BookDropService.java | 14 + .../fileprocessor/AudiobookProcessor.java | 174 ++++++- .../service/fileprocessor/Azw3Processor.java | 12 +- .../fileprocessor/BookFileProcessor.java | 10 + .../service/fileprocessor/CbxProcessor.java | 14 +- .../service/fileprocessor/EpubProcessor.java | 14 +- .../service/fileprocessor/Fb2Processor.java | 12 +- .../service/fileprocessor/MobiProcessor.java | 12 +- .../service/fileprocessor/PdfProcessor.java | 14 +- .../service/library/FileAsBookProcessor.java | 145 +++++- .../service/library/LibraryFileHelper.java | 12 +- .../library/LibraryProcessingService.java | 1 + .../service/library/LibraryService.java | 51 +- .../service/metadata/BookCoverService.java | 166 +++++- .../service/metadata/BookMetadataUpdater.java | 23 +- .../service/metadata/CoverImageGenerator.java | 175 +++++++ .../metadata/DuckDuckGoCoverService.java | 12 +- .../extractor/AudiobookMetadataExtractor.java | 332 +++++++++++- .../extractor/MetadataExtractorFactory.java | 12 + .../metadata/parser/AudibleParser.java | 492 ++++++++++++++++++ .../writer/AudiobookMetadataWriter.java | 346 ++++++++++++ .../progress/ReadingProgressService.java | 34 +- .../service/reader/AudioMetadataService.java | 399 +++++--------- .../service/upload/FileUploadService.java | 11 +- .../java/org/booklore/util/FileService.java | 165 +++++- .../java/org/booklore/util/FileUtils.java | 11 + .../booklore/util/MetadataChangeDetector.java | 443 ++++++++++------ .../migration/V109__Add_audiobook_support.sql | 27 + .../library/FileAsBookProcessorTest.java | 17 +- .../metadata/BookCoverServiceTest.java | 10 +- .../reader/AudioMetadataServiceTest.java | 74 +-- .../org/booklore/util/FileServiceTest.java | 7 +- booklore-ui/src/app/app.routes.ts | 6 +- .../book-browser/book-browser.component.ts | 11 +- .../book-card/book-card.component.html | 2 +- .../book-card/book-card.component.scss | 7 +- .../book-card/book-card.component.ts | 44 +- .../book-dialog-helper.service.ts | 3 +- .../cover-scale-preference.service.ts | 9 +- .../book-card-lite-component.html | 4 +- .../book-card-lite-component.scss | 7 + .../book-card-lite-component.ts | 13 + .../src/app/features/book/model/book.model.ts | 32 ++ .../app/features/book/model/library.model.ts | 1 + .../app/features/book/service/book.service.ts | 31 +- .../features/book/service/library.service.ts | 4 + .../dashboard-scroller.component.html | 3 +- .../dashboard-scroller.component.scss | 17 + .../dashboard-scroller.component.ts | 9 +- .../dashboard-settings.component.ts | 3 + .../main-dashboard.component.html | 1 + .../main-dashboard.component.ts | 31 +- .../models/dashboard-config.model.ts | 8 +- .../library-creator.component.html | 54 ++ .../library-creator.component.scss | 79 ++- .../library-creator.component.ts | 62 ++- .../metadata-editor.component.html | 262 +++++++--- .../metadata-editor.component.scss | 59 ++- .../metadata-editor.component.ts | 173 +++++- .../metadata-picker.component.html | 349 +++++++++++-- .../metadata-picker.component.scss | 74 ++- .../metadata-picker.component.ts | 179 ++++++- .../metadata-searcher.component.ts | 5 +- .../metadata-tabs.component.html | 38 ++ .../metadata-tabs.component.scss | 50 ++ .../metadata-tabs/metadata-tabs.component.ts | 15 +- .../metadata-viewer.component.html | 22 +- .../metadata-viewer.component.ts | 13 +- .../cover-search/cover-search.component.html | 4 +- .../cover-search/cover-search.component.ts | 53 +- ...tadata-advanced-fetch-options.component.ts | 14 +- ...adata-provider-field-selector.component.ts | 10 +- .../request/metadata-refresh-options.model.ts | 3 + .../audiobook-player.component.html} | 2 +- .../audiobook-player.component.scss} | 5 +- .../audiobook-player.component.ts} | 22 +- .../audiobook.model.ts | 0 .../audiobook.service.ts | 0 .../index.ts | 2 +- .../metadata-match-weights-component.ts | 4 + .../metadata-provider-settings.component.html | 20 + .../metadata-provider-settings.component.ts | 24 +- .../library-metadata-settings.component.ts | 3 + ...tadata-persistence-settings-component.html | 34 ++ ...metadata-persistence-settings-component.ts | 8 + .../cover-generator.component.ts | 205 ++++++-- .../shared/metadata/metadata-field.config.ts | 35 +- .../shared/metadata/metadata-form.builder.ts | 23 +- .../shared/metadata/metadata-utils.service.ts | 1 + .../app/shared/model/app-settings.model.ts | 10 + .../app/shared/service/url-helper.service.ts | 36 ++ .../app/shared/services/book-cover.service.ts | 2 +- 121 files changed, 5078 insertions(+), 909 deletions(-) create mode 100644 booklore-api/src/main/java/org/booklore/convertor/AudioFileChapterListConverter.java create mode 100644 booklore-api/src/main/java/org/booklore/model/dto/AudiobookMetadata.java create mode 100644 booklore-api/src/main/java/org/booklore/service/metadata/parser/AudibleParser.java create mode 100644 booklore-api/src/main/java/org/booklore/service/metadata/writer/AudiobookMetadataWriter.java create mode 100644 booklore-api/src/main/resources/db/migration/V109__Add_audiobook_support.sql rename booklore-ui/src/app/features/readers/{audiobook-reader/audiobook-reader.component.html => audiobook-player/audiobook-player.component.html} (99%) rename booklore-ui/src/app/features/readers/{audiobook-reader/audiobook-reader.component.scss => audiobook-player/audiobook-player.component.scss} (99%) rename booklore-ui/src/app/features/readers/{audiobook-reader/audiobook-reader.component.ts => audiobook-player/audiobook-player.component.ts} (97%) rename booklore-ui/src/app/features/readers/{audiobook-reader => audiobook-player}/audiobook.model.ts (100%) rename booklore-ui/src/app/features/readers/{audiobook-reader => audiobook-player}/audiobook.service.ts (100%) rename booklore-ui/src/app/features/readers/{audiobook-reader => audiobook-player}/index.ts (61%) diff --git a/booklore-api/src/main/java/org/booklore/config/BookParserConfig.java b/booklore-api/src/main/java/org/booklore/config/BookParserConfig.java index b6686a318..8df78833d 100644 --- a/booklore-api/src/main/java/org/booklore/config/BookParserConfig.java +++ b/booklore-api/src/main/java/org/booklore/config/BookParserConfig.java @@ -12,7 +12,7 @@ public class BookParserConfig { @Bean public Map parserMap(GoogleParser googleParser, AmazonBookParser amazonBookParser, - GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, RanobeDbParser ranobedbParser, LubimyCzytacParser lubimyczytacParser) { + GoodReadsParser goodReadsParser, HardcoverParser hardcoverParser, ComicvineBookParser comicvineBookParser, DoubanBookParser doubanBookParser, RanobeDbParser ranobedbParser, LubimyCzytacParser lubimyczytacParser, AudibleParser audibleParser) { return Map.of( MetadataProvider.Amazon, amazonBookParser, MetadataProvider.GoodReads, goodReadsParser, @@ -21,7 +21,8 @@ public class BookParserConfig { MetadataProvider.Comicvine, comicvineBookParser, MetadataProvider.Douban, doubanBookParser, MetadataProvider.Lubimyczytac, lubimyczytacParser, - MetadataProvider.Ranobedb, ranobedbParser + MetadataProvider.Ranobedb, ranobedbParser, + MetadataProvider.Audible, audibleParser ); } } diff --git a/booklore-api/src/main/java/org/booklore/controller/BookCoverController.java b/booklore-api/src/main/java/org/booklore/controller/BookCoverController.java index 55f8ff3b8..263c34159 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookCoverController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookCoverController.java @@ -51,6 +51,46 @@ public class BookCoverController { bookCoverService.updateCoverFromUrl(bookId, body.get("url")); } + @Operation(summary = "Upload audiobook cover image from file", description = "Upload an audiobook cover image for a book from a file. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "200", description = "Audiobook cover image uploaded successfully") + @PostMapping("/{bookId}/metadata/audiobook-cover/upload") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void uploadAudiobookCoverFromFile( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) { + bookCoverService.updateAudiobookCoverFromFile(bookId, file); + } + + @Operation(summary = "Upload audiobook cover image from URL", description = "Upload an audiobook cover image for a book from a URL. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "200", description = "Audiobook cover image uploaded successfully") + @PostMapping("/{bookId}/metadata/audiobook-cover/from-url") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void uploadAudiobookCoverFromUrl( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "URL body") @RequestBody Map body) { + bookCoverService.updateAudiobookCoverFromUrl(bookId, body.get("url")); + } + + @Operation(summary = "Regenerate audiobook cover for a book", description = "Regenerate audiobook cover for a specific book by extracting from the audiobook file. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Audiobook cover regenerated successfully") + @PostMapping("/{bookId}/regenerate-audiobook-cover") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void regenerateAudiobookCover(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.regenerateAudiobookCover(bookId); + } + + @Operation(summary = "Generate custom audiobook cover for a book", description = "Generate a custom audiobook cover for a specific book based on its metadata. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Custom audiobook cover generated successfully") + @PostMapping("/{bookId}/generate-custom-audiobook-cover") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void generateCustomAudiobookCover(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.generateCustomAudiobookCover(bookId); + } + @Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.") @ApiResponse(responseCode = "204", description = "Covers regenerated successfully") @PostMapping("/regenerate-covers") diff --git a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java index 45eb89dd8..6e6e2a248 100644 --- a/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java +++ b/booklore-api/src/main/java/org/booklore/controller/BookMediaController.java @@ -43,6 +43,20 @@ public class BookMediaController { return ResponseEntity.ok(bookService.getBookCover(bookId)); } + @Operation(summary = "Get audiobook thumbnail", description = "Retrieve the audiobook thumbnail image for a specific book.") + @ApiResponse(responseCode = "200", description = "Audiobook thumbnail returned successfully") + @GetMapping("/book/{bookId}/audiobook-thumbnail") + public ResponseEntity getAudiobookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) { + return ResponseEntity.ok(bookService.getAudiobookThumbnail(bookId)); + } + + @Operation(summary = "Get audiobook cover", description = "Retrieve the audiobook cover image for a specific book.") + @ApiResponse(responseCode = "200", description = "Audiobook cover returned successfully") + @GetMapping("/book/{bookId}/audiobook-cover") + public ResponseEntity getAudiobookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) { + return ResponseEntity.ok(bookService.getAudiobookCover(bookId)); + } + @Operation(summary = "Get PDF page as image", description = "Retrieve a specific page from a PDF book as an image.") @ApiResponse(responseCode = "200", description = "PDF page image returned successfully") @GetMapping("/book/{bookId}/pdf/pages/{pageNumber}") diff --git a/booklore-api/src/main/java/org/booklore/controller/LibraryController.java b/booklore-api/src/main/java/org/booklore/controller/LibraryController.java index 7a37c9eaa..8013385c4 100644 --- a/booklore-api/src/main/java/org/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/org/booklore/controller/LibraryController.java @@ -126,4 +126,13 @@ public class LibraryController { int processableFilesCount = libraryService.scanLibraryPaths(request); return ResponseEntity.ok(processableFilesCount); } + + @Operation(summary = "Get book counts by format", description = "Get the count of books for each format in a library.") + @ApiResponse(responseCode = "200", description = "Book counts returned successfully") + @GetMapping("/{libraryId}/format-counts") + @CheckLibraryAccess(libraryIdParam = "libraryId") + public ResponseEntity> getBookCountsByFormat( + @Parameter(description = "ID of the library") @PathVariable long libraryId) { + return ResponseEntity.ok(libraryService.getBookCountsByFormat(libraryId)); + } } \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/convertor/AudioFileChapterListConverter.java b/booklore-api/src/main/java/org/booklore/convertor/AudioFileChapterListConverter.java new file mode 100644 index 000000000..8d9dbb139 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/convertor/AudioFileChapterListConverter.java @@ -0,0 +1,45 @@ +package org.booklore.convertor; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.persistence.AttributeConverter; +import jakarta.persistence.Converter; +import lombok.extern.slf4j.Slf4j; +import org.booklore.model.entity.BookFileEntity.AudioFileChapter; + +import java.util.List; + +@Converter +@Slf4j +public class AudioFileChapterListConverter implements AttributeConverter, String> { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + private static final TypeReference> LIST_TYPE_REF = new TypeReference<>() {}; + + @Override + public String convertToDatabaseColumn(List attribute) { + if (attribute == null || attribute.isEmpty()) { + return null; + } + try { + return objectMapper.writeValueAsString(attribute); + } catch (JsonProcessingException e) { + log.error("Error converting chapter list to JSON", e); + return null; + } + } + + @Override + public List convertToEntityAttribute(String dbData) { + if (dbData == null || dbData.isEmpty()) { + return null; + } + try { + return objectMapper.readValue(dbData, LIST_TYPE_REF); + } catch (JsonProcessingException e) { + log.error("Error converting JSON to chapter list", e); + return null; + } + } +} diff --git a/booklore-api/src/main/java/org/booklore/exception/ApiError.java b/booklore-api/src/main/java/org/booklore/exception/ApiError.java index 8cdd33a5c..28afcedc5 100644 --- a/booklore-api/src/main/java/org/booklore/exception/ApiError.java +++ b/booklore-api/src/main/java/org/booklore/exception/ApiError.java @@ -35,6 +35,7 @@ public enum ApiError { ANOTHER_METADATA_JOB_RUNNING(HttpStatus.CONFLICT, "A metadata refresh job is currently running. Please wait for it to complete before initiating a new one."), METADATA_SOURCE_NOT_IMPLEMENT_OR_DOES_NOT_EXIST(HttpStatus.BAD_REQUEST, "Metadata source not implement or does not exist"), FAILED_TO_REGENERATE_COVER(HttpStatus.BAD_REQUEST, "Failed to regenerate cover"), + NO_COVER_IN_FILE(HttpStatus.BAD_REQUEST, "No embedded cover image found in the audiobook file"), FAILED_TO_DOWNLOAD_FILE(HttpStatus.INTERNAL_SERVER_ERROR, "Error while downloading file, bookId: %s"), INVALID_REFRESH_TYPE(HttpStatus.BAD_REQUEST, "The refresh type is invalid"), METADATA_LOCKED(HttpStatus.FORBIDDEN, "Attempt to update locked metadata"), @@ -60,7 +61,8 @@ public enum ApiError { ICON_ALREADY_EXISTS(HttpStatus.CONFLICT, "SVG icon with name '%s' already exists"), DEMO_USER_PASSWORD_CHANGE_NOT_ALLOWED(HttpStatus.FORBIDDEN, "Demo user password change not allowed."), PERMISSION_DENIED(HttpStatus.FORBIDDEN, "Permission denied: %s"), - LIBRARY_PATH_NOT_ACCESSIBLE(HttpStatus.SERVICE_UNAVAILABLE, "Library scan aborted: path not accessible or empty: %s"); + LIBRARY_PATH_NOT_ACCESSIBLE(HttpStatus.SERVICE_UNAVAILABLE, "Library scan aborted: path not accessible or empty: %s"), + FORMAT_NOT_ALLOWED(HttpStatus.BAD_REQUEST, "File format '%s' is not allowed in library '%s'"); private final HttpStatus status; private final String message; diff --git a/booklore-api/src/main/java/org/booklore/mapper/BookMapper.java b/booklore-api/src/main/java/org/booklore/mapper/BookMapper.java index c6a2210da..4114f6b04 100644 --- a/booklore-api/src/main/java/org/booklore/mapper/BookMapper.java +++ b/booklore-api/src/main/java/org/booklore/mapper/BookMapper.java @@ -1,13 +1,13 @@ package org.booklore.mapper; -import org.booklore.model.dto.BookFile; -import org.booklore.model.dto.Book; -import org.booklore.model.dto.LibraryPath; +import org.booklore.model.dto.*; import org.booklore.model.entity.*; import org.booklore.model.enums.BookFileType; +import org.mapstruct.AfterMapping; import org.mapstruct.Context; import org.mapstruct.Mapper; import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; import org.mapstruct.Named; import org.mapstruct.ReportingPolicy; @@ -160,4 +160,55 @@ public interface BookMapper { int lastDot = fileName.lastIndexOf('.'); return lastDot > 0 ? fileName.substring(lastDot + 1).toLowerCase() : null; } + + @AfterMapping + default void mapAudiobookMetadata(BookEntity bookEntity, @MappingTarget Book book) { + if (book.getMetadata() == null) { + return; + } + + BookMetadataEntity metadataEntity = bookEntity.getMetadata(); + BookMetadata metadata = book.getMetadata(); + + if (metadataEntity != null) { + metadata.setNarrator(metadataEntity.getNarrator()); + metadata.setAbridged(metadataEntity.getAbridged()); + metadata.setNarratorLocked(metadataEntity.getNarratorLocked()); + metadata.setAbridgedLocked(metadataEntity.getAbridgedLocked()); + } + + BookFileEntity audiobookFile = bookEntity.getBookFiles() != null + ? bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == BookFileType.AUDIOBOOK && bf.isBook()) + .findFirst() + .orElse(null) + : null; + + if (audiobookFile != null && audiobookFile.getDurationSeconds() != null) { + List chapters = null; + if (audiobookFile.getChapters() != null) { + chapters = audiobookFile.getChapters().stream() + .map(ch -> AudiobookMetadata.ChapterInfo.builder() + .index(ch.getIndex()) + .title(ch.getTitle()) + .startTimeMs(ch.getStartTimeMs()) + .endTimeMs(ch.getEndTimeMs()) + .durationMs(ch.getDurationMs()) + .build()) + .toList(); + } + + metadata.setAudiobookMetadata( + AudiobookMetadata.builder() + .durationSeconds(audiobookFile.getDurationSeconds()) + .bitrate(audiobookFile.getBitrate()) + .sampleRate(audiobookFile.getSampleRate()) + .channels(audiobookFile.getChannels()) + .codec(audiobookFile.getCodec()) + .chapterCount(audiobookFile.getChapterCount()) + .chapters(chapters) + .build() + ); + } + } } diff --git a/booklore-api/src/main/java/org/booklore/mapper/v2/BookMapperV2.java b/booklore-api/src/main/java/org/booklore/mapper/v2/BookMapperV2.java index 33c3c8640..90cf06cd8 100644 --- a/booklore-api/src/main/java/org/booklore/mapper/v2/BookMapperV2.java +++ b/booklore-api/src/main/java/org/booklore/mapper/v2/BookMapperV2.java @@ -1,14 +1,13 @@ package org.booklore.mapper.v2; import org.booklore.mapper.ShelfMapper; -import org.booklore.model.dto.Book; -import org.booklore.model.dto.BookFile; -import org.booklore.model.dto.BookMetadata; -import org.booklore.model.dto.LibraryPath; +import org.booklore.model.dto.*; import org.booklore.model.entity.*; import org.booklore.model.enums.BookFileType; +import org.mapstruct.AfterMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; import org.mapstruct.Named; import org.mapstruct.ReportingPolicy; @@ -35,6 +34,57 @@ public interface BookMapperV2 { @Mapping(target = "tags", source = "tags", qualifiedByName = "mapTags") BookMetadata mapMetadata(BookMetadataEntity metadataEntity); + @AfterMapping + default void mapAudiobookMetadata(BookEntity bookEntity, @MappingTarget Book book) { + if (book.getMetadata() == null) { + return; + } + + BookMetadataEntity metadataEntity = bookEntity.getMetadata(); + BookMetadata metadata = book.getMetadata(); + + if (metadataEntity != null) { + metadata.setNarrator(metadataEntity.getNarrator()); + metadata.setAbridged(metadataEntity.getAbridged()); + metadata.setNarratorLocked(metadataEntity.getNarratorLocked()); + metadata.setAbridgedLocked(metadataEntity.getAbridgedLocked()); + } + + BookFileEntity audiobookFile = bookEntity.getBookFiles() != null + ? bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == BookFileType.AUDIOBOOK && bf.isBook()) + .findFirst() + .orElse(null) + : null; + + if (audiobookFile != null && audiobookFile.getDurationSeconds() != null) { + List chapters = null; + if (audiobookFile.getChapters() != null) { + chapters = audiobookFile.getChapters().stream() + .map(ch -> AudiobookMetadata.ChapterInfo.builder() + .index(ch.getIndex()) + .title(ch.getTitle()) + .startTimeMs(ch.getStartTimeMs()) + .endTimeMs(ch.getEndTimeMs()) + .durationMs(ch.getDurationMs()) + .build()) + .toList(); + } + + metadata.setAudiobookMetadata( + AudiobookMetadata.builder() + .durationSeconds(audiobookFile.getDurationSeconds()) + .bitrate(audiobookFile.getBitrate()) + .sampleRate(audiobookFile.getSampleRate()) + .channels(audiobookFile.getChannels()) + .codec(audiobookFile.getCodec()) + .chapterCount(audiobookFile.getChapterCount()) + .chapters(chapters) + .build() + ); + } + } + @Named("mapAuthors") default Set mapAuthors(Set authors) { return authors == null ? Set.of() : @@ -149,4 +199,4 @@ public interface BookMapperV2 { .id(entity.getId()) .build(); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java index a09c6c4f0..65229f008 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java +++ b/booklore-api/src/main/java/org/booklore/mobile/controller/MobileBookController.java @@ -83,6 +83,16 @@ public class MobileBookController { return ResponseEntity.ok(mobileBookService.getContinueReading(limit)); } + @Operation(summary = "Get continue listening list", + description = "Get audiobooks currently in progress, sorted by last listened time (most recent first).") + @ApiResponse(responseCode = "200", description = "Continue listening list retrieved successfully") + @GetMapping("/continue-listening") + public ResponseEntity> getContinueListening( + @Parameter(description = "Maximum number of audiobooks to return") @RequestParam(required = false, defaultValue = "10") Integer limit) { + + return ResponseEntity.ok(mobileBookService.getContinueListening(limit)); + } + @Operation(summary = "Get recently added books", description = "Get books added in the last 30 days, sorted by added date (most recent first).") @ApiResponse(responseCode = "200", description = "Recently added books retrieved successfully") diff --git a/booklore-api/src/main/java/org/booklore/mobile/dto/MobileBookSummary.java b/booklore-api/src/main/java/org/booklore/mobile/dto/MobileBookSummary.java index cd7628cb6..ecd283a72 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/dto/MobileBookSummary.java +++ b/booklore-api/src/main/java/org/booklore/mobile/dto/MobileBookSummary.java @@ -22,4 +22,6 @@ public class MobileBookSummary { private Long libraryId; private Instant addedOn; private Instant lastReadTime; + private Float readProgress; + private Boolean hasAudiobook; } diff --git a/booklore-api/src/main/java/org/booklore/mobile/mapper/MobileBookMapper.java b/booklore-api/src/main/java/org/booklore/mobile/mapper/MobileBookMapper.java index e8d7adcf2..cae18a4de 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/mapper/MobileBookMapper.java +++ b/booklore-api/src/main/java/org/booklore/mobile/mapper/MobileBookMapper.java @@ -29,6 +29,8 @@ public interface MobileBookMapper { @Mapping(target = "libraryId", source = "book.library.id") @Mapping(target = "addedOn", source = "book.addedOn") @Mapping(target = "lastReadTime", source = "progress.lastReadTime") + @Mapping(target = "readProgress", source = "progress", qualifiedByName = "mapReadProgress") + @Mapping(target = "hasAudiobook", source = "book", qualifiedByName = "mapHasAudiobook") MobileBookSummary toSummary(BookEntity book, UserBookProgressEntity progress); @Mapping(target = "id", source = "book.id") @@ -126,9 +128,27 @@ public interface MobileBookMapper { if (progress.getKoboProgressPercent() != null) { return progress.getKoboProgressPercent(); } + if (progress.getEpubProgressPercent() != null) { + return progress.getEpubProgressPercent(); + } + if (progress.getPdfProgressPercent() != null) { + return progress.getPdfProgressPercent(); + } + if (progress.getCbxProgressPercent() != null) { + return progress.getCbxProgressPercent(); + } return null; } + @Named("mapHasAudiobook") + default Boolean mapHasAudiobook(BookEntity book) { + if (book == null || book.getBookFiles() == null || book.getBookFiles().isEmpty()) { + return false; + } + return book.getBookFiles().stream() + .anyMatch(bf -> bf.getBookType() == BookFileType.AUDIOBOOK); + } + @Named("mapEpubProgress") default MobileBookDetail.EpubProgress mapEpubProgress(UserBookProgressEntity progress) { if (progress == null || progress.getEpubProgress() == null) { diff --git a/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java b/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java index 9f8eef99a..6a14c19f5 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java +++ b/booklore-api/src/main/java/org/booklore/mobile/service/MobileBookService.java @@ -150,7 +150,42 @@ public class MobileBookService { MobileBookSpecification.notDeleted(), MobileBookSpecification.hasDigitalFile(), MobileBookSpecification.inLibraries(accessibleLibraryIds), - MobileBookSpecification.inProgress(userId) + MobileBookSpecification.inProgress(userId), + MobileBookSpecification.hasNonAudiobookFile() + ); + + List books = bookRepository.findAll(spec); + Map progressMap = getProgressMapForBooks(userId, books); + + return books.stream() + .filter(book -> progressMap.containsKey(book.getId())) + .sorted((b1, b2) -> { + Instant t1 = progressMap.get(b1.getId()).getLastReadTime(); + Instant t2 = progressMap.get(b2.getId()).getLastReadTime(); + if (t1 == null && t2 == null) return 0; + if (t1 == null) return 1; + if (t2 == null) return -1; + return t2.compareTo(t1); + }) + .limit(maxItems) + .map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId()))) + .collect(Collectors.toList()); + } + + @Transactional(readOnly = true) + public List getContinueListening(Integer limit) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Long userId = user.getId(); + Set accessibleLibraryIds = getAccessibleLibraryIds(user); + + int maxItems = validateLimit(limit, 10); + + Specification spec = MobileBookSpecification.combine( + MobileBookSpecification.notDeleted(), + MobileBookSpecification.hasDigitalFile(), + MobileBookSpecification.inLibraries(accessibleLibraryIds), + MobileBookSpecification.inProgress(userId), + MobileBookSpecification.hasAudiobookFile() ); List books = bookRepository.findAll(spec); diff --git a/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java b/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java index 6dfcbca69..94e57ad03 100644 --- a/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java +++ b/booklore-api/src/main/java/org/booklore/mobile/specification/MobileBookSpecification.java @@ -1,6 +1,7 @@ package org.booklore.mobile.specification; import org.booklore.model.entity.*; +import org.booklore.model.enums.BookFileType; import org.booklore.model.enums.ReadStatus; import jakarta.persistence.criteria.*; import org.springframework.data.jpa.domain.Specification; @@ -118,6 +119,26 @@ public class MobileBookSpecification { ); } + public static Specification hasAudiobookFile() { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root bookFileRoot = subquery.from(BookFileEntity.class); + subquery.select(bookFileRoot.get("book").get("id")) + .where(cb.equal(bookFileRoot.get("bookType"), BookFileType.AUDIOBOOK)); + return root.get("id").in(subquery); + }; + } + + public static Specification hasNonAudiobookFile() { + return (root, query, cb) -> { + Subquery subquery = query.subquery(Long.class); + Root bookFileRoot = subquery.from(BookFileEntity.class); + subquery.select(bookFileRoot.get("book").get("id")) + .where(cb.notEqual(bookFileRoot.get("bookType"), BookFileType.AUDIOBOOK)); + return root.get("id").in(subquery); + }; + } + @SafeVarargs public static Specification combine(Specification... specs) { Specification result = (root, query, cb) -> cb.conjunction(); diff --git a/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java b/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java index 108e7b62b..6f06749b8 100644 --- a/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java +++ b/booklore-api/src/main/java/org/booklore/model/MetadataClearFlags.java @@ -38,5 +38,8 @@ public class MetadataClearFlags { private boolean moods; private boolean tags; private boolean cover; + private boolean audiobookCover; private boolean reviews; + private boolean narrator; + private boolean abridged; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/AudiobookMetadata.java b/booklore-api/src/main/java/org/booklore/model/dto/AudiobookMetadata.java new file mode 100644 index 000000000..a26791cc5 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/model/dto/AudiobookMetadata.java @@ -0,0 +1,33 @@ +package org.booklore.model.dto; + +import lombok.*; + +import java.util.List; + +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class AudiobookMetadata { + private Long durationSeconds; + private Integer bitrate; + private Integer sampleRate; + private Integer channels; + private String codec; + private Integer chapterCount; + private List chapters; + + @Getter + @Setter + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class ChapterInfo { + private Integer index; + private String title; + private Long startTimeMs; + private Long endTimeMs; + private Long durationMs; + } +} diff --git a/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java b/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java index 6cfdb2a04..9398f63c4 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/BookMetadata.java @@ -29,6 +29,11 @@ public class BookMetadata { private String isbn10; private Integer pageCount; private String language; + private String narrator; + private Boolean abridged; + + private AudiobookMetadata audiobookMetadata; + private String asin; private Double amazonRating; private Integer amazonReviewCount; @@ -48,8 +53,12 @@ public class BookMetadata { private String lubimyczytacId; private String ranobedbId; private Double ranobedbRating; + private String audibleId; + private Double audibleRating; + private Integer audibleReviewCount; private String externalUrl; private Instant coverUpdatedOn; + private Instant audiobookCoverUpdatedOn; private Set authors; @Singular private Set categories; @@ -90,11 +99,17 @@ public class BookMetadata { private Boolean lubimyczytacRatingLocked; private Boolean ranobedbIdLocked; private Boolean ranobedbRatingLocked; + private Boolean audibleIdLocked; + private Boolean audibleRatingLocked; + private Boolean audibleReviewCountLocked; private Boolean externalUrlLocked; private Boolean coverLocked; + private Boolean audiobookCoverLocked; private Boolean authorsLocked; private Boolean categoriesLocked; private Boolean moodsLocked; private Boolean tagsLocked; private Boolean reviewsLocked; + private Boolean narratorLocked; + private Boolean abridgedLocked; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/Library.java b/booklore-api/src/main/java/org/booklore/model/dto/Library.java index 9a984ce8e..ce135e3e5 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/Library.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/Library.java @@ -22,6 +22,7 @@ public class Library { private boolean watch; private List paths; private List formatPriority; + private List allowedFormats; private LibraryOrganizationMode organizationMode; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/CoverFetchRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/CoverFetchRequest.java index 08fde5603..40eeb70cb 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/request/CoverFetchRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/CoverFetchRequest.java @@ -9,5 +9,5 @@ public class CoverFetchRequest { private String isbn; private String title; private String author; - private boolean squareCover; + private String coverType; // "ebook" or "audiobook" } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java index bd6e30778..73febf150 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/request/CreateLibraryRequest.java @@ -30,4 +30,5 @@ public class CreateLibraryRequest { private boolean watch; private List formatPriority; + private List allowedFormats; } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataPersistenceSettings.java b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataPersistenceSettings.java index b2359516a..b5f04ab0c 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataPersistenceSettings.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataPersistenceSettings.java @@ -22,11 +22,13 @@ public class MetadataPersistenceSettings { private FormatSettings epub; private FormatSettings pdf; private FormatSettings cbx; + private FormatSettings audiobook; public boolean isAnyFormatEnabled() { return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled()) - || (cbx != null && cbx.isEnabled()); + || (cbx != null && cbx.isEnabled()) + || (audiobook != null && audiobook.isEnabled()); } } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSettings.java b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSettings.java index 604cc197e..a8895c310 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSettings.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/settings/MetadataProviderSettings.java @@ -14,6 +14,7 @@ public class MetadataProviderSettings { private Douban douban; @JsonProperty("lubimyczytac") private Lubimyczytac lubimyczytac; + private Audible audible; @Data public static class Amazon { @@ -59,4 +60,10 @@ public class MetadataProviderSettings { public static class Lubimyczytac { private boolean enabled; } + + @Data + public static class Audible { + private boolean enabled; + private String domain; + } } diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookEntity.java index 701887ee3..6d66aff9d 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookEntity.java @@ -57,6 +57,9 @@ public class BookEntity { @Column(name = "book_cover_hash", length = 20) private String bookCoverHash; + @Column(name = "audiobook_cover_hash", length = 20) + private String audiobookCoverHash; + @Column(name = "deleted") @Builder.Default private Boolean deleted = Boolean.FALSE; diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookFileEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookFileEntity.java index 65858c878..a5e3e293e 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookFileEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookFileEntity.java @@ -1,10 +1,15 @@ package org.booklore.model.entity; -import org.booklore.model.enums.BookFileType; -import org.booklore.util.ArchiveUtils; import jakarta.persistence.*; import lombok.*; +import org.booklore.convertor.AudioFileChapterListConverter; +import org.booklore.model.enums.BookFileType; +import org.booklore.util.ArchiveUtils; +import java.util.List; + +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; @@ -65,6 +70,28 @@ public class BookFileEntity { @Column(name = "added_on") private Instant addedOn; + @Column(name = "duration_seconds") + private Long durationSeconds; + + @Column(name = "bitrate") + private Integer bitrate; + + @Column(name = "sample_rate") + private Integer sampleRate; + + @Column(name = "channels") + private Integer channels; + + @Column(name = "codec", length = 50) + private String codec; + + @Column(name = "chapter_count") + private Integer chapterCount; + + @Convert(converter = AudioFileChapterListConverter.class) + @Column(name = "chapters_json", columnDefinition = "TEXT") + private List chapters; + public boolean isBook() { return isBookFormat; } @@ -97,7 +124,7 @@ public class BookFileEntity { } Path folderPath = getFullFilePath(); try { - return java.nio.file.Files.list(folderPath) + return Files.list(folderPath) .filter(java.nio.file.Files::isRegularFile) .filter(p -> { String name = p.getFileName().toString().toLowerCase(); @@ -108,8 +135,21 @@ public class BookFileEntity { .sorted() .findFirst() .orElse(folderPath); - } catch (java.io.IOException e) { + } catch (IOException e) { return folderPath; } } + + @Getter + @Setter + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class AudioFileChapter { + private Integer index; + private String title; + private Long startTimeMs; + private Long endTimeMs; + private Long durationMs; + } } diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java index 975b67f4f..eaaedde3b 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookMetadataEntity.java @@ -70,6 +70,9 @@ public class BookMetadataEntity { @Column(name = "cover_updated_on") private Instant coverUpdatedOn; + @Column(name = "audiobook_cover_updated_on") + private Instant audiobookCoverUpdatedOn; + @Column(name = "amazon_rating") private Double amazonRating; @@ -118,6 +121,15 @@ public class BookMetadataEntity { @Column(name = "ranobedb_rating") private Double ranobedbRating; + @Column(name = "audible_id", length = 100) + private String audibleId; + + @Column(name = "audible_rating") + private Double audibleRating; + + @Column(name = "audible_review_count") + private Integer audibleReviewCount; + @Column(name = "title_locked") @Builder.Default private Boolean titleLocked = Boolean.FALSE; @@ -186,6 +198,10 @@ public class BookMetadataEntity { @Builder.Default private Boolean coverLocked = Boolean.FALSE; + @Column(name = "audiobook_cover_locked") + @Builder.Default + private Boolean audiobookCoverLocked = Boolean.FALSE; + @Column(name = "series_name_locked") @Builder.Default private Boolean seriesNameLocked = Boolean.FALSE; @@ -250,10 +266,36 @@ public class BookMetadataEntity { @Builder.Default private Boolean ranobedbRatingLocked = Boolean.FALSE; + @Column(name = "audible_id_locked") + @Builder.Default + private Boolean audibleIdLocked = Boolean.FALSE; + + @Column(name = "audible_rating_locked") + @Builder.Default + private Boolean audibleRatingLocked = Boolean.FALSE; + + @Column(name = "audible_review_count_locked") + @Builder.Default + private Boolean audibleReviewCountLocked = Boolean.FALSE; + + @Column(name = "narrator", length = 500) + private String narrator; + + @Column(name = "abridged") + private Boolean abridged; + @Column(name = "reviews_locked") @Builder.Default private Boolean reviewsLocked = Boolean.FALSE; + @Column(name = "narrator_locked") + @Builder.Default + private Boolean narratorLocked = Boolean.FALSE; + + @Column(name = "abridged_locked") + @Builder.Default + private Boolean abridgedLocked = Boolean.FALSE; + @Column(name = "embedding_vector", columnDefinition = "TEXT") private String embeddingVector; @@ -327,6 +369,7 @@ public class BookMetadataEntity { this.pageCountLocked = lock; this.languageLocked = lock; this.coverLocked = lock; + this.audiobookCoverLocked = lock; this.seriesNameLocked = lock; this.seriesNumberLocked = lock; this.seriesTotalLocked = lock; @@ -349,7 +392,12 @@ public class BookMetadataEntity { this.lubimyczytacIdLocked = lock; this.ranobedbIdLocked = lock; this.ranobedbRatingLocked = lock; + this.audibleIdLocked = lock; + this.audibleRatingLocked = lock; + this.audibleReviewCountLocked = lock; this.reviewsLocked = lock; + this.narratorLocked = lock; + this.abridgedLocked = lock; } public boolean areAllFieldsLocked() { @@ -364,6 +412,7 @@ public class BookMetadataEntity { && Boolean.TRUE.equals(this.pageCountLocked) && Boolean.TRUE.equals(this.languageLocked) && Boolean.TRUE.equals(this.coverLocked) + && Boolean.TRUE.equals(this.audiobookCoverLocked) && Boolean.TRUE.equals(this.seriesNameLocked) && Boolean.TRUE.equals(this.seriesNumberLocked) && Boolean.TRUE.equals(this.seriesTotalLocked) @@ -386,7 +435,12 @@ public class BookMetadataEntity { && Boolean.TRUE.equals(this.lubimyczytacIdLocked) && Boolean.TRUE.equals(this.ranobedbIdLocked) && Boolean.TRUE.equals(this.ranobedbRatingLocked) + && Boolean.TRUE.equals(this.audibleIdLocked) + && Boolean.TRUE.equals(this.audibleRatingLocked) + && Boolean.TRUE.equals(this.audibleReviewCountLocked) && Boolean.TRUE.equals(this.reviewsLocked) + && Boolean.TRUE.equals(this.narratorLocked) + && Boolean.TRUE.equals(this.abridgedLocked) ; } } diff --git a/booklore-api/src/main/java/org/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/LibraryEntity.java index d922df3a1..bd8126f91 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/LibraryEntity.java @@ -56,6 +56,10 @@ public class LibraryEntity { @Builder.Default private List formatPriority = new ArrayList<>(); + @Convert(converter = FormatPriorityConverter.class) + @Column(name = "allowed_formats") + private List allowedFormats; + @Enumerated(EnumType.STRING) @Column(name = "organization_mode") @Builder.Default diff --git a/booklore-api/src/main/java/org/booklore/model/enums/MetadataProvider.java b/booklore-api/src/main/java/org/booklore/model/enums/MetadataProvider.java index 6c39c4d28..3759e32fc 100644 --- a/booklore-api/src/main/java/org/booklore/model/enums/MetadataProvider.java +++ b/booklore-api/src/main/java/org/booklore/model/enums/MetadataProvider.java @@ -1,5 +1,5 @@ package org.booklore.model.enums; public enum MetadataProvider { - Amazon, GoodReads, Google, Hardcover, Comicvine, Douban, Lubimyczytac, Ranobedb + Amazon, GoodReads, Google, Hardcover, Comicvine, Douban, Lubimyczytac, Ranobedb, Audible } diff --git a/booklore-api/src/main/java/org/booklore/repository/BookMetadataRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookMetadataRepository.java index 29c1a9861..5b372a509 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookMetadataRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookMetadataRepository.java @@ -20,6 +20,11 @@ public interface BookMetadataRepository extends JpaRepository findAllByAuthorsContaining(AuthorEntity author); List findAllByCategoriesContaining(CategoryEntity category); diff --git a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java index 0d0e45002..25273cc20 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookRepository.java @@ -143,6 +143,16 @@ public interface BookRepository extends JpaRepository, JpaSpec """) long countByBookType(@Param("type") BookFileType type); + @Query(""" + SELECT COUNT(DISTINCT b) FROM BookEntity b + JOIN b.bookFiles bf + WHERE b.library.id = :libraryId + AND bf.isBookFormat = true + AND bf.bookType = :type + AND (b.deleted IS NULL OR b.deleted = false) + """) + long countByLibraryIdAndBookType(@Param("libraryId") Long libraryId, @Param("type") BookFileType type); + @Query("SELECT COUNT(b) FROM BookEntity b WHERE b.library.id = :libraryId AND (b.deleted IS NULL OR b.deleted = false)") long countByLibraryId(@Param("libraryId") Long libraryId); @@ -265,7 +275,7 @@ public interface BookRepository extends JpaRepository, JpaSpec * Find books by series name for a library when groupUnknown=true. * Uses the first bookFile.fileName as fallback when metadata.seriesName is null. */ - @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath", "bookFiles"}) @Query(""" SELECT DISTINCT b FROM BookEntity b LEFT JOIN b.metadata m @@ -295,7 +305,7 @@ public interface BookRepository extends JpaRepository, JpaSpec * Find books by series name for a library when groupUnknown=false. * Matches by series name, or by title/filename for books without series. */ - @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath"}) + @EntityGraph(attributePaths = {"metadata", "shelves", "libraryPath", "bookFiles"}) @Query(""" SELECT b FROM BookEntity b LEFT JOIN b.metadata m diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookService.java b/booklore-api/src/main/java/org/booklore/service/book/BookService.java index d36a5ffe0..c31a6c4a3 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookService.java @@ -257,6 +257,32 @@ public class BookService { return getBookCover(bookEntity.getId()); } + public Resource getAudiobookThumbnail(long bookId) { + Path thumbnailPath = Paths.get(fileService.getAudiobookThumbnailFile(bookId)); + try { + if (Files.exists(thumbnailPath)) { + return new UrlResource(thumbnailPath.toUri()); + } else { + return new ClassPathResource("static/images/missing-cover.jpg"); + } + } catch (MalformedURLException e) { + throw new RuntimeException("Failed to load audiobook thumbnail for bookId=" + bookId, e); + } + } + + public Resource getAudiobookCover(long bookId) { + Path coverPath = Paths.get(fileService.getAudiobookCoverFile(bookId)); + try { + if (Files.exists(coverPath)) { + return new UrlResource(coverPath.toUri()); + } else { + return new ClassPathResource("static/images/missing-cover.jpg"); + } + } catch (MalformedURLException e) { + throw new RuntimeException("Failed to load audiobook cover for bookId=" + bookId, e); + } + } + public ResponseEntity downloadBook(Long bookId) { return bookDownloadService.downloadBook(bookId); } diff --git a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java index 39c489d2f..0a75d5e9e 100644 --- a/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java +++ b/booklore-api/src/main/java/org/booklore/service/bookdrop/BookDropService.java @@ -382,6 +382,15 @@ public class BookDropService { .findFirst() .orElseThrow(() -> ApiError.INVALID_LIBRARY_PATH.createException(libraryId)); + BookFileType fileType = BookFileExtension.fromFileName(bookdropFile.getFileName()) + .map(BookFileExtension::getType) + .orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension")); + + if (!isFormatAllowed(library, fileType)) { + return failureResult(bookdropFile.getFileName(), + "Format '" + fileType.name() + "' is not allowed in library '" + library.getName() + "'"); + } + String filePattern = fileMovingHelper.getFileNamingPattern(library); Path source = Path.of(bookdropFile.getFilePath()); Path target = fileMovingHelper.generateNewFilePath(path.getPath(), metadata, filePattern, bookdropFile.getFilePath()); @@ -625,6 +634,11 @@ public class BookDropService { .build(); } + private boolean isFormatAllowed(LibraryEntity library, BookFileType fileType) { + var allowedFormats = library.getAllowedFormats(); + return allowedFormats == null || allowedFormats.isEmpty() || allowedFormats.contains(fileType); + } + private record FileProcessingContext(Long libraryId, Long pathId, BookMetadata metadata) { } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/AudiobookProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/AudiobookProcessor.java index d1a7c6ae8..96269159e 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/AudiobookProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/AudiobookProcessor.java @@ -1,9 +1,12 @@ package org.booklore.service.fileprocessor; +import org.booklore.exception.ApiError; import org.booklore.mapper.BookMapper; +import org.booklore.model.dto.AudiobookMetadata; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -20,6 +23,7 @@ import org.springframework.stereotype.Service; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; +import java.time.Instant; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -48,8 +52,8 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil BookEntity bookEntity = bookCreatorService.createShellBook(libraryFile, BookFileType.AUDIOBOOK); setBookMetadata(bookEntity, libraryFile.isFolderBased()); if (generateCover(bookEntity, libraryFile.isFolderBased())) { - FileService.setBookCoverPath(bookEntity.getMetadata()); - bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); + bookEntity.getMetadata().setAudiobookCoverUpdatedOn(Instant.now()); + bookEntity.setAudiobookCoverHash(BookCoverUtils.generateCoverHash()); } return bookEntity; } @@ -59,6 +63,18 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil return generateCover(bookEntity, bookEntity.getPrimaryBookFile().isFolderBased()); } + @Override + public boolean generateAudiobookCover(BookEntity bookEntity) { + var audiobookFile = bookEntity.getBookFiles().stream() + .filter(f -> f.getBookType() == BookFileType.AUDIOBOOK) + .findFirst() + .orElse(null); + if (audiobookFile == null) { + return false; + } + return generateCoverFromFile(bookEntity, audiobookFile); + } + public boolean generateCover(BookEntity bookEntity, boolean isFolderBased) { try { File audioFile = getAudioFileForMetadata(bookEntity, isFolderBased); @@ -67,25 +83,7 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil return false; } - byte[] coverData = audiobookMetadataExtractor.extractCover(audioFile); - - if (coverData == null) { - log.debug("No cover image found in audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName()); - return false; - } - - boolean saved; - try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { - BufferedImage originalImage = FileService.readImage(bais); - if (originalImage == null) { - log.warn("Failed to decode cover image for audiobook '{}'", bookEntity.getPrimaryBookFile().getFileName()); - return false; - } - saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); - originalImage.flush(); - } - - return saved; + return extractAndSaveCover(bookEntity, audioFile, false); } catch (Exception e) { log.error("Error generating cover for audiobook '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e); @@ -93,10 +91,57 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil } } - /** - * Get the audio file to use for metadata extraction. - * For folder-based audiobooks, returns the first audio file in the folder. - */ + private boolean generateCoverFromFile(BookEntity bookEntity, BookFileEntity audiobookFile) { + try { + File audioFile = getAudioFileForBookFile(bookEntity, audiobookFile); + if (audioFile == null) { + log.warn("Could not resolve audio file path for audiobook '{}' (bookId: {})", audiobookFile.getFileName(), bookEntity.getId()); + return false; + } + if (!audioFile.exists()) { + log.warn("Audio file does not exist: {} for audiobook '{}' (bookId: {})", audioFile.getAbsolutePath(), audiobookFile.getFileName(), bookEntity.getId()); + return false; + } + + log.debug("Extracting cover from audio file: {}", audioFile.getAbsolutePath()); + return extractAndSaveCover(bookEntity, audioFile, true); + + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + log.error("Error generating cover for audiobook '{}' (bookId: {}): {}", + audiobookFile.getFileName(), bookEntity.getId(), e.getMessage(), e); + return false; + } + } + + private boolean extractAndSaveCover(BookEntity bookEntity, File audioFile, boolean throwOnNoCover) throws Exception { + byte[] coverData = audiobookMetadataExtractor.extractCover(audioFile); + + if (coverData == null) { + log.warn("No embedded cover image found in audiobook file '{}' (bookId: {})", audioFile.getAbsolutePath(), bookEntity.getId()); + if (throwOnNoCover) { + throw ApiError.NO_COVER_IN_FILE.createException(); + } + return false; + } + + log.debug("Found cover data ({} bytes) in audiobook file '{}'", coverData.length, audioFile.getName()); + + boolean saved; + try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { + BufferedImage originalImage = FileService.readImage(bais); + if (originalImage == null) { + log.warn("Failed to decode cover image for audiobook '{}'", audioFile.getName()); + return false; + } + saved = fileService.saveAudiobookCoverImages(originalImage, bookEntity.getId()); + originalImage.flush(); + } + + return saved; + } + private File getAudioFileForMetadata(BookEntity bookEntity, boolean isFolderBased) { if (isFolderBased) { java.nio.file.Path folderPath = bookEntity.getFullFilePath(); @@ -108,6 +153,41 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil } } + private File getAudioFileForBookFile(BookEntity bookEntity, BookFileEntity bookFile) { + if (bookEntity.getLibraryPath() == null || bookFile == null) { + log.debug("Cannot get audio file: libraryPath or bookFile is null"); + return null; + } + + String libraryPath = bookEntity.getLibraryPath().getPath(); + String subPath = bookFile.getFileSubPath(); + String fileName = bookFile.getFileName(); + + if (libraryPath == null || fileName == null) { + log.debug("Cannot get audio file: libraryPath='{}', fileName='{}'", libraryPath, fileName); + return null; + } + + java.nio.file.Path filePath; + if (subPath == null || subPath.isEmpty()) { + filePath = java.nio.file.Paths.get(libraryPath, fileName).normalize(); + } else { + filePath = java.nio.file.Paths.get(libraryPath, subPath, fileName).normalize(); + } + + log.debug("Constructed audiobook path: {}, isFolderBased: {}", filePath, bookFile.isFolderBased()); + + if (bookFile.isFolderBased()) { + var audioFile = FileUtils.getFirstAudioFileInFolder(filePath); + if (audioFile.isEmpty()) { + log.debug("No audio file found in folder: {}", filePath); + } + return audioFile.map(java.nio.file.Path::toFile).orElse(null); + } else { + return filePath.toFile(); + } + } + @Override public List getSupportedTypes() { return List.of(BookFileType.AUDIOBOOK); @@ -137,6 +217,8 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil String lang = audioMetadata.getLanguage(); metadata.setLanguage(truncate((lang == null || "UND".equalsIgnoreCase(lang)) ? "en" : lang, 1000)); + metadata.setNarrator(truncate(audioMetadata.getNarrator(), 500)); + bookCreatorService.addAuthorsToBook(audioMetadata.getAuthors(), bookEntity); if (audioMetadata.getCategories() != null) { @@ -145,5 +227,47 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil .collect(Collectors.toSet()); bookCreatorService.addCategoriesToBook(validCategories, bookEntity); } + + setAudiobookTechnicalMetadata(bookEntity, audioMetadata); + } + + private void setAudiobookTechnicalMetadata(BookEntity bookEntity, BookMetadata audioMetadata) { + AudiobookMetadata audiobookDto = audioMetadata.getAudiobookMetadata(); + if (audiobookDto == null) { + return; + } + + BookFileEntity audiobookFile = bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == BookFileType.AUDIOBOOK && bf.isBook()) + .findFirst() + .orElse(null); + + if (audiobookFile == null) { + log.warn("No audiobook file found for book ID {}", bookEntity.getId()); + return; + } + + audiobookFile.setDurationSeconds(audiobookDto.getDurationSeconds()); + audiobookFile.setBitrate(audiobookDto.getBitrate()); + audiobookFile.setSampleRate(audiobookDto.getSampleRate()); + audiobookFile.setChannels(audiobookDto.getChannels()); + audiobookFile.setCodec(truncate(audiobookDto.getCodec(), 50)); + audiobookFile.setChapterCount(audiobookDto.getChapterCount()); + audiobookFile.setChapters(mapChapters(audiobookDto.getChapters())); + } + + private List mapChapters(List chapters) { + if (chapters == null || chapters.isEmpty()) { + return null; + } + return chapters.stream() + .map(ch -> BookFileEntity.AudioFileChapter.builder() + .index(ch.getIndex()) + .title(ch.getTitle()) + .startTimeMs(ch.getStartTimeMs()) + .endTimeMs(ch.getEndTimeMs()) + .durationMs(ch.getDurationMs()) + .build()) + .collect(Collectors.toList()); } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/Azw3Processor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/Azw3Processor.java index dc1fcf49d..e53076efa 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/Azw3Processor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/Azw3Processor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -56,19 +57,24 @@ public class Azw3Processor extends AbstractFileProcessor implements BookFileProc @Override public boolean generateCover(BookEntity bookEntity) { + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { try { - File azw3File = new File(FileUtils.getBookFullPath(bookEntity)); + File azw3File = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); byte[] coverData = azw3MetadataExtractor.extractCover(azw3File); if (coverData == null || coverData.length == 0) { - log.warn("No cover image found in AZW3 '{}'", bookEntity.getPrimaryBookFile()); + log.warn("No cover image found in AZW3 '{}'", bookFile.getFileName()); return false; } return saveCoverImage(coverData, bookEntity.getId()); } catch (Exception e) { - log.error("Error generating cover for AZW3 '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e); + log.error("Error generating cover for AZW3 '{}': {}", bookFile.getFileName(), e.getMessage(), e); return false; } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/BookFileProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/BookFileProcessor.java index 34f939915..bb4e93c97 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/BookFileProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/BookFileProcessor.java @@ -7,10 +7,20 @@ import org.booklore.model.enums.BookFileType; import java.util.List; +import org.booklore.model.entity.BookFileEntity; + public interface BookFileProcessor { List getSupportedTypes(); FileProcessResult processFile(LibraryFile libraryFile); boolean generateCover(BookEntity bookEntity); + + default boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { + return generateCover(bookEntity); + } + + default boolean generateAudiobookCover(BookEntity bookEntity) { + return generateCover(bookEntity); + } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java index 2438241ed..44751e90b 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/CbxProcessor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -69,7 +70,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce @Override public boolean generateCover(BookEntity bookEntity) { - File file = new File(FileUtils.getBookFullPath(bookEntity)); + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { + File file = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); try { Optional imageOptional = extractImagesFromArchive(file); if (imageOptional.isPresent()) { @@ -79,16 +85,16 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce if (saved) { return true; } else { - log.warn("Could not save image extracted from CBZ as cover for '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("Could not save image extracted from CBZ as cover for '{}'", bookFile.getFileName()); } } finally { image.flush(); // Release resources after processing } } else { - log.warn("Could not find cover image in CBZ file '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("Could not find cover image in CBZ file '{}'", bookFile.getFileName()); } } catch (Exception e) { - log.error("Error generating cover for '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage()); + log.error("Error generating cover for '{}': {}", bookFile.getFileName(), e.getMessage()); } return false; } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java index 76073383d..1d3be78a0 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/EpubProcessor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -57,12 +58,17 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc @Override public boolean generateCover(BookEntity bookEntity) { + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { try { - File epubFile = new File(FileUtils.getBookFullPath(bookEntity)); + File epubFile = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); byte[] coverData = epubMetadataExtractor.extractCover(epubFile); if (coverData == null) { - log.warn("No cover image found in EPUB '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("No cover image found in EPUB '{}'", bookFile.getFileName()); return false; } @@ -70,7 +76,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { BufferedImage originalImage = ImageIO.read(bais); if (originalImage == null) { - log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookFile.getFileName()); return false; } saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); @@ -80,7 +86,7 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc return saved; } catch (Exception e) { - log.error("Error generating cover for EPUB '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e); + log.error("Error generating cover for EPUB '{}': {}", bookFile.getFileName(), e.getMessage(), e); return false; } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/Fb2Processor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/Fb2Processor.java index 685fbd4f4..411f153e9 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/Fb2Processor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/Fb2Processor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -55,12 +56,17 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce @Override public boolean generateCover(BookEntity bookEntity) { + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { try { - File fb2File = new File(FileUtils.getBookFullPath(bookEntity)); + File fb2File = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); byte[] coverData = fb2MetadataExtractor.extractCover(fb2File); if (coverData == null || coverData.length == 0) { - log.warn("No cover image found in FB2 '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("No cover image found in FB2 '{}'", bookFile.getFileName()); return false; } @@ -68,7 +74,7 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce return saved; } catch (Exception e) { - log.error("Error generating cover for FB2 '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage(), e); + log.error("Error generating cover for FB2 '{}': {}", bookFile.getFileName(), e.getMessage(), e); return false; } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/MobiProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/MobiProcessor.java index 38f00b812..f7b4561f6 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/MobiProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/MobiProcessor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.BookMetadataEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; @@ -56,19 +57,24 @@ public class MobiProcessor extends AbstractFileProcessor implements BookFileProc @Override public boolean generateCover(BookEntity bookEntity) { + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { try { - File mobiFile = new File(FileUtils.getBookFullPath(bookEntity)); + File mobiFile = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); byte[] coverData = mobiMetadataExtractor.extractCover(mobiFile); if (coverData == null || coverData.length == 0) { - log.warn("No cover image found in MOBI '{}'", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("No cover image found in MOBI '{}'", bookFile.getFileName()); return false; } return saveCoverImage(coverData, bookEntity.getId()); } catch (Exception e) { - log.error("Error generating cover for MOBI '{}': {}", bookEntity.getPrimaryBookFile(), e.getMessage(), e); + log.error("Error generating cover for MOBI '{}': {}", bookFile.getFileName(), e.getMessage(), e); return false; } } diff --git a/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java b/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java index de13d6f64..81b258e6f 100644 --- a/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/fileprocessor/PdfProcessor.java @@ -4,6 +4,7 @@ import org.booklore.mapper.BookMapper; import org.booklore.model.dto.BookMetadata; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.enums.BookFileType; import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.repository.BookRepository; @@ -59,7 +60,12 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce @Override public boolean generateCover(BookEntity bookEntity) { - File pdfFile = new File(FileUtils.getBookFullPath(bookEntity)); + return generateCover(bookEntity, bookEntity.getPrimaryBookFile()); + } + + @Override + public boolean generateCover(BookEntity bookEntity, BookFileEntity bookFile) { + File pdfFile = new File(FileUtils.getBookFullPath(bookEntity, bookFile)); try (RandomAccessReadBufferedFile randomAccessRead = new RandomAccessReadBufferedFile(pdfFile); PDDocument pdf = Loader.loadPDF(randomAccessRead)) { return generateCoverImageAndSave(bookEntity.getId(), pdf); @@ -67,17 +73,17 @@ public class PdfProcessor extends AbstractFileProcessor implements BookFileProce // Note: Catching OOM is generally discouraged, but for batch processing // of potentially large/corrupted PDFs, we prefer graceful degradation // over crashing the entire service. - log.error("Out of memory (heap space exhausted) while generating cover for '{}'. Skipping cover generation.", bookEntity.getPrimaryBookFile().getFileName()); + log.error("Out of memory (heap space exhausted) while generating cover for '{}'. Skipping cover generation.", bookFile.getFileName()); System.gc(); // Hint to JVM to reclaim memory return false; } catch (NegativeArraySizeException e) { // This can appear on corrupted PDF, or PDF with such large images that the // initial memory buffer is already bigger than the entire JVM heap, therefore // it leads to NegativeArrayException (basically run out of memory, and overflows) - log.warn("Corrupted PDF structure for '{}'. Skipping cover generation.", bookEntity.getPrimaryBookFile().getFileName()); + log.warn("Corrupted PDF structure for '{}'. Skipping cover generation.", bookFile.getFileName()); return false; } catch (Exception e) { - log.warn("Failed to generate cover for '{}': {}", bookEntity.getPrimaryBookFile().getFileName(), e.getMessage()); + log.warn("Failed to generate cover for '{}': {}", bookFile.getFileName(), e.getMessage()); return false; } } diff --git a/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java b/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java index a4a4418b3..4bcd0886b 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java +++ b/booklore-api/src/main/java/org/booklore/service/library/FileAsBookProcessor.java @@ -1,5 +1,7 @@ package org.booklore.service.library; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.booklore.model.FileProcessResult; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; @@ -13,13 +15,19 @@ import org.booklore.service.file.FileFingerprint; import org.booklore.service.fileprocessor.BookFileProcessor; import org.booklore.service.fileprocessor.BookFileProcessorRegistry; import org.booklore.service.kobo.KoboAutoShelfService; +import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor; +import org.booklore.service.metadata.extractor.MetadataExtractorFactory; +import org.booklore.util.BookCoverUtils; import org.booklore.util.BookFileGroupingUtils; +import org.booklore.util.FileService; import org.booklore.util.FileUtils; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.nio.file.Path; import java.time.Instant; import java.util.Comparator; import java.util.List; @@ -36,6 +44,9 @@ public class FileAsBookProcessor { private final KoboAutoShelfService koboAutoShelfService; private final BookRepository bookRepository; private final BookAdditionalFileRepository bookAdditionalFileRepository; + private final FileService fileService; + private final MetadataExtractorFactory metadataExtractorFactory; + private final AudiobookMetadataExtractor audiobookMetadataExtractor; @Transactional public void processLibraryFiles(List libraryFiles, LibraryEntity libraryEntity) { @@ -43,10 +54,6 @@ public class FileAsBookProcessor { processLibraryFilesGrouped(groups, libraryEntity); } - /** - * Process pre-grouped library files. Use this when grouping has already been done - * (e.g., by BookGroupingService during rescan). - */ @Transactional public void processLibraryFilesGrouped(Map> groups, LibraryEntity libraryEntity) { for (Map.Entry> entry : groups.entrySet()) { @@ -127,7 +134,6 @@ public class FileAsBookProcessor { return; } - // Handle folder-based audiobooks vs regular files String hash; Long fileSizeKb; if (file.isFolderBased()) { @@ -154,8 +160,133 @@ public class FileAsBookProcessor { try { bookAdditionalFileRepository.save(additionalFile); log.info("Attached additional format {} to book: {}", file.getFileName(), bookEntity.getPrimaryBookFile().getFileName()); + generateCoverFromAdditionalFile(bookEntity, file); } catch (Exception e) { log.error("Error creating additional file {}: {}", file.getFileName(), e.getMessage()); } } + + void generateCoverFromAdditionalFile(BookEntity bookEntity, LibraryFile additionalFile) { + BookFileType additionalType = additionalFile.getBookFileType(); + boolean additionalIsAudiobook = additionalType == BookFileType.AUDIOBOOK; + + // For fileless books, generate cover based on the additional file type + if (!bookEntity.hasFiles()) { + try { + if (additionalIsAudiobook) { + generateAudiobookCoverFromFile(bookEntity, additionalFile); + } else { + generateEbookCoverFromFile(bookEntity, additionalFile); + } + } catch (Exception e) { + log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage()); + } + return; + } + + BookFileType primaryType = bookEntity.getPrimaryBookFile().getBookType(); + boolean primaryIsAudiobook = primaryType == BookFileType.AUDIOBOOK; + + // Only generate cover when mixing audiobook with ebook formats + if (primaryIsAudiobook == additionalIsAudiobook) { + return; + } + + try { + if (additionalIsAudiobook) { + generateAudiobookCoverFromFile(bookEntity, additionalFile); + } else { + generateEbookCoverFromFile(bookEntity, additionalFile); + } + } catch (Exception e) { + log.warn("Failed to generate cover from additional file {}: {}", additionalFile.getFileName(), e.getMessage()); + } + } + + private void generateAudiobookCoverFromFile(BookEntity bookEntity, LibraryFile audioFile) { + try { + File file = getFileForCoverExtraction(audioFile); + if (file == null || !file.exists()) { + log.debug("Audio file not found for cover extraction: {}", audioFile.getFileName()); + return; + } + + byte[] coverData = audiobookMetadataExtractor.extractCover(file); + if (coverData == null) { + log.debug("No cover image found in audiobook '{}'", audioFile.getFileName()); + return; + } + + try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { + BufferedImage originalImage = FileService.readImage(bais); + if (originalImage == null) { + log.warn("Failed to decode cover image for audiobook '{}'", audioFile.getFileName()); + return; + } + boolean saved = fileService.saveAudiobookCoverImages(originalImage, bookEntity.getId()); + originalImage.flush(); + + if (saved) { + bookEntity.getMetadata().setAudiobookCoverUpdatedOn(Instant.now()); + bookEntity.setAudiobookCoverHash(BookCoverUtils.generateCoverHash()); + bookRepository.save(bookEntity); + log.info("Generated audiobook cover from additional file: {}", audioFile.getFileName()); + } + } + } catch (Exception e) { + log.warn("Error generating audiobook cover from {}: {}", audioFile.getFileName(), e.getMessage()); + } + } + + private void generateEbookCoverFromFile(BookEntity bookEntity, LibraryFile ebookFile) { + try { + File file = ebookFile.getFullPath().toFile(); + if (!file.exists()) { + log.debug("Ebook file not found for cover extraction: {}", ebookFile.getFileName()); + return; + } + + var extractor = metadataExtractorFactory.getExtractor(ebookFile.getBookFileType()); + if (extractor == null) { + log.debug("No extractor available for file type: {}", ebookFile.getBookFileType()); + return; + } + + byte[] coverData = extractor.extractCover(file); + if (coverData == null) { + log.debug("No cover image found in ebook '{}'", ebookFile.getFileName()); + return; + } + + try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { + BufferedImage originalImage = FileService.readImage(bais); + if (originalImage == null) { + log.warn("Failed to decode cover image for ebook '{}'", ebookFile.getFileName()); + return; + } + boolean saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); + originalImage.flush(); + + if (saved) { + FileService.setBookCoverPath(bookEntity.getMetadata()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); + bookRepository.save(bookEntity); + log.info("Generated ebook cover from additional file: {}", ebookFile.getFileName()); + } + } + } catch (Exception e) { + log.warn("Error generating ebook cover from {}: {}", ebookFile.getFileName(), e.getMessage()); + } + } + + private File getFileForCoverExtraction(LibraryFile libraryFile) { + if (libraryFile.isFolderBased()) { + Path folderPath = libraryFile.getFullPath(); + return FileUtils.getFirstAudioFileInFolder(folderPath) + .map(Path::toFile) + .orElse(null); + } else { + return libraryFile.getFullPath().toFile(); + } + } } diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java index 9e2dd770e..94f65aac1 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryFileHelper.java @@ -37,7 +37,17 @@ public class LibraryFileHelper { for (LibraryPathEntity pathEntity : libraryEntity.getLibraryPaths()) { allFiles.addAll(findLibraryFiles(pathEntity, libraryEntity)); } - return allFiles; + return filterByAllowedFormats(allFiles, libraryEntity.getAllowedFormats()); + } + + private List filterByAllowedFormats(List files, List allowedFormats) { + if (allowedFormats == null || allowedFormats.isEmpty()) { + return files; + } + Set allowed = new HashSet<>(allowedFormats); + return files.stream() + .filter(file -> allowed.contains(file.getBookFileType())) + .collect(java.util.stream.Collectors.toList()); } private List findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException { diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java index b1687d377..12f458408 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryProcessingService.java @@ -211,6 +211,7 @@ public class LibraryProcessingService { bookAdditionalFileRepository.save(additionalFile); String primaryFileName = book.hasFiles() ? book.getPrimaryBookFile().getFileName() : "book#" + book.getId(); log.info("Auto-attached new format {} to existing book: {}", file.getFileName(), primaryFileName); + fileAsBookProcessor.generateCoverFromAdditionalFile(book, file); } catch (Exception e) { log.error("Error auto-attaching file {}: {}", file.getFileName(), e.getMessage()); } diff --git a/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java b/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java index 07210ef9d..66fe144de 100644 --- a/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java +++ b/booklore-api/src/main/java/org/booklore/service/library/LibraryService.java @@ -1,5 +1,9 @@ package org.booklore.service.library; +import jakarta.annotation.PostConstruct; +import jakarta.transaction.Transactional; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.booklore.config.security.service.AuthenticationService; import org.booklore.exception.ApiError; import org.booklore.mapper.BookMapper; @@ -24,10 +28,6 @@ import org.booklore.service.monitoring.MonitoringService; import org.booklore.task.options.RescanLibraryContext; import org.booklore.util.FileService; import org.booklore.util.SecurityContextVirtualThread; -import jakarta.annotation.PostConstruct; -import jakarta.transaction.Transactional; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @@ -37,10 +37,7 @@ import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; @Slf4j @@ -77,6 +74,7 @@ public class LibraryService { library.setIconType(request.getIconType()); library.setWatch(request.isWatch()); library.setFormatPriority(request.getFormatPriority()); + library.setAllowedFormats(request.getAllowedFormats()); Set currentPaths = library.getLibraryPaths().stream() .map(LibraryPathEntity::getPath) @@ -156,6 +154,7 @@ public class LibraryService { .iconType(request.getIconType()) .watch(request.isWatch()) .formatPriority(request.getFormatPriority()) + .allowedFormats(request.getAllowedFormats()) .users(List.of(user.get())) .build(); @@ -252,11 +251,26 @@ public class LibraryService { return libraryMapper.toLibrary(libraryRepository.save(library)); } + public Map getBookCountsByFormat(long libraryId) { + libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); + Map counts = new HashMap<>(); + for (BookFileType type : BookFileType.values()) { + long count = bookRepository.countByLibraryIdAndBookType(libraryId, type); + if (count > 0) { + counts.put(type.name(), count); + } + } + return counts; + } + public int scanLibraryPaths(CreateLibraryRequest request) { int count = 0; if (request.getPaths() == null || request.getPaths().isEmpty()) { return count; } + Set allowedFormats = request.getAllowedFormats() != null && !request.getAllowedFormats().isEmpty() + ? Set.copyOf(request.getAllowedFormats()) + : null; for (LibraryPath libraryPath : request.getPaths()) { Path path = Paths.get(libraryPath.getPath()); if (!Files.exists(path)) { @@ -264,21 +278,21 @@ public class LibraryService { continue; } if (Files.isDirectory(path)) { - count += scanDirectory(path); - } else if (Files.isRegularFile(path) && isProcessableFile(path)) { + count += scanDirectory(path, allowedFormats); + } else if (Files.isRegularFile(path) && isProcessableFile(path, allowedFormats)) { count++; } } return count; } - private int scanDirectory(Path directory) { + private int scanDirectory(Path directory, Set allowedFormats) { int count = 0; try (DirectoryStream stream = Files.newDirectoryStream(directory)) { for (Path entry : stream) { if (Files.isDirectory(entry)) { - count += scanDirectory(entry); - } else if (Files.isRegularFile(entry) && isProcessableFile(entry)) { + count += scanDirectory(entry, allowedFormats); + } else if (Files.isRegularFile(entry) && isProcessableFile(entry, allowedFormats)) { count++; } } @@ -288,11 +302,16 @@ public class LibraryService { return count; } - private boolean isProcessableFile(Path file) { + private boolean isProcessableFile(Path file, Set allowedFormats) { String fileName = file.getFileName().toString().toLowerCase(); for (BookFileType fileType : BookFileType.values()) { - if (fileName.endsWith("." + fileType.name().toLowerCase())) { - return true; + if (allowedFormats != null && !allowedFormats.contains(fileType)) { + continue; + } + for (String ext : fileType.getExtensions()) { + if (fileName.endsWith("." + ext)) { + return true; + } } } return false; diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java b/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java index 68ece0761..3b7c36a8a 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java @@ -4,6 +4,7 @@ import org.booklore.exception.ApiError; import org.booklore.model.dto.settings.MetadataPersistenceSettings; import org.booklore.model.entity.AuthorEntity; import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; import org.booklore.model.enums.BookFileType; import org.booklore.model.websocket.LogNotification; import org.booklore.model.websocket.Topic; @@ -118,6 +119,93 @@ public class BookCoverService { notifyBookCoverUpdate(bookEntity); } + // ========================= + // SECTION: AUDIOBOOK COVER UPDATES + // ========================= + + /** + * Update audiobook cover image from uploaded file for a single book. + */ + @Transactional + public void updateAudiobookCoverFromFile(Long bookId, MultipartFile file) { + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isAudiobookCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + + fileService.createAudiobookThumbnailFromFile(bookId, file); + writeAudiobookCoverToFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); + updateAudiobookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); + } + + /** + * Update audiobook cover image from a URL for a single book. + */ + @Transactional + public void updateAudiobookCoverFromUrl(Long bookId, String url) { + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isAudiobookCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + + fileService.createAudiobookThumbnailFromUrl(bookId, url); + writeAudiobookCoverToFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + updateAudiobookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); + } + + /** + * Regenerate audiobook cover for a single book by extracting from the audiobook file. + */ + public void regenerateAudiobookCover(long bookId) { + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (isAudiobookCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + + // Find the audiobook file + var audiobookFile = bookEntity.getBookFiles().stream() + .filter(f -> f.getBookType() == BookFileType.AUDIOBOOK) + .findFirst() + .orElseThrow(ApiError.FAILED_TO_REGENERATE_COVER::createException); + + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(audiobookFile.getBookType()); + boolean success = processor.generateAudiobookCover(bookEntity); + if (!success) { + throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); + } + updateAudiobookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); + } + + /** + * Generate a custom cover for the audiobook cover of a single book. + * Uses square cover format appropriate for audiobooks. + */ + public void generateCustomAudiobookCover(long bookId) { + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isAudiobookCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + + String title = bookEntity.getMetadata().getTitle(); + String author = getAuthorNames(bookEntity); + byte[] coverBytes = coverImageGenerator.generateSquareCover(title, author); + + fileService.createAudiobookThumbnailFromBytes(bookId, coverBytes); + writeAudiobookCoverToFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes)); + updateAudiobookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); + } + /** * Bulk update cover images from a file for multiple books. */ @@ -133,19 +221,23 @@ public class BookCoverService { // ========================= /** - * Regenerate cover for a single book. + * Regenerate cover for a single book from its ebook file. + * For books with multiple formats, this specifically uses an ebook (non-audiobook) file, + * respecting the library's format priority setting. */ public void regenerateCover(long bookId) { - BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } - var primaryFile = bookEntity.getPrimaryBookFile(); - if (primaryFile == null) { + + BookFileEntity ebookFile = findEbookFile(bookEntity); + if (ebookFile == null) { throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); } - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(primaryFile.getBookType()); - boolean success = processor.generateCover(bookEntity); + + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(ebookFile.getBookType()); + boolean success = processor.generateCover(bookEntity, ebookFile); if (!success) { throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); } @@ -153,6 +245,37 @@ public class BookCoverService { bookRepository.save(bookEntity); } + /** + * Find the best ebook (non-audiobook) file for a book, respecting library format priority. + */ + private BookFileEntity findEbookFile(BookEntity bookEntity) { + var bookFiles = bookEntity.getBookFiles(); + if (bookFiles == null || bookFiles.isEmpty()) { + return null; + } + + var library = bookEntity.getLibrary(); + if (library != null && library.getFormatPriority() != null && !library.getFormatPriority().isEmpty()) { + for (BookFileType format : library.getFormatPriority()) { + if (format == BookFileType.AUDIOBOOK) { + continue; + } + var match = bookFiles.stream() + .filter(bf -> bf.isBookFormat() && bf.getBookType() == format) + .findFirst(); + if (match.isPresent()) { + return match.get(); + } + } + } + + // Fallback: return first non-audiobook file + return bookFiles.stream() + .filter(f -> f.getBookType() != BookFileType.AUDIOBOOK) + .findFirst() + .orElse(null); + } + /** * Regenerate covers for a set of books. */ @@ -401,6 +524,10 @@ public class BookCoverService { return book.getMetadata().getCoverLocked() != null && book.getMetadata().getCoverLocked(); } + private boolean isAudiobookCoverLocked(BookEntity book) { + return book.getMetadata().getAudiobookCoverLocked() != null && book.getMetadata().getAudiobookCoverLocked(); + } + private String getAuthorNames(BookEntity bookEntity) { if (bookEntity.getMetadata().getAuthors() != null && !bookEntity.getMetadata().getAuthors().isEmpty()) { return bookEntity.getMetadata().getAuthors().stream() @@ -430,6 +557,26 @@ public class BookCoverService { } } + private void writeAudiobookCoverToFile(BookEntity bookEntity, BiConsumer writerAction) { + var audiobookFile = bookEntity.getBookFiles().stream() + .filter(f -> f.getBookType() == BookFileType.AUDIOBOOK) + .findFirst() + .orElse(null); + + if (audiobookFile == null) { + return; + } + + metadataWriterFactory.getWriter(BookFileType.AUDIOBOOK) + .ifPresent(writer -> { + writerAction.accept(writer, bookEntity); + if (!audiobookFile.isFolderBased()) { + String newHash = FileFingerprint.generateHash(audiobookFile.getFullFilePath()); + audiobookFile.setCurrentHash(newHash); + } + }); + } + private void updateBookCoverMetadata(BookEntity bookEntity) { Instant now = Instant.now(); bookEntity.setMetadataUpdatedAt(now); @@ -437,6 +584,13 @@ public class BookCoverService { bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); } + private void updateAudiobookCoverMetadata(BookEntity bookEntity) { + Instant now = Instant.now(); + bookEntity.setMetadataUpdatedAt(now); + bookEntity.getMetadata().setAudiobookCoverUpdatedOn(now); + bookEntity.setAudiobookCoverHash(BookCoverUtils.generateCoverHash()); + } + private void notifyBookCoverUpdate(BookEntity bookEntity) { List updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId())); if (!updates.isEmpty()) { diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java index 52bbaea8d..abfc8d0e1 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/BookMetadataUpdater.java @@ -1,5 +1,8 @@ package org.booklore.service.metadata; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; import org.booklore.model.MetadataClearFlags; import org.booklore.model.MetadataUpdateContext; import org.booklore.model.MetadataUpdateWrapper; @@ -17,9 +20,6 @@ import org.booklore.service.metadata.writer.MetadataWriterFactory; import org.booklore.util.BookCoverUtils; import org.booklore.util.FileService; import org.booklore.util.MetadataChangeDetector; -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.tuple.Pair; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @@ -98,6 +98,7 @@ public class BookMetadataUpdater { updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode); bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories); updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail); + updateAudiobookMetadataIfNeeded(bookEntity, newMetadata, metadata, clearFlags, replaceMode); updateLocks(newMetadata, metadata); bookEntity.setMetadataUpdatedAt(Instant.now()); @@ -351,6 +352,14 @@ public class BookMetadataUpdater { } } + private void updateAudiobookMetadataIfNeeded(BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, MetadataClearFlags clear, MetadataReplaceMode replaceMode) { + if (clear == null) { + clear = new MetadataClearFlags(); + } + handleFieldUpdate(e.getNarratorLocked(), clear.isNarrator(), m.getNarrator(), v -> e.setNarrator(nullIfBlank(v)), e::getNarrator, replaceMode); + handleFieldUpdate(e.getAbridgedLocked(), clear.isAbridged(), m.getAbridged(), e::setAbridged, e::getAbridged, replaceMode); + } + private void updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set) { if (Boolean.TRUE.equals(e.getCoverLocked())) { return; @@ -396,12 +405,18 @@ public class BookMetadataUpdater { Pair.of(m.getHardcoverReviewCountLocked(), e::setHardcoverReviewCountLocked), Pair.of(m.getRanobedbIdLocked(), e::setRanobedbIdLocked), Pair.of(m.getRanobedbRatingLocked(), e::setRanobedbRatingLocked), + Pair.of(m.getAudibleIdLocked(), e::setAudibleIdLocked), + Pair.of(m.getAudibleRatingLocked(), e::setAudibleRatingLocked), + Pair.of(m.getAudibleReviewCountLocked(), e::setAudibleReviewCountLocked), Pair.of(m.getCoverLocked(), e::setCoverLocked), + Pair.of(m.getAudiobookCoverLocked(), e::setAudiobookCoverLocked), Pair.of(m.getAuthorsLocked(), e::setAuthorsLocked), Pair.of(m.getCategoriesLocked(), e::setCategoriesLocked), Pair.of(m.getMoodsLocked(), e::setMoodsLocked), Pair.of(m.getTagsLocked(), e::setTagsLocked), - Pair.of(m.getReviewsLocked(), e::setReviewsLocked) + Pair.of(m.getReviewsLocked(), e::setReviewsLocked), + Pair.of(m.getNarratorLocked(), e::setNarratorLocked), + Pair.of(m.getAbridgedLocked(), e::setAbridgedLocked) ); lockMappings.forEach(pair -> { if (pair.getLeft() != null) pair.getRight().accept(pair.getLeft()); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/CoverImageGenerator.java b/booklore-api/src/main/java/org/booklore/service/metadata/CoverImageGenerator.java index 316b36d2d..69869e807 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/CoverImageGenerator.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/CoverImageGenerator.java @@ -23,6 +23,7 @@ public class CoverImageGenerator { private static final int WIDTH = 1200; private static final int HEIGHT = 1600; + private static final int SQUARE_SIZE = 1200; private static final int SCALE = 2; private static final double PHI = 1.618033988749; private static final double PHI_INV = 1.0 / PHI; @@ -93,6 +94,57 @@ public class CoverImageGenerator { } } + /** + * Generates a square cover image suitable for audiobooks. + */ + public byte[] generateSquareCover(String title, String author) { + BufferedImage render = null; + BufferedImage result = null; + Graphics2D g = null; + + try { + String safeTitle = sanitize(title, MAX_TITLE_LEN, "Unknown Title"); + String safeAuthor = sanitize(author, MAX_AUTHOR_LEN, "Unknown Author"); + + int size = SQUARE_SIZE * SCALE; + + render = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); + g = render.createGraphics(); + + try { + configureGraphics(g); + Palette p = selectPalette(safeTitle); + int margin = calcSquareMargin(size); + + renderBaseGradient(g, p, size, size); + renderDepthGradient(g, p, size, size); + renderGlow(g, p, size, size); + renderBokeh(g, p, size, size); + renderTexture(g, size, size); + renderSquareFrame(g, p, size); + renderSquareTitle(g, safeTitle, p, size, margin); + renderSquareAuthor(g, safeAuthor, p, size, margin); + renderVignette(g, size, size); + renderEdges(g, size, size); + + } finally { + if (g != null) g.dispose(); + } + + result = downscaleSquare(render); + render.flush(); + render = null; + + return encodeJpeg(result); + + } catch (Exception e) { + log.error("Square cover generation failed: {}", title, e); + throw new RuntimeException("Square cover generation failed", e); + } finally { + cleanup(g, render, result); + } + } + private record Palette(Color primary, Color secondary, Color tertiary, Color accent, Color textMain, Color textSub, Color ornament) {} @@ -671,6 +723,129 @@ public class CoverImageGenerator { } } + private BufferedImage downscaleSquare(BufferedImage src) { + BufferedImage dst = new BufferedImage(SQUARE_SIZE, SQUARE_SIZE, BufferedImage.TYPE_INT_RGB); + Graphics2D g = dst.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.drawImage(src, 0, 0, SQUARE_SIZE, SQUARE_SIZE, null); + return dst; + } finally { + g.dispose(); + } + } + + private int calcSquareMargin(int size) { + int frameOuter = (int) (size * PHI_SQ_INV * 0.10); + int frameInner = (int) (frameOuter * PHI); + return frameInner + (int) (size * 0.04); + } + + private void renderSquareFrame(Graphics2D g, Palette p, int size) { + int outer = (int) (size * PHI_SQ_INV * 0.10); + int inner = (int) (outer * PHI); + + g.setColor(alpha(p.ornament, 28)); + g.setStroke(new BasicStroke(8f)); + g.drawRect(outer - 4, outer - 4, size - (outer - 4) * 2, size - (outer - 4) * 2); + + g.setColor(alpha(p.ornament, 95)); + g.setStroke(new BasicStroke(2.5f)); + g.drawRect(outer, outer, size - outer * 2, size - outer * 2); + + g.setColor(alpha(p.ornament, 55)); + g.setStroke(new BasicStroke(1f)); + g.drawRect(inner, inner, size - inner * 2, size - inner * 2); + + renderSquareCorners(g, p, size, outer); + } + + private static void renderSquareCorners(Graphics2D g, Palette p, int size, int m) { + g.setColor(alpha(p.ornament, 105)); + g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int cornerSize = (int) (m * PHI * 0.8); + + int[][] corners = {{m, m, 0}, {size - m, m, 90}, {size - m, size - m, 180}, {m, size - m, 270}}; + for (int[] c : corners) renderCorner(g, c[0], c[1], cornerSize, c[2]); + } + + private void renderSquareTitle(Graphics2D g, String title, Palette p, int size, int margin) { + int maxW = size - margin * 2; + + String text = title.toUpperCase(); + Font font = resolveFont(g, text, maxW, squareTitleSize(title.length()), 3, true); + g.setFont(font); + FontMetrics fm = g.getFontMetrics(); + + List lines = wrapText(text, fm, maxW, 3); + int lineH = (int) (fm.getHeight() * 1.12); + int totalH = lines.size() * lineH; + + // Center title vertically in top portion + int topZone = (int) (size * 0.55); + int startY = margin + (topZone - margin - totalH) / 2 + fm.getAscent(); + startY = Math.max(startY, margin + fm.getAscent()); + + float tracking = 0.05f; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int lw = trackedWidth(fm, line, tracking); + int x = (size - lw) / 2; + int y = startY + i * lineH; + if (y + fm.getDescent() > topZone) break; + renderText(g, line, x, y, tracking, p.textMain, true); + } + } + + private void renderSquareAuthor(Graphics2D g, String author, Palette p, int size, int margin) { + int maxW = size - margin * 2; + + Font authorFont = resolveFont(g, author, maxW, squareAuthorSize(author.length()), 2, false); + g.setFont(authorFont); + FontMetrics authorFm = g.getFontMetrics(); + + List lines = wrapText(author, authorFm, maxW, 2); + int authorLineH = (int) (authorFm.getHeight() * 1.15); + int totalH = lines.size() * authorLineH; + + // Position author in bottom portion + int bottomStart = (int) (size * 0.65); + int bottomEnd = size - margin; + int availableH = bottomEnd - bottomStart - totalH; + int startY = bottomStart + availableH / 2 + authorFm.getAscent(); + + float tracking = 0.08f; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + if (!line.isEmpty()) { + int lw = trackedWidth(authorFm, line, tracking); + int x = (size - lw) / 2; + int y = startY + i * authorLineH; + if (y + authorFm.getDescent() > bottomEnd) break; + renderText(g, line, x, y, tracking, p.textSub, false); + } + } + } + + private int squareTitleSize(int len) { + if (len < 8) return 130 * SCALE; + if (len < 15) return 110 * SCALE; + if (len < 25) return 95 * SCALE; + if (len < 40) return 80 * SCALE; + if (len < 60) return 68 * SCALE; + return 58 * SCALE; + } + + private int squareAuthorSize(int len) { + if (len < 15) return 70 * SCALE; + if (len < 25) return 60 * SCALE; + if (len < 40) return 52 * SCALE; + return 45 * SCALE; + } + private byte[] encodeJpeg(BufferedImage img) { ImageWriter writer = null; ImageOutputStream ios = null; diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java b/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java index c34b23c7c..464bc64d8 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/DuckDuckGoCoverService.java @@ -65,14 +65,14 @@ public class DuckDuckGoCoverService implements BookCoverProvider { public List getCovers(CoverFetchRequest request) { String title = request.getTitle(); String author = request.getAuthor(); - boolean squareCover = request.isSquareCover(); - String bookType = squareCover ? "audiobook" : "book"; + boolean isAudiobook = "audiobook".equalsIgnoreCase(request.getCoverType()); + String bookType = isAudiobook ? "audiobook" : "book"; String searchTerm = (author != null && !author.isEmpty()) ? title + " " + author + " " + bookType : title + " " + bookType; - String searchParams = squareCover ? SEARCH_PARAMS_SQUARE : SEARCH_PARAMS_TALL; - String jsonParams = squareCover ? JSON_PARAMS_SQUARE : JSON_PARAMS_TALL; + String searchParams = isAudiobook ? SEARCH_PARAMS_SQUARE : SEARCH_PARAMS_TALL; + String jsonParams = isAudiobook ? JSON_PARAMS_SQUARE : JSON_PARAMS_TALL; String encodedSiteQuery = URLEncoder.encode(searchTerm, StandardCharsets.UTF_8); String siteUrl = SEARCH_BASE_URL + encodedSiteQuery + SITE_FILTER + searchParams; @@ -88,7 +88,7 @@ public class DuckDuckGoCoverService implements BookCoverProvider { String siteSearchToken = siteMatcher.group(1); List siteFilteredImages = fetchImagesFromApi(searchTerm + " (site:amazon.com OR site:goodreads.com)", siteSearchToken, cookies, siteUrl, jsonParams); siteFilteredImages.removeIf(dto -> dto.getWidth() < 350); - if (squareCover) { + if (isAudiobook) { siteFilteredImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight())); } else { siteFilteredImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); @@ -108,7 +108,7 @@ public class DuckDuckGoCoverService implements BookCoverProvider { String generalSearchToken = generalMatcher.group(1); generalBookImages = fetchImagesFromApi(searchTerm, generalSearchToken, generalCookies, generalUrl, jsonParams); generalBookImages.removeIf(dto -> dto.getWidth() < 350); - if (squareCover) { + if (isAudiobook) { generalBookImages.removeIf(dto -> !isApproximatelySquare(dto.getWidth(), dto.getHeight())); } else { generalBookImages.removeIf(dto -> dto.getWidth() >= dto.getHeight()); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java index 19d1d5828..4cb9753f1 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/AudiobookMetadataExtractor.java @@ -1,19 +1,31 @@ package org.booklore.service.metadata.extractor; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.booklore.model.dto.AudiobookMetadata; import org.booklore.model.dto.BookMetadata; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.Tag; +import org.jaudiotagger.tag.id3.AbstractID3v2Frame; +import org.jaudiotagger.tag.id3.AbstractID3v2Tag; +import org.jaudiotagger.tag.id3.ID3v2ChapterFrames; +import org.jaudiotagger.tag.id3.framebody.FrameBodyCHAP; import org.jaudiotagger.tag.images.Artwork; import org.springframework.stereotype.Component; +import java.io.BufferedReader; import java.io.File; +import java.io.InputStreamReader; import java.time.LocalDate; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; @@ -23,7 +35,6 @@ import java.util.logging.Logger; public class AudiobookMetadataExtractor implements FileMetadataExtractor { static { - // Suppress verbose JAudioTagger logging Logger.getLogger("org.jaudiotagger").setLevel(Level.WARNING); } @@ -32,16 +43,33 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { try { AudioFile f = AudioFileIO.read(audioFile); Tag tag = f.getTag(); - - if (tag == null) { - return BookMetadata.builder() - .title(FilenameUtils.getBaseName(audioFile.getName())) - .build(); - } + AudioHeader header = f.getAudioHeader(); BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); + AudiobookMetadata.AudiobookMetadataBuilder audiobookBuilder = AudiobookMetadata.builder(); + + extractAudioHeaderInfo(audiobookBuilder, header); + + List chapters = extractChapters(audioFile, f, header); + if (chapters != null && !chapters.isEmpty()) { + audiobookBuilder.chapters(chapters); + audiobookBuilder.chapterCount(chapters.size()); + } + + if (tag != null) { + String narrator = tag.getFirst(FieldKey.COMPOSER); + if (StringUtils.isNotBlank(narrator)) { + builder.narrator(narrator); + } + } + + builder.audiobookMetadata(audiobookBuilder.build()); + + if (tag == null) { + builder.title(FilenameUtils.getBaseName(audioFile.getName())); + return builder.build(); + } - // Title - prefer album for audiobooks, fallback to title, then filename String album = tag.getFirst(FieldKey.ALBUM); String title = tag.getFirst(FieldKey.TITLE); if (StringUtils.isNotBlank(album)) { @@ -52,7 +80,6 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { builder.title(FilenameUtils.getBaseName(audioFile.getName())); } - // Author - use album artist or artist String albumArtist = tag.getFirst(FieldKey.ALBUM_ARTIST); String artist = tag.getFirst(FieldKey.ARTIST); Set authors = new HashSet<>(); @@ -65,19 +92,16 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { builder.authors(authors); } - // Description - use comment field String comment = tag.getFirst(FieldKey.COMMENT); if (StringUtils.isNotBlank(comment)) { builder.description(comment); } - // Publisher - use record label or publisher String publisher = tag.getFirst(FieldKey.RECORD_LABEL); if (StringUtils.isNotBlank(publisher)) { builder.publisher(publisher); } - // Year/Date String year = tag.getFirst(FieldKey.YEAR); if (StringUtils.isNotBlank(year)) { try { @@ -89,7 +113,6 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { } } - // Genre as category String genre = tag.getFirst(FieldKey.GENRE); if (StringUtils.isNotBlank(genre)) { Set categories = new HashSet<>(); @@ -97,19 +120,16 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { builder.categories(categories); } - // Language String language = tag.getFirst(FieldKey.LANGUAGE); if (StringUtils.isNotBlank(language)) { builder.language(language); } - // Series info from grouping or custom tags String grouping = tag.getFirst(FieldKey.GROUPING); if (StringUtils.isNotBlank(grouping)) { builder.seriesName(grouping); } - // Try to extract track number as series number for multi-part audiobooks String trackNo = tag.getFirst(FieldKey.TRACK); if (StringUtils.isNotBlank(trackNo)) { try { @@ -119,7 +139,6 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { } } - // Try to get total tracks String trackTotal = tag.getFirst(FieldKey.TRACK_TOTAL); if (StringUtils.isNotBlank(trackTotal)) { try { @@ -138,6 +157,285 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor { } } + private void extractAudioHeaderInfo(AudiobookMetadata.AudiobookMetadataBuilder builder, AudioHeader header) { + if (header == null) { + return; + } + + long durationSeconds = (long) header.getPreciseTrackLength(); + if (durationSeconds > 0) { + builder.durationSeconds(durationSeconds); + } + + long bitrate = header.getBitRateAsNumber(); + if (bitrate > 0) { + builder.bitrate((int) bitrate); + } + + int sampleRate = header.getSampleRateAsNumber(); + if (sampleRate > 0) { + builder.sampleRate(sampleRate); + } + + String channelsStr = header.getChannels(); + Integer channels = parseChannels(channelsStr); + if (channels != null) { + builder.channels(channels); + } + + String codec = header.getEncodingType(); + if (StringUtils.isNotBlank(codec)) { + builder.codec(codec); + } + } + + private Integer parseChannels(String channels) { + if (channels == null) { + return null; + } + String lower = channels.toLowerCase(); + if (lower.contains("stereo")) { + return 2; + } + if (lower.contains("mono")) { + return 1; + } + if (lower.contains("5.1") || lower.contains("surround")) { + return 6; + } + try { + return Integer.parseInt(channels.replaceAll("[^0-9]", "")); + } catch (NumberFormatException e) { + return null; + } + } + + private List extractChapters(File audioFile, AudioFile taggedFile, AudioHeader header) { + List chapters = extractId3v2Chapters(taggedFile); + if (chapters != null && !chapters.isEmpty()) { + log.debug("Extracted {} chapters from ID3v2 CHAP frames for {}", chapters.size(), audioFile.getName()); + return chapters; + } + + chapters = extractChaptersWithFfprobe(audioFile); + if (chapters != null && !chapters.isEmpty()) { + log.debug("Extracted {} chapters using ffprobe for {}", chapters.size(), audioFile.getName()); + return chapters; + } + + return createDefaultChapter(header); + } + + @SuppressWarnings("unchecked") + private List extractId3v2Chapters(AudioFile taggedFile) { + try { + Tag tag = taggedFile.getTag(); + if (!(tag instanceof AbstractID3v2Tag id3v2Tag)) { + return null; + } + + Object chapFrames = id3v2Tag.getFrame(ID3v2ChapterFrames.FRAME_ID_CHAPTER); + if (chapFrames == null) { + return null; + } + + List chapters = new ArrayList<>(); + List frameList; + + if (chapFrames instanceof List) { + frameList = (List) chapFrames; + } else if (chapFrames instanceof AbstractID3v2Frame) { + frameList = List.of((AbstractID3v2Frame) chapFrames); + } else { + return null; + } + + frameList = new ArrayList<>(frameList); + frameList.sort((f1, f2) -> { + if (f1.getBody() instanceof FrameBodyCHAP chap1 && f2.getBody() instanceof FrameBodyCHAP chap2) { + long start1 = getChapStartTime(chap1); + long start2 = getChapStartTime(chap2); + return Long.compare(start1, start2); + } + return 0; + }); + + for (int i = 0; i < frameList.size(); i++) { + AbstractID3v2Frame frame = frameList.get(i); + if (!(frame.getBody() instanceof FrameBodyCHAP chapBody)) { + continue; + } + + long startTimeMs = getChapStartTime(chapBody); + long endTimeMs = getChapEndTime(chapBody); + long durationMs = endTimeMs - startTimeMs; + + String title = extractChapterTitle(chapBody, i); + + chapters.add(AudiobookMetadata.ChapterInfo.builder() + .index(i) + .title(title) + .startTimeMs(startTimeMs) + .endTimeMs(endTimeMs) + .durationMs(durationMs) + .build()); + } + + return chapters.isEmpty() ? null : chapters; + } catch (Exception e) { + log.debug("Failed to extract ID3v2 CHAP frames: {}", e.getMessage()); + return null; + } + } + + private long getChapStartTime(FrameBodyCHAP chapBody) { + Object startTime = chapBody.getObjectValue("StartTime"); + if (startTime instanceof Number) { + return ((Number) startTime).longValue(); + } + return 0; + } + + private long getChapEndTime(FrameBodyCHAP chapBody) { + Object endTime = chapBody.getObjectValue("EndTime"); + if (endTime instanceof Number) { + return ((Number) endTime).longValue(); + } + return 0; + } + + private String extractChapterTitle(FrameBodyCHAP chapBody, int index) { + try { + Object elementId = chapBody.getObjectValue("ElementID"); + if (elementId instanceof String str && StringUtils.isNotBlank(str)) { + if (!str.matches("(?i)^(chp?|chapter)?\\d+$")) { + return str; + } + } + } catch (Exception ignored) { + } + + return "Chapter " + (index + 1); + } + + private List extractChaptersWithFfprobe(File audioFile) { + List chapters = new ArrayList<>(); + + try { + ProcessBuilder pb = new ProcessBuilder( + "ffprobe", + "-v", "quiet", + "-print_format", "json", + "-show_chapters", + audioFile.getAbsolutePath() + ); + pb.redirectErrorStream(true); + + Process process = pb.start(); + StringBuilder output = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + output.append(line); + } + } + + int exitCode = process.waitFor(); + if (exitCode != 0) { + log.debug("FFprobe exited with code {} for {}", exitCode, audioFile.getName()); + return null; + } + + String jsonOutput = output.toString().trim(); + if (jsonOutput.isEmpty() || jsonOutput.equals("{}")) { + return null; + } + + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(jsonOutput); + JsonNode chaptersNode = root.get("chapters"); + + if (chaptersNode == null || !chaptersNode.isArray() || chaptersNode.isEmpty()) { + return null; + } + + for (int i = 0; i < chaptersNode.size(); i++) { + JsonNode chapterNode = chaptersNode.get(i); + + double startTime = 0; + double endTime = 0; + + if (chapterNode.has("start_time")) { + startTime = chapterNode.get("start_time").asDouble(); + } else if (chapterNode.has("start")) { + long start = chapterNode.get("start").asLong(); + String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; + startTime = convertTimebaseToSeconds(start, timeBase); + } + + if (chapterNode.has("end_time")) { + endTime = chapterNode.get("end_time").asDouble(); + } else if (chapterNode.has("end")) { + long end = chapterNode.get("end").asLong(); + String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; + endTime = convertTimebaseToSeconds(end, timeBase); + } + + long startTimeMs = Math.round(startTime * 1000); + long endTimeMs = Math.round(endTime * 1000); + long durationMs = endTimeMs - startTimeMs; + + String title = "Chapter " + (i + 1); + JsonNode tagsNode = chapterNode.get("tags"); + if (tagsNode != null && tagsNode.has("title")) { + title = tagsNode.get("title").asText(); + } + + chapters.add(AudiobookMetadata.ChapterInfo.builder() + .index(i) + .title(title) + .startTimeMs(startTimeMs) + .endTimeMs(endTimeMs) + .durationMs(durationMs) + .build()); + } + + return chapters; + } catch (Exception e) { + log.debug("Failed to extract chapters with ffprobe from {}: {}", audioFile.getName(), e.getMessage()); + return null; + } + } + + private List createDefaultChapter(AudioHeader header) { + if (header == null) { + return new ArrayList<>(); + } + long durationMs = (long) (header.getPreciseTrackLength() * 1000); + return List.of(AudiobookMetadata.ChapterInfo.builder() + .index(0) + .title("Full Audiobook") + .startTimeMs(0L) + .endTimeMs(durationMs) + .durationMs(durationMs) + .build()); + } + + private double convertTimebaseToSeconds(long value, String timeBase) { + String[] parts = timeBase.split("/"); + if (parts.length == 2) { + try { + double numerator = Double.parseDouble(parts[0]); + double denominator = Double.parseDouble(parts[1]); + return value * (numerator / denominator); + } catch (NumberFormatException e) { + return value / 1000.0; + } + } + return value / 1000.0; + } + @Override public byte[] extractCover(File audioFile) { try { diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/MetadataExtractorFactory.java b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/MetadataExtractorFactory.java index e48092599..d788f4bb1 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/extractor/MetadataExtractorFactory.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/extractor/MetadataExtractorFactory.java @@ -55,4 +55,16 @@ public class MetadataExtractorFactory { case M4B, M4A, MP3, AAC, FLAC, OPUS, OGG -> audiobookMetadataExtractor.extractCover(file); }; } + + public FileMetadataExtractor getExtractor(BookFileType bookFileType) { + return switch (bookFileType) { + case PDF -> pdfMetadataExtractor; + case EPUB -> epubMetadataExtractor; + case CBX -> cbxMetadataExtractor; + case FB2 -> fb2MetadataExtractor; + case MOBI -> mobiMetadataExtractor; + case AZW3 -> azw3MetadataExtractor; + case AUDIOBOOK -> audiobookMetadataExtractor; + }; + } } diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudibleParser.java b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudibleParser.java new file mode 100644 index 000000000..4f7a07461 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/metadata/parser/AudibleParser.java @@ -0,0 +1,492 @@ +package org.booklore.service.metadata.parser; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.booklore.model.dto.AudiobookMetadata; +import org.booklore.model.dto.Book; +import org.booklore.model.dto.BookMetadata; +import org.booklore.model.dto.request.FetchMetadataRequest; +import org.booklore.model.enums.MetadataProvider; +import org.booklore.service.appsettings.AppSettingService; +import org.booklore.util.BookUtils; +import org.jsoup.Connection; +import org.jsoup.HttpStatusException; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.nodes.Element; +import org.jsoup.select.Elements; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.time.Duration; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; +import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +@Slf4j +@Service +@AllArgsConstructor +public class AudibleParser implements BookParser { + + private static final long MIN_REQUEST_INTERVAL_MS = 1500; + private static final int MAX_DETAILED_RESULTS = 3; + private static final String DEFAULT_DOMAIN = "com"; + + private static final Pattern NON_ALPHANUMERIC_PATTERN = Pattern.compile("[^\\p{L}\\p{M}0-9]"); + private static final Pattern ASIN_PATTERN = Pattern.compile("/pd/[^/]+/([A-Z0-9]{10})"); + private static final Pattern SERIES_BOOK_PATTERN = Pattern.compile(",?\\s*Book\\s*(\\d+(?:\\.\\d+)?)$"); + + private static final Map DOMAIN_LOCALE_MAP = Map.ofEntries( + Map.entry("com", new LocaleInfo("en-US,en;q=0.9", Locale.US)), + Map.entry("co.uk", new LocaleInfo("en-GB,en;q=0.9", Locale.UK)), + Map.entry("de", new LocaleInfo("en-GB,en;q=0.9,de;q=0.8", Locale.GERMANY)), + Map.entry("fr", new LocaleInfo("en-GB,en;q=0.9,fr;q=0.8", Locale.FRANCE)), + Map.entry("it", new LocaleInfo("en-GB,en;q=0.9,it;q=0.8", Locale.ITALY)), + Map.entry("es", new LocaleInfo("en-GB,en;q=0.9,es;q=0.8", new Locale.Builder().setLanguage("es").setRegion("ES").build())), + Map.entry("ca", new LocaleInfo("en-US,en;q=0.9", Locale.CANADA)), + Map.entry("com.au", new LocaleInfo("en-GB,en;q=0.9", new Locale.Builder().setLanguage("en").setRegion("AU").build())), + Map.entry("co.jp", new LocaleInfo("en-GB,en;q=0.9,ja;q=0.8", Locale.JAPAN)), + Map.entry("in", new LocaleInfo("en-GB,en;q=0.9", new Locale.Builder().setLanguage("en").setRegion("IN").build())) + ); + + private static final LocaleInfo DEFAULT_LOCALE_INFO = new LocaleInfo("en-US,en;q=0.9", Locale.US); + + private final AppSettingService appSettingService; + private final ObjectMapper objectMapper; + private final AtomicLong lastRequestTime = new AtomicLong(0); + + private record LocaleInfo(String acceptLanguage, Locale locale) {} + + @Override + public BookMetadata fetchTopMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) { + List audibleIds = getAudibleIds(book, fetchMetadataRequest); + if (audibleIds == null || audibleIds.isEmpty()) { + return null; + } + return getBookMetadata(audibleIds.getFirst()); + } + + @Override + public List fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) { + List audibleIds = Optional.ofNullable(getAudibleIds(book, fetchMetadataRequest)) + .map(list -> list.stream() + .limit(MAX_DETAILED_RESULTS) + .collect(Collectors.toList())) + .orElse(new ArrayList<>()); + + if (audibleIds.isEmpty()) { + return null; + } + + List fetchedMetadata = new ArrayList<>(); + for (String audibleId : audibleIds) { + if (audibleId == null || audibleId.isBlank()) { + log.debug("Skipping null or blank Audible ID."); + continue; + } + BookMetadata metadata = getBookMetadata(audibleId); + if (metadata == null) { + log.debug("Skipping null metadata for Audible ID: {}", audibleId); + continue; + } + if (metadata.getTitle() == null || metadata.getTitle().isBlank()) { + log.debug("Skipping metadata with missing title for Audible ID: {}", audibleId); + continue; + } + fetchedMetadata.add(metadata); + } + return fetchedMetadata; + } + + private List getAudibleIds(Book book, FetchMetadataRequest request) { + String queryUrl = buildQueryUrl(request, book); + if (queryUrl == null) { + log.error("Query URL is null, cannot proceed with Audible search."); + return null; + } + + List bookIds = new ArrayList<>(); + try { + enforceRateLimit(); + Document doc = fetchDocument(queryUrl); + + Elements allLinks = doc.select("a[href*='/pd/']"); + for (Element link : allLinks) { + String href = link.attr("href"); + Matcher matcher = ASIN_PATTERN.matcher(href); + if (matcher.find()) { + String asin = matcher.group(1); + if (!bookIds.contains(asin)) { + bookIds.add(asin); + } + } + } + + } catch (Exception e) { + log.error("Failed to get Audible IDs: {}", e.getMessage(), e); + } + + log.info("Audible: Found {} book ids", bookIds.size()); + return bookIds; + } + + private BookMetadata getBookMetadata(String audibleId) { + log.info("Audible: Fetching metadata for: {}", audibleId); + + String domain = getDomain(); + String url = "https://www.audible." + domain + "/pd/" + audibleId; + + try { + enforceRateLimit(); + Document doc = fetchDocument(url); + return buildBookMetadataFromJsonLd(doc, audibleId); + } catch (Exception e) { + log.error("Failed to fetch Audible metadata for ID {}: {}", audibleId, e.getMessage()); + return null; + } + } + + private BookMetadata buildBookMetadataFromJsonLd(Document doc, String audibleId) { + JsonNode audiobookNode = null; + JsonNode productNode = null; + JsonNode breadcrumbNode = null; + + Elements jsonLdScripts = doc.select("script[type='application/ld+json']"); + for (Element script : jsonLdScripts) { + try { + String jsonContent = script.html(); + JsonNode rootNode = objectMapper.readTree(jsonContent); + + if (rootNode.isArray()) { + for (JsonNode node : rootNode) { + String type = node.path("@type").asText(""); + if ("Audiobook".equals(type)) { + audiobookNode = node; + } else if ("Product".equals(type)) { + productNode = node; + } else if ("BreadcrumbList".equals(type)) { + breadcrumbNode = node; + } + } + } else { + String type = rootNode.path("@type").asText(""); + if ("Audiobook".equals(type)) { + audiobookNode = rootNode; + } else if ("Product".equals(type)) { + productNode = rootNode; + } else if ("BreadcrumbList".equals(type)) { + breadcrumbNode = rootNode; + } + } + } catch (Exception e) { + log.debug("Failed to parse JSON-LD block: {}", e.getMessage()); + } + } + + if (audiobookNode == null && productNode == null) { + log.warn("No JSON-LD structured data found for Audible ID: {}", audibleId); + return null; + } + + String title = null; + String subtitle = null; + String fullName = getJsonString(audiobookNode, "name"); + if (fullName == null) { + fullName = getJsonString(productNode, "name"); + } + + if (fullName != null) { + Matcher seriesMatcher = SERIES_BOOK_PATTERN.matcher(fullName); + if (seriesMatcher.find()) { + fullName = seriesMatcher.replaceFirst("").trim(); + } + + int colonIdx = fullName.indexOf(':'); + if (colonIdx > 0 && colonIdx < fullName.length() - 1) { + title = fullName.substring(0, colonIdx).trim(); + subtitle = fullName.substring(colonIdx + 1).trim(); + } else { + title = fullName; + } + } + + Set authors = extractPersonNames(audiobookNode, "author"); + String narrator = extractFirstPersonName(audiobookNode, "readBy"); + String publisher = getJsonString(audiobookNode, "publisher"); + String description = getJsonString(audiobookNode, "description"); + String language = getJsonString(audiobookNode, "inLanguage"); + String imageUrl = getJsonString(audiobookNode, "image"); + if (imageUrl == null) { + imageUrl = getJsonString(productNode, "image"); + } + + LocalDate publishedDate = null; + String dateStr = getJsonString(audiobookNode, "datePublished"); + if (dateStr != null) { + try { + publishedDate = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE); + } catch (DateTimeParseException e) { + log.debug("Failed to parse date: {}", dateStr); + } + } + + Long durationSeconds = null; + String durationStr = getJsonString(audiobookNode, "duration"); + if (durationStr != null) { + durationSeconds = parseIsoDuration(durationStr); + } + + Boolean abridged = null; + String abridgedStr = getJsonString(audiobookNode, "abridged"); + if (abridgedStr != null) { + abridged = "true".equalsIgnoreCase(abridgedStr); + } + + Double rating = null; + Integer reviewCount = null; + JsonNode ratingNode = audiobookNode != null ? audiobookNode.path("aggregateRating") : null; + if (ratingNode == null || ratingNode.isMissingNode()) { + ratingNode = productNode != null ? productNode.path("aggregateRating") : null; + } + if (ratingNode != null && !ratingNode.isMissingNode()) { + String ratingValue = ratingNode.path("ratingValue").asText(null); + String ratingCountStr = ratingNode.path("ratingCount").asText(null); + if (ratingValue != null) { + try { + rating = Double.parseDouble(ratingValue); + } catch (NumberFormatException e) { + log.debug("Failed to parse rating: {}", ratingValue); + } + } + if (ratingCountStr != null) { + try { + reviewCount = Integer.parseInt(ratingCountStr); + } catch (NumberFormatException e) { + log.debug("Failed to parse review count: {}", ratingCountStr); + } + } + } + + Set categories = new HashSet<>(); + if (breadcrumbNode != null) { + JsonNode itemListElement = breadcrumbNode.path("itemListElement"); + if (itemListElement.isArray()) { + for (JsonNode item : itemListElement) { + String categoryName = item.path("item").path("name").asText(null); + if (categoryName != null && !"Home".equalsIgnoreCase(categoryName)) { + categories.add(categoryName); + } + } + } + } + + String seriesName = null; + Float seriesNumber = null; + Elements seriesLinks = doc.select("a[href*='/series/']"); + for (Element link : seriesLinks) { + String seriesText = link.text().trim(); + if (!seriesText.isEmpty()) { + Matcher bookMatcher = SERIES_BOOK_PATTERN.matcher(seriesText); + if (bookMatcher.find()) { + seriesName = bookMatcher.replaceFirst("").trim(); + try { + seriesNumber = Float.parseFloat(bookMatcher.group(1)); + } catch (NumberFormatException e) { + log.debug("Failed to parse series number from: {}", seriesText); + } + } else { + if (seriesName == null) { + seriesName = seriesText; + } + } + } + } + + AudiobookMetadata audiobookMetadata = AudiobookMetadata.builder() + .durationSeconds(durationSeconds) + .build(); + + return BookMetadata.builder() + .provider(MetadataProvider.Audible) + .audibleId(audibleId) + .title(title) + .subtitle(subtitle) + .authors(authors) + .categories(categories) + .description(description) + .seriesName(seriesName) + .seriesNumber(seriesNumber) + .publisher(publisher) + .publishedDate(publishedDate) + .language(language) + .thumbnailUrl(imageUrl) + .audibleRating(rating) + .audibleReviewCount(reviewCount) + .narrator(narrator) + .abridged(abridged) + .audiobookMetadata(audiobookMetadata) + .build(); + } + + private String getJsonString(JsonNode node, String field) { + if (node == null) return null; + JsonNode fieldNode = node.path(field); + if (fieldNode.isMissingNode() || fieldNode.isNull()) return null; + return fieldNode.asText(null); + } + + private Set extractPersonNames(JsonNode node, String field) { + Set names = new HashSet<>(); + if (node == null) return names; + + JsonNode fieldNode = node.path(field); + if (fieldNode.isMissingNode()) return names; + + if (fieldNode.isArray()) { + for (JsonNode person : fieldNode) { + String name = person.path("name").asText(null); + if (name != null && !name.isEmpty()) { + names.add(name); + } + } + } else if (fieldNode.isObject()) { + String name = fieldNode.path("name").asText(null); + if (name != null && !name.isEmpty()) { + names.add(name); + } + } + + return names; + } + + private String extractFirstPersonName(JsonNode node, String field) { + if (node == null) return null; + + JsonNode fieldNode = node.path(field); + if (fieldNode.isMissingNode()) return null; + + if (fieldNode.isArray() && fieldNode.size() > 0) { + return fieldNode.get(0).path("name").asText(null); + } else if (fieldNode.isObject()) { + return fieldNode.path("name").asText(null); + } + + return null; + } + + private Long parseIsoDuration(String duration) { + if (duration == null || duration.isEmpty()) return null; + + try { + Duration d = Duration.parse(duration); + return d.getSeconds(); + } catch (DateTimeParseException e) { + log.debug("Failed to parse ISO duration: {}", duration); + } + + return null; + } + + private String buildQueryUrl(FetchMetadataRequest request, Book book) { + String domain = getDomain(); + StringBuilder searchTerm = new StringBuilder(256); + + String title = request.getTitle(); + if (title != null && !title.isEmpty()) { + searchTerm.append(cleanSearchTerm(title)); + } else if (book.getPrimaryFile() != null && book.getPrimaryFile().getFileName() != null) { + String filename = BookUtils.cleanAndTruncateSearchTerm(BookUtils.cleanFileName(book.getPrimaryFile().getFileName())); + if (!filename.isEmpty()) { + searchTerm.append(cleanSearchTerm(filename)); + } + } + + String author = request.getAuthor(); + if (author != null && !author.isEmpty()) { + if (!searchTerm.isEmpty()) { + searchTerm.append(" "); + } + searchTerm.append(cleanSearchTerm(author)); + } + + if (searchTerm.isEmpty()) { + return null; + } + + String encodedSearchTerm = searchTerm.toString().replace(" ", "+"); + String url = "https://www.audible." + domain + "/search?keywords=" + encodedSearchTerm; + log.info("Audible Query URL: {}", url); + return url; + } + + private String cleanSearchTerm(String text) { + return Arrays.stream(text.split(" ")) + .map(word -> NON_ALPHANUMERIC_PATTERN.matcher(word).replaceAll("").trim()) + .filter(word -> !word.isEmpty()) + .collect(Collectors.joining(" ")); + } + + private Document fetchDocument(String url) { + try { + String domain = getDomain(); + LocaleInfo localeInfo = DOMAIN_LOCALE_MAP.getOrDefault(domain, DEFAULT_LOCALE_INFO); + + Connection connection = Jsoup.connect(url) + .header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") + .header("accept-language", localeInfo.acceptLanguage) + .header("cache-control", "no-cache") + .header("pragma", "no-cache") + .header("sec-ch-ua", "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not_A Brand\";v=\"24\"") + .header("sec-ch-ua-mobile", "?0") + .header("sec-ch-ua-platform", "\"macOS\"") + .header("sec-fetch-dest", "document") + .header("sec-fetch-mode", "navigate") + .header("sec-fetch-site", "none") + .header("sec-fetch-user", "?1") + .header("upgrade-insecure-requests", "1") + .header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36") + .timeout(30000) + .method(Connection.Method.GET); + + Connection.Response response = connection.execute(); + return response.parse(); + } catch (HttpStatusException e) { + log.error("HTTP error fetching Audible URL. Status={}, URL=[{}]", e.getStatusCode(), url); + throw new RuntimeException(e); + } catch (IOException e) { + log.error("Error fetching Audible URL: {}", url, e); + throw new RuntimeException(e); + } + } + + private void enforceRateLimit() { + long now = System.currentTimeMillis(); + long lastRequest = lastRequestTime.get(); + long elapsed = now - lastRequest; + + if (elapsed < MIN_REQUEST_INTERVAL_MS) { + try { + Thread.sleep(MIN_REQUEST_INTERVAL_MS - elapsed); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + lastRequestTime.set(System.currentTimeMillis()); + } + + private String getDomain() { + var settings = appSettingService.getAppSettings().getMetadataProviderSettings(); + if (settings != null && settings.getAudible() != null && settings.getAudible().getDomain() != null) { + return settings.getAudible().getDomain(); + } + return DEFAULT_DOMAIN; + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/writer/AudiobookMetadataWriter.java b/booklore-api/src/main/java/org/booklore/service/metadata/writer/AudiobookMetadataWriter.java new file mode 100644 index 000000000..072fd2b97 --- /dev/null +++ b/booklore-api/src/main/java/org/booklore/service/metadata/writer/AudiobookMetadataWriter.java @@ -0,0 +1,346 @@ +package org.booklore.service.metadata.writer; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.booklore.model.MetadataClearFlags; +import org.booklore.model.dto.settings.MetadataPersistenceSettings; +import org.booklore.model.entity.BookEntity; +import org.booklore.model.entity.BookFileEntity; +import org.booklore.model.entity.BookMetadataEntity; +import org.booklore.model.enums.BookFileType; +import org.booklore.service.appsettings.AppSettingService; +import org.jaudiotagger.audio.AudioFile; +import org.jaudiotagger.audio.AudioFileIO; +import org.jaudiotagger.tag.FieldKey; +import org.jaudiotagger.tag.Tag; +import org.jaudiotagger.tag.images.Artwork; +import org.jaudiotagger.tag.images.ArtworkFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import java.io.*; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.logging.Level; +import java.util.logging.Logger; + +@Slf4j +@Component +@RequiredArgsConstructor +public class AudiobookMetadataWriter implements MetadataWriter { + + static { + Logger.getLogger("org.jaudiotagger").setLevel(Level.WARNING); + } + + private final AppSettingService appSettingService; + + @Override + public void saveMetadataToFile(File audioFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) { + if (audioFile.isDirectory()) { + if (StringUtils.isNotBlank(thumbnailUrl)) { + byte[] coverData = loadImage(thumbnailUrl); + if (coverData != null) { + saveCoverToFolder(audioFile.toPath(), coverData); + } + } + return; + } + + if (!shouldSaveMetadataToFile(audioFile)) { + return; + } + + File backupFile = new File(audioFile.getParentFile(), audioFile.getName() + ".bak"); + try { + Files.copy(audioFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ex) { + log.warn("Failed to create backup of audiobook {}: {}", audioFile.getName(), ex.getMessage()); + return; + } + + try { + AudioFile f = AudioFileIO.read(audioFile); + Tag tag = f.getTagOrCreateAndSetDefault(); + + boolean[] hasChanges = {false}; + MetadataCopyHelper helper = new MetadataCopyHelper(metadata); + + helper.copyTitle(clear != null && clear.isTitle(), val -> { + setTagField(tag, FieldKey.ALBUM, val, hasChanges); + setTagField(tag, FieldKey.TITLE, val, hasChanges); + }); + + helper.copyAuthors(clear != null && clear.isAuthors(), authors -> { + String authorStr = authors != null ? String.join("; ", authors) : null; + setTagField(tag, FieldKey.ALBUM_ARTIST, authorStr, hasChanges); + setTagField(tag, FieldKey.ARTIST, authorStr, hasChanges); + }); + + if (StringUtils.isNotBlank(metadata.getNarrator())) { + setTagField(tag, FieldKey.COMPOSER, metadata.getNarrator(), hasChanges); + } + + helper.copyDescription(clear != null && clear.isDescription(), val -> { + setTagField(tag, FieldKey.COMMENT, val, hasChanges); + }); + + helper.copyPublisher(clear != null && clear.isPublisher(), val -> { + setTagField(tag, FieldKey.RECORD_LABEL, val, hasChanges); + }); + + helper.copyPublishedDate(clear != null && clear.isPublishedDate(), val -> { + String year = val != null ? String.valueOf(val.getYear()) : null; + setTagField(tag, FieldKey.YEAR, year, hasChanges); + }); + + helper.copyCategories(clear != null && clear.isCategories(), categories -> { + String genre = categories != null && !categories.isEmpty() + ? String.join("; ", categories) + : null; + setTagField(tag, FieldKey.GENRE, genre, hasChanges); + }); + + helper.copyLanguage(clear != null && clear.isLanguage(), val -> { + setTagField(tag, FieldKey.LANGUAGE, val, hasChanges); + }); + + helper.copySeriesName(clear != null && clear.isSeriesName(), val -> { + setTagField(tag, FieldKey.GROUPING, val, hasChanges); + }); + + helper.copySeriesNumber(clear != null && clear.isSeriesNumber(), val -> { + String trackNo = val != null ? String.format("%.0f", val) : null; + setTagField(tag, FieldKey.TRACK, trackNo, hasChanges); + }); + + helper.copySeriesTotal(clear != null && clear.isSeriesTotal(), val -> { + String trackTotal = val != null ? String.valueOf(val) : null; + setTagField(tag, FieldKey.TRACK_TOTAL, trackTotal, hasChanges); + }); + + if (StringUtils.isNotBlank(thumbnailUrl)) { + byte[] coverData = loadImage(thumbnailUrl); + if (coverData != null) { + try { + tag.deleteArtworkField(); + Artwork artwork = ArtworkFactory.getNew(); + artwork.setBinaryData(coverData); + artwork.setMimeType(detectMimeType(coverData)); + tag.setField(artwork); + hasChanges[0] = true; + } catch (Exception e) { + log.warn("Failed to set cover art for {}: {}", audioFile.getName(), e.getMessage()); + } + } + } + + if (hasChanges[0]) { + f.commit(); + log.info("Metadata updated in audiobook: {}", audioFile.getName()); + } else { + log.debug("No changes detected. Skipping audiobook write for: {}", audioFile.getName()); + } + + } catch (Exception e) { + log.warn("Failed to write metadata to audiobook file {}: {}", audioFile.getName(), e.getMessage(), e); + if (backupFile.exists()) { + try { + Files.copy(backupFile.toPath(), audioFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + log.info("Restored audiobook from backup: {}", audioFile.getName()); + } catch (IOException io) { + log.error("Failed to restore audiobook from backup for {}: {}", audioFile.getName(), io.getMessage(), io); + } + } + } finally { + if (backupFile.exists()) { + try { + Files.delete(backupFile.toPath()); + } catch (IOException ex) { + log.warn("Failed to delete backup for {}: {}", audioFile.getName(), ex.getMessage()); + } + } + } + } + + public void saveCoverToFolder(Path folderPath, byte[] coverData) { + if (coverData == null || coverData.length == 0 || folderPath == null) { + return; + } + + try { + String extension = detectImageExtension(coverData); + String filename = "cover" + extension; + Path coverPath = folderPath.resolve(filename); + + deleteExistingCovers(folderPath); + + Files.write(coverPath, coverData); + log.info("Cover image saved to folder: {}", coverPath); + } catch (IOException e) { + log.warn("Failed to save cover to folder {}: {}", folderPath, e.getMessage()); + } + } + + private void deleteExistingCovers(Path folderPath) throws IOException { + String[] coverNames = {"cover.jpg", "cover.jpeg", "cover.png", "folder.jpg", "folder.jpeg", "folder.png"}; + for (String name : coverNames) { + Path existing = folderPath.resolve(name); + Files.deleteIfExists(existing); + } + } + + private String detectImageExtension(byte[] data) { + if (data.length > 3 && data[0] == (byte) 0x89 && data[1] == (byte) 0x50 && data[2] == (byte) 0x4E && data[3] == (byte) 0x47) { + return ".png"; + } + return ".jpg"; + } + + private void setTagField(Tag tag, FieldKey key, String value, boolean[] hasChanges) { + try { + String existingValue = tag.getFirst(key); + if (value == null || value.isBlank()) { + if (StringUtils.isNotBlank(existingValue)) { + tag.deleteField(key); + hasChanges[0] = true; + } + } else if (!value.equals(existingValue)) { + tag.setField(key, value); + hasChanges[0] = true; + } + } catch (Exception e) { + log.debug("Failed to set tag field {}: {}", key, e.getMessage()); + } + } + + @Override + public void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] coverData) { + if (coverData == null || coverData.length == 0) { + log.warn("Cover update failed: empty or null byte array."); + return; + } + + BookFileEntity audioFile = getAudiobookFile(bookEntity); + if (audioFile == null) { + return; + } + + if (audioFile.isFolderBased()) { + Path folderPath = audioFile.getFullFilePath(); + saveCoverToFolder(folderPath, coverData); + } else { + File file = audioFile.getFullFilePath().toFile(); + if (!shouldSaveMetadataToFile(file)) { + return; + } + replaceCoverImageInternal(file, coverData, "byte array"); + } + } + + @Override + public void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile multipartFile) { + if (multipartFile == null || multipartFile.isEmpty()) { + log.warn("Cover upload failed: empty or null file."); + return; + } + + try { + byte[] coverData = multipartFile.getBytes(); + replaceCoverImageFromBytes(bookEntity, coverData); + } catch (IOException e) { + log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e); + } + } + + @Override + public void replaceCoverImageFromUrl(BookEntity bookEntity, String url) { + if (url == null || url.isBlank()) { + log.warn("Cover update via URL failed: empty or null URL."); + return; + } + + byte[] coverData = loadImage(url); + if (coverData == null) { + log.warn("Failed to load image from URL: {}", url); + return; + } + + replaceCoverImageFromBytes(bookEntity, coverData); + } + + private void replaceCoverImageInternal(File audioFile, byte[] coverData, String source) { + try { + AudioFile f = AudioFileIO.read(audioFile); + Tag tag = f.getTagOrCreateAndSetDefault(); + + tag.deleteArtworkField(); + Artwork artwork = ArtworkFactory.getNew(); + artwork.setBinaryData(coverData); + artwork.setMimeType(detectMimeType(coverData)); + tag.setField(artwork); + f.commit(); + + log.info("Cover image updated in audiobook from {}: {}", source, audioFile.getName()); + } catch (Exception e) { + log.warn("Failed to update audiobook cover image from {}: {}", source, e.getMessage(), e); + } + } + + private BookFileEntity getAudiobookFile(BookEntity bookEntity) { + if (bookEntity == null || bookEntity.getBookFiles() == null) { + return null; + } + return bookEntity.getBookFiles().stream() + .filter(bf -> bf.getBookType() == BookFileType.AUDIOBOOK) + .findFirst() + .orElse(null); + } + + @Override + public BookFileType getSupportedBookType() { + return BookFileType.AUDIOBOOK; + } + + @Override + public boolean shouldSaveMetadataToFile(File audioFile) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings() + .getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings audiobookSettings = settings.getAudiobook(); + if (audiobookSettings == null || !audiobookSettings.isEnabled()) { + log.debug("Audiobook metadata writing is disabled. Skipping: {}", audioFile.getName()); + return false; + } + + long fileSizeInMb = audioFile.length() / (1024 * 1024); + if (fileSizeInMb > audiobookSettings.getMaxFileSizeInMb()) { + log.info("Audiobook file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", + audioFile.getName(), fileSizeInMb, audiobookSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } + + private byte[] loadImage(String pathOrUrl) { + try (InputStream stream = pathOrUrl.startsWith("http") + ? URI.create(pathOrUrl).toURL().openStream() + : new FileInputStream(pathOrUrl)) { + return stream.readAllBytes(); + } catch (IOException e) { + log.warn("Failed to load image from {}: {}", pathOrUrl, e.getMessage()); + return null; + } + } + + private String detectMimeType(byte[] data) { + if (data.length > 3 && data[0] == (byte) 0x89 && data[1] == (byte) 0x50 && data[2] == (byte) 0x4E && data[3] == (byte) 0x47) { + return "image/png"; + } + return "image/jpeg"; + } +} diff --git a/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java b/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java index 9c0f88b55..ac1d4ba1e 100644 --- a/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java +++ b/booklore-api/src/main/java/org/booklore/service/progress/ReadingProgressService.java @@ -35,7 +35,7 @@ import java.util.stream.Collectors; @Service public class ReadingProgressService { - private static final float READING_THRESHOLD = 0.5f; + private static final float READING_THRESHOLD = 0.1f; private static final float COMPLETED_THRESHOLD = 99.5f; private final UserBookProgressRepository userBookProgressRepository; @@ -233,7 +233,7 @@ public class ReadingProgressService { } if (percentage != null) { - progress.setReadStatus(calculateReadStatus(percentage)); + progress.setReadStatus(calculateReadStatus(percentage, progress.getReadStatus())); BookFileEntity primaryFile = book.getPrimaryBookFile(); if (primaryFile != null) { setProgressPercent(progress, primaryFile.getBookType(), percentage); @@ -399,10 +399,32 @@ public class ReadingProgressService { } } - private ReadStatus calculateReadStatus(Float percentage) { - if (percentage >= COMPLETED_THRESHOLD) return ReadStatus.READ; - if (percentage > READING_THRESHOLD) return ReadStatus.READING; - return ReadStatus.UNREAD; + private ReadStatus calculateReadStatus(Float percentage, ReadStatus currentStatus) { + ReadStatus newStatus; + if (percentage >= COMPLETED_THRESHOLD) { + newStatus = ReadStatus.READ; + } else if (percentage > READING_THRESHOLD) { + newStatus = ReadStatus.READING; + } else { + newStatus = ReadStatus.UNREAD; + } + + // Only allow automatic status changes that represent progress upgrades + // Don't downgrade from manually set or higher progress statuses + if (newStatus == ReadStatus.UNREAD) { + // Preserve any status that indicates the user has engaged with the book + if (currentStatus == ReadStatus.READING || + currentStatus == ReadStatus.RE_READING || + currentStatus == ReadStatus.READ || + currentStatus == ReadStatus.PARTIALLY_READ || + currentStatus == ReadStatus.PAUSED || + currentStatus == ReadStatus.ABANDONED || + currentStatus == ReadStatus.WONT_READ) { + return currentStatus; + } + } + + return newStatus; } private void performReset(Long userId, Set bookIds, ResetProgressType type, Instant now) { diff --git a/booklore-api/src/main/java/org/booklore/service/reader/AudioMetadataService.java b/booklore-api/src/main/java/org/booklore/service/reader/AudioMetadataService.java index 57aea6bfe..9fefeb455 100644 --- a/booklore-api/src/main/java/org/booklore/service/reader/AudioMetadataService.java +++ b/booklore-api/src/main/java/org/booklore/service/reader/AudioMetadataService.java @@ -4,8 +4,7 @@ import org.booklore.model.dto.response.AudiobookChapter; import org.booklore.model.dto.response.AudiobookInfo; import org.booklore.model.dto.response.AudiobookTrack; import org.booklore.model.entity.BookFileEntity; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; +import org.booklore.model.entity.BookMetadataEntity; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.jaudiotagger.audio.AudioFile; @@ -16,180 +15,77 @@ import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.images.Artwork; import org.springframework.stereotype.Service; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Comparator; import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Stream; +import java.util.stream.Collectors; @Slf4j @Service @RequiredArgsConstructor public class AudioMetadataService { - private static final int MAX_CACHE_ENTRIES = 50; - private final AudioFileUtilityService audioFileUtility; - private final Map metadataCache = new ConcurrentHashMap<>(); - - private static class CachedAudiobookMetadata { - final AudiobookInfo info; - final long lastModified; - volatile long lastAccessed; - - CachedAudiobookMetadata(AudiobookInfo info, long lastModified) { - this.info = info; - this.lastModified = lastModified; - this.lastAccessed = System.currentTimeMillis(); - } - } public AudiobookInfo getMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { - CachedAudiobookMetadata metadata = getCachedMetadata(bookFile, audioPath); - return metadata.info; - } - - public byte[] getEmbeddedCoverArt(Path audioPath) { - try { - AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); - Tag tag = audioFile.getTag(); - if (tag != null) { - Artwork artwork = tag.getFirstArtwork(); - if (artwork != null) { - return artwork.getBinaryData(); - } - } - } catch (Exception e) { - log.debug("No embedded cover art found: {}", e.getMessage()); - } - return null; - } - - public String getCoverArtMimeType(Path audioPath) { - try { - AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); - Tag tag = audioFile.getTag(); - if (tag != null) { - Artwork artwork = tag.getFirstArtwork(); - if (artwork != null) { - String mimeType = artwork.getMimeType(); - if (mimeType != null && !mimeType.isEmpty()) { - return mimeType; - } - byte[] data = artwork.getBinaryData(); - if (data != null && data.length > 2) { - if (data[0] == (byte) 0xFF && data[1] == (byte) 0xD8) { - return "image/jpeg"; - } else if (data[0] == (byte) 0x89 && data[1] == (byte) 0x50) { - return "image/png"; - } - } - return "image/jpeg"; - } - } - } catch (Exception e) { - log.debug("Could not determine cover art MIME type: {}", e.getMessage()); - } - return "image/jpeg"; - } - - private CachedAudiobookMetadata getCachedMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { - String cacheKey = audioPath.toString(); - long currentModified = getLastModified(bookFile, audioPath); - CachedAudiobookMetadata cached = metadataCache.get(cacheKey); - - if (cached != null && cached.lastModified == currentModified) { - cached.lastAccessed = System.currentTimeMillis(); - log.debug("Cache hit for audiobook: {}", audioPath.getFileName()); - return cached; - } - - log.debug("Cache miss for audiobook: {}, parsing...", audioPath.getFileName()); - AudiobookInfo info = parseAudiobookMetadata(bookFile, audioPath); - CachedAudiobookMetadata newMetadata = new CachedAudiobookMetadata(info, currentModified); - metadataCache.put(cacheKey, newMetadata); - evictOldestCacheEntries(); - return newMetadata; - } - - private long getLastModified(BookFileEntity bookFile, Path audioPath) throws IOException { if (bookFile.isFolderBased()) { - try (Stream files = Files.list(audioPath)) { - return files.filter(audioFileUtility::isAudioFile) - .mapToLong(p -> { - try { - return Files.getLastModifiedTime(p).toMillis(); - } catch (IOException e) { - return 0; - } - }) - .max() - .orElse(Files.getLastModifiedTime(audioPath).toMillis()); - } + return buildFolderBasedAudiobookInfo(bookFile, audioPath); + } else { + return buildSingleFileAudiobookInfo(bookFile, audioPath); } - return Files.getLastModifiedTime(audioPath).toMillis(); } - private void evictOldestCacheEntries() { - if (metadataCache.size() <= MAX_CACHE_ENTRIES) { - return; - } - List keysToRemove = metadataCache.entrySet().stream() - .sorted(Comparator.comparingLong(e -> e.getValue().lastAccessed)) - .limit(metadataCache.size() - MAX_CACHE_ENTRIES) - .map(Map.Entry::getKey) - .toList(); - keysToRemove.forEach(key -> { - metadataCache.remove(key); - log.debug("Evicted audiobook cache entry: {}", key); - }); - } - - private AudiobookInfo parseAudiobookMetadata(BookFileEntity bookFile, Path audioPath) throws Exception { + private AudiobookInfo buildSingleFileAudiobookInfo(BookFileEntity bookFile, Path audioPath) throws Exception { AudiobookInfo.AudiobookInfoBuilder builder = AudiobookInfo.builder() .bookId(bookFile.getBook().getId()) .bookFileId(bookFile.getId()) - .folderBased(bookFile.isFolderBased()); + .folderBased(false); - if (bookFile.isFolderBased()) { - return parseFolderBasedAudiobook(builder, audioPath); - } else { - return parseSingleFileAudiobook(builder, audioPath); - } - } + if (bookFile.getDurationSeconds() != null) { + BookMetadataEntity metadata = bookFile.getBook().getMetadata(); + String narrator = metadata != null ? metadata.getNarrator() : null; - private AudiobookInfo parseSingleFileAudiobook(AudiobookInfo.AudiobookInfoBuilder builder, Path audioPath) throws Exception { - AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); - AudioHeader header = audioFile.getAudioHeader(); - Tag tag = audioFile.getTag(); + builder.narrator(narrator) + .durationMs(bookFile.getDurationSeconds() * 1000) + .bitrate(bookFile.getBitrate()) + .sampleRate(bookFile.getSampleRate()) + .channels(bookFile.getChannels()) + .codec(bookFile.getCodec()); - long durationMs = (long) (header.getPreciseTrackLength() * 1000); - long bitrateValue = header.getBitRateAsNumber(); - builder.durationMs(durationMs) - .bitrate(bitrateValue > 0 ? (int) bitrateValue : null) - .codec(header.getEncodingType()) - .sampleRate(header.getSampleRateAsNumber()) - .channels(parseChannels(header.getChannels())); + if (bookFile.getChapters() != null && !bookFile.getChapters().isEmpty()) { + List chapters = bookFile.getChapters().stream() + .map(ch -> AudiobookChapter.builder() + .index(ch.getIndex()) + .title(ch.getTitle()) + .startTimeMs(ch.getStartTimeMs()) + .endTimeMs(ch.getEndTimeMs()) + .durationMs(ch.getDurationMs()) + .build()) + .collect(Collectors.toList()); + builder.chapters(chapters); + } - if (tag != null) { - builder.title(getTagValue(tag, FieldKey.TITLE, FieldKey.ALBUM)) - .author(getTagValue(tag, FieldKey.ARTIST, FieldKey.ALBUM_ARTIST)) - .narrator(getTagValue(tag, FieldKey.COMPOSER)); + if (metadata != null) { + builder.title(metadata.getTitle()); + if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) { + builder.author(metadata.getAuthors().iterator().next().getName()); + } + } + + return builder.build(); } - List chapters = extractChapters(audioPath, durationMs); - builder.chapters(chapters); - - return builder.build(); + log.debug("No DB metadata found for audiobook {}, extracting from file", bookFile.getId()); + return extractSingleFileMetadata(builder, audioPath); } - private AudiobookInfo parseFolderBasedAudiobook(AudiobookInfo.AudiobookInfoBuilder builder, Path folderPath) throws Exception { + private AudiobookInfo buildFolderBasedAudiobookInfo(BookFileEntity bookFile, Path folderPath) throws Exception { + AudiobookInfo.AudiobookInfoBuilder builder = AudiobookInfo.builder() + .bookId(bookFile.getBook().getId()) + .bookFileId(bookFile.getId()) + .folderBased(true); + List audioFiles = audioFileUtility.listAudioFiles(folderPath); if (audioFiles.isEmpty()) { throw new IllegalStateException("No audio files found in folder: " + folderPath); @@ -258,140 +154,129 @@ public class AudioMetadataService { } } + BookMetadataEntity metadata = bookFile.getBook().getMetadata(); + if (metadata != null && metadata.getNarrator() != null) { + builder.narrator(metadata.getNarrator()); + } else { + builder.narrator(narrator); + } + + if (bookFile.getBitrate() != null) { + builder.bitrate(bookFile.getBitrate()); + } else { + builder.bitrate(bitrate); + } + + if (bookFile.getCodec() != null) { + builder.codec(bookFile.getCodec()); + } else { + builder.codec(codec); + } + + if (bookFile.getSampleRate() != null) { + builder.sampleRate(bookFile.getSampleRate()); + } else { + builder.sampleRate(sampleRate); + } + + if (bookFile.getChannels() != null) { + builder.channels(bookFile.getChannels()); + } else { + builder.channels(channels); + } + + if (metadata != null) { + String bookTitle = metadata.getTitle(); + if (bookTitle != null) { + title = bookTitle; + } + if (metadata.getAuthors() != null && !metadata.getAuthors().isEmpty()) { + author = metadata.getAuthors().iterator().next().getName(); + } + } + return builder .title(title) .author(author) - .narrator(narrator) .durationMs(totalDurationMs) - .bitrate(bitrate) - .codec(codec) - .sampleRate(sampleRate) - .channels(channels) .tracks(tracks) .build(); } - private List extractChapters(Path audioPath, long totalDurationMs) { - List chapters = new ArrayList<>(); + private AudiobookInfo extractSingleFileMetadata(AudiobookInfo.AudiobookInfoBuilder builder, Path audioPath) throws Exception { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + AudioHeader header = audioFile.getAudioHeader(); + Tag tag = audioFile.getTag(); - try { - chapters = extractChaptersWithFFprobe(audioPath); - if (!chapters.isEmpty()) { - log.debug("Extracted {} chapters from {} using FFprobe", chapters.size(), audioPath.getFileName()); - return chapters; - } - } catch (Exception e) { - log.debug("FFprobe chapter extraction failed for {}: {}", audioPath.getFileName(), e.getMessage()); + long durationMs = (long) (header.getPreciseTrackLength() * 1000); + long bitrateValue = header.getBitRateAsNumber(); + builder.durationMs(durationMs) + .bitrate(bitrateValue > 0 ? (int) bitrateValue : null) + .codec(header.getEncodingType()) + .sampleRate(header.getSampleRateAsNumber()) + .channels(parseChannels(header.getChannels())); + + if (tag != null) { + builder.title(getTagValue(tag, FieldKey.TITLE, FieldKey.ALBUM)) + .author(getTagValue(tag, FieldKey.ARTIST, FieldKey.ALBUM_ARTIST)) + .narrator(getTagValue(tag, FieldKey.COMPOSER)); } + List chapters = new ArrayList<>(); chapters.add(AudiobookChapter.builder() .index(0) .title("Full Audiobook") .startTimeMs(0L) - .endTimeMs(totalDurationMs) - .durationMs(totalDurationMs) + .endTimeMs(durationMs) + .durationMs(durationMs) .build()); + builder.chapters(chapters); - return chapters; + return builder.build(); } - private List extractChaptersWithFFprobe(Path audioPath) throws Exception { - List chapters = new ArrayList<>(); - - ProcessBuilder pb = new ProcessBuilder( - "ffprobe", - "-v", "quiet", - "-print_format", "json", - "-show_chapters", - audioPath.toAbsolutePath().toString() - ); - pb.redirectErrorStream(true); - - Process process = pb.start(); - StringBuilder output = new StringBuilder(); - - try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { - String line; - while ((line = reader.readLine()) != null) { - output.append(line); + public byte[] getEmbeddedCoverArt(Path audioPath) { + try { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + Tag tag = audioFile.getTag(); + if (tag != null) { + Artwork artwork = tag.getFirstArtwork(); + if (artwork != null) { + return artwork.getBinaryData(); + } } + } catch (Exception e) { + log.debug("No embedded cover art found: {}", e.getMessage()); } - - int exitCode = process.waitFor(); - if (exitCode != 0) { - log.debug("FFprobe exited with code {} for {}", exitCode, audioPath.getFileName()); - return chapters; - } - - String jsonOutput = output.toString().trim(); - if (jsonOutput.isEmpty() || jsonOutput.equals("{}")) { - return chapters; - } - - ObjectMapper mapper = new ObjectMapper(); - JsonNode root = mapper.readTree(jsonOutput); - JsonNode chaptersNode = root.get("chapters"); - - if (chaptersNode == null || !chaptersNode.isArray() || chaptersNode.isEmpty()) { - return chapters; - } - - for (int i = 0; i < chaptersNode.size(); i++) { - JsonNode chapterNode = chaptersNode.get(i); - - double startTime = 0; - double endTime = 0; - - if (chapterNode.has("start_time")) { - startTime = chapterNode.get("start_time").asDouble(); - } else if (chapterNode.has("start")) { - long start = chapterNode.get("start").asLong(); - String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; - startTime = convertTimebaseToSeconds(start, timeBase); - } - - if (chapterNode.has("end_time")) { - endTime = chapterNode.get("end_time").asDouble(); - } else if (chapterNode.has("end")) { - long end = chapterNode.get("end").asLong(); - String timeBase = chapterNode.has("time_base") ? chapterNode.get("time_base").asText() : "1/1000"; - endTime = convertTimebaseToSeconds(end, timeBase); - } - - long startTimeMs = Math.round(startTime * 1000); - long endTimeMs = Math.round(endTime * 1000); - long durationMs = endTimeMs - startTimeMs; - - String title = "Chapter " + (i + 1); - JsonNode tagsNode = chapterNode.get("tags"); - if (tagsNode != null && tagsNode.has("title")) { - title = tagsNode.get("title").asText(); - } - - chapters.add(AudiobookChapter.builder() - .index(i) - .title(title) - .startTimeMs(startTimeMs) - .endTimeMs(endTimeMs) - .durationMs(durationMs) - .build()); - } - - return chapters; + return null; } - private double convertTimebaseToSeconds(long value, String timeBase) { - String[] parts = timeBase.split("/"); - if (parts.length == 2) { - try { - double numerator = Double.parseDouble(parts[0]); - double denominator = Double.parseDouble(parts[1]); - return value * (numerator / denominator); - } catch (NumberFormatException e) { - return value / 1000.0; + public String getCoverArtMimeType(Path audioPath) { + try { + AudioFile audioFile = AudioFileIO.read(audioPath.toFile()); + Tag tag = audioFile.getTag(); + if (tag != null) { + Artwork artwork = tag.getFirstArtwork(); + if (artwork != null) { + String mimeType = artwork.getMimeType(); + if (mimeType != null && !mimeType.isEmpty()) { + return mimeType; + } + byte[] data = artwork.getBinaryData(); + if (data != null && data.length > 2) { + if (data[0] == (byte) 0xFF && data[1] == (byte) 0xD8) { + return "image/jpeg"; + } else if (data[0] == (byte) 0x89 && data[1] == (byte) 0x50) { + return "image/png"; + } + } + return "image/jpeg"; + } } + } catch (Exception e) { + log.debug("Could not determine cover art MIME type: {}", e.getMessage()); } - return value / 1000.0; + return "image/jpeg"; } private String getTagValue(Tag tag, FieldKey... keys) { diff --git a/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java b/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java index 4b64ef227..48e662e2e 100644 --- a/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java +++ b/booklore-api/src/main/java/org/booklore/service/upload/FileUploadService.java @@ -61,13 +61,13 @@ public class FileUploadService { final LibraryEntity libraryEntity = findLibraryById(libraryId); final LibraryPathEntity libraryPathEntity = findLibraryPathById(libraryEntity, pathId); final String originalFileName = getValidatedFileName(file); + final BookFileExtension fileExtension = getFileExtension(originalFileName); + validateAllowedFormat(libraryEntity, fileExtension.getType()); Path tempPath = null; try { tempPath = createTempFile(UPLOAD_TEMP_PREFIX, originalFileName); file.transferTo(tempPath); - - final BookFileExtension fileExtension = getFileExtension(originalFileName); final BookMetadata metadata = extractMetadata(fileExtension, tempPath.toFile(), originalFileName); final String uploadPattern = fileMovingHelper.getFileNamingPattern(libraryEntity); @@ -359,4 +359,11 @@ public class FileUploadService { throw ApiError.FILE_TOO_LARGE.createException(maxSizeMb); } } + + private void validateAllowedFormat(LibraryEntity library, BookFileType fileType) { + var allowedFormats = library.getAllowedFormats(); + if (allowedFormats != null && !allowedFormats.isEmpty() && !allowedFormats.contains(fileType)) { + throw ApiError.FORMAT_NOT_ALLOWED.createException(fileType.name(), library.getName()); + } + } } diff --git a/booklore-api/src/main/java/org/booklore/util/FileService.java b/booklore-api/src/main/java/org/booklore/util/FileService.java index 33d33d004..cd5c35013 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileService.java +++ b/booklore-api/src/main/java/org/booklore/util/FileService.java @@ -4,7 +4,6 @@ import org.booklore.config.AppProperties; import org.booklore.exception.ApiError; import org.booklore.model.dto.settings.CoverCroppingSettings; import org.booklore.model.entity.BookMetadataEntity; -import org.booklore.repository.BookMetadataRepository; import org.booklore.service.appsettings.AppSettingService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -39,27 +38,30 @@ public class FileService { private final AppProperties appProperties; private final RestTemplate restTemplate; private final AppSettingService appSettingService; - private final BookMetadataRepository bookMetadataRepository; private static final double TARGET_COVER_ASPECT_RATIO = 1.5; private static final int SMART_CROP_COLOR_TOLERANCE = 30; private static final double SMART_CROP_MARGIN_PERCENT = 0.02; // @formatter:off - private static final String IMAGES_DIR = "images"; - private static final String BACKGROUNDS_DIR = "backgrounds"; - private static final String ICONS_DIR = "icons"; - private static final String SVG_DIR = "svg"; - private static final String THUMBNAIL_FILENAME = "thumbnail.jpg"; - private static final String COVER_FILENAME = "cover.jpg"; - private static final String JPEG_MIME_TYPE = "image/jpeg"; - private static final String PNG_MIME_TYPE = "image/png"; - private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; - private static final int THUMBNAIL_WIDTH = 250; - private static final int THUMBNAIL_HEIGHT = 350; - private static final int MAX_ORIGINAL_WIDTH = 1000; - private static final int MAX_ORIGINAL_HEIGHT = 1500; - private static final String IMAGE_FORMAT = "JPEG"; + private static final String IMAGES_DIR = "images"; + private static final String BACKGROUNDS_DIR = "backgrounds"; + private static final String ICONS_DIR = "icons"; + private static final String SVG_DIR = "svg"; + private static final String THUMBNAIL_FILENAME = "thumbnail.jpg"; + private static final String COVER_FILENAME = "cover.jpg"; + private static final String AUDIOBOOK_THUMBNAIL_FILENAME = "audiobook-thumbnail.jpg"; + private static final String AUDIOBOOK_COVER_FILENAME = "audiobook-cover.jpg"; + private static final String JPEG_MIME_TYPE = "image/jpeg"; + private static final String PNG_MIME_TYPE = "image/png"; + private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; + private static final int THUMBNAIL_WIDTH = 250; + private static final int THUMBNAIL_HEIGHT = 350; + private static final int SQUARE_THUMBNAIL_SIZE = 250; + private static final int MAX_ORIGINAL_WIDTH = 1000; + private static final int MAX_ORIGINAL_HEIGHT = 1500; + private static final int MAX_SQUARE_SIZE = 1000; + private static final String IMAGE_FORMAT = "JPEG"; // @formatter:on // ======================================== @@ -78,6 +80,14 @@ public class FileService { return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), COVER_FILENAME).toString(); } + public String getAudiobookThumbnailFile(long bookId) { + return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), AUDIOBOOK_THUMBNAIL_FILENAME).toString(); + } + + public String getAudiobookCoverFile(long bookId) { + return Paths.get(appProperties.getPathConfig(), IMAGES_DIR, String.valueOf(bookId), AUDIOBOOK_COVER_FILENAME).toString(); + } + public String getBackgroundsFolder(Long userId) { if (userId != null) { return Paths.get(appProperties.getPathConfig(), BACKGROUNDS_DIR, "user-" + userId).toString(); @@ -282,6 +292,126 @@ public class FileService { } } + // ======================================== + // AUDIOBOOK COVER OPERATIONS + // ======================================== + + public void createAudiobookThumbnailFromFile(long bookId, MultipartFile file) { + try { + validateCoverFile(file); + BufferedImage originalImage; + try (InputStream inputStream = file.getInputStream()) { + originalImage = readImage(inputStream); + } + if (originalImage == null) { + log.warn("Could not decode image from file, skipping audiobook thumbnail creation for book: {}", bookId); + return; + } + boolean success = saveAudiobookCoverImages(originalImage, bookId); + if (!success) { + throw ApiError.FILE_READ_ERROR.createException("Failed to save audiobook cover images"); + } + originalImage.flush(); + log.info("Audiobook cover images created and saved for book ID: {}", bookId); + } catch (Exception e) { + log.error("An error occurred while creating the audiobook thumbnail: {}", e.getMessage(), e); + throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + } + } + + public void createAudiobookThumbnailFromBytes(long bookId, byte[] imageBytes) { + try { + BufferedImage originalImage = readImage(imageBytes); + if (originalImage == null) { + log.warn("Skipping audiobook thumbnail creation for book {}: image decode failed", bookId); + return; + } + boolean success = saveAudiobookCoverImages(originalImage, bookId); + if (!success) { + throw ApiError.FILE_READ_ERROR.createException("Failed to save audiobook cover images"); + } + originalImage.flush(); + log.info("Audiobook cover images created and saved from bytes for book ID: {}", bookId); + } catch (Exception e) { + log.error("An error occurred while creating audiobook thumbnail from bytes: {}", e.getMessage(), e); + throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + } + } + + public void createAudiobookThumbnailFromUrl(long bookId, String imageUrl) { + try { + BufferedImage originalImage = downloadImageFromUrl(imageUrl); + if (originalImage == null) { + log.warn("Skipping audiobook thumbnail creation for book {}: download/decode failed", bookId); + return; + } + boolean success = saveAudiobookCoverImages(originalImage, bookId); + if (!success) { + throw ApiError.FILE_READ_ERROR.createException("Failed to save audiobook cover images"); + } + originalImage.flush(); + log.info("Audiobook cover images created and saved from URL for book ID: {}", bookId); + } catch (Exception e) { + log.error("An error occurred while creating audiobook thumbnail from URL: {}", e.getMessage(), e); + throw ApiError.FILE_READ_ERROR.createException(e.getMessage()); + } + } + + public boolean saveAudiobookCoverImages(BufferedImage coverImage, long bookId) throws IOException { + BufferedImage rgbImage = null; + BufferedImage resized = null; + BufferedImage thumb = null; + try { + String folderPath = getImagesFolder(bookId); + File folder = new File(folderPath); + if (!folder.exists() && !folder.mkdirs()) { + throw new IOException("Failed to create directory: " + folder.getAbsolutePath()); + } + + rgbImage = new BufferedImage( + coverImage.getWidth(), + coverImage.getHeight(), + BufferedImage.TYPE_INT_RGB + ); + Graphics2D g = rgbImage.createGraphics(); + g.drawImage(coverImage, 0, 0, Color.WHITE, null); + g.dispose(); + + // Resize to square if needed, maintaining 1:1 aspect ratio + int size = Math.min(rgbImage.getWidth(), rgbImage.getHeight()); + int x = (rgbImage.getWidth() - size) / 2; + int y = (rgbImage.getHeight() - size) / 2; + BufferedImage cropped = rgbImage.getSubimage(x, y, size, size); + + // Resize if too large + if (size > MAX_SQUARE_SIZE) { + resized = resizeImage(cropped, MAX_SQUARE_SIZE, MAX_SQUARE_SIZE); + } else { + resized = cropped; + } + + File originalFile = new File(folder, AUDIOBOOK_COVER_FILENAME); + boolean originalSaved = ImageIO.write(resized, IMAGE_FORMAT, originalFile); + + // Create square thumbnail + thumb = resizeImage(resized, SQUARE_THUMBNAIL_SIZE, SQUARE_THUMBNAIL_SIZE); + File thumbnailFile = new File(folder, AUDIOBOOK_THUMBNAIL_FILENAME); + boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile); + + return originalSaved && thumbnailSaved; + } finally { + if (rgbImage != null) { + rgbImage.flush(); + } + if (resized != null && resized != rgbImage) { + resized.flush(); + } + if (thumb != null) { + thumb.flush(); + } + } + } + public boolean saveCoverImages(BufferedImage coverImage, long bookId) throws IOException { BufferedImage rgbImage = null; BufferedImage cropped = null; @@ -340,9 +470,6 @@ public class FileService { File thumbnailFile = new File(folder, THUMBNAIL_FILENAME); boolean thumbnailSaved = ImageIO.write(thumb, IMAGE_FORMAT, thumbnailFile); - if (originalSaved && thumbnailSaved) { - bookMetadataRepository.updateCoverTimestamp(bookId, Instant.now()); - } return originalSaved && thumbnailSaved; } finally { // Cleanup resources created within this method diff --git a/booklore-api/src/main/java/org/booklore/util/FileUtils.java b/booklore-api/src/main/java/org/booklore/util/FileUtils.java index cf8e166d4..e0811a8a5 100644 --- a/booklore-api/src/main/java/org/booklore/util/FileUtils.java +++ b/booklore-api/src/main/java/org/booklore/util/FileUtils.java @@ -33,6 +33,17 @@ public class FileUtils { .replace("\\", "/"); } + public String getBookFullPath(BookEntity bookEntity, BookFileEntity bookFile) { + if (bookFile == null || bookEntity.getLibraryPath() == null) { + return null; + } + + return Path.of(bookEntity.getLibraryPath().getPath(), bookFile.getFileSubPath(), bookFile.getFileName()) + .normalize() + .toString() + .replace("\\", "/"); + } + public String getBookFullPath(Book book) { return book.getPrimaryFile().getFilePath(); } diff --git a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java index fc826338b..c2aac11a4 100644 --- a/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java +++ b/booklore-api/src/main/java/org/booklore/util/MetadataChangeDetector.java @@ -1,158 +1,315 @@ package org.booklore.util; +import lombok.experimental.UtilityClass; import org.booklore.model.MetadataClearFlags; import org.booklore.model.dto.BookMetadata; import org.booklore.model.entity.*; -import lombok.experimental.UtilityClass; -import lombok.extern.slf4j.Slf4j; import java.util.*; -import java.util.function.BooleanSupplier; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Collectors; import static org.apache.commons.lang3.BooleanUtils.isTrue; @UtilityClass -@Slf4j public class MetadataChangeDetector { + private record FieldDescriptor( + String name, + Function dtoValueGetter, + Function entityValueGetter, + Function dtoLockGetter, + Function entityLockGetter, + Predicate clearFlagGetter, + boolean includedInFileWrite + ) { + boolean isUnlocked(BookMetadataEntity entity) { + return !isTrue(entityLockGetter.apply(entity)); + } + + boolean shouldClear(MetadataClearFlags flags) { + return clearFlagGetter.test(flags); + } + + T getNewValue(BookMetadata dto) { + return dtoValueGetter.apply(dto); + } + + T getOldValue(BookMetadataEntity entity) { + return entityValueGetter.apply(entity); + } + + Boolean getNewLock(BookMetadata dto) { + return dtoLockGetter != null ? dtoLockGetter.apply(dto) : null; + } + + Boolean getOldLock(BookMetadataEntity entity) { + return entityLockGetter != null ? entityLockGetter.apply(entity) : null; + } + } + + private record CollectionFieldDescriptor( + String name, + Function> dtoValueGetter, + Function> entityValueGetter, + Function dtoLockGetter, + Function entityLockGetter, + Predicate clearFlagGetter, + boolean includedInFileWrite + ) { + boolean isUnlocked(BookMetadataEntity entity) { + return !isTrue(entityLockGetter.apply(entity)); + } + + boolean shouldClear(MetadataClearFlags flags) { + return clearFlagGetter.test(flags); + } + + Set getNewValue(BookMetadata dto) { + return dtoValueGetter.apply(dto); + } + + Set getOldValue(BookMetadataEntity entity) { + return toNameSet(entityValueGetter.apply(entity)); + } + + Boolean getNewLock(BookMetadata dto) { + return dtoLockGetter != null ? dtoLockGetter.apply(dto) : null; + } + + Boolean getOldLock(BookMetadataEntity entity) { + return entityLockGetter != null ? entityLockGetter.apply(entity) : null; + } + } + + private static final List> SIMPLE_FIELDS = List.of( + new FieldDescriptor<>("title", + BookMetadata::getTitle, BookMetadataEntity::getTitle, + BookMetadata::getTitleLocked, BookMetadataEntity::getTitleLocked, + MetadataClearFlags::isTitle, true), + new FieldDescriptor<>("subtitle", + BookMetadata::getSubtitle, BookMetadataEntity::getSubtitle, + BookMetadata::getSubtitleLocked, BookMetadataEntity::getSubtitleLocked, + MetadataClearFlags::isSubtitle, true), + new FieldDescriptor<>("publisher", + BookMetadata::getPublisher, BookMetadataEntity::getPublisher, + BookMetadata::getPublisherLocked, BookMetadataEntity::getPublisherLocked, + MetadataClearFlags::isPublisher, true), + new FieldDescriptor<>("publishedDate", + BookMetadata::getPublishedDate, BookMetadataEntity::getPublishedDate, + BookMetadata::getPublishedDateLocked, BookMetadataEntity::getPublishedDateLocked, + MetadataClearFlags::isPublishedDate, true), + new FieldDescriptor<>("description", + BookMetadata::getDescription, BookMetadataEntity::getDescription, + BookMetadata::getDescriptionLocked, BookMetadataEntity::getDescriptionLocked, + MetadataClearFlags::isDescription, true), + new FieldDescriptor<>("seriesName", + BookMetadata::getSeriesName, BookMetadataEntity::getSeriesName, + BookMetadata::getSeriesNameLocked, BookMetadataEntity::getSeriesNameLocked, + MetadataClearFlags::isSeriesName, true), + new FieldDescriptor<>("seriesNumber", + BookMetadata::getSeriesNumber, BookMetadataEntity::getSeriesNumber, + BookMetadata::getSeriesNumberLocked, BookMetadataEntity::getSeriesNumberLocked, + MetadataClearFlags::isSeriesNumber, true), + new FieldDescriptor<>("seriesTotal", + BookMetadata::getSeriesTotal, BookMetadataEntity::getSeriesTotal, + BookMetadata::getSeriesTotalLocked, BookMetadataEntity::getSeriesTotalLocked, + MetadataClearFlags::isSeriesTotal, true), + new FieldDescriptor<>("isbn13", + BookMetadata::getIsbn13, BookMetadataEntity::getIsbn13, + BookMetadata::getIsbn13Locked, BookMetadataEntity::getIsbn13Locked, + MetadataClearFlags::isIsbn13, true), + new FieldDescriptor<>("isbn10", + BookMetadata::getIsbn10, BookMetadataEntity::getIsbn10, + BookMetadata::getIsbn10Locked, BookMetadataEntity::getIsbn10Locked, + MetadataClearFlags::isIsbn10, true), + new FieldDescriptor<>("asin", + BookMetadata::getAsin, BookMetadataEntity::getAsin, + BookMetadata::getAsinLocked, BookMetadataEntity::getAsinLocked, + MetadataClearFlags::isAsin, true), + new FieldDescriptor<>("goodreadsId", + BookMetadata::getGoodreadsId, BookMetadataEntity::getGoodreadsId, + BookMetadata::getGoodreadsIdLocked, BookMetadataEntity::getGoodreadsIdLocked, + MetadataClearFlags::isGoodreadsId, true), + new FieldDescriptor<>("comicvineId", + BookMetadata::getComicvineId, BookMetadataEntity::getComicvineId, + BookMetadata::getComicvineIdLocked, BookMetadataEntity::getComicvineIdLocked, + MetadataClearFlags::isComicvineId, true), + new FieldDescriptor<>("hardcoverId", + BookMetadata::getHardcoverId, BookMetadataEntity::getHardcoverId, + BookMetadata::getHardcoverIdLocked, BookMetadataEntity::getHardcoverIdLocked, + MetadataClearFlags::isHardcoverId, true), + new FieldDescriptor<>("hardcoverBookId", + BookMetadata::getHardcoverBookId, BookMetadataEntity::getHardcoverBookId, + BookMetadata::getHardcoverBookIdLocked, BookMetadataEntity::getHardcoverBookIdLocked, + MetadataClearFlags::isHardcoverBookId, true), + new FieldDescriptor<>("googleId", + BookMetadata::getGoogleId, BookMetadataEntity::getGoogleId, + BookMetadata::getGoogleIdLocked, BookMetadataEntity::getGoogleIdLocked, + MetadataClearFlags::isGoogleId, true), + new FieldDescriptor<>("lubimyczytacId", + BookMetadata::getLubimyczytacId, BookMetadataEntity::getLubimyczytacId, + BookMetadata::getLubimyczytacIdLocked, BookMetadataEntity::getLubimyczytacIdLocked, + MetadataClearFlags::isLubimyczytacId, true), + new FieldDescriptor<>("ranobedbId", + BookMetadata::getRanobedbId, BookMetadataEntity::getRanobedbId, + BookMetadata::getRanobedbIdLocked, BookMetadataEntity::getRanobedbIdLocked, + MetadataClearFlags::isRanobedbId, true), + new FieldDescriptor<>("language", + BookMetadata::getLanguage, BookMetadataEntity::getLanguage, + BookMetadata::getLanguageLocked, BookMetadataEntity::getLanguageLocked, + MetadataClearFlags::isLanguage, true), + new FieldDescriptor<>("pageCount", + BookMetadata::getPageCount, BookMetadataEntity::getPageCount, + BookMetadata::getPageCountLocked, BookMetadataEntity::getPageCountLocked, + MetadataClearFlags::isPageCount, false), + new FieldDescriptor<>("amazonRating", + BookMetadata::getAmazonRating, BookMetadataEntity::getAmazonRating, + BookMetadata::getAmazonRatingLocked, BookMetadataEntity::getAmazonRatingLocked, + MetadataClearFlags::isAmazonRating, false), + new FieldDescriptor<>("amazonReviewCount", + BookMetadata::getAmazonReviewCount, BookMetadataEntity::getAmazonReviewCount, + BookMetadata::getAmazonReviewCountLocked, BookMetadataEntity::getAmazonReviewCountLocked, + MetadataClearFlags::isAmazonReviewCount, false), + new FieldDescriptor<>("goodreadsRating", + BookMetadata::getGoodreadsRating, BookMetadataEntity::getGoodreadsRating, + BookMetadata::getGoodreadsRatingLocked, BookMetadataEntity::getGoodreadsRatingLocked, + MetadataClearFlags::isGoodreadsRating, false), + new FieldDescriptor<>("goodreadsReviewCount", + BookMetadata::getGoodreadsReviewCount, BookMetadataEntity::getGoodreadsReviewCount, + BookMetadata::getGoodreadsReviewCountLocked, BookMetadataEntity::getGoodreadsReviewCountLocked, + MetadataClearFlags::isGoodreadsReviewCount, false), + new FieldDescriptor<>("hardcoverRating", + BookMetadata::getHardcoverRating, BookMetadataEntity::getHardcoverRating, + BookMetadata::getHardcoverRatingLocked, BookMetadataEntity::getHardcoverRatingLocked, + MetadataClearFlags::isHardcoverRating, false), + new FieldDescriptor<>("hardcoverReviewCount", + BookMetadata::getHardcoverReviewCount, BookMetadataEntity::getHardcoverReviewCount, + BookMetadata::getHardcoverReviewCountLocked, BookMetadataEntity::getHardcoverReviewCountLocked, + MetadataClearFlags::isHardcoverReviewCount, false), + new FieldDescriptor<>("lubimyczytacRating", + BookMetadata::getLubimyczytacRating, BookMetadataEntity::getLubimyczytacRating, + BookMetadata::getLubimyczytacRatingLocked, BookMetadataEntity::getLubimyczytacRatingLocked, + MetadataClearFlags::isLubimyczytacRating, false), + new FieldDescriptor<>("ranobedbRating", + BookMetadata::getRanobedbRating, BookMetadataEntity::getRanobedbRating, + BookMetadata::getRanobedbRatingLocked, BookMetadataEntity::getRanobedbRatingLocked, + MetadataClearFlags::isRanobedbRating, false), + new FieldDescriptor<>("narrator", + BookMetadata::getNarrator, BookMetadataEntity::getNarrator, + BookMetadata::getNarratorLocked, BookMetadataEntity::getNarratorLocked, + MetadataClearFlags::isNarrator, false), + new FieldDescriptor<>("abridged", + BookMetadata::getAbridged, BookMetadataEntity::getAbridged, + BookMetadata::getAbridgedLocked, BookMetadataEntity::getAbridgedLocked, + MetadataClearFlags::isAbridged, false) + ); + + private static final List COLLECTION_FIELDS = List.of( + new CollectionFieldDescriptor("authors", + BookMetadata::getAuthors, BookMetadataEntity::getAuthors, + BookMetadata::getAuthorsLocked, BookMetadataEntity::getAuthorsLocked, + MetadataClearFlags::isAuthors, true), + new CollectionFieldDescriptor("categories", + BookMetadata::getCategories, BookMetadataEntity::getCategories, + BookMetadata::getCategoriesLocked, BookMetadataEntity::getCategoriesLocked, + MetadataClearFlags::isCategories, true), + new CollectionFieldDescriptor("moods", + BookMetadata::getMoods, BookMetadataEntity::getMoods, + BookMetadata::getMoodsLocked, BookMetadataEntity::getMoodsLocked, + MetadataClearFlags::isMoods, false), + new CollectionFieldDescriptor("tags", + BookMetadata::getTags, BookMetadataEntity::getTags, + BookMetadata::getTagsLocked, BookMetadataEntity::getTagsLocked, + MetadataClearFlags::isTags, false) + ); + public static boolean isDifferent(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { if (clear == null) return true; - - List changes = new ArrayList<>(); - - compare(changes, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked()), newMeta.getTitleLocked(), existingMeta.getTitleLocked()); - compare(changes, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked()), newMeta.getSubtitleLocked(), existingMeta.getSubtitleLocked()); - compare(changes, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked()), newMeta.getPublisherLocked(), existingMeta.getPublisherLocked()); - compare(changes, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked()), newMeta.getPublishedDateLocked(), existingMeta.getPublishedDateLocked()); - compare(changes, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked()), newMeta.getDescriptionLocked(), existingMeta.getDescriptionLocked()); - compare(changes, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked()), newMeta.getSeriesNameLocked(), existingMeta.getSeriesNameLocked()); - compare(changes, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked()), newMeta.getSeriesNumberLocked(), existingMeta.getSeriesNumberLocked()); - compare(changes, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked()), newMeta.getSeriesTotalLocked(), existingMeta.getSeriesTotalLocked()); - compare(changes, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked()), newMeta.getIsbn13Locked(), existingMeta.getIsbn13Locked()); - compare(changes, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked()), newMeta.getIsbn10Locked(), existingMeta.getIsbn10Locked()); - compare(changes, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked()), newMeta.getAsinLocked(), existingMeta.getAsinLocked()); - compare(changes, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked()), newMeta.getGoodreadsIdLocked(), existingMeta.getGoodreadsIdLocked()); - compare(changes, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked()), newMeta.getComicvineIdLocked(), existingMeta.getComicvineIdLocked()); - compare(changes, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked()), newMeta.getHardcoverIdLocked(), existingMeta.getHardcoverIdLocked()); - compare(changes, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked()), newMeta.getHardcoverBookIdLocked(), existingMeta.getHardcoverBookIdLocked()); - compare(changes, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked()), newMeta.getGoogleIdLocked(), existingMeta.getGoogleIdLocked()); - compare(changes, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked()), newMeta.getPageCountLocked(), existingMeta.getPageCountLocked()); - compare(changes, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked()), newMeta.getLanguageLocked(), existingMeta.getLanguageLocked()); - compare(changes, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked()), newMeta.getAmazonRatingLocked(), existingMeta.getAmazonRatingLocked()); - compare(changes, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked()), newMeta.getAmazonReviewCountLocked(), existingMeta.getAmazonReviewCountLocked()); - compare(changes, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked()), newMeta.getGoodreadsRatingLocked(), existingMeta.getGoodreadsRatingLocked()); - compare(changes, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked()), newMeta.getGoodreadsReviewCountLocked(), existingMeta.getGoodreadsReviewCountLocked()); - compare(changes, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked()), newMeta.getHardcoverRatingLocked(), existingMeta.getHardcoverRatingLocked()); - compare(changes, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked()), newMeta.getHardcoverReviewCountLocked(), existingMeta.getHardcoverReviewCountLocked()); - compare(changes, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked()), newMeta.getLubimyczytacIdLocked(), existingMeta.getLubimyczytacIdLocked()); - compare(changes, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked()), newMeta.getLubimyczytacRatingLocked(), existingMeta.getLubimyczytacRatingLocked()); - compare(changes, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked()), newMeta.getRanobedbIdLocked(), existingMeta.getRanobedbIdLocked()); - compare(changes, "ranobedbRating", clear.isRanobedbRating(), newMeta.getRanobedbRating(), existingMeta.getRanobedbRating(), () -> !isTrue(existingMeta.getRanobedbRatingLocked()), newMeta.getRanobedbRatingLocked(), existingMeta.getRanobedbRatingLocked()); - compare(changes, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked()), newMeta.getAuthorsLocked(), existingMeta.getAuthorsLocked()); - compare(changes, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked()), newMeta.getCategoriesLocked(), existingMeta.getCategoriesLocked()); - compare(changes, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked()), newMeta.getMoodsLocked(), existingMeta.getMoodsLocked()); - compare(changes, "tags", clear.isTags(), newMeta.getTags(), toNameSet(existingMeta.getTags()), () -> !isTrue(existingMeta.getTagsLocked()), newMeta.getTagsLocked(), existingMeta.getTagsLocked()); - - Boolean coverLockedNew = newMeta.getCoverLocked(); - Boolean coverLockedExisting = existingMeta.getCoverLocked(); - if (differsLock(coverLockedNew, coverLockedExisting)) { - changes.add("cover lock: [" + isTrue(coverLockedExisting) + "] → [" + isTrue(coverLockedNew) + "]"); + for (FieldDescriptor field : SIMPLE_FIELDS) { + if (hasFieldDifference(field, newMeta, existingMeta, clear)) { + return true; + } } - - /*changes.forEach(change -> log.info("Metadata change: {}", change));*/ - return !changes.isEmpty(); + for (CollectionFieldDescriptor field : COLLECTION_FIELDS) { + if (hasCollectionFieldDifference(field, newMeta, existingMeta, clear)) { + return true; + } + } + return differsLock(newMeta.getCoverLocked(), existingMeta.getCoverLocked()) || differsLock(newMeta.getAudiobookCoverLocked(), existingMeta.getAudiobookCoverLocked()); } public static boolean hasValueChanges(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { - List diffs = new ArrayList<>(); - compareValue(diffs, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked())); - compareValue(diffs, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked())); - compareValue(diffs, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked())); - compareValue(diffs, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked())); - compareValue(diffs, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked())); - compareValue(diffs, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked())); - compareValue(diffs, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked())); - compareValue(diffs, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked())); - compareValue(diffs, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked())); - compareValue(diffs, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked())); - compareValue(diffs, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked())); - compareValue(diffs, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked())); - compareValue(diffs, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked())); - compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked())); - compareValue(diffs, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked())); - compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked())); - compareValue(diffs, "pageCount", clear.isPageCount(), newMeta.getPageCount(), existingMeta.getPageCount(), () -> !isTrue(existingMeta.getPageCountLocked())); - compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked())); - compareValue(diffs, "amazonRating", clear.isAmazonRating(), newMeta.getAmazonRating(), existingMeta.getAmazonRating(), () -> !isTrue(existingMeta.getAmazonRatingLocked())); - compareValue(diffs, "amazonReviewCount", clear.isAmazonReviewCount(), newMeta.getAmazonReviewCount(), existingMeta.getAmazonReviewCount(), () -> !isTrue(existingMeta.getAmazonReviewCountLocked())); - compareValue(diffs, "goodreadsRating", clear.isGoodreadsRating(), newMeta.getGoodreadsRating(), existingMeta.getGoodreadsRating(), () -> !isTrue(existingMeta.getGoodreadsRatingLocked())); - compareValue(diffs, "goodreadsReviewCount", clear.isGoodreadsReviewCount(), newMeta.getGoodreadsReviewCount(), existingMeta.getGoodreadsReviewCount(), () -> !isTrue(existingMeta.getGoodreadsReviewCountLocked())); - compareValue(diffs, "hardcoverRating", clear.isHardcoverRating(), newMeta.getHardcoverRating(), existingMeta.getHardcoverRating(), () -> !isTrue(existingMeta.getHardcoverRatingLocked())); - compareValue(diffs, "hardcoverReviewCount", clear.isHardcoverReviewCount(), newMeta.getHardcoverReviewCount(), existingMeta.getHardcoverReviewCount(), () -> !isTrue(existingMeta.getHardcoverReviewCountLocked())); - compareValue(diffs, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked())); - compareValue(diffs, "lubimyczytacRating", clear.isLubimyczytacRating(), newMeta.getLubimyczytacRating(), existingMeta.getLubimyczytacRating(), () -> !isTrue(existingMeta.getLubimyczytacRatingLocked())); - compareValue(diffs, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked())); - compareValue(diffs, "ranobedbRating", clear.isRanobedbRating(), newMeta.getRanobedbRating(), existingMeta.getRanobedbRating(), () -> !isTrue(existingMeta.getRanobedbRatingLocked())); - compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked())); - compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked())); - compareValue(diffs, "moods", clear.isMoods(), newMeta.getMoods(), toNameSet(existingMeta.getMoods()), () -> !isTrue(existingMeta.getMoodsLocked())); - compareValue(diffs, "tags", clear.isTags(), newMeta.getTags(), toNameSet(existingMeta.getTags()), () -> !isTrue(existingMeta.getTagsLocked())); - return !diffs.isEmpty(); + for (FieldDescriptor field : SIMPLE_FIELDS) { + if (hasValueDifference(field, newMeta, existingMeta, clear)) { + return true; + } + } + for (CollectionFieldDescriptor field : COLLECTION_FIELDS) { + if (hasCollectionValueDifference(field, newMeta, existingMeta, clear)) { + return true; + } + } + return false; } public static boolean hasValueChangesForFileWrite(BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { - List diffs = new ArrayList<>(); - compareValue(diffs, "title", clear.isTitle(), newMeta.getTitle(), existingMeta.getTitle(), () -> !isTrue(existingMeta.getTitleLocked())); - compareValue(diffs, "subtitle", clear.isSubtitle(), newMeta.getSubtitle(), existingMeta.getSubtitle(), () -> !isTrue(existingMeta.getSubtitleLocked())); - compareValue(diffs, "publisher", clear.isPublisher(), newMeta.getPublisher(), existingMeta.getPublisher(), () -> !isTrue(existingMeta.getPublisherLocked())); - compareValue(diffs, "publishedDate", clear.isPublishedDate(), newMeta.getPublishedDate(), existingMeta.getPublishedDate(), () -> !isTrue(existingMeta.getPublishedDateLocked())); - compareValue(diffs, "description", clear.isDescription(), newMeta.getDescription(), existingMeta.getDescription(), () -> !isTrue(existingMeta.getDescriptionLocked())); - compareValue(diffs, "seriesName", clear.isSeriesName(), newMeta.getSeriesName(), existingMeta.getSeriesName(), () -> !isTrue(existingMeta.getSeriesNameLocked())); - compareValue(diffs, "seriesNumber", clear.isSeriesNumber(), newMeta.getSeriesNumber(), existingMeta.getSeriesNumber(), () -> !isTrue(existingMeta.getSeriesNumberLocked())); - compareValue(diffs, "seriesTotal", clear.isSeriesTotal(), newMeta.getSeriesTotal(), existingMeta.getSeriesTotal(), () -> !isTrue(existingMeta.getSeriesTotalLocked())); - compareValue(diffs, "isbn13", clear.isIsbn13(), newMeta.getIsbn13(), existingMeta.getIsbn13(), () -> !isTrue(existingMeta.getIsbn13Locked())); - compareValue(diffs, "isbn10", clear.isIsbn10(), newMeta.getIsbn10(), existingMeta.getIsbn10(), () -> !isTrue(existingMeta.getIsbn10Locked())); - compareValue(diffs, "asin", clear.isAsin(), newMeta.getAsin(), existingMeta.getAsin(), () -> !isTrue(existingMeta.getAsinLocked())); - compareValue(diffs, "goodreadsId", clear.isGoodreadsId(), newMeta.getGoodreadsId(), existingMeta.getGoodreadsId(), () -> !isTrue(existingMeta.getGoodreadsIdLocked())); - compareValue(diffs, "comicvineId", clear.isComicvineId(), newMeta.getComicvineId(), existingMeta.getComicvineId(), () -> !isTrue(existingMeta.getComicvineIdLocked())); - compareValue(diffs, "hardcoverId", clear.isHardcoverId(), newMeta.getHardcoverId(), existingMeta.getHardcoverId(), () -> !isTrue(existingMeta.getHardcoverIdLocked())); - compareValue(diffs, "hardcoverBookId", clear.isHardcoverBookId(), newMeta.getHardcoverBookId(), existingMeta.getHardcoverBookId(), () -> !isTrue(existingMeta.getHardcoverBookIdLocked())); - compareValue(diffs, "googleId", clear.isGoogleId(), newMeta.getGoogleId(), existingMeta.getGoogleId(), () -> !isTrue(existingMeta.getGoogleIdLocked())); - compareValue(diffs, "lubimyczytacId", clear.isLubimyczytacId(), newMeta.getLubimyczytacId(), existingMeta.getLubimyczytacId(), () -> !isTrue(existingMeta.getLubimyczytacIdLocked())); - compareValue(diffs, "ranobedbId", clear.isRanobedbId(), newMeta.getRanobedbId(), existingMeta.getRanobedbId(), () -> !isTrue(existingMeta.getRanobedbIdLocked())); - compareValue(diffs, "language", clear.isLanguage(), newMeta.getLanguage(), existingMeta.getLanguage(), () -> !isTrue(existingMeta.getLanguageLocked())); - compareValue(diffs, "authors", clear.isAuthors(), newMeta.getAuthors(), toNameSet(existingMeta.getAuthors()), () -> !isTrue(existingMeta.getAuthorsLocked())); - compareValue(diffs, "categories", clear.isCategories(), newMeta.getCategories(), toNameSet(existingMeta.getCategories()), () -> !isTrue(existingMeta.getCategoriesLocked())); - return !diffs.isEmpty(); - } - - private static void compare(List diffs, String field, boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked, Boolean newLock, Boolean oldLock) { - boolean valueChanged = differs(shouldClear, newVal, oldVal, isUnlocked); - boolean lockChanged = differsLock(newLock, oldLock); - - if (valueChanged || lockChanged) { - StringBuilder sb = new StringBuilder(); - sb.append(field); - if (valueChanged) sb.append(" value: [").append(safe(oldVal)).append("] → [").append(safe(newVal)).append("]"); - if (lockChanged) sb.append(" lock: [").append(isTrue(oldLock)).append("] → [").append(isTrue(newLock)).append("]"); - diffs.add(sb.toString()); + for (FieldDescriptor field : SIMPLE_FIELDS) { + if (field.includedInFileWrite() && hasValueDifference(field, newMeta, existingMeta, clear)) { + return true; + } } - } - - private static void compareValue(List diffs, - String field, - boolean shouldClear, - T newVal, - T oldVal, - BooleanSupplier isUnlocked) { - if (differs(shouldClear, newVal, oldVal, isUnlocked)) { - diffs.add(field + " changed"); + for (CollectionFieldDescriptor field : COLLECTION_FIELDS) { + if (field.includedInFileWrite() && hasCollectionValueDifference(field, newMeta, existingMeta, clear)) { + return true; + } } + return false; } - private static boolean differs(boolean shouldClear, Object newVal, Object oldVal, BooleanSupplier isUnlocked) { - if (!isUnlocked.getAsBoolean()) return false; + private static boolean hasFieldDifference(FieldDescriptor field, BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { + boolean valueChanged = differs( + field.shouldClear(clear), + field.getNewValue(newMeta), + field.getOldValue(existingMeta), + field.isUnlocked(existingMeta) + ); + boolean lockChanged = differsLock(field.getNewLock(newMeta), field.getOldLock(existingMeta)); + return valueChanged || lockChanged; + } + + private static boolean hasCollectionFieldDifference(CollectionFieldDescriptor field, BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { + boolean valueChanged = differs( + field.shouldClear(clear), + field.getNewValue(newMeta), + field.getOldValue(existingMeta), + field.isUnlocked(existingMeta) + ); + boolean lockChanged = differsLock(field.getNewLock(newMeta), field.getOldLock(existingMeta)); + return valueChanged || lockChanged; + } + + private static boolean hasValueDifference(FieldDescriptor field, BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { + return differs( + field.shouldClear(clear), + field.getNewValue(newMeta), + field.getOldValue(existingMeta), + field.isUnlocked(existingMeta) + ); + } + + private static boolean hasCollectionValueDifference(CollectionFieldDescriptor field, BookMetadata newMeta, BookMetadataEntity existingMeta, MetadataClearFlags clear) { + return differs( + field.shouldClear(clear), + field.getNewValue(newMeta), + field.getOldValue(existingMeta), + field.isUnlocked(existingMeta) + ); + } + + private static boolean differs(boolean shouldClear, Object newVal, Object oldVal, boolean isUnlocked) { + if (!isUnlocked) return false; Object normNew = normalize(newVal); Object normOld = normalize(oldVal); @@ -177,12 +334,6 @@ public class MetadataChangeDetector { return !Objects.equals(Boolean.TRUE.equals(dtoLock), Boolean.TRUE.equals(entityLock)); } - private static String safe(Object val) { - if (val == null) return "null"; - if (val instanceof Set set) return set.stream().map(String::valueOf).sorted().collect(Collectors.joining(", ", "[", "]")); - return val.toString().strip(); - } - private static Object normalize(Object value) { if (value instanceof String s) return s.strip(); return value; @@ -193,21 +344,13 @@ public class MetadataChangeDetector { return Collections.emptySet(); } return entities.stream() - .map(e -> { - if (e instanceof AuthorEntity author) { - return author.getName(); - } - if (e instanceof CategoryEntity category) { - return category.getName(); - } - if (e instanceof MoodEntity mood) { - return mood.getName(); - } - if (e instanceof TagEntity tag) { - return tag.getName(); - } - return e.toString(); - }) - .collect(Collectors.toSet()); + .map(e -> switch (e) { + case AuthorEntity author -> author.getName(); + case CategoryEntity category -> category.getName(); + case MoodEntity mood -> mood.getName(); + case TagEntity tag -> tag.getName(); + default -> e.toString(); + }) + .collect(Collectors.toSet()); } } diff --git a/booklore-api/src/main/resources/db/migration/V109__Add_audiobook_support.sql b/booklore-api/src/main/resources/db/migration/V109__Add_audiobook_support.sql new file mode 100644 index 000000000..b293c8340 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V109__Add_audiobook_support.sql @@ -0,0 +1,27 @@ +ALTER TABLE book_metadata ADD COLUMN audiobook_cover_updated_on TIMESTAMP; +ALTER TABLE book_metadata ADD COLUMN audible_id VARCHAR(100); +ALTER TABLE book_metadata ADD COLUMN audible_rating FLOAT; +ALTER TABLE book_metadata ADD COLUMN audible_review_count INTEGER; +ALTER TABLE book_metadata ADD COLUMN audible_id_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN audible_rating_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN audible_review_count_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN audiobook_cover_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN narrator_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN abridged_locked BOOLEAN DEFAULT FALSE; +ALTER TABLE book_metadata ADD COLUMN narrator VARCHAR(500); +ALTER TABLE book_metadata ADD COLUMN abridged BOOLEAN; + +ALTER TABLE book ADD COLUMN audiobook_cover_hash VARCHAR(20); + +-- Add allowed_formats column to library table +-- Stores JSON array of allowed BookFileType values (e.g., ["EPUB", "PDF", "AUDIOBOOK"]) +-- NULL means all formats are allowed (backward compatible) +ALTER TABLE library ADD COLUMN allowed_formats TEXT; + +ALTER TABLE book_file ADD COLUMN duration_seconds BIGINT; +ALTER TABLE book_file ADD COLUMN bitrate INTEGER; +ALTER TABLE book_file ADD COLUMN sample_rate INTEGER; +ALTER TABLE book_file ADD COLUMN channels INTEGER; +ALTER TABLE book_file ADD COLUMN codec VARCHAR(50); +ALTER TABLE book_file ADD COLUMN chapter_count INTEGER; +ALTER TABLE book_file ADD COLUMN chapters_json TEXT; diff --git a/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java b/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java index 92f8bf1dc..9f9dd29ad 100644 --- a/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java +++ b/booklore-api/src/test/java/org/booklore/service/library/FileAsBookProcessorTest.java @@ -15,6 +15,9 @@ import org.booklore.service.file.FileFingerprint; import org.booklore.service.fileprocessor.BookFileProcessor; import org.booklore.service.fileprocessor.BookFileProcessorRegistry; import org.booklore.service.kobo.KoboAutoShelfService; +import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor; +import org.booklore.service.metadata.extractor.MetadataExtractorFactory; +import org.booklore.util.FileService; import org.booklore.util.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -47,6 +50,15 @@ class FileAsBookProcessorTest { @Mock private BookAdditionalFileRepository bookAdditionalFileRepository; + @Mock + private FileService fileService; + + @Mock + private MetadataExtractorFactory metadataExtractorFactory; + + @Mock + private AudiobookMetadataExtractor audiobookMetadataExtractor; + @Mock private BookFileProcessor bookFileProcessor; @@ -64,7 +76,10 @@ class FileAsBookProcessorTest { processorRegistry, koboAutoShelfService, bookRepository, - bookAdditionalFileRepository + bookAdditionalFileRepository, + fileService, + metadataExtractorFactory, + audiobookMetadataExtractor ); fileFingerprintMock = mockStatic(FileFingerprint.class); fileFingerprintMock.when(() -> FileFingerprint.generateHash(any(Path.class))).thenReturn("testhash"); diff --git a/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java index bbdbefcef..34daa197f 100644 --- a/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/metadata/BookCoverServiceTest.java @@ -188,24 +188,22 @@ class BookCoverServiceTest { @Test void regenerateCover_success() { BookEntity book = mockBookEntity(7L, false); - when(bookRepository.findById(7L)).thenReturn(Optional.of(book)); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findByIdWithBookFiles(7L)).thenReturn(Optional.of(book)); BookFileProcessor processor = mock(BookFileProcessor.class); when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor); - when(processor.generateCover(any())).thenReturn(true); + when(processor.generateCover(any(BookEntity.class), any(BookFileEntity.class))).thenReturn(true); when(bookRepository.save(any())).thenReturn(book); bookCoverService.regenerateCover(7L); - verify(processor).generateCover(book); + verify(processor).generateCover(eq(book), any(BookFileEntity.class)); verify(bookRepository).save(book); } @Test void regenerateCover_coverLocked_throws() { BookEntity book = mockBookEntity(8L, true); - when(bookRepository.findById(8L)).thenReturn(Optional.of(book)); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findByIdWithBookFiles(8L)).thenReturn(Optional.of(book)); assertThatThrownBy(() -> bookCoverService.regenerateCover(8L)) .isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass()); } diff --git a/booklore-api/src/test/java/org/booklore/service/reader/AudioMetadataServiceTest.java b/booklore-api/src/test/java/org/booklore/service/reader/AudioMetadataServiceTest.java index 34247402d..544ec87bc 100644 --- a/booklore-api/src/test/java/org/booklore/service/reader/AudioMetadataServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/reader/AudioMetadataServiceTest.java @@ -60,8 +60,6 @@ class AudioMetadataServiceTest { Files.createFile(audioPath); } - // ==================== getMetadata tests for single file ==================== - @Test void getMetadata_singleFile_extractsBasicInfo() throws Exception { AudioFile audioFile = mock(AudioFile.class); @@ -70,7 +68,7 @@ class AudioMetadataServiceTest { when(audioFile.getAudioHeader()).thenReturn(header); when(audioFile.getTag()).thenReturn(tag); - when(header.getPreciseTrackLength()).thenReturn(3600.0); // 1 hour + when(header.getPreciseTrackLength()).thenReturn(3600.0); when(header.getBitRateAsNumber()).thenReturn(128L); when(header.getEncodingType()).thenReturn("AAC"); when(header.getSampleRateAsNumber()).thenReturn(44100); @@ -89,11 +87,11 @@ class AudioMetadataServiceTest { assertEquals(1L, info.getBookId()); assertEquals(10L, info.getBookFileId()); assertFalse(info.isFolderBased()); - assertEquals(3600000L, info.getDurationMs()); // 1 hour in ms + assertEquals(3600000L, info.getDurationMs()); assertEquals(128, info.getBitrate()); assertEquals("AAC", info.getCodec()); assertEquals(44100, info.getSampleRate()); - assertEquals(2, info.getChannels()); // Stereo = 2 + assertEquals(2, info.getChannels()); assertEquals("Test Audiobook", info.getTitle()); assertEquals("Test Author", info.getAuthor()); assertEquals("Test Narrator", info.getNarrator()); @@ -120,7 +118,7 @@ class AudioMetadataServiceTest { assertNotNull(info); assertEquals(1800000L, info.getDurationMs()); - assertEquals(1, info.getChannels()); // Mono = 1 + assertEquals(1, info.getChannels()); assertNull(info.getTitle()); assertNull(info.getAuthor()); assertNull(info.getNarrator()); @@ -134,7 +132,7 @@ class AudioMetadataServiceTest { when(audioFile.getAudioHeader()).thenReturn(header); when(audioFile.getTag()).thenReturn(null); - when(header.getPreciseTrackLength()).thenReturn(7200.0); // 2 hours + when(header.getPreciseTrackLength()).thenReturn(7200.0); try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); @@ -153,30 +151,44 @@ class AudioMetadataServiceTest { } @Test - void getMetadata_cachesResult() throws Exception { - AudioFile audioFile = mock(AudioFile.class); - AudioHeader header = mock(AudioHeader.class); + void getMetadata_usesDbMetadataWhenAvailable() throws Exception { + bookFileEntity.setDurationSeconds(3600L); + bookFileEntity.setBitrate(192); + bookFileEntity.setSampleRate(48000); + bookFileEntity.setChannels(2); + bookFileEntity.setCodec("MP3"); + bookFileEntity.setChapterCount(5); + bookFileEntity.setChapters(List.of( + BookFileEntity.AudioFileChapter.builder() + .index(0) + .title("Chapter 1") + .startTimeMs(0L) + .endTimeMs(1000000L) + .durationMs(1000000L) + .build() + )); - when(audioFile.getAudioHeader()).thenReturn(header); - when(audioFile.getTag()).thenReturn(null); - when(header.getPreciseTrackLength()).thenReturn(100.0); + var bookMetadata = new org.booklore.model.entity.BookMetadataEntity(); + bookMetadata.setTitle("DB Book Title"); + bookMetadata.setNarrator("DB Narrator"); + bookEntity.setMetadata(bookMetadata); try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { - audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile); + AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath); - // First call - AudiobookInfo info1 = audioMetadataService.getMetadata(bookFileEntity, audioPath); - // Second call should use cache - AudiobookInfo info2 = audioMetadataService.getMetadata(bookFileEntity, audioPath); + assertNotNull(info); + assertEquals("DB Narrator", info.getNarrator()); + assertEquals(3600000L, info.getDurationMs()); + assertEquals(192, info.getBitrate()); + assertEquals("MP3", info.getCodec()); + assertEquals("DB Book Title", info.getTitle()); + assertEquals(1, info.getChapters().size()); + assertEquals("Chapter 1", info.getChapters().get(0).getTitle()); - assertSame(info1, info2); - // AudioFileIO.read should only be called once - audioFileIOMock.verify(() -> AudioFileIO.read(audioPath.toFile()), times(1)); + audioFileIOMock.verify(() -> AudioFileIO.read(any()), never()); } } - // ==================== getMetadata tests for folder-based ==================== - @Test void getMetadata_folderBased_extractsTracksInfo() throws Exception { bookFileEntity.setFolderBased(true); @@ -201,7 +213,7 @@ class AudioMetadataServiceTest { when(audioFile1.getAudioHeader()).thenReturn(header1); when(audioFile1.getTag()).thenReturn(tag1); - when(header1.getPreciseTrackLength()).thenReturn(1800.0); // 30 min + when(header1.getPreciseTrackLength()).thenReturn(1800.0); when(header1.getBitRateAsNumber()).thenReturn(192L); when(header1.getEncodingType()).thenReturn("MP3"); when(header1.getSampleRateAsNumber()).thenReturn(44100); @@ -212,7 +224,7 @@ class AudioMetadataServiceTest { when(audioFile2.getAudioHeader()).thenReturn(header2); when(audioFile2.getTag()).thenReturn(null); - when(header2.getPreciseTrackLength()).thenReturn(2400.0); // 40 min + when(header2.getPreciseTrackLength()).thenReturn(2400.0); try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile1); @@ -222,7 +234,7 @@ class AudioMetadataServiceTest { assertNotNull(info); assertTrue(info.isFolderBased()); - assertEquals(4200000L, info.getDurationMs()); // 30 + 40 min = 70 min + assertEquals(4200000L, info.getDurationMs()); assertEquals("Test Album", info.getTitle()); assertEquals("Test Author", info.getAuthor()); @@ -274,7 +286,7 @@ class AudioMetadataServiceTest { when(audioFile.getAudioHeader()).thenReturn(header); when(audioFile.getTag()).thenReturn(tag); when(header.getPreciseTrackLength()).thenReturn(600.0); - when(tag.getFirst(FieldKey.TITLE)).thenReturn(""); // Empty title + when(tag.getFirst(FieldKey.TITLE)).thenReturn(""); try (MockedStatic audioFileIOMock = mockStatic(AudioFileIO.class)) { audioFileIOMock.when(() -> AudioFileIO.read(track1.toFile())).thenReturn(audioFile); @@ -285,8 +297,6 @@ class AudioMetadataServiceTest { } } - // ==================== getEmbeddedCoverArt tests ==================== - @Test void getEmbeddedCoverArt_returnsArtworkData() throws Exception { byte[] expectedData = new byte[]{(byte) 0xFF, (byte) 0xD8, 0x00, 0x01}; @@ -350,8 +360,6 @@ class AudioMetadataServiceTest { } } - // ==================== getCoverArtMimeType tests ==================== - @Test void getCoverArtMimeType_returnsMimeTypeFromArtwork() throws Exception { AudioFile audioFile = mock(AudioFile.class); @@ -442,8 +450,6 @@ class AudioMetadataServiceTest { } } - // ==================== Channel parsing tests ==================== - @Test void getMetadata_parsesStereoChannels() throws Exception { AudioFile audioFile = mock(AudioFile.class); @@ -516,8 +522,6 @@ class AudioMetadataServiceTest { } } - // ==================== Bitrate handling ==================== - @Test void getMetadata_handlesZeroBitrate() throws Exception { AudioFile audioFile = mock(AudioFile.class); diff --git a/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java index b6cc159c8..df3212699 100644 --- a/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/util/FileServiceTest.java @@ -4,7 +4,6 @@ import org.booklore.config.AppProperties; import org.booklore.model.dto.settings.AppSettings; import org.booklore.model.dto.settings.CoverCroppingSettings; import org.booklore.model.entity.BookMetadataEntity; -import org.booklore.repository.BookMetadataRepository; import org.booklore.service.appsettings.AppSettingService; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -62,7 +61,7 @@ class FileServiceTest { .build(); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); - fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService, mock(BookMetadataRepository.class)); + fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService); } @Nested @@ -1177,7 +1176,7 @@ class FileServiceTest { .build(); lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings); - fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, mock(BookMetadataRepository.class)); + fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork); } @Nested @@ -1194,7 +1193,7 @@ class FileServiceTest { RestTemplate mockRestTemplate = mock(RestTemplate.class); AppSettingService mockAppSettingService = mock(AppSettingService.class); - FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService, mock(BookMetadataRepository.class)); + FileService testFileService = new FileService(appProperties, mockRestTemplate, mockAppSettingService); ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(mockRestTemplate.exchange( diff --git a/booklore-ui/src/app/app.routes.ts b/booklore-ui/src/app/app.routes.ts index 7afd536be..e7618a925 100644 --- a/booklore-ui/src/app/app.routes.ts +++ b/booklore-ui/src/app/app.routes.ts @@ -25,7 +25,7 @@ import {UserStatsGuard} from './core/security/guards/user-stats.guard'; import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard'; import {EbookReaderComponent} from './features/readers/ebook-reader'; import {LibraryStatsComponent} from './features/stats/component/library-stats/library-stats.component'; -import {AudiobookReaderComponent} from './features/readers/audiobook-reader/audiobook-reader.component'; +import {AudiobookPlayerComponent} from './features/readers/audiobook-player'; export const routes: Routes = [ { @@ -75,8 +75,8 @@ export const routes: Routes = [ canActivate: [AuthGuard] }, { - path: 'audiobook-reader/book/:bookId', - component: AudiobookReaderComponent, + path: 'audiobook-player/book/:bookId', + component: AudiobookPlayerComponent, canActivate: [AuthGuard] }, { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index c6981c8d0..d6872ca47 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -207,15 +207,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy { return this.coverScalePreferenceService.gridColumnMinWidth; } - getCardHeight(book: Book): number { + getCardHeight(_book: Book): number { + // Use uniform height for all book types to ensure smooth virtual scrolling. + // Mixed heights cause choppy/jumpy scrolling because the virtual scroller + // cannot accurately estimate positions when item heights vary. if (this.isMobile) { - const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; - if (isAudiobook) { - return this.mobileCardSize.width + this.MOBILE_TITLE_BAR_HEIGHT; - } return this.mobileCardSize.height; } - return this.coverScalePreferenceService.getCardHeight(book); + return this.coverScalePreferenceService.getCardHeight(_book); } get viewIcon(): string { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html index 0ee65b6f3..32ad94c73 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.html @@ -39,7 +39,7 @@ } @if (!_isSeriesViewActive && hasDigitalFile()) { - + } @if (isCheckboxEnabled) { diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss index 4b41e2131..d2421b971 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.scss @@ -3,6 +3,9 @@ border-radius: 8px 8px 8px 8px; position: relative; overflow: hidden; + height: 100%; + display: flex; + flex-direction: column; &.selected { border: 2px solid var(--primary-color); @@ -22,7 +25,9 @@ } .cover-container.audiobook-cover { - aspect-ratio: 1/1; + // Use same aspect-ratio as ebooks for uniform virtual scroller row heights. + // The square audiobook cover image will be centered via object-fit: contain. + aspect-ratio: 5/7; background-color: var(--surface-ground); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts index ae24f4351..76c9c01ad 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-card/book-card.component.ts @@ -1,6 +1,6 @@ import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; import {TooltipModule} from "primeng/tooltip"; -import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model'; +import {AdditionalFile, Book, BookType, ReadStatus} from '../../../model/book.model'; import {Button} from 'primeng/button'; import {MenuModule} from 'primeng/menu'; import {ConfirmationService, MenuItem, MessageService} from 'primeng/api'; @@ -49,6 +49,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { @Input() seriesViewEnabled: boolean = false; @Input() isSeriesCollapsed: boolean = false; @Input() overlayPreferenceService?: BookCardOverlayPreferenceService; + @Input() forceEbookMode: boolean = false; @ViewChild('checkboxElem') checkboxElem!: ElementRef; @@ -128,9 +129,9 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { } ngOnChanges(changes: SimpleChanges): void { - if (changes['book']) { + if (changes['book'] || changes['forceEbookMode']) { this.computeAllMemoizedValues(); - if (!changes['book'].firstChange && this.menuInitialized) { + if (changes['book'] && !changes['book'].firstChange && this.menuInitialized) { this.additionalFilesLoaded = false; this.initMenu(); } @@ -158,7 +159,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title; - this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn); + this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK' && !this.forceEbookMode; + this._coverImageUrl = this._isAudiobook + ? this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn) + : this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn); this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus); this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus); @@ -167,7 +171,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books'; this._titleTooltip = 'Title: ' + this._displayTitle; - this._isAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK'; } get hasProgress(): boolean { @@ -200,9 +203,26 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { } readBook(book: Book): void { + if (this.forceEbookMode && book.primaryFile?.bookType === 'AUDIOBOOK') { + const ebookType = this.getEbookType(book); + if (ebookType) { + this.bookService.readBook(book.id, undefined, ebookType); + return; + } + } this.bookService.readBook(book.id); } + private getEbookType(book: Book): BookType | undefined { + if (book.epubProgress) return 'EPUB'; + if (book.pdfProgress) return 'PDF'; + if (book.cbxProgress) return 'CBX'; + const alternativeFormat = book.alternativeFormats?.find(f => + f.bookType && ['EPUB', 'PDF', 'CBX', 'FB2', 'MOBI', 'AZW3'].includes(f.bookType) + ); + return alternativeFormat?.bookType; + } + onMenuShow(): void { this.menuToggled.emit(true); } @@ -425,10 +445,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { summary: 'Success', detail: 'Cover regeneration started' }), - error: () => this.messageService.add({ + error: (err) => this.messageService.add({ severity: 'error', summary: 'Error', - detail: 'Failed to regenerate cover' + detail: err?.error?.message || 'Failed to regenerate cover' }) }); } @@ -443,10 +463,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { summary: 'Success', detail: 'Cover generated successfully' }), - error: () => this.messageService.add({ + error: (err) => this.messageService.add({ severity: 'error', summary: 'Error', - detail: 'Failed to generate cover' + detail: err?.error?.message || 'Failed to generate cover' }) }); } @@ -740,6 +760,12 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { if (!this.book?.primaryFile) { return 'PHYSICAL'; } + if (this.forceEbookMode && this.book.primaryFile?.bookType === 'AUDIOBOOK') { + const ebookType = this.getEbookType(this.book); + if (ebookType) { + return ebookType; + } + } const ext = this.book?.primaryFile?.extension; if (ext) { return ext.toUpperCase(); diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts index afc45c391..cb1fa13c6 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts @@ -124,12 +124,13 @@ export class BookDialogHelperService { }); } - openCoverSearchDialog(bookId: number): DynamicDialogRef | null { + openCoverSearchDialog(bookId: number, coverType?: 'ebook' | 'audiobook'): DynamicDialogRef | null { return this.openDialog(CoverSearchComponent, { showHeader: false, styleClass: `${DialogSize.FULL} ${DialogStyle.MINIMAL}`, data: { bookId: bookId, + coverType: coverType, }, }); } diff --git a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts index c4f4c1cf1..08ffb352b 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts @@ -52,11 +52,10 @@ export class CoverScalePreferenceService { return `${this.currentCardSize.width}px`; } - getCardHeight(book: Book): number { - const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK'; - if (isAudiobook) { - return Math.round((this.BASE_WIDTH + this.TITLE_BAR_HEIGHT) * this.scaleFactor); - } + getCardHeight(_book: Book): number { + // Use uniform height for all book types to ensure smooth virtual scrolling. + // Mixed heights cause choppy/jumpy scrolling because the virtual scroller + // cannot accurately estimate positions when item heights vary. return this.currentCardSize.height; } diff --git a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html index dae0d897d..0e67d9dc8 100644 --- a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html +++ b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.html @@ -1,6 +1,6 @@ -
+
Cover of {{ book.metadata?.title }} diff --git a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.scss b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.scss index a240bfac9..77c51ffd8 100644 --- a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.scss +++ b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.scss @@ -10,6 +10,13 @@ border-radius: 0.5rem; } + &.audiobook-only { + .book-cover { + aspect-ratio: 1 / 1; + object-fit: cover; + } + } + .info-btn { position: absolute; top: 50%; diff --git a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts index 1c1d39443..409b33ec1 100644 --- a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts +++ b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts @@ -35,6 +35,19 @@ export class BookCardLiteComponent implements OnInit, OnDestroy { private metadataCenterViewMode: 'route' | 'dialog' = 'route'; isHovered: boolean = false; + isAudiobookOnly(): boolean { + const primaryIsAudiobook = this.book.primaryFile?.bookType === 'AUDIOBOOK'; + const hasEbookAlternative = this.book.alternativeFormats?.some(f => f.bookType !== 'AUDIOBOOK') ?? false; + return primaryIsAudiobook && !hasEbookAlternative; + } + + getThumbnailUrl(): string { + if (this.isAudiobookOnly()) { + return this.urlHelper.getAudiobookThumbnailUrl(this.book.id, this.book.metadata?.audiobookCoverUpdatedOn); + } + return this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn); + } + ngOnInit(): void { this.userService.userState$ .pipe( diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index 4c9060c30..580c62b45 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -97,6 +97,19 @@ export interface BookFileProgress { progressPercent: number; } +export interface AudiobookMetadata { + narrator?: string; + abridged?: boolean | null; + durationSeconds?: number; + bitrate?: number; + sampleRate?: number; + channels?: number; + codec?: string; + chapterCount?: number; + narratorLocked?: boolean; + abridgedLocked?: boolean; +} + export interface BookMetadata { bookId: number; title?: string; @@ -129,7 +142,16 @@ export interface BookMetadata { ranobedbId?: string; ranobedbRating?: number | null; hardcoverRating?: number | null; + audibleId?: string; + audibleRating?: number | null; + audibleReviewCount?: number | null; + narrator?: string; + abridged?: boolean | null; + narratorLocked?: boolean; + abridgedLocked?: boolean; + audiobookMetadata?: AudiobookMetadata; coverUpdatedOn?: string; + audiobookCoverUpdatedOn?: string; authors?: string[]; categories?: string[]; moods?: string[]; @@ -166,12 +188,16 @@ export interface BookMetadata { lubimyczytacRatingLocked?: boolean; ranobedbIdLocked?: boolean; ranobedbRatingLocked?: boolean; + audibleIdLocked?: boolean; + audibleRatingLocked?: boolean; + audibleReviewCountLocked?: boolean; coverUpdatedOnLocked?: boolean; authorsLocked?: boolean; categoriesLocked?: boolean; moodsLocked?: boolean; tagsLocked?: boolean; coverLocked?: boolean; + audiobookCoverLocked?: boolean; reviewsLocked?: boolean; [key: string]: unknown; @@ -206,11 +232,17 @@ export interface MetadataClearFlags { lubimyczytacRating?: boolean; ranobedbId?: boolean; ranobedbRating?: boolean; + audibleId?: boolean; + audibleRating?: boolean; + audibleReviewCount?: boolean; + narrator?: boolean; + abridged?: boolean; authors?: boolean; categories?: boolean; moods?: boolean; tags?: boolean; cover?: boolean; + audiobookCover?: boolean; } export interface MetadataUpdateWrapper { diff --git a/booklore-ui/src/app/features/book/model/library.model.ts b/booklore-ui/src/app/features/book/model/library.model.ts index 97218c392..23fba9bb8 100644 --- a/booklore-ui/src/app/features/book/model/library.model.ts +++ b/booklore-ui/src/app/features/book/model/library.model.ts @@ -11,6 +11,7 @@ export interface Library { sort?: SortOption; paths: LibraryPath[]; formatPriority?: BookType[]; + allowedFormats?: BookType[]; } export interface LibraryPath { diff --git a/booklore-ui/src/app/features/book/service/book.service.ts b/booklore-ui/src/app/features/book/service/book.service.ts index 10f6bdeb4..680ad5d57 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -310,7 +310,7 @@ export class BookService { break; case 'AUDIOBOOK': - baseUrl = 'audiobook-reader'; + baseUrl = 'audiobook-player'; break; } @@ -700,6 +700,35 @@ export class BookService { return this.http.post(`${this.url}/bulk-regenerate-covers`, {bookIds}); } + uploadAudiobookCoverFromUrl(bookId: number, url: string): Observable { + return this.http.post(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url}); + } + + uploadAudiobookCoverFromFile(bookId: number, file: File): Observable { + const formData = new FormData(); + formData.append('file', file); + return this.http.post(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData); + } + + getUploadAudiobookCoverUrl(bookId: number): string { + return this.url + '/' + bookId + "/metadata/audiobook-cover/upload"; + } + + regenerateAudiobookCover(bookId: number): Observable { + return this.http.post(`${this.url}/${bookId}/regenerate-audiobook-cover`, {}); + } + + generateCustomAudiobookCover(bookId: number): Observable { + return this.http.post(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {}); + } + + supportsDualCovers(book: Book): boolean { + const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); + const hasAudiobook = allFiles.some(f => f!.bookType === 'AUDIOBOOK'); + const hasEbook = allFiles.some(f => f!.bookType !== 'AUDIOBOOK'); + return hasAudiobook && hasEbook; + } + bulkUploadCover(bookIds: number[], file: File): Observable { const formData = new FormData(); formData.append('file', file); diff --git a/booklore-ui/src/app/features/book/service/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index 679b37f45..b842dbc8c 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -165,4 +165,8 @@ export class LibraryService { setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void { this.largeLibraryLoadingSubject.next({ isLoading, expectedCount }); } + + getBookCountsByFormat(libraryId: number): Observable> { + return this.http.get>(`${this.url}/${libraryId}/format-counts`); + } } diff --git a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.html b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.html index ca7d91316..8e54a8e0e 100644 --- a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.html +++ b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.html @@ -23,10 +23,11 @@ #scrollContainer [horizontal]="true"> @for (book of books; track book.id) { -
+
diff --git a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss index bc8f9b5a9..b687515a7 100644 --- a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss +++ b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.scss @@ -96,6 +96,17 @@ transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); position: relative; + &.square-card { + width: 160px; + height: auto; + flex-basis: 160px; + + ::ng-deep .cover-container.audiobook-cover { + aspect-ratio: 1/1 !important; + flex: none; + } + } + &:hover, &.menu-open { transform: translateY(-4px) scale(1.04); filter: drop-shadow(0 25px 50px rgba(0, 0, 0, 0.4)); @@ -180,6 +191,12 @@ height: 184px; width: 108px; flex-basis: 108px; + + &.square-card { + width: 150px; + height: auto; + flex-basis: 150px; + } } .dashboard-scroller-no-books { diff --git a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.ts b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.ts index 87d0e8fea..b399bfa4e 100644 --- a/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.ts +++ b/booklore-ui/src/app/features/dashboard/components/dashboard-scroller/dashboard-scroller.component.ts @@ -1,6 +1,7 @@ import {Component, ElementRef, Input, ViewChild, inject} from '@angular/core'; import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component'; import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; +import {NgClass} from '@angular/common'; import {ProgressSpinnerModule} from 'primeng/progressspinner'; import {Book} from '../../../book/model/book.model'; @@ -14,7 +15,8 @@ import { BookCardOverlayPreferenceService } from '../../../book/components/book- imports: [ InfiniteScrollDirective, BookCardComponent, - ProgressSpinnerModule + ProgressSpinnerModule, + NgClass ], standalone: true }) @@ -24,12 +26,17 @@ export class DashboardScrollerComponent { @Input() title!: string; @Input() books!: Book[] | null; @Input() isMagicShelf: boolean = false; + @Input() useSquareCovers: boolean = false; @ViewChild('scrollContainer') scrollContainer!: ElementRef; openMenuBookId: number | null = null; public bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService); + get forceEbookMode(): boolean { + return this.bookListType === ScrollerType.LAST_READ; + } + handleMenuToggle(bookId: number, isOpen: boolean) { this.openMenuBookId = isOpen ? bookId : null; } diff --git a/booklore-ui/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.ts b/booklore-ui/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.ts index d6212641b..23c6fd803 100644 --- a/booklore-ui/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.ts +++ b/booklore-ui/src/app/features/dashboard/components/dashboard-settings/dashboard-settings.component.ts @@ -41,6 +41,7 @@ export class DashboardSettingsComponent implements OnInit { availableScrollerTypes = [ {label: 'Continue Reading', value: ScrollerType.LAST_READ}, + {label: 'Continue Listening', value: ScrollerType.LAST_LISTENED}, {label: 'Recently Added', value: ScrollerType.LATEST_ADDED}, {label: 'Discover Something New', value: ScrollerType.RANDOM}, {label: 'Magic Shelf', value: ScrollerType.MAGIC_SHELF} @@ -102,6 +103,8 @@ export class DashboardSettingsComponent implements OnInit { switch (scroller.type) { case ScrollerType.LAST_READ: return 'Continue Reading'; + case ScrollerType.LAST_LISTENED: + return 'Continue Listening'; case ScrollerType.LATEST_ADDED: return 'Recently Added'; case ScrollerType.RANDOM: diff --git a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.html b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.html index 54ac23e8e..495e5fd61 100644 --- a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.html +++ b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.html @@ -57,6 +57,7 @@ [bookListType]="scroller.type" [title]="scroller.title" [isMagicShelf]="scroller.type === ScrollerType.MAGIC_SHELF" + [useSquareCovers]="scroller.type === ScrollerType.LAST_LISTENED" [books]="getBooksForScroller(scroller) | async"> } diff --git a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts index dc23d43fd..868cc21c7 100644 --- a/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts +++ b/booklore-ui/src/app/features/dashboard/components/main-dashboard/main-dashboard.component.ts @@ -74,7 +74,11 @@ export class MainDashboardComponent implements OnInit { private getLastReadBooks(maxItems: number, sortBy?: string): Observable { return this.bookService.bookState$.pipe( map((state: BookState) => { - let books = (state.books || []).filter(book => book.lastReadTime && (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED)); + let books = (state.books || []).filter(book => + book.lastReadTime && + (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) && + this.hasEbookProgress(book) + ); books = books.sort((a, b) => { const aTime = new Date(a.lastReadTime!).getTime(); const bTime = new Date(b.lastReadTime!).getTime(); @@ -85,6 +89,28 @@ export class MainDashboardComponent implements OnInit { ); } + private getLastListenedBooks(maxItems: number): Observable { + return this.bookService.bookState$.pipe( + map((state: BookState) => { + let books = (state.books || []).filter(book => + book.lastReadTime && + (book.readStatus === ReadStatus.READING || book.readStatus === ReadStatus.RE_READING || book.readStatus === ReadStatus.PAUSED) && + book.audiobookProgress + ); + books = books.sort((a, b) => { + const aTime = new Date(a.lastReadTime!).getTime(); + const bTime = new Date(b.lastReadTime!).getTime(); + return bTime - aTime; + }); + return books.slice(0, maxItems); + }) + ); + } + + private hasEbookProgress(book: Book): boolean { + return !!(book.epubProgress || book.pdfProgress || book.cbxProgress || book.koreaderProgress || book.koboProgress); + } + private getLatestAddedBooks(maxItems: number, sortBy?: string): Observable { return this.bookService.bookState$.pipe( map((state: BookState) => { @@ -156,6 +182,9 @@ export class MainDashboardComponent implements OnInit { case ScrollerType.LAST_READ: books$ = this.getLastReadBooks(config.maxItems || DEFAULT_MAX_ITEMS); break; + case ScrollerType.LAST_LISTENED: + books$ = this.getLastListenedBooks(config.maxItems || DEFAULT_MAX_ITEMS); + break; case ScrollerType.LATEST_ADDED: books$ = this.getLatestAddedBooks(config.maxItems || DEFAULT_MAX_ITEMS); break; diff --git a/booklore-ui/src/app/features/dashboard/models/dashboard-config.model.ts b/booklore-ui/src/app/features/dashboard/models/dashboard-config.model.ts index 46d120508..403070a2e 100644 --- a/booklore-ui/src/app/features/dashboard/models/dashboard-config.model.ts +++ b/booklore-ui/src/app/features/dashboard/models/dashboard-config.model.ts @@ -2,6 +2,7 @@ import {DEFAULT_MAX_ITEMS} from '../components/dashboard-settings/dashboard-sett export enum ScrollerType { LAST_READ = 'lastRead', + LAST_LISTENED = 'lastListened', LATEST_ADDED = 'latestAdded', RANDOM = 'random', MAGIC_SHELF = 'magicShelf' @@ -25,8 +26,9 @@ export interface DashboardConfig { export const DEFAULT_DASHBOARD_CONFIG: DashboardConfig = { scrollers: [ - {id: '1', type: ScrollerType.LAST_READ, title: 'Continue Reading', enabled: true, order: 1, maxItems: DEFAULT_MAX_ITEMS}, - {id: '2', type: ScrollerType.LATEST_ADDED, title: 'Recently Added', enabled: true, order: 2, maxItems: DEFAULT_MAX_ITEMS}, - {id: '3', type: ScrollerType.RANDOM, title: 'Discover Something New', enabled: true, order: 3, maxItems: DEFAULT_MAX_ITEMS} + {id: '1', type: ScrollerType.LAST_LISTENED, title: 'Continue Listening', enabled: true, order: 1, maxItems: DEFAULT_MAX_ITEMS}, + {id: '2', type: ScrollerType.LAST_READ, title: 'Continue Reading', enabled: true, order: 2, maxItems: DEFAULT_MAX_ITEMS}, + {id: '3', type: ScrollerType.LATEST_ADDED, title: 'Recently Added', enabled: true, order: 3, maxItems: DEFAULT_MAX_ITEMS}, + {id: '4', type: ScrollerType.RANDOM, title: 'Discover Something New', enabled: true, order: 4, maxItems: DEFAULT_MAX_ITEMS} ] }; diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.html b/booklore-ui/src/app/features/library-creator/library-creator.component.html index 66d1da5ee..2db1a83f5 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.html +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.html @@ -155,6 +155,60 @@ }
+ +
+
+ Allowed formats + +
+ +
+
+ + +
+ + @if (!allowAllFormats) { +
+ @for (format of allBookFormats; track format.type) { +
+ + + @if (getFormatWarning(format.type); as warning) { + + } +
+ } +
+ @if (hasAnyFormatWarning()) { +
+ + Deselected formats with existing books will not be affected, but won't appear in future scans +
+ } + } +
+
diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.scss b/booklore-ui/src/app/features/library-creator/library-creator.component.scss index cd48d4161..d814e5086 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.scss +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.scss @@ -2,7 +2,7 @@ max-width: 90vw; display: flex; flex-direction: column; - max-height: 85vh; + max-height: 90vh; background: var(--card-background); border: 1px solid var(--border-color); border-radius: 12px; @@ -88,7 +88,7 @@ display: flex; align-items: center; gap: 0.5rem; - margin-bottom: 1.125rem; + margin-bottom: 0.75rem; font-size: 0.85rem; font-weight: 600; text-transform: uppercase; @@ -408,7 +408,8 @@ --p-toggleswitch-checked-hover-background: var(--p-green-600); } - &.format-priority-option { + &.format-priority-option, + &.allowed-formats-option { flex-direction: column; align-items: flex-start; } @@ -434,6 +435,78 @@ } } +// Allowed formats +.allowed-formats-container { + display: flex; + flex-direction: column; + gap: 0.875rem; + width: 100%; +} + +.allow-all-toggle { + display: flex; + align-items: center; + gap: 0.5rem; + + .allow-all-label { + font-size: 0.875rem; + color: var(--text-color); + cursor: pointer; + } +} + +.format-checkboxes { + display: flex; + flex-wrap: wrap; + gap: 0.75rem 1.25rem; + padding: 0.75rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-radius: 6px; +} + +.format-checkbox-item { + display: flex; + align-items: center; + gap: 0.375rem; + min-width: 100px; + + .format-checkbox-label { + font-size: 0.8rem; + color: var(--text-color); + cursor: pointer; + } + + .warning-icon { + font-size: 0.75rem; + color: var(--p-orange-400); + margin-left: 0.25rem; + } + + &.has-warning { + .format-checkbox-label { + color: var(--p-orange-400); + } + } +} + +.format-warning-message { + display: flex; + align-items: flex-start; + gap: 0.5rem; + padding: 0.625rem 0.75rem; + background: rgba(234, 179, 8, 0.1); + border: 1px solid var(--p-orange-400); + border-radius: 6px; + font-size: 0.8rem; + color: var(--p-orange-400); + + i { + flex-shrink: 0; + margin-top: 0.125rem; + } +} + // Format chips .format-chips { display: flex; diff --git a/booklore-ui/src/app/features/library-creator/library-creator.component.ts b/booklore-ui/src/app/features/library-creator/library-creator.component.ts index c2cf3e473..d9da9caef 100644 --- a/booklore-ui/src/app/features/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/features/library-creator/library-creator.component.ts @@ -16,12 +16,13 @@ import {DialogLauncherService} from '../../shared/services/dialog-launcher.servi import {switchMap} from 'rxjs/operators'; import {map} from 'rxjs'; import {CdkDragDrop, DragDropModule, moveItemInArray} from '@angular/cdk/drag-drop'; +import {Checkbox} from 'primeng/checkbox'; @Component({ selector: 'app-library-creator', standalone: true, templateUrl: './library-creator.component.html', - imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule], + imports: [FormsModule, InputText, ToggleSwitch, Tooltip, Button, IconDisplayComponent, DragDropModule, Checkbox], styleUrl: './library-creator.component.scss' }) export class LibraryCreatorComponent implements OnInit { @@ -34,6 +35,9 @@ export class LibraryCreatorComponent implements OnInit { editModeLibraryName: string = ''; watch: boolean = false; formatPriority: {type: BookType, label: string}[] = []; + allowAllFormats: boolean = true; + selectedAllowedFormats: Set = new Set(); + formatCounts: Record = {}; readonly allBookFormats: {type: BookType, label: string}[] = [ {type: 'EPUB', label: 'EPUB'}, @@ -55,13 +59,14 @@ export class LibraryCreatorComponent implements OnInit { ngOnInit(): void { this.initializeFormatPriority(); + this.initializeAllowedFormats(); const data = this.dynamicDialogConfig?.data; if (data?.mode === 'edit') { this.mode = data.mode; this.library = this.libraryService.findLibraryById(data.libraryId); if (this.library) { - const {name, icon, iconType, paths, watch, formatPriority} = this.library; + const {name, icon, iconType, paths, watch, formatPriority, allowedFormats} = this.library; this.chosenLibraryName = name; this.editModeLibraryName = name; @@ -84,6 +89,19 @@ export class LibraryCreatorComponent implements OnInit { } }); } + + if (allowedFormats && allowedFormats.length > 0) { + this.allowAllFormats = false; + this.selectedAllowedFormats = new Set(allowedFormats); + } else { + this.allowAllFormats = true; + this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); + } + + this.libraryService.getBookCountsByFormat(this.library.id!).subscribe(counts => { + this.formatCounts = counts; + }); + this.folders = paths.map(path => path.path); } } @@ -93,6 +111,43 @@ export class LibraryCreatorComponent implements OnInit { this.formatPriority = [...this.allBookFormats]; } + private initializeAllowedFormats(): void { + this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); + } + + onAllowAllFormatsChange(): void { + if (this.allowAllFormats) { + this.selectedAllowedFormats = new Set(this.allBookFormats.map(f => f.type)); + } + } + + onFormatCheckboxChange(formatType: BookType, checked: boolean): void { + if (checked) { + this.selectedAllowedFormats.add(formatType); + } else { + this.selectedAllowedFormats.delete(formatType); + } + this.allowAllFormats = this.selectedAllowedFormats.size === this.allBookFormats.length; + } + + isFormatSelected(formatType: BookType): boolean { + return this.selectedAllowedFormats.has(formatType); + } + + getFormatWarning(formatType: BookType): string | null { + if (this.mode !== 'edit') return null; + const count = this.formatCounts[formatType]; + if (count && count > 0 && !this.selectedAllowedFormats.has(formatType)) { + return `${count} existing book${count > 1 ? 's' : ''} will not appear in future scans`; + } + return null; + } + + hasAnyFormatWarning(): boolean { + if (this.mode !== 'edit') return false; + return this.allBookFormats.some(f => this.getFormatWarning(f.type) !== null); + } + closeDialog(): void { this.dynamicDialogRef.close(); } @@ -161,7 +216,8 @@ export class LibraryCreatorComponent implements OnInit { iconType: iconType, paths: this.folders.map(folder => ({path: folder})), watch: this.watch, - formatPriority: this.formatPriority.map(f => f.type) + formatPriority: this.formatPriority.map(f => f.type), + allowedFormats: this.allowAllFormats ? [] : Array.from(this.selectedAllowedFormats) }; if (this.mode === 'edit') { 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 468388ece..7db5987f8 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 @@ -8,73 +8,161 @@ }
-
- - - @if (isUploading) { - +
+ + @if (hasEbookFormat(book)) { +
+ @if (supportsDualCovers(book)) { +
+ Ebook Cover +
+ } + + + @if (isUploading) { + + } +
+ @if (!book.isPhysical) { + + + } + + + + + + + @if (!book.metadata!['coverLocked']) { + + } + @if (book.metadata!['coverLocked']) { + + } +
+
+ } + + + @if (hasAudiobookFormat(book)) { +
+
+ Audiobook Cover +
+ + + @if (isUploading) { + + } +
+ + + + + + + + + @if (!book.metadata!['audiobookCoverLocked']) { + + } + @if (book.metadata!['audiobookCoverLocked']) { + + } +
+
} -
- - - - - - - - - @if (!book.metadata!['coverLocked']) { - - } - @if (book.metadata!['coverLocked']) { - - } -
@@ -596,6 +684,48 @@
} + @if (isFieldVisible('audibleId')) { + + } + @if (isFieldVisible('audibleRating')) { + + } + @if (isFieldVisible('audibleReviewCount')) { + + }
diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.scss index 60011f981..a1b701d61 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.scss @@ -6,10 +6,6 @@ } } -::ng-deep p-image { - width: 250px; -} - ::ng-deep .cover-item p-image { width: 150px; } @@ -120,15 +116,64 @@ label { } } +.covers-section { + display: flex; + flex-direction: column; + gap: 1.5rem; + flex-shrink: 0; + margin: 0 auto; + + &.dual-covers { + flex-direction: row; + gap: 1rem; + + @media (max-width: 767px) { + flex-direction: column; + align-items: center; + } + } +} + .cover-section { display: flex; flex-direction: column; align-items: center; - gap: 0; + gap: 0.5rem; position: relative; - width: 250px; flex-shrink: 0; - margin: 0 auto; + + &.audiobook-cover-section { + ::ng-deep .square-cover img { + aspect-ratio: 1; + object-fit: cover; + border-radius: 0.5rem; + } + } +} + +.cover-type-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.8rem; + font-weight: 600; + padding: 0.25rem 0.75rem; + border-radius: 0.5rem; + margin-bottom: 0.25rem; + + i { + font-size: 0.9rem; + } + + &.ebook { + color: var(--primary-color); + background: color-mix(in srgb, var(--primary-color) 15%, transparent); + } + + &.audiobook { + color: var(--purple-500); + background: color-mix(in srgb, var(--purple-500) 15%, transparent); + } } .upload-spinner { diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index 89ad15000..6783867de 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -80,6 +80,7 @@ export class MetadataEditorComponent implements OnInit { isLoading = false; isSaving = false; isGeneratingCover = false; + isGeneratingAudiobookCover = false; refreshingBookIds = new Set(); isAutoFetching = false; @@ -118,6 +119,9 @@ export class MetadataEditorComponent implements OnInit { lubimyczytacRating: true, ranobedbId: true, ranobedbRating: true, + audibleId: true, + audibleRating: true, + audibleReviewCount: true, }; navigationState$ = this.bookNavigationService.getNavigationState(); @@ -195,10 +199,14 @@ export class MetadataEditorComponent implements OnInit { ranobedbId: new FormControl(""), ranobedbRating: new FormControl(""), googleId: new FormControl(""), + audibleId: new FormControl(""), + audibleRating: new FormControl(""), + audibleReviewCount: new FormControl(""), seriesName: new FormControl(""), seriesNumber: new FormControl(""), seriesTotal: new FormControl(""), thumbnailUrl: new FormControl(""), + audiobookCover: new FormControl(""), titleLocked: new FormControl(false), subtitleLocked: new FormControl(false), @@ -229,10 +237,14 @@ export class MetadataEditorComponent implements OnInit { ranobedbIdLocked: new FormControl(""), ranobedbRatingLocked: new FormControl(false), googleIdLocked: new FormControl(false), + audibleIdLocked: new FormControl(false), + audibleRatingLocked: new FormControl(false), + audibleReviewCountLocked: new FormControl(false), seriesNameLocked: new FormControl(false), seriesNumberLocked: new FormControl(false), seriesTotalLocked: new FormControl(false), coverLocked: new FormControl(false), + audiobookCoverLocked: new FormControl(false), reviewsLocked: new FormControl(false), }); } @@ -345,6 +357,9 @@ export class MetadataEditorComponent implements OnInit { ranobedbId: metadata.ranobedbId ?? null, ranobedbRating: metadata.ranobedbRating ?? null, googleId: metadata.googleId ?? null, + audibleId: metadata.audibleId ?? null, + audibleRating: metadata.audibleRating ?? null, + audibleReviewCount: metadata.audibleReviewCount ?? null, seriesName: metadata.seriesName ?? null, seriesNumber: metadata.seriesNumber ?? null, seriesTotal: metadata.seriesTotal ?? null, @@ -377,10 +392,14 @@ export class MetadataEditorComponent implements OnInit { ranobedbIdLocked: metadata.ranobedbIdLocked ?? false, ranobedbRatingLocked: metadata.ranobedbRatingLocked ?? false, googleIdLocked: metadata.googleIdLocked ?? false, + audibleIdLocked: metadata.audibleIdLocked ?? false, + audibleRatingLocked: metadata.audibleRatingLocked ?? false, + audibleReviewCountLocked: metadata.audibleReviewCountLocked ?? false, seriesNameLocked: metadata.seriesNameLocked ?? false, seriesNumberLocked: metadata.seriesNumberLocked ?? false, seriesTotalLocked: metadata.seriesTotalLocked ?? false, coverLocked: metadata.coverLocked ?? false, + audiobookCoverLocked: metadata.audiobookCoverLocked ?? false, reviewsLocked: metadata.reviewsLocked ?? false, }); @@ -413,12 +432,16 @@ export class MetadataEditorComponent implements OnInit { {key: "ranobedbIdLocked", control: "ranobedbId"}, {key: "ranobedbRatingLocked", control: "ranobedbRating"}, {key: "googleIdLocked", control: "googleId"}, + {key: "audibleIdLocked", control: "audibleId"}, + {key: "audibleRatingLocked", control: "audibleRating"}, + {key: "audibleReviewCountLocked", control: "audibleReviewCount"}, {key: "pageCountLocked", control: "pageCount"}, {key: "descriptionLocked", control: "description"}, {key: "seriesNameLocked", control: "seriesName"}, {key: "seriesNumberLocked", control: "seriesNumber"}, {key: "seriesTotalLocked", control: "seriesTotal"}, {key: "coverLocked", control: "thumbnailUrl"}, + {key: "audiobookCoverLocked", control: "audiobookCover"}, {key: "reviewsLocked", control: "reviews"}, ]; @@ -496,6 +519,7 @@ export class MetadataEditorComponent implements OnInit { const isLocked = this.metadataForm.get(field + "Locked")?.value; const updatedLockedState = !isLocked; this.metadataForm.get(field + "Locked")?.setValue(updatedLockedState); + if (updatedLockedState) { this.metadataForm.get(field)?.disable(); } else { @@ -561,11 +585,15 @@ export class MetadataEditorComponent implements OnInit { ranobedbId: form.get("ranobedbId")?.value, ranobedbRating: form.get("ranobedbRating")?.value, googleId: form.get("googleId")?.value, + audibleId: form.get("audibleId")?.value, + audibleRating: form.get("audibleRating")?.value, + audibleReviewCount: form.get("audibleReviewCount")?.value, language: form.get("language")?.value, seriesName: form.get("seriesName")?.value, seriesNumber: form.get("seriesNumber")?.value, seriesTotal: form.get("seriesTotal")?.value, thumbnailUrl: form.get("thumbnailUrl")?.value, + audiobookCover: form.get("audiobookCover")?.value, // Locks titleLocked: form.get("titleLocked")?.value, @@ -597,10 +625,14 @@ export class MetadataEditorComponent implements OnInit { ranobedbIdLocked: form.get("ranobedbIdLocked")?.value, ranobedbRatingLocked: form.get("ranobedbRatingLocked")?.value, googleIdLocked: form.get("googleIdLocked")?.value, + audibleIdLocked: form.get("audibleIdLocked")?.value, + audibleRatingLocked: form.get("audibleRatingLocked")?.value, + audibleReviewCountLocked: form.get("audibleReviewCountLocked")?.value, seriesNameLocked: form.get("seriesNameLocked")?.value, seriesNumberLocked: form.get("seriesNumberLocked")?.value, seriesTotalLocked: form.get("seriesTotalLocked")?.value, coverLocked: form.get("coverLocked")?.value, + audiobookCoverLocked: form.get("audiobookCoverLocked")?.value, reviewsLocked: form.get("reviewsLocked")?.value, ...(shouldLockAllFields !== undefined && { @@ -650,9 +682,13 @@ export class MetadataEditorComponent implements OnInit { ranobedbId: wasCleared("ranobedbId"), ranobedbRating: wasCleared("ranobedbRating"), googleId: wasCleared("googleId"), + audibleId: wasCleared("audibleId"), + audibleRating: wasCleared("audibleRating"), + audibleReviewCount: wasCleared("audibleReviewCount"), seriesName: wasCleared("seriesName"), seriesNumber: wasCleared("seriesNumber"), seriesTotal: wasCleared("seriesTotal"), + audiobookCover: wasCleared("audiobookCover"), cover: false, }; @@ -742,6 +778,13 @@ export class MetadataEditorComponent implements OnInit { }, }); }, + error: (err) => { + this.messageService.add({ + severity: "error", + summary: "Error", + detail: err?.error?.message || "Failed to regenerate cover", + }); + } }); } @@ -779,6 +822,71 @@ export class MetadataEditorComponent implements OnInit { }); } + regenerateAudiobookCover(bookId: number) { + this.bookService.regenerateAudiobookCover(bookId).subscribe({ + next: () => { + this.bookService.getBookByIdFromAPI(bookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + this.messageService.add({ + severity: "success", + summary: "Success", + detail: "Audiobook cover regenerated successfully.", + }); + }, + error: () => { + this.messageService.add({ + severity: "warning", + summary: "Partial Success", + detail: "Cover regenerated but failed to refresh display. Please refresh the page.", + }); + }, + }); + }, + error: (err) => { + this.messageService.add({ + severity: "error", + summary: "Error", + detail: err?.error?.message || "Failed to regenerate audiobook cover", + }); + } + }); + } + + generateCustomAudiobookCover(bookId: number) { + this.isGeneratingAudiobookCover = true; + this.bookService.generateCustomAudiobookCover(bookId) + .pipe(finalize(() => this.isGeneratingAudiobookCover = false)) + .subscribe({ + next: () => { + this.bookService.getBookByIdFromAPI(bookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + this.messageService.add({ + severity: "success", + summary: "Success", + detail: "Custom audiobook cover generated successfully.", + }); + }, + error: () => { + this.messageService.add({ + severity: "warning", + summary: "Partial Success", + detail: "Cover generated but failed to refresh display. Please refresh the page.", + }); + }, + }); + }, + error: (err) => { + this.messageService.add({ + severity: "error", + summary: "Error", + detail: "Failed to generate custom audiobook cover", + }); + } + }); + } + autoFetch(bookId: number) { this.refreshingBookIds.add(bookId); this.isAutoFetching = true; @@ -818,11 +926,14 @@ export class MetadataEditorComponent implements OnInit { } openCoverSearch() { - const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId); + const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId, 'ebook'); ref?.onClose.subscribe((result) => { if (result) { - this.metadataForm.get("thumbnailUrl")?.setValue(result); - this.onSave(); + this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + }, + }); } }); } @@ -882,4 +993,60 @@ export class MetadataEditorComponent implements OnInit { onFieldChange(): void { this.metadataForm.markAsDirty(); } + + // Cover type detection methods + hasEbookFormat(book: Book): boolean { + if (book.isPhysical) { + return true; + } + const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); + return allFiles.some(f => f!.bookType !== 'AUDIOBOOK'); + } + + hasAudiobookFormat(book: Book): boolean { + const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); + return allFiles.some(f => f!.bookType === 'AUDIOBOOK'); + } + + supportsDualCovers(book: Book): boolean { + return this.bookService.supportsDualCovers(book); + } + + getUploadAudiobookCoverUrl(): string { + return this.bookService.getUploadAudiobookCoverUrl(this.currentBookId); + } + + openAudiobookCoverSearch() { + const ref = this.bookDialogHelperService.openCoverSearchDialog(this.currentBookId, 'audiobook'); + ref?.onClose.subscribe((result) => { + if (result) { + this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + }, + }); + } + }); + } + + onAudiobookCoverUpload(event: FileUploadEvent): void { + const response: HttpResponse = + event.originalEvent as HttpResponse; + if (response && response.status === 200) { + this.isUploading = false; + this.bookService.getBookByIdFromAPI(this.currentBookId, false).subscribe({ + next: (updatedBook) => { + this.bookService.handleBookUpdate(updatedBook); + }, + }); + } else { + this.isUploading = false; + this.messageService.add({ + severity: 'error', + summary: 'Upload Failed', + detail: 'An error occurred while uploading the audiobook cover', + life: 3000, + }); + } + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html index 7d9d64bc2..54ce65a5e 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.html @@ -40,62 +40,143 @@ Cover Image
-
-
- -
-
- Current -
- - +
+ + @if (!currentBook || hasEbookFormat(currentBook)) { +
+ +
+
+ Current +
+ + +
-
- + -
- Fetched -
- +
+ Fetched +
+ +
-
+ } + + + @if (currentBook && hasAudiobookFormat(currentBook)) { +
+ +
+
+ Current +
+ + +
+
+ + @if (isAudibleProvider()) { + + } @else { +
+ } + +
+ Fetched +
+ @if (isAudibleProvider()) { + + } @else { +
+ + N/A +
+ } +
+
+
+
+ }
@@ -261,16 +342,108 @@
- - @if (metadataFieldsBottom.length > 0) { + +
+
+ + Series Information +
+ +
+ @for (field of metadataSeriesFields; track field) { +
+ +
+
+ + +
+ + + +
+ +
+
+
+ } +
+
+ + +
+
+ + Book Details +
+ +
+ @for (field of metadataBookDetailsFields; track field) { +
+ +
+
+ + +
+ + + +
+ +
+
+
+ } +
+
+ + + @if (metadataProviderFields.length > 0) {
- - Additional Details + + Provider Metadata
- @for (field of metadataFieldsBottom; track field) { + @for (field of metadataProviderFields; track field) {
@@ -308,6 +481,72 @@
} + + + @if (currentBook && hasAudiobookFormat(currentBook)) { +
+
+ + Audiobook Details +
+ +
+ @for (field of audiobookMetadataFields; track field) { +
+ +
+
+ + @if (field.type === 'boolean') { + + } @else { + + } +
+ + + +
+ @if (field.type === 'boolean') { + + } @else { + + } +
+
+
+ } +
+
+ }
@if (!reviewMode) { diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.scss index a420294ff..8317fae41 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.scss @@ -144,21 +144,20 @@ } .cover-image { - width: 100px; - height: 150px; + width: 120px; + height: auto; border-radius: 6px; overflow: hidden; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15); @media (min-width: 768px) { - width: 120px; - height: 180px; + width: 150px; } ::ng-deep img { width: 100%; - height: 100%; - object-fit: cover; + height: auto; + display: block; } } @@ -199,6 +198,65 @@ color: var(--text-secondary-color); } +// Cover type icon in label +.cover-type-icon { + font-size: 0.8rem; + margin-right: 0.25rem; +} + +// Square cover for audiobooks +.square-cover { + aspect-ratio: 1; + + ::ng-deep img { + object-fit: cover; + aspect-ratio: 1; + } +} + +// Audiobook cover row +.audiobook-cover-row { + background: rgba(var(--p-primary-500-rgb), 0.03); +} + +// Transfer button placeholder (same width as button) +.transfer-btn-placeholder { + width: 32px; + height: 32px; + flex-shrink: 0; +} + +// No cover placeholder +.no-cover-placeholder { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 120px; + height: 120px; + background: var(--surface-ground); + border: 1px dashed var(--border-color); + border-radius: 6px; + color: var(--text-secondary-color); + + @media (min-width: 768px) { + width: 150px; + height: 150px; + } + + i { + font-size: 1.75rem; + margin-bottom: 0.5rem; + opacity: 0.5; + } + + span { + font-size: 0.75rem; + text-transform: uppercase; + letter-spacing: 0.05em; + } +} + // Field Rows .field-row { @@ -221,7 +279,7 @@ // Cover field row specific styles .cover-field-row { - padding: 1.25rem 1rem; + padding: 1rem; .field-label { text-align: center; @@ -255,7 +313,7 @@ // Position covers towards the arrow on desktop only @media (min-width: 768px) { - padding: 1.5rem 1rem; + padding: 1rem; .field-side.current { justify-content: flex-end; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts index c0a07247b..a10c5dc9b 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-picker/metadata-picker.component.ts @@ -5,19 +5,20 @@ import {Button} from 'primeng/button'; import {FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {InputText} from 'primeng/inputtext'; import {AsyncPipe} from '@angular/common'; -import {Observable} from 'rxjs'; +import {forkJoin, Observable} from 'rxjs'; import {Tooltip} from 'primeng/tooltip'; import {UrlHelperService} from '../../../../../shared/service/url-helper.service'; import {BookService} from '../../../../book/service/book.service'; import {Textarea} from 'primeng/textarea'; -import {filter, map, take} from 'rxjs/operators'; +import {filter, take} from 'rxjs/operators'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {AutoComplete, AutoCompleteSelectEvent} from 'primeng/autocomplete'; import {Image} from 'primeng/image'; +import {Checkbox} from 'primeng/checkbox'; import {LazyLoadImageModule} from 'ng-lazyload-image'; import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; import {MetadataProviderSpecificFields} from '../../../../../shared/model/app-settings.model'; -import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata'; +import {ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, getArrayFields, getBookDetailsFields, getBottomFields, getProviderFields, getSeriesFields, getTextareaFields, getTopFields, MetadataFieldConfig, MetadataFormBuilder, MetadataUtilsService} from '../../../../../shared/metadata'; @Component({ selector: 'app-metadata-picker', @@ -34,7 +35,8 @@ import {ALL_METADATA_FIELDS, getArrayFields, getBottomFields, getTextareaFields, Textarea, AutoComplete, Image, - LazyLoadImageModule + LazyLoadImageModule, + Checkbox ] }) export class MetadataPickerComponent implements OnInit { @@ -43,13 +45,19 @@ export class MetadataPickerComponent implements OnInit { metadataFieldsTop: MetadataFieldConfig[] = []; metadataChips: MetadataFieldConfig[] = []; metadataDescription: MetadataFieldConfig[] = []; + metadataSeriesFields: MetadataFieldConfig[] = []; + metadataBookDetailsFields: MetadataFieldConfig[] = []; + metadataProviderFields: MetadataFieldConfig[] = []; metadataFieldsBottom: MetadataFieldConfig[] = []; + audiobookMetadataFields: MetadataFieldConfig[] = []; @Input() reviewMode!: boolean; @Input() fetchedMetadata!: BookMetadata; @Input() book$!: Observable; @Output() goBack = new EventEmitter(); + currentBook: Book | null = null; + private allItems: Record = {}; filteredItems: Record = {}; @@ -80,7 +88,15 @@ export class MetadataPickerComponent implements OnInit { this.metadataFieldsTop = getTopFields(); this.metadataChips = getArrayFields(); this.metadataDescription = getTextareaFields(); + this.metadataSeriesFields = getSeriesFields(); + this.metadataBookDetailsFields = getBookDetailsFields(); + this.updateProviderFields(); this.updateBottomFields(); + this.audiobookMetadataFields = AUDIOBOOK_METADATA_FIELDS; + } + + private updateProviderFields(): void { + this.metadataProviderFields = getProviderFields(this.enabledProviderFields); } private updateBottomFields(): void { @@ -106,6 +122,7 @@ export class MetadataPickerComponent implements OnInit { .subscribe(settings => { if (settings?.metadataProviderSpecificFields) { this.enabledProviderFields = settings.metadataProviderSpecificFields; + this.updateProviderFields(); this.updateBottomFields(); } }); @@ -138,9 +155,8 @@ export class MetadataPickerComponent implements OnInit { this.book$ .pipe( filter((book): book is Book => !!book && !!book.metadata), - map(book => book.metadata), takeUntilDestroyed(this.destroyRef) - ).subscribe((metadata) => { + ).subscribe((book) => { if (this.reviewMode) { this.metadataForm.reset(); this.copiedFields = {}; @@ -148,16 +164,16 @@ export class MetadataPickerComponent implements OnInit { this.hoveredFields = {}; } - if (metadata) { - this.originalMetadata = metadata; - this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); - this.currentBookId = metadata.bookId; - this.patchMetadataToForm(metadata); - } + this.currentBook = book; + const metadata = book.metadata!; + this.originalMetadata = metadata; + this.originalMetadata.thumbnailUrl = this.urlHelper.getThumbnailUrl(metadata.bookId, metadata.coverUpdatedOn); + this.currentBookId = metadata.bookId; + this.patchMetadataToForm(metadata, book); }); } - private patchMetadataToForm(metadata: BookMetadata): void { + private patchMetadataToForm(metadata: BookMetadata, book: Book): void { const patchData: Record = {}; for (const field of ALL_METADATA_FIELDS) { @@ -173,10 +189,26 @@ export class MetadataPickerComponent implements OnInit { patchData[field.lockedKey] = metadata[lockedKey] ?? false; } - // Handle special fields + // Handle special fields - ebook cover patchData['thumbnailUrl'] = this.urlHelper.getCoverUrl(metadata.bookId, metadata.coverUpdatedOn); patchData['coverLocked'] = metadata.coverLocked ?? false; + // Handle audiobook cover + patchData['audiobookThumbnailUrl'] = this.urlHelper.getAudiobookCoverUrl(metadata.bookId, metadata.audiobookCoverUpdatedOn); + patchData['audiobookCoverLocked'] = metadata.audiobookCoverLocked ?? false; + + // Handle audiobook-specific metadata fields + // narrator/abridged are now at top-level of BookMetadata, but we also check nested for backward compatibility + for (const field of AUDIOBOOK_METADATA_FIELDS) { + const key = field.controlName as keyof BookMetadata; + const lockedKey = field.lockedKey as keyof BookMetadata; + // Prefer top-level fields, fallback to nested audiobookMetadata + const topLevelValue = metadata[key]; + const topLevelLocked = metadata[lockedKey]; + patchData[field.controlName] = topLevelValue ?? (field.type === 'boolean' ? null : ''); + patchData[field.lockedKey] = topLevelLocked ?? false; + } + this.metadataForm.patchValue(patchData); this.applyLockStates(metadata); } @@ -186,6 +218,10 @@ export class MetadataPickerComponent implements OnInit { for (const field of ALL_METADATA_FIELDS) { lockedFields[field.lockedKey] = !!metadata[field.lockedKey as keyof BookMetadata]; } + // Also handle audiobook metadata lock states (now at top-level of BookMetadata) + for (const field of AUDIOBOOK_METADATA_FIELDS) { + lockedFields[field.lockedKey] = !!metadata[field.lockedKey as keyof BookMetadata]; + } this.formBuilder.applyLockStates(this.metadataForm, lockedFields); } @@ -214,7 +250,20 @@ export class MetadataPickerComponent implements OnInit { onSave(): void { this.isSaving = true; const updatedBookMetadata = this.buildMetadataWrapper(undefined); - this.bookService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false).subscribe({ + + const requests: Observable[] = [ + this.bookService.updateBookMetadata(this.currentBookId, updatedBookMetadata, false) + ]; + + // Handle audiobook cover upload when fetched from Audible provider + if (this.isAudibleProvider() && this.copiedFields['audiobookThumbnailUrl']) { + const audiobookCoverUrl = this.fetchedMetadata.thumbnailUrl; + if (audiobookCoverUrl) { + requests.push(this.bookService.uploadAudiobookCoverFromUrl(this.currentBookId, audiobookCoverUrl)); + } + } + + forkJoin(requests).subscribe({ next: () => { this.isSaving = false; for (const field of Object.keys(this.copiedFields)) { @@ -254,6 +303,8 @@ export class MetadataPickerComponent implements OnInit { metadata[field.controlName] = this.getArrayValue(field.controlName); } else if (field.type === 'number') { metadata[field.controlName] = this.getNumberValue(field.controlName); + } else if (field.type === 'boolean') { + metadata[field.controlName] = this.getBooleanValue(field.controlName); } else { metadata[field.controlName] = this.getStringValue(field.controlName); } @@ -263,6 +314,17 @@ export class MetadataPickerComponent implements OnInit { metadata['thumbnailUrl'] = this.getThumbnail(); metadata['coverLocked'] = this.metadataForm.get('coverLocked')?.value; + metadata['audiobookCoverLocked'] = this.metadataForm.get('audiobookCoverLocked')?.value; + + // Set audiobook content metadata (narrator/abridged) at top level + for (const field of AUDIOBOOK_METADATA_FIELDS) { + if (field.type === 'boolean') { + metadata[field.controlName] = this.getBooleanValue(field.controlName); + } else { + metadata[field.controlName] = this.getStringValue(field.controlName); + } + metadata[field.lockedKey] = this.metadataForm.get(field.lockedKey)?.value ?? false; + } return metadata as BookMetadata; } @@ -304,6 +366,17 @@ export class MetadataPickerComponent implements OnInit { return Array.isArray(fieldValue) ? fieldValue as string[] : []; } + private getBooleanValue(field: string): boolean | null { + const formValue = this.metadataForm.get(field)?.value; + if (formValue === null || formValue === undefined) { + if (this.copiedFields[field]) { + return (this.fetchedMetadata[field as keyof BookMetadata] as boolean | null) ?? null; + } + return null; + } + return !!formValue; + } + private inferClearFlags(current: BookMetadata, original: BookMetadata): MetadataClearFlags { const flags: Record = {}; @@ -316,16 +389,36 @@ export class MetadataPickerComponent implements OnInit { flags[key] = !(curr as string[])?.length && !!(orig as string[])?.length; } else if (field.type === 'number') { flags[key] = curr === null && orig !== null; + } else if (field.type === 'boolean') { + flags[key] = curr === null && orig !== null; } else { flags[key] = !curr && !!orig; } } flags['cover'] = !current.thumbnailUrl && !!original.thumbnailUrl; + + // Handle audiobook metadata clear flags (now at top-level of BookMetadata) + for (const field of AUDIOBOOK_METADATA_FIELDS) { + const key = field.controlName as keyof BookMetadata; + const curr = current[key]; + const orig = original[key]; + + if (field.type === 'boolean') { + flags[key] = curr === null && orig !== null; + } else { + flags[key] = !curr && !!orig; + } + } + return flags as MetadataClearFlags; } getThumbnail(): string | null { + // For Audible provider, cover is handled separately via uploadAudiobookCoverFromUrl + if (this.isAudibleProvider()) { + return null; + } const thumbnailUrl = this.metadataForm.get('thumbnailUrl')?.value; if (thumbnailUrl?.includes('api/v1')) { return null; @@ -360,16 +453,20 @@ export class MetadataPickerComponent implements OnInit { } toggleLock(field: string): void { + const controlName = field; + let lockField = field; if (field === 'thumbnailUrl') { - field = 'cover'; + lockField = 'cover'; + } else if (field === 'audiobookThumbnailUrl') { + lockField = 'audiobookCover'; } - const isLocked = this.metadataForm.get(field + 'Locked')?.value; + const isLocked = this.metadataForm.get(lockField + 'Locked')?.value; const updatedLockedState = !isLocked; - this.metadataForm.get(field + 'Locked')?.setValue(updatedLockedState); + this.metadataForm.get(lockField + 'Locked')?.setValue(updatedLockedState); if (updatedLockedState) { - this.metadataForm.get(field)?.disable(); + this.metadataForm.get(controlName)?.disable(); } else { - this.metadataForm.get(field)?.enable(); + this.metadataForm.get(controlName)?.enable(); } this.updateMetadata(undefined); } @@ -392,20 +489,26 @@ export class MetadataPickerComponent implements OnInit { } copyFetchedToCurrent(field: string): void { + let lockField = field; if (field === 'thumbnailUrl') { - field = 'cover'; + lockField = 'cover'; + } else if (field === 'audiobookThumbnailUrl') { + lockField = 'audiobookCover'; } - const isLocked = this.metadataForm.get(`${field}Locked`)?.value; + const isLocked = this.metadataForm.get(`${lockField}Locked`)?.value; if (isLocked) { this.messageService.add({ severity: 'warn', summary: 'Action Blocked', - detail: `${field} is locked and cannot be updated.` + detail: `${lockField} is locked and cannot be updated.` }); return; } - if (field === 'cover') { - field = 'thumbnailUrl'; + // For audiobook cover from Audible, use the thumbnailUrl from fetched metadata + if (field === 'audiobookThumbnailUrl') { + this.metadataForm.get('audiobookThumbnailUrl')?.setValue(this.fetchedMetadata.thumbnailUrl); + this.highlightCopiedInput(field); + return; } if (this.metadataUtils.copyFieldToForm(field, this.fetchedMetadata, this.metadataForm, this.copiedFields)) { this.highlightCopiedInput(field); @@ -451,4 +554,30 @@ export class MetadataPickerComponent implements OnInit { resetField(field: string): void { this.metadataUtils.resetField(field, this.metadataForm, this.originalMetadata, this.copiedFields, this.hoveredFields); } + + isAudibleProvider(): boolean { + return this.fetchedMetadata?.provider?.toLowerCase() === 'audible'; + } + + getFetchedAudiobookValue(key: string): unknown { + return this.fetchedMetadata?.[key as keyof BookMetadata]; + } + + // Cover type detection methods + hasEbookFormat(book: Book): boolean { + if (book.isPhysical) { + return true; + } + const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); + return allFiles.some(f => f!.bookType !== 'AUDIOBOOK'); + } + + hasAudiobookFormat(book: Book): boolean { + const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType); + return allFiles.some(f => f!.bookType === 'AUDIOBOOK'); + } + + supportsDualCovers(book: Book): boolean { + return this.hasEbookFormat(book) && this.hasAudiobookFormat(book); + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts index 2c0f996e9..3f3d0c28b 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts @@ -266,6 +266,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { if (metadata['lubimyczytacId']) return 'lubimyczytac'; if (metadata.comicvineId) return 'comicvine'; if (metadata.ranobedbId) return 'ranobedb'; + if (metadata.audibleId) return 'audible'; return null; } @@ -378,13 +379,15 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { return `Comicvine`; } else if (metadata.ranobedbId) { return `RanobeDB`; + } else if (metadata.audibleId) { + return `Audible`; } throw new Error("No provider ID found in metadata."); } trackByMetadata(index: number, metadata: BookMetadata): string { return metadata.googleId || metadata.goodreadsId || metadata.asin || - metadata.hardcoverId || metadata.comicvineId || index.toString(); + metadata.hardcoverId || metadata.comicvineId || metadata.audibleId || index.toString(); } onProviderClick(event: MouseEvent) { diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html index 2cd9b9f21..ad2332475 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.html @@ -8,6 +8,11 @@ Similar Books + @if (supportsDualCovers()) { + + Covers + + } Files @@ -54,6 +59,39 @@
+ + +
+
+
+
+ Ebook Cover +
+ + +
+
+
+ Audiobook Cover +
+ + +
+
+
+
+
diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.scss index 7195a70d3..fd7d05658 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.scss @@ -214,3 +214,53 @@ margin: 0; opacity: 0.8; } + +// Covers tab styles +.covers-tab-content { + padding: 1rem 0; +} + +.covers-grid { + display: flex; + flex-wrap: wrap; + gap: 2rem; + justify-content: center; + + @media (min-width: 768px) { + justify-content: flex-start; + } +} + +.cover-item { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.75rem; + + ::ng-deep .square-cover img { + aspect-ratio: 1; + object-fit: cover; + border-radius: 0.5rem; + } +} + +.cover-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.875rem; + font-weight: 600; + color: var(--primary-color); + padding: 0.25rem 0.75rem; + background: color-mix(in srgb, var(--primary-color) 15%, transparent); + border-radius: 0.5rem; + + i { + font-size: 1rem; + } + + &.audiobook { + color: var(--purple-500); + background: color-mix(in srgb, var(--purple-500) 15%, transparent); + } +} diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts index df80ce78a..c2bc75d24 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-tabs/metadata-tabs.component.ts @@ -1,4 +1,4 @@ -import {Component, EventEmitter, Input, Output} from '@angular/core'; +import {Component, EventEmitter, inject, Input, Output} from '@angular/core'; import {UpperCasePipe} from '@angular/common'; import {Book, BookRecommendation, BookType, FileInfo} from '../../../../../book/model/book.model'; import {Tab, TabList, TabPanel, TabPanels, Tabs} from 'primeng/tabs'; @@ -9,6 +9,9 @@ import {BookNotesComponent} from '../../../../../book/components/book-notes/book import {BookReadingSessionsComponent} from '../../book-reading-sessions/book-reading-sessions.component'; import {Button} from 'primeng/button'; import {Tooltip} from 'primeng/tooltip'; +import {Image} from 'primeng/image'; +import {UrlHelperService} from '../../../../../../shared/service/url-helper.service'; +import {BookService} from '../../../../../book/service/book.service'; export interface ReadEvent { bookId: number; @@ -59,7 +62,8 @@ export interface DeleteSupplementaryFileEvent { BookReadingSessionsComponent, Button, Tooltip, - UpperCasePipe + UpperCasePipe, + Image ], templateUrl: './metadata-tabs.component.html', styleUrl: './metadata-tabs.component.scss' @@ -69,6 +73,9 @@ export class MetadataTabsComponent { @Input() bookInSeries: Book[] = []; @Input() recommendedBooks: BookRecommendation[] = []; + protected urlHelper = inject(UrlHelperService); + private bookService = inject(BookService); + @Output() readBook = new EventEmitter(); @Output() downloadBook = new EventEmitter(); @Output() downloadFile = new EventEmitter(); @@ -161,4 +168,8 @@ export class MetadataTabsComponent { isPhysicalBook(): boolean { return !this.book?.primaryFile && (!this.book?.alternativeFormats || this.book.alternativeFormats.length === 0); } + + supportsDualCovers(): boolean { + return this.bookService.supportsDualCovers(this.book); + } } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html index 3fd035721..9c342ae95 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-viewer/metadata-viewer.component.html @@ -6,7 +6,7 @@
@if (book?.metadata?.seriesName) { - }
@@ -154,7 +154,7 @@
- @if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.lubimyczytacRating || book?.metadata?.ranobedbRating || book?.metadata?.googleId) { + @if (book?.metadata?.amazonRating || book?.metadata?.goodreadsRating || book?.metadata?.hardcoverRating || book?.metadata?.lubimyczytacRating || book?.metadata?.ranobedbRating || book?.metadata?.audibleRating || book?.metadata?.googleId) {
} @@ -229,6 +229,20 @@ } + @if (book?.metadata?.audibleRating) { + + Audible + {{ getRatingPercent(book.metadata!.audibleRating) }}% + + } + @if (book?.metadata?.googleId) {
- +
-

Search Cover Images

+

Search {{ coverType === 'audiobook' ? 'Audiobook' : 'Ebook' }} Cover

Find and select a cover for your book

0 ? book.metadata?.authors[0] : '' @@ -70,7 +78,7 @@ export class CoverSearchComponent implements OnInit { const request: CoverFetchRequest = { title: this.searchForm.value.title, author: this.searchForm.value.author, - squareCover: this.isAudiobook + coverType: this.coverType }; this.bookCoverService.fetchBookCovers(request) @@ -95,24 +103,27 @@ export class CoverSearchComponent implements OnInit { } selectAndSave(image: CoverImage) { - this.bookService.uploadCoverFromUrl(this.bookId, image.url) - .subscribe({ - next: () => { - this.messageService.add({ - severity: 'success', - summary: 'Cover Updated', - detail: 'Cover image updated successfully.' - }); - this.dynamicDialogRef.close(); - }, - error: err => { - this.messageService.add({ - severity: 'error', - summary: 'Cover Update Failed', - detail: err?.message || 'Failed to update cover image.' - }); - } - }); + const uploadObservable = this.coverType === 'audiobook' + ? this.bookService.uploadAudiobookCoverFromUrl(this.bookId, image.url) + : this.bookService.uploadCoverFromUrl(this.bookId, image.url); + + uploadObservable.subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Cover Updated', + detail: `${this.coverType === 'audiobook' ? 'Audiobook' : 'Ebook'} cover image updated successfully.` + }); + this.dynamicDialogRef.close(true); + }, + error: err => { + this.messageService.add({ + severity: 'error', + summary: 'Cover Update Failed', + detail: err?.message || 'Failed to update cover image.' + }); + } + }); } onClear() { diff --git a/booklore-ui/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.ts b/booklore-ui/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.ts index d1693475e..b6a48c17a 100644 --- a/booklore-ui/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.ts +++ b/booklore-ui/src/app/features/metadata/component/metadata-options-dialog/metadata-advanced-fetch-options/metadata-advanced-fetch-options.component.ts @@ -35,7 +35,8 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges { 'hardcoverId', 'hardcoverRating', 'hardcoverReviewCount', 'moods', 'tags', 'comicvineId', 'lubimyczytacId', 'lubimyczytacRating', - 'ranobedbId', 'ranobedbRating' + 'ranobedbId', 'ranobedbRating', + 'audibleId', 'audibleRating', 'audibleReviewCount' ]; providerSpecificFields: (keyof FieldOptions)[] = [ @@ -46,6 +47,7 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges { 'comicvineId', 'lubimyczytacId', 'lubimyczytacRating', 'ranobedbId', 'ranobedbRating', + 'audibleId', 'audibleRating', 'audibleReviewCount', ]; nonProviderSpecificFields: (keyof FieldOptions)[] = [ @@ -54,8 +56,8 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges { 'language', 'categories', 'cover', 'pageCount', ]; - providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb']; - providersWithClear: string[] = ['Clear All', 'Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb']; + providers: string[] = ['Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb', 'Audible']; + providersWithClear: string[] = ['Clear All', 'Amazon', 'Google', 'GoodReads', 'Hardcover', 'Comicvine', 'Douban', 'Lubimyczytac', 'Ranobedb', 'Audible']; refreshCovers: boolean = false; mergeCategories: boolean = false; @@ -102,6 +104,9 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges { // Ranobedb 'ranobedbId', 'ranobedbRating', + // Audible + 'audibleId', 'audibleRating', 'audibleReviewCount', + // Generic provider-specific 'moods', 'tags' ]; @@ -274,6 +279,9 @@ export class MetadataAdvancedFetchOptionsComponent implements OnChanges { 'lubimyczytacRating': 'Lubimyczytac Rating', 'ranobedbId': 'Ranobedb ID', 'ranobedbRating': 'Ranobedb Rating', + 'audibleId': 'Audible ID', + 'audibleRating': 'Audible Rating', + 'audibleReviewCount': 'Audible Review Count', 'moods': 'Moods (Hardcover)', 'tags': 'Tags (Hardcover)' }; diff --git a/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts b/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts index 8ae2370de..c6d05be83 100644 --- a/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts +++ b/booklore-ui/src/app/features/metadata/component/metadata-provider-field-selector/metadata-provider-field-selector.component.ts @@ -45,6 +45,10 @@ export class MetadataProviderFieldSelectorComponent implements OnInit { { label: 'Ranobedb', fields: ['ranobedbId', 'ranobedbRating'] + }, + { + label: 'Audible', + fields: ['audibleId', 'audibleRating', 'audibleReviewCount'] } ]; @@ -65,6 +69,9 @@ export class MetadataProviderFieldSelectorComponent implements OnInit { 'lubimyczytacRating': 'Lubimyczytac Rating', 'ranobedbId': 'Ranobedb ID', 'ranobedbRating': 'Ranobedb Rating', + 'audibleId': 'Audible ID', + 'audibleRating': 'Audible Rating', + 'audibleReviewCount': 'Audible Review Count', }; private readonly allFieldNames: (keyof MetadataProviderSpecificFields)[] = [ @@ -74,7 +81,8 @@ export class MetadataProviderFieldSelectorComponent implements OnInit { 'hardcoverId', 'hardcoverBookId', 'hardcoverRating', 'hardcoverReviewCount', 'comicvineId', 'lubimyczytacId', 'lubimyczytacRating', - 'ranobedbId', 'ranobedbRating' + 'ranobedbId', 'ranobedbRating', + 'audibleId', 'audibleRating', 'audibleReviewCount' ]; ngOnInit(): void { diff --git a/booklore-ui/src/app/features/metadata/model/request/metadata-refresh-options.model.ts b/booklore-ui/src/app/features/metadata/model/request/metadata-refresh-options.model.ts index ff27752e6..0ed13f815 100644 --- a/booklore-ui/src/app/features/metadata/model/request/metadata-refresh-options.model.ts +++ b/booklore-ui/src/app/features/metadata/model/request/metadata-refresh-options.model.ts @@ -53,6 +53,9 @@ export interface FieldOptions { lubimyczytacRating: FieldProvider; ranobedbId: FieldProvider; ranobedbRating: FieldProvider; + audibleId: FieldProvider; + audibleRating: FieldProvider; + audibleReviewCount: FieldProvider; moods: FieldProvider; tags: FieldProvider; } diff --git a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html b/booklore-ui/src/app/features/readers/audiobook-player/audiobook-player.component.html similarity index 99% rename from booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html rename to booklore-ui/src/app/features/readers/audiobook-player/audiobook-player.component.html index d1c1f63db..e375d0a61 100644 --- a/booklore-ui/src/app/features/readers/audiobook-reader/audiobook-reader.component.html +++ b/booklore-ui/src/app/features/readers/audiobook-player/audiobook-player.component.html @@ -4,7 +4,7 @@ Loading audiobook...
} @else { -
+
}
+ +
+
+ + +
+ @if (audibleEnabled) { +
+
+ + + +
+
+ } +
diff --git a/booklore-ui/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.ts b/booklore-ui/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.ts index 0ead80ac6..99c0c922f 100644 --- a/booklore-ui/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.ts +++ b/booklore-ui/src/app/features/settings/global-preferences/metadata-provider-settings/metadata-provider-settings.component.ts @@ -68,6 +68,22 @@ export class MetadataProviderSettingsComponent implements OnInit { selectedGoogleLanguage = ''; + audibleDomains = [ + {label: 'audible.com', value: 'com'}, + {label: 'audible.co.uk', value: 'co.uk'}, + {label: 'audible.de', value: 'de'}, + {label: 'audible.fr', value: 'fr'}, + {label: 'audible.it', value: 'it'}, + {label: 'audible.es', value: 'es'}, + {label: 'audible.ca', value: 'ca'}, + {label: 'audible.com.au', value: 'com.au'}, + {label: 'audible.co.jp', value: 'co.jp'}, + {label: 'audible.in', value: 'in'} + ]; + + selectedAudibleDomain = 'com'; + audibleEnabled: boolean = false; + hardcoverToken: string = ''; amazonCookie: string = ''; hardcoverEnabled: boolean = false; @@ -107,6 +123,8 @@ export class MetadataProviderSettingsComponent implements OnInit { this.doubanEnabled = metadataProviderSettings?.douban?.enabled ?? false; this.lubimyCzytacEnabled = metadataProviderSettings?.lubimyczytac?.enabled ?? false; this.ranobedbEnabled = metadataProviderSettings?.ranobedb?.enabled ?? false; + this.audibleEnabled = metadataProviderSettings?.audible?.enabled ?? false; + this.selectedAudibleDomain = metadataProviderSettings?.audible?.domain ?? 'com'; }); } @@ -146,7 +164,11 @@ export class MetadataProviderSettingsComponent implements OnInit { }, douban: {enabled: this.doubanEnabled}, lubimyczytac: {enabled: this.lubimyCzytacEnabled}, - ranobedb: {enabled: this.ranobedbEnabled} + ranobedb: {enabled: this.ranobedbEnabled}, + audible: { + enabled: this.audibleEnabled, + domain: this.selectedAudibleDomain + } } } ]; diff --git a/booklore-ui/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.ts b/booklore-ui/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.ts index 792ae7074..727d40889 100644 --- a/booklore-ui/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.ts +++ b/booklore-ui/src/app/features/settings/library-metadata-settings/library-metadata-settings.component.ts @@ -224,6 +224,9 @@ export class LibraryMetadataSettingsComponent implements OnInit { lubimyczytacRating: {p1: null, p2: null, p3: null, p4: null}, ranobedbId: {p1: null, p2: null, p3: null, p4: null}, ranobedbRating: {p1: null, p2: null, p3: null, p4: null}, + audibleId: {p1: null, p2: null, p3: null, p4: null}, + audibleRating: {p1: null, p2: null, p3: null, p4: null}, + audibleReviewCount: {p1: null, p2: null, p3: null, p4: null}, moods: {p1: null, p2: null, p3: null, p4: null}, tags: {p1: null, p2: null, p3: null, p4: null} } diff --git a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html index 3ad2acea7..93776b95b 100644 --- a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html +++ b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.html @@ -122,6 +122,40 @@ }
+
+
+ + + +
+

+ Write metadata directly into audiobook files (M4B, M4A, MP3, etc.) when editing book information. + Supports title, authors, narrator, description, publisher, categories, series, language, and cover art. For folder-based audiobooks, cover is saved as cover.jpg in the folder. +

+ @if (metadataPersistence.saveToOriginalFile.audiobook.enabled) { +
+
+ + + MB + + +
+
+ } +
+ @if ((appSettings$ | async)?.diskType === 'LOCAL') {
diff --git a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.ts b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.ts index 94bb15da6..bcca23989 100644 --- a/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.ts +++ b/booklore-ui/src/app/features/settings/metadata-settings/metadata-persistence-settings/metadata-persistence-settings-component.ts @@ -35,6 +35,10 @@ export class MetadataPersistenceSettingsComponent implements OnInit { cbx: { enabled: false, maxFileSizeInMb: 250 + }, + audiobook: { + enabled: false, + maxFileSizeInMb: 1000 } }, convertCbrCb7ToCbz: false, @@ -98,6 +102,10 @@ export class MetadataPersistenceSettingsComponent implements OnInit { cbx: { enabled: persistenceSettings.saveToOriginalFile?.cbx?.enabled ?? false, maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.cbx?.maxFileSizeInMb ?? 250 + }, + audiobook: { + enabled: persistenceSettings.saveToOriginalFile?.audiobook?.enabled ?? false, + maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.audiobook?.maxFileSizeInMb ?? 1000 } } }; diff --git a/booklore-ui/src/app/shared/components/cover-generator/cover-generator.component.ts b/booklore-ui/src/app/shared/components/cover-generator/cover-generator.component.ts index 115ef5024..5c223616b 100644 --- a/booklore-ui/src/app/shared/components/cover-generator/cover-generator.component.ts +++ b/booklore-ui/src/app/shared/components/cover-generator/cover-generator.component.ts @@ -7,6 +7,7 @@ import {Component, Input} from '@angular/core'; export class CoverGeneratorComponent { @Input() title: string = ''; @Input() author: string = ''; + @Input() isSquare: boolean = false; private wrapText(text: string, maxLineLength: number): string[] { const words = text.split(' '); @@ -40,26 +41,159 @@ export class CoverGeneratorComponent { return text.substring(0, maxLength - 3) + '...'; } - private calculateTitleFontSize(lineCount: number): number { - if (lineCount <= 2) return 36; - if (lineCount === 3) return 30; - return 24; + private escapeXml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); } - private calculateAuthorFontSize(lineCount: number): number { - if (lineCount <= 2) return 28; - return 22; + private hashString(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = ((hash << 5) - hash) + char; + hash = hash & hash; + } + return Math.abs(hash); } generateCover(): string { + const width = 250; + const height = this.isSquare ? 250 : 350; + const hash = this.hashString(this.title + this.author); + + if (this.isSquare) { + return this.generateAudiobookCover(width, height, hash); + } else { + return this.generateEbookCover(width, height, hash); + } + } + + private generateEbookCover(width: number, height: number, hash: number): string { + const palettes = [ + {bg1: '#1a1a2e', bg2: '#16213e', accent: '#e94560', text: '#eaeaea', textSecondary: '#b8b8b8'}, + {bg1: '#2d3436', bg2: '#636e72', accent: '#74b9ff', text: '#ffffff', textSecondary: '#dfe6e9'}, + {bg1: '#0c3547', bg2: '#1a5276', accent: '#f39c12', text: '#ecf0f1', textSecondary: '#bdc3c7'}, + {bg1: '#1e3d59', bg2: '#17263a', accent: '#ffc13b', text: '#f5f0e1', textSecondary: '#c7b198'}, + {bg1: '#2c2c54', bg2: '#474787', accent: '#ff793f', text: '#f8f8f8', textSecondary: '#d1ccc0'}, + {bg1: '#1b262c', bg2: '#0f4c75', accent: '#3282b8', text: '#bbe1fa', textSecondary: '#8fbdd3'}, + ]; + + const palette = palettes[hash % palettes.length]; + const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(false); + + const titleLineHeight = titleFontSize * 1.3; + const titleStartY = 80; + + const titleElements = titleLines.map((line, index) => { + const y = titleStartY + (index * titleLineHeight); + return `${this.escapeXml(line)}`; + }).join('\n'); + + const authorLineHeight = authorFontSize * 1.3; + const authorStartY = height - 50 - ((authorLines.length - 1) * authorLineHeight); + + const authorElements = authorLines.map((line, index) => { + const y = authorStartY + (index * authorLineHeight); + return `${this.escapeXml(line)}`; + }).join('\n'); + + const decorY = titleStartY + (titleLines.length * titleLineHeight) + 20; + + const svg = ` + + + + + + + + + + + + + + + ${titleElements} + + + ${authorElements} + + `; + + return this.svgToDataUrl(svg); + } + + private generateAudiobookCover(width: number, height: number, hash: number): string { + const palettes = [ + {bg1: '#667eea', bg2: '#764ba2', accent: '#ffffff', text: '#ffffff', textSecondary: '#e8e8e8'}, + {bg1: '#f093fb', bg2: '#f5576c', accent: '#ffffff', text: '#ffffff', textSecondary: '#ffeaea'}, + {bg1: '#4facfe', bg2: '#00f2fe', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'}, + {bg1: '#43e97b', bg2: '#38f9d7', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'}, + {bg1: '#fa709a', bg2: '#fee140', accent: '#ffffff', text: '#1a1a2e', textSecondary: '#2d3436'}, + {bg1: '#a18cd1', bg2: '#fbc2eb', accent: '#ffffff', text: '#2d3436', textSecondary: '#4a4a4a'}, + ]; + + const palette = palettes[hash % palettes.length]; + const {titleLines, authorLines, titleFontSize, authorFontSize} = this.processText(true); + + const titleLineHeight = titleFontSize * 1.3; + const titleStartY = 70; + + const titleElements = titleLines.map((line, index) => { + const y = titleStartY + (index * titleLineHeight); + return `${this.escapeXml(line)}`; + }).join('\n'); + + const authorLineHeight = authorFontSize * 1.3; + const authorStartY = height - 40 - ((authorLines.length - 1) * authorLineHeight); + + const authorElements = authorLines.map((line, index) => { + const y = authorStartY + (index * authorLineHeight); + return `${this.escapeXml(line)}`; + }).join('\n'); + + const iconY = titleStartY + (titleLines.length * titleLineHeight) + 25; + + const svg = ` + + + + + + + + + + ${titleElements} + + + + + ${authorElements} + `; + + return this.svgToDataUrl(svg); + } + + private processText(isSquare: boolean): { + titleLines: string[]; + authorLines: string[]; + titleFontSize: number; + authorFontSize: number; + } { const maxTitleLength = 60; const maxAuthorLength = 40; const truncatedTitle = this.truncateText(this.title, maxTitleLength); const truncatedAuthor = this.truncateText(this.author, maxAuthorLength); - const maxLineLength = 12; - const maxTitleLines = 4; - const maxAuthorLines = 3; + const maxLineLength = 14; + const maxTitleLines = isSquare ? 3 : 4; + const maxAuthorLines = isSquare ? 2 : 3; let titleLines = this.wrapText(truncatedTitle, maxLineLength); let authorLines = this.wrapText(truncatedAuthor, maxLineLength); @@ -77,49 +211,24 @@ export class CoverGeneratorComponent { const titleFontSize = this.calculateTitleFontSize(titleLines.length); const authorFontSize = this.calculateAuthorFontSize(authorLines.length); - const titleLineHeight = titleFontSize * 1.2; - const titlePadding = 15; - const titleBoxHeight = titleLines.length * titleLineHeight + (titlePadding * 2); + return {titleLines, authorLines, titleFontSize, authorFontSize}; + } - const titleElements = titleLines.map((line, index) => { - const y = 40 + titlePadding + titleFontSize + (index * titleLineHeight); - return `${line}`; - }).join('\n'); + private calculateTitleFontSize(lineCount: number): number { + if (lineCount <= 2) return 28; + if (lineCount === 3) return 24; + return 20; + } - const titleWithBackground = ` - - ${titleElements} - `; + private calculateAuthorFontSize(lineCount: number): number { + if (lineCount <= 2) return 18; + return 16; + } - const authorLineHeight = authorFontSize * 1.2; - const authorStartY = 330 - (authorLines.length - 1) * authorLineHeight; - - const authorElements = authorLines.map((line, index) => { - const y = authorStartY + index * authorLineHeight; - return `${line}`; - }).join('\n'); - - const svg = ` - - - - - - - - - - - - ${titleWithBackground} - ${authorElements} - - `; - - const base64 = btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (match, p1) => { + private svgToDataUrl(svg: string): string { + const base64 = btoa(encodeURIComponent(svg).replace(/%([0-9A-F]{2})/g, (_, p1) => { return String.fromCharCode(parseInt(p1, 16)); })); - return `data:image/svg+xml;base64,${base64}`; } } diff --git a/booklore-ui/src/app/shared/metadata/metadata-field.config.ts b/booklore-ui/src/app/shared/metadata/metadata-field.config.ts index 3275f15e7..b2df747f8 100644 --- a/booklore-ui/src/app/shared/metadata/metadata-field.config.ts +++ b/booklore-ui/src/app/shared/metadata/metadata-field.config.ts @@ -1,6 +1,6 @@ import {MetadataProviderSpecificFields} from '../model/app-settings.model'; -export type FieldType = 'string' | 'number' | 'array' | 'textarea'; +export type FieldType = 'string' | 'number' | 'array' | 'textarea' | 'boolean'; export interface MetadataFieldConfig { label: string; @@ -43,12 +43,23 @@ export const ALL_METADATA_FIELDS: MetadataFieldConfig[] = [ {label: 'LB ID', controlName: 'lubimyczytacId', lockedKey: 'lubimyczytacIdLocked', fetchedKey: 'lubimyczytacId', type: 'string', providerKey: 'lubimyczytacId'}, {label: 'LB ★', controlName: 'lubimyczytacRating', lockedKey: 'lubimyczytacRatingLocked', fetchedKey: 'lubimyczytacRating', type: 'number', providerKey: 'lubimyczytacRating'}, {label: 'Ranobedb ID', controlName: 'ranobedbId', lockedKey: 'ranobedbIdLocked', fetchedKey: 'ranobedbId', type: 'string', providerKey: 'ranobedbId'}, - {label: 'Ranobedb ★', controlName: 'ranobedbRating', lockedKey: 'ranobedbRatingLocked', fetchedKey: 'ranobedbRating', type: 'number', providerKey: 'ranobedbRating'} + {label: 'Ranobedb ★', controlName: 'ranobedbRating', lockedKey: 'ranobedbRatingLocked', fetchedKey: 'ranobedbRating', type: 'number', providerKey: 'ranobedbRating'}, + {label: 'Audible ID', controlName: 'audibleId', lockedKey: 'audibleIdLocked', fetchedKey: 'audibleId', type: 'string', providerKey: 'audibleId'}, + {label: 'Audible ★', controlName: 'audibleRating', lockedKey: 'audibleRatingLocked', fetchedKey: 'audibleRating', type: 'number', providerKey: 'audibleRating'}, + {label: 'Audible #', controlName: 'audibleReviewCount', lockedKey: 'audibleReviewCountLocked', fetchedKey: 'audibleReviewCount', type: 'number', providerKey: 'audibleReviewCount'} +]; + +// Audiobook content metadata fields (narrator/abridged) - now stored at top level of BookMetadata +export const AUDIOBOOK_METADATA_FIELDS: MetadataFieldConfig[] = [ + {label: 'Narrator', controlName: 'narrator', lockedKey: 'narratorLocked', fetchedKey: 'narrator', type: 'string'}, + {label: 'Abridged', controlName: 'abridged', lockedKey: 'abridgedLocked', fetchedKey: 'abridged', type: 'boolean'} ]; export const TOP_FIELD_NAMES = ['title', 'subtitle', 'publisher', 'publishedDate']; export const ARRAY_FIELD_NAMES = ['authors', 'categories', 'moods', 'tags']; export const TEXTAREA_FIELD_NAMES = ['description']; +export const SERIES_FIELD_NAMES = ['seriesName', 'seriesNumber', 'seriesTotal']; +export const BOOK_DETAILS_FIELD_NAMES = ['language', 'isbn10', 'isbn13', 'pageCount']; export function getTopFields(): MetadataFieldConfig[] { return ALL_METADATA_FIELDS.filter(f => TOP_FIELD_NAMES.includes(f.controlName)); @@ -62,6 +73,26 @@ export function getTextareaFields(): MetadataFieldConfig[] { return ALL_METADATA_FIELDS.filter(f => f.type === 'textarea'); } +export function getSeriesFields(): MetadataFieldConfig[] { + return ALL_METADATA_FIELDS.filter(f => SERIES_FIELD_NAMES.includes(f.controlName)); +} + +export function getBookDetailsFields(): MetadataFieldConfig[] { + return ALL_METADATA_FIELDS.filter(f => BOOK_DETAILS_FIELD_NAMES.includes(f.controlName)); +} + +export function getProviderFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] { + const providerFields = ALL_METADATA_FIELDS.filter(f => !!f.providerKey); + + if (enabledProviderFields) { + return providerFields.filter(field => + !field.providerKey || enabledProviderFields[field.providerKey] + ); + } + + return providerFields; +} + export function getBottomFields(enabledProviderFields?: MetadataProviderSpecificFields | null): MetadataFieldConfig[] { const bottomFields = ALL_METADATA_FIELDS.filter(f => !TOP_FIELD_NAMES.includes(f.controlName) && diff --git a/booklore-ui/src/app/shared/metadata/metadata-form.builder.ts b/booklore-ui/src/app/shared/metadata/metadata-form.builder.ts index 5a47017d0..8722116ef 100644 --- a/booklore-ui/src/app/shared/metadata/metadata-form.builder.ts +++ b/booklore-ui/src/app/shared/metadata/metadata-form.builder.ts @@ -1,6 +1,6 @@ import {Injectable} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; -import {ALL_METADATA_FIELDS, MetadataFieldConfig} from './metadata-field.config'; +import {ALL_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, MetadataFieldConfig} from './metadata-field.config'; @Injectable({ providedIn: 'root' @@ -22,9 +22,20 @@ export class MetadataFormBuilder { } } + // Add audiobook-specific metadata fields + for (const field of AUDIOBOOK_METADATA_FIELDS) { + const defaultValue = this.getDefaultValue(field.type); + controls[field.controlName] = new FormControl(defaultValue); + if (includeLockedControls) { + controls[field.lockedKey] = new FormControl(false); + } + } + controls['thumbnailUrl'] = new FormControl(''); + controls['audiobookThumbnailUrl'] = new FormControl(''); if (includeLockedControls) { controls['coverLocked'] = new FormControl(false); + controls['audiobookCoverLocked'] = new FormControl(false); } return new FormGroup(controls); @@ -36,6 +47,8 @@ export class MetadataFormBuilder { return []; case 'number': return null; + case 'boolean': + return null; default: return ''; } @@ -52,11 +65,19 @@ export class MetadataFormBuilder { } } + // Apply locks for standard fields for (const field of fields) { if (lockedFields[field.lockedKey]) { metadataForm.get(field.controlName)?.disable({emitEvent: false}); } } + + // Apply locks for audiobook metadata fields + for (const field of AUDIOBOOK_METADATA_FIELDS) { + if (lockedFields[field.lockedKey]) { + metadataForm.get(field.controlName)?.disable({emitEvent: false}); + } + } } setAllFieldsLocked(metadataForm: FormGroup, locked: boolean): void { diff --git a/booklore-ui/src/app/shared/metadata/metadata-utils.service.ts b/booklore-ui/src/app/shared/metadata/metadata-utils.service.ts index 6e6d42533..7bf288288 100644 --- a/booklore-ui/src/app/shared/metadata/metadata-utils.service.ts +++ b/booklore-ui/src/app/shared/metadata/metadata-utils.service.ts @@ -117,6 +117,7 @@ export class MetadataUtilsService { copiedFields: Record, hoveredFields?: Record ): void { + // All fields including narrator/abridged are now at top level of BookMetadata metadataForm.get(field)?.setValue(originalMetadata?.[field as keyof BookMetadata]); copiedFields[field] = false; if (hoveredFields) { diff --git a/booklore-ui/src/app/shared/model/app-settings.model.ts b/booklore-ui/src/app/shared/model/app-settings.model.ts index fd2fb984b..1d843c370 100644 --- a/booklore-ui/src/app/shared/model/app-settings.model.ts +++ b/booklore-ui/src/app/shared/model/app-settings.model.ts @@ -54,6 +54,7 @@ export interface MetadataProviderSettings { comicvine: Comicvine; douban: Douban; lubimyczytac: Lubimyczytac; + audible: Audible; } export interface Amazon { @@ -93,6 +94,11 @@ export interface Lubimyczytac { enabled: boolean; } +export interface Audible { + enabled: boolean; + domain: string; +} + export interface FormatWriteSettings { enabled: boolean; maxFileSizeInMb: number; @@ -102,6 +108,7 @@ export interface SaveToOriginalFileSettings { epub: FormatWriteSettings; pdf: FormatWriteSettings; cbx: FormatWriteSettings; + audiobook: FormatWriteSettings; } export interface MetadataPersistenceSettings { @@ -181,6 +188,9 @@ export interface MetadataProviderSpecificFields { lubimyczytacRating: boolean; ranobedbId: boolean; ranobedbRating: boolean; + audibleId: boolean; + audibleRating: boolean; + audibleReviewCount: boolean; } export enum AppSettingKey { diff --git a/booklore-ui/src/app/shared/service/url-helper.service.ts b/booklore-ui/src/app/shared/service/url-helper.service.ts index d6c9a7904..960d7d6e4 100644 --- a/booklore-ui/src/app/shared/service/url-helper.service.ts +++ b/booklore-ui/src/app/shared/service/url-helper.service.ts @@ -72,6 +72,42 @@ export class UrlHelperService { return this.appendToken(url); } + getAudiobookCoverUrl(bookId: number, audiobookCoverUpdatedOn?: string): string { + if (!audiobookCoverUpdatedOn) { + const book = this.bookService.getBookByIdFromState(bookId); + if (book && book.metadata) { + const coverGenerator = new CoverGeneratorComponent(); + coverGenerator.title = book.metadata.title || ''; + coverGenerator.author = (book.metadata.authors || []).join(', '); + coverGenerator.isSquare = true; + return coverGenerator.generateCover(); + } + } + let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-cover`; + if (audiobookCoverUpdatedOn) { + url += `?${audiobookCoverUpdatedOn}`; + } + return this.appendToken(url); + } + + getAudiobookThumbnailUrl(bookId: number, audiobookCoverUpdatedOn?: string): string { + if (!audiobookCoverUpdatedOn) { + const book = this.bookService.getBookByIdFromState(bookId); + if (book && book.metadata) { + const coverGenerator = new CoverGeneratorComponent(); + coverGenerator.title = book.metadata.title || ''; + coverGenerator.author = (book.metadata.authors || []).join(', '); + coverGenerator.isSquare = true; + return coverGenerator.generateCover(); + } + } + let url = `${this.mediaBaseUrl}/book/${bookId}/audiobook-thumbnail`; + if (audiobookCoverUpdatedOn) { + url += `?${audiobookCoverUpdatedOn}`; + } + return this.appendToken(url); + } + getBookdropCoverUrl(bookdropId: number): string { const url = `${this.mediaBaseUrl}/bookdrop/${bookdropId}/cover`; return this.appendToken(url); diff --git a/booklore-ui/src/app/shared/services/book-cover.service.ts b/booklore-ui/src/app/shared/services/book-cover.service.ts index 401b7869b..f83b3e2e8 100644 --- a/booklore-ui/src/app/shared/services/book-cover.service.ts +++ b/booklore-ui/src/app/shared/services/book-cover.service.ts @@ -14,7 +14,7 @@ export interface CoverImage { export interface CoverFetchRequest { title?: string; author?: string; - squareCover?: boolean; + coverType?: 'ebook' | 'audiobook'; } @Injectable({