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 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-02-05 13:33:08 -07:00
committed by GitHub
co-authored by acx10
parent 92d1334f25
commit d38271de9c
121 changed files with 5078 additions and 909 deletions
@@ -12,7 +12,7 @@ public class BookParserConfig {
@Bean
public Map<MetadataProvider, BookParser> 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
);
}
}
@@ -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<String, String> 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")
@@ -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<Resource> 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<Resource> 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}")
@@ -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<Map<String, Long>> getBookCountsByFormat(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
return ResponseEntity.ok(libraryService.getBookCountsByFormat(libraryId));
}
}
@@ -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<List<AudioFileChapter>, String> {
private static final ObjectMapper objectMapper = new ObjectMapper();
private static final TypeReference<List<AudioFileChapter>> LIST_TYPE_REF = new TypeReference<>() {};
@Override
public String convertToDatabaseColumn(List<AudioFileChapter> 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<AudioFileChapter> 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;
}
}
}
@@ -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;
@@ -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<AudiobookMetadata.ChapterInfo> 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()
);
}
}
}
@@ -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<AudiobookMetadata.ChapterInfo> 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<String> mapAuthors(Set<AuthorEntity> authors) {
return authors == null ? Set.of() :
@@ -149,4 +199,4 @@ public interface BookMapperV2 {
.id(entity.getId())
.build();
}
}
}
@@ -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<List<MobileBookSummary>> 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")
@@ -22,4 +22,6 @@ public class MobileBookSummary {
private Long libraryId;
private Instant addedOn;
private Instant lastReadTime;
private Float readProgress;
private Boolean hasAudiobook;
}
@@ -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) {
@@ -150,7 +150,42 @@ public class MobileBookService {
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.inProgress(userId)
MobileBookSpecification.inProgress(userId),
MobileBookSpecification.hasNonAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
Map<Long, UserBookProgressEntity> 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<MobileBookSummary> getContinueListening(Integer limit) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
Set<Long> accessibleLibraryIds = getAccessibleLibraryIds(user);
int maxItems = validateLimit(limit, 10);
Specification<BookEntity> spec = MobileBookSpecification.combine(
MobileBookSpecification.notDeleted(),
MobileBookSpecification.hasDigitalFile(),
MobileBookSpecification.inLibraries(accessibleLibraryIds),
MobileBookSpecification.inProgress(userId),
MobileBookSpecification.hasAudiobookFile()
);
List<BookEntity> books = bookRepository.findAll(spec);
@@ -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<BookEntity> hasAudiobookFile() {
return (root, query, cb) -> {
Subquery<Long> subquery = query.subquery(Long.class);
Root<BookFileEntity> 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<BookEntity> hasNonAudiobookFile() {
return (root, query, cb) -> {
Subquery<Long> subquery = query.subquery(Long.class);
Root<BookFileEntity> 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<BookEntity> combine(Specification<BookEntity>... specs) {
Specification<BookEntity> result = (root, query, cb) -> cb.conjunction();
@@ -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;
}
@@ -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<ChapterInfo> 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;
}
}
@@ -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<String> authors;
@Singular
private Set<String> 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;
}
@@ -22,6 +22,7 @@ public class Library {
private boolean watch;
private List<LibraryPath> paths;
private List<BookFileType> formatPriority;
private List<BookFileType> allowedFormats;
private LibraryOrganizationMode organizationMode;
}
@@ -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"
}
@@ -30,4 +30,5 @@ public class CreateLibraryRequest {
private boolean watch;
private List<BookFileType> formatPriority;
private List<BookFileType> allowedFormats;
}
@@ -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());
}
}
@@ -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;
}
}
@@ -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;
@@ -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<AudioFileChapter> 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;
}
}
@@ -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)
;
}
}
@@ -56,6 +56,10 @@ public class LibraryEntity {
@Builder.Default
private List<BookFileType> formatPriority = new ArrayList<>();
@Convert(converter = FormatPriorityConverter.class)
@Column(name = "allowed_formats")
private List<BookFileType> allowedFormats;
@Enumerated(EnumType.STRING)
@Column(name = "organization_mode")
@Builder.Default
@@ -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
}
@@ -20,6 +20,11 @@ public interface BookMetadataRepository extends JpaRepository<BookMetadataEntity
@Query("UPDATE BookMetadataEntity m SET m.coverUpdatedOn = :timestamp WHERE m.bookId = :bookId")
void updateCoverTimestamp(@Param("bookId") Long bookId, @Param("timestamp") Instant timestamp);
@Modifying
@Transactional
@Query("UPDATE BookMetadataEntity m SET m.audiobookCoverUpdatedOn = :timestamp WHERE m.bookId = :bookId")
void updateAudiobookCoverTimestamp(@Param("bookId") Long bookId, @Param("timestamp") Instant timestamp);
List<BookMetadataEntity> findAllByAuthorsContaining(AuthorEntity author);
List<BookMetadataEntity> findAllByCategoriesContaining(CategoryEntity category);
@@ -143,6 +143,16 @@ public interface BookRepository extends JpaRepository<BookEntity, Long>, 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<BookEntity, Long>, 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<BookEntity, Long>, 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
@@ -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<Resource> downloadBook(Long bookId) {
return bookDownloadService.downloadBook(bookId);
}
@@ -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) {
}
}
@@ -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<BookFileType> 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<BookFileEntity.AudioFileChapter> mapChapters(List<AudiobookMetadata.ChapterInfo> 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());
}
}
@@ -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;
}
}
@@ -7,10 +7,20 @@ import org.booklore.model.enums.BookFileType;
import java.util.List;
import org.booklore.model.entity.BookFileEntity;
public interface BookFileProcessor {
List<BookFileType> 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);
}
}
@@ -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<BufferedImage> 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;
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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<LibraryFile> 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<String, List<LibraryFile>> groups, LibraryEntity libraryEntity) {
for (Map.Entry<String, List<LibraryFile>> 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();
}
}
}
@@ -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<LibraryFile> filterByAllowedFormats(List<LibraryFile> files, List<BookFileType> allowedFormats) {
if (allowedFormats == null || allowedFormats.isEmpty()) {
return files;
}
Set<BookFileType> allowed = new HashSet<>(allowedFormats);
return files.stream()
.filter(file -> allowed.contains(file.getBookFileType()))
.collect(java.util.stream.Collectors.toList());
}
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
@@ -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());
}
@@ -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<String> 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<String, Long> getBookCountsByFormat(long libraryId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
Map<String, Long> 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<BookFileType> 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<BookFileType> allowedFormats) {
int count = 0;
try (DirectoryStream<Path> 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<BookFileType> 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;
@@ -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<MetadataWriter, BookEntity> 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<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId()));
if (!updates.isEmpty()) {
@@ -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());
@@ -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<String> 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<String> 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;
@@ -65,14 +65,14 @@ public class DuckDuckGoCoverService implements BookCoverProvider {
public List<CoverImage> 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<CoverImage> 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());
@@ -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<AudiobookMetadata.ChapterInfo> 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<String> 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<String> 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<AudiobookMetadata.ChapterInfo> extractChapters(File audioFile, AudioFile taggedFile, AudioHeader header) {
List<AudiobookMetadata.ChapterInfo> 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<AudiobookMetadata.ChapterInfo> 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<AudiobookMetadata.ChapterInfo> chapters = new ArrayList<>();
List<AbstractID3v2Frame> frameList;
if (chapFrames instanceof List) {
frameList = (List<AbstractID3v2Frame>) 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<AudiobookMetadata.ChapterInfo> extractChaptersWithFfprobe(File audioFile) {
List<AudiobookMetadata.ChapterInfo> 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<AudiobookMetadata.ChapterInfo> 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 {
@@ -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;
};
}
}
@@ -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<String, LocaleInfo> 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<String> audibleIds = getAudibleIds(book, fetchMetadataRequest);
if (audibleIds == null || audibleIds.isEmpty()) {
return null;
}
return getBookMetadata(audibleIds.getFirst());
}
@Override
public List<BookMetadata> fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) {
List<String> 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<BookMetadata> 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<String> 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<String> 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<String> 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<String> 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<String> extractPersonNames(JsonNode node, String field) {
Set<String> 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;
}
}
@@ -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";
}
}
@@ -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<Long> bookIds, ResetProgressType type, Instant now) {
@@ -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<String, CachedAudiobookMetadata> 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<Path> 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<String> 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<AudiobookChapter> 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<AudiobookChapter> 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<Path> 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<AudiobookChapter> extractChapters(Path audioPath, long totalDurationMs) {
List<AudiobookChapter> 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<AudiobookChapter> 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<AudiobookChapter> extractChaptersWithFFprobe(Path audioPath) throws Exception {
List<AudiobookChapter> 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) {
@@ -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());
}
}
}
@@ -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
@@ -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();
}
@@ -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<T>(
String name,
Function<BookMetadata, T> dtoValueGetter,
Function<BookMetadataEntity, T> entityValueGetter,
Function<BookMetadata, Boolean> dtoLockGetter,
Function<BookMetadataEntity, Boolean> entityLockGetter,
Predicate<MetadataClearFlags> 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<BookMetadata, Set<String>> dtoValueGetter,
Function<BookMetadataEntity, Set<?>> entityValueGetter,
Function<BookMetadata, Boolean> dtoLockGetter,
Function<BookMetadataEntity, Boolean> entityLockGetter,
Predicate<MetadataClearFlags> clearFlagGetter,
boolean includedInFileWrite
) {
boolean isUnlocked(BookMetadataEntity entity) {
return !isTrue(entityLockGetter.apply(entity));
}
boolean shouldClear(MetadataClearFlags flags) {
return clearFlagGetter.test(flags);
}
Set<String> getNewValue(BookMetadata dto) {
return dtoValueGetter.apply(dto);
}
Set<String> 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<FieldDescriptor<?>> 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<CollectionFieldDescriptor> 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<String> 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<String> 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<String> 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<String> 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 <T> void compareValue(List<String> 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 <T> boolean hasFieldDifference(FieldDescriptor<T> 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 <T> boolean hasValueDifference(FieldDescriptor<T> 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());
}
}
@@ -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;
@@ -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");
@@ -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());
}
@@ -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<AudioFileIO> 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<AudioFileIO> 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<AudioFileIO> 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<AudioFileIO> 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);
@@ -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<byte[]> responseEntity = ResponseEntity.ok(imageBytes);
when(mockRestTemplate.exchange(
+3 -3
View File
@@ -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]
},
{
@@ -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 {
@@ -39,7 +39,7 @@
}
@if (!_isSeriesViewActive && hasDigitalFile()) {
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
<p-button [rounded]="true" [icon]="_isAudiobook ? 'pi pi-play' : 'pi pi-book'" class="read-btn" (click)="readBook(book)"></p-button>
}
@if (isCheckboxEnabled) {
@@ -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);
}
@@ -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<HTMLInputElement>;
@@ -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();
@@ -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,
},
});
}
@@ -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;
}
@@ -1,6 +1,6 @@
<div class="book-cover-wrapper" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
<div class="book-cover-wrapper" [class.audiobook-only]="isAudiobookOnly()" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
<img
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
[src]="getThumbnailUrl()"
class="book-cover"
alt="Cover of {{ book.metadata?.title }}"
loading="lazy"/>
@@ -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%;
@@ -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(
@@ -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 {
@@ -11,6 +11,7 @@ export interface Library {
sort?: SortOption;
paths: LibraryPath[];
formatPriority?: BookType[];
allowedFormats?: BookType[];
}
export interface LibraryPath {
@@ -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<void>(`${this.url}/bulk-regenerate-covers`, {bookIds});
}
uploadAudiobookCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url});
}
uploadAudiobookCoverFromFile(bookId: number, file: File): Observable<void> {
const formData = new FormData();
formData.append('file', file);
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData);
}
getUploadAudiobookCoverUrl(bookId: number): string {
return this.url + '/' + bookId + "/metadata/audiobook-cover/upload";
}
regenerateAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {});
}
generateCustomAudiobookCover(bookId: number): Observable<void> {
return this.http.post<void>(`${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<void> {
const formData = new FormData();
formData.append('file', file);
@@ -165,4 +165,8 @@ export class LibraryService {
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
this.largeLibraryLoadingSubject.next({ isLoading, expectedCount });
}
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
return this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`);
}
}
@@ -23,10 +23,11 @@
#scrollContainer
[horizontal]="true">
@for (book of books; track book.id) {
<div class="dashboard-scroller-card" [class.menu-open]="openMenuBookId === book.id">
<div class="dashboard-scroller-card" [ngClass]="{'menu-open': openMenuBookId === book.id, 'square-card': useSquareCovers}">
<app-book-card
[book]="book"
[isCheckboxEnabled]="false"
[forceEbookMode]="forceEbookMode"
(menuToggled)="handleMenuToggle(book.id, $event)"
[overlayPreferenceService]="bookCardOverlayPreferenceService"
></app-book-card>
@@ -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 {
@@ -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;
}
@@ -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:
@@ -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">
</app-dashboard-scroller>
}
@@ -74,7 +74,11 @@ export class MainDashboardComponent implements OnInit {
private getLastReadBooks(maxItems: number, sortBy?: string): Observable<Book[]> {
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<Book[]> {
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<Book[]> {
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;
@@ -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}
]
};
@@ -155,6 +155,60 @@
}
</div>
</div>
<div class="option-item allowed-formats-option">
<div class="option-label">
<span>Allowed formats</span>
<i
class="pi pi-question-circle info-icon"
pTooltip="Select which book formats this library should accept. Files of other formats will be ignored during scans."
tooltipPosition="right"
></i>
</div>
<div class="allowed-formats-container">
<div class="allow-all-toggle">
<p-checkbox
[(ngModel)]="allowAllFormats"
[binary]="true"
inputId="allowAll"
(onChange)="onAllowAllFormatsChange()"
/>
<label for="allowAll" class="allow-all-label">Allow all formats</label>
</div>
@if (!allowAllFormats) {
<div class="format-checkboxes">
@for (format of allBookFormats; track format.type) {
<div class="format-checkbox-item" [class.has-warning]="getFormatWarning(format.type)">
<p-checkbox
[ngModel]="isFormatSelected(format.type)"
[binary]="true"
[inputId]="'format-' + format.type"
(onChange)="onFormatCheckboxChange(format.type, $event.checked)"
/>
<label [for]="'format-' + format.type" class="format-checkbox-label">
{{ format.label }}
</label>
@if (getFormatWarning(format.type); as warning) {
<i
class="pi pi-exclamation-triangle warning-icon"
[pTooltip]="warning"
tooltipPosition="top"
></i>
}
</div>
}
</div>
@if (hasAnyFormatWarning()) {
<div class="format-warning-message">
<i class="pi pi-info-circle"></i>
<span>Deselected formats with existing books will not be affected, but won't appear in future scans</span>
</div>
}
}
</div>
</div>
</div>
</section>
</div>
@@ -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;
@@ -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<BookType> = new Set();
formatCounts: Record<string, number> = {};
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') {
@@ -8,73 +8,161 @@
}
<div class="form-content">
<div class="main-section">
<div class="cover-section">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Cover Image"
width="250"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
<div class="covers-section" [class.dual-covers]="supportsDualCovers(book)">
<!-- Ebook Cover Section -->
@if (hasEbookFormat(book)) {
<div class="cover-section">
@if (supportsDualCovers(book)) {
<div class="cover-type-label ebook">
<i class="pi pi-book"></i> Ebook Cover
</div>
}
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Cover Image"
width="200"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
<div class="cover-actions">
@if (!book.isPhysical) {
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['coverLocked']">
</p-button>
}
<p-button
icon="pi pi-palette"
(onClick)="generateCustomCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingCover"
[disabled]="book.metadata!['coverLocked'] || isGeneratingCover">
</p-button>
<p-button
[disabled]="book.metadata!['coverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openCoverSearch()"
pTooltip="Search for cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload cover"
tooltipPosition="top"
[disabled]="book.metadata!['coverLocked']"
name="file"
[url]="getUploadCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['coverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (book.metadata!['coverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
</div>
</div>
}
<!-- Audiobook Cover Section -->
@if (hasAudiobookFormat(book)) {
<div class="cover-section audiobook-cover-section">
<div class="cover-type-label audiobook">
<i class="pi pi-headphones"></i> Audiobook Cover
</div>
<p-image
[src]="urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)"
alt="Audiobook Cover"
width="200"
appendTo="body"
lazyLoad
[preview]="true"
class="square-cover">
</p-image>
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
<div class="cover-actions">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateAudiobookCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['audiobookCoverLocked']">
</p-button>
<p-button
icon="pi pi-palette"
(onClick)="generateCustomAudiobookCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingAudiobookCover"
[disabled]="book.metadata!['audiobookCoverLocked'] || isGeneratingAudiobookCover">
</p-button>
<p-button
[disabled]="book.metadata!['audiobookCoverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openAudiobookCoverSearch()"
pTooltip="Search for audiobook cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload audiobook cover"
tooltipPosition="top"
[disabled]="book.metadata!['audiobookCoverLocked']"
name="file"
[url]="getUploadAudiobookCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onAudiobookCoverUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['audiobookCoverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audiobookCover')" severity="success"></p-button>
}
@if (book.metadata!['audiobookCoverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audiobookCover')" severity="warn"></p-button>
}
</div>
</div>
}
<div class="cover-actions">
<p-button
icon="pi pi-refresh"
(onClick)="regenerateCover(book.id)"
pTooltip="Regenerate cover (From File)"
tooltipPosition="top"
[outlined]="true"
severity="warn"
size="small"
[disabled]="book.metadata!['coverLocked']">
</p-button>
<p-button
icon="pi pi-palette"
(onClick)="generateCustomCover(book.id)"
pTooltip="Generate Custom Cover"
tooltipPosition="top"
[outlined]="true"
severity="help"
size="small"
[loading]="isGeneratingCover"
[disabled]="book.metadata!['coverLocked'] || isGeneratingCover">
</p-button>
<p-button
[disabled]="book.metadata!['coverLocked']"
outlined
size="small"
icon="pi pi-search"
(onClick)="openCoverSearch()"
pTooltip="Search for cover"
tooltipPosition="top"
severity="info">
</p-button>
<p-fileupload
[chooseStyleClass]="'p-button-sm p-button-outlined p-button-danger'"
pTooltip="Upload cover"
tooltipPosition="top"
[disabled]="book.metadata!['coverLocked']"
name="file"
[url]="getUploadCoverUrl()"
mode="basic"
chooseIcon="pi pi-upload"
accept="image/jpeg,image/png"
maxFileSize="5000000"
(onUpload)="onUpload($event)"
(onError)="onUploadError($event)"
[auto]="true"
(onBeforeUpload)="onBeforeSend()">
</p-fileupload>
@if (!book.metadata!['coverLocked']) {
<p-button pTooltip="Lock Cover" tooltipPosition="top" size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="success"></p-button>
}
@if (book.metadata!['coverLocked']) {
<p-button pTooltip="Unlock Cover" tooltipPosition="top" size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('thumbnailUrl')" severity="warn"></p-button>
}
</div>
</div>
<div class="fields-section">
@@ -596,6 +684,48 @@
</div>
</div>
}
@if (isFieldVisible('audibleId')) {
<div class="field-group metadata-id-field">
<label for="audibleId">Audible ID</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleId" formControlName="audibleId"/>
@if (!book.metadata!['audibleIdLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="success"></p-button>
}
@if (book.metadata!['audibleIdLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleId')" severity="warn"></p-button>
}
</div>
</div>
}
@if (isFieldVisible('audibleRating')) {
<div class="field-group metadata-id-field">
<label for="audibleRating">Audible ★</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleRating" formControlName="audibleRating"/>
@if (!book.metadata!['audibleRatingLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="success"></p-button>
}
@if (book.metadata!['audibleRatingLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleRating')" severity="warn"></p-button>
}
</div>
</div>
}
@if (isFieldVisible('audibleReviewCount')) {
<div class="field-group metadata-id-field">
<label for="audibleReviewCount">Audible #</label>
<div class="field-with-lock">
<input pSize="small" pInputText id="audibleReviewCount" formControlName="audibleReviewCount"/>
@if (!book.metadata!['audibleReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock-open" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="success"></p-button>
}
@if (book.metadata!['audibleReviewCountLocked']) {
<p-button size="small" icon="pi pi-lock" [outlined]="true" (onClick)="toggleLock('audibleReviewCount')" severity="warn"></p-button>
}
</div>
</div>
}
</div>
<div class="description-section">
@@ -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 {
@@ -80,6 +80,7 @@ export class MetadataEditorComponent implements OnInit {
isLoading = false;
isSaving = false;
isGeneratingCover = false;
isGeneratingAudiobookCover = false;
refreshingBookIds = new Set<number>();
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<unknown> =
event.originalEvent as HttpResponse<unknown>;
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,
});
}
}
}
@@ -40,62 +40,143 @@
<span>Cover Image</span>
</div>
<div class="section-content">
<div class="field-row cover-field-row">
<label class="field-label">Cover</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="metadataForm.get('thumbnailUrl')?.value"
alt="Current cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('coverLocked')?.value"
(click)="toggleLock('thumbnailUrl')"
[pTooltip]="metadataForm.get('coverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('coverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<div class="section-content" [class.dual-covers-section]="currentBook && supportsDualCovers(currentBook)">
<!-- Ebook Cover Row -->
@if (!currentBook || hasEbookFormat(currentBook)) {
<div class="field-row cover-field-row">
<label class="field-label">
@if (currentBook && supportsDualCovers(currentBook)) {
<i class="pi pi-book cover-type-icon"></i> Ebook
} @else {
Cover
}
</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="metadataForm.get('thumbnailUrl')?.value"
alt="Current cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('coverLocked')?.value"
(click)="toggleLock('thumbnailUrl')"
[pTooltip]="metadataForm.get('coverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('coverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
</div>
</div>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('thumbnailUrl')"
[class.copied]="isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl']"
[class.reset]="isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']"
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
(mouseenter)="onMouseEnter('thumbnailUrl')"
(mouseleave)="onMouseLeave('thumbnailUrl')"
>
<i [class]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('thumbnailUrl')"
[class.copied]="isValueCopied('thumbnailUrl') && !hoveredFields['thumbnailUrl']"
[class.reset]="isValueCopied('thumbnailUrl') && hoveredFields['thumbnailUrl']"
(click)="hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? resetField('thumbnailUrl') : copyFetchedToCurrent('thumbnailUrl')"
(mouseenter)="onMouseEnter('thumbnailUrl')"
(mouseleave)="onMouseLeave('thumbnailUrl')"
>
<i [class]="isValueSaved('thumbnailUrl') ? 'pi pi-check' : (hoveredFields['thumbnailUrl'] && isValueCopied('thumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
<p-image
class="cover-image"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
</div>
</div>
</div>
</div>
</div>
}
<!-- Audiobook Cover Row -->
@if (currentBook && hasAudiobookFormat(currentBook)) {
<div class="field-row cover-field-row audiobook-cover-row">
<label class="field-label">
<i class="pi pi-headphones cover-type-icon"></i> Audiobook
</label>
<div class="field-content">
<div class="field-side current cover-side">
<span class="cover-label mobile-only">Current</span>
<div class="cover-wrapper">
<p-image
class="cover-image square-cover"
[src]="metadataForm.get('audiobookThumbnailUrl')?.value"
alt="Current audiobook cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
<button
type="button"
class="lock-badge"
[class.locked]="metadataForm.get('audiobookCoverLocked')?.value"
(click)="toggleLock('audiobookThumbnailUrl')"
[pTooltip]="metadataForm.get('audiobookCoverLocked')?.value ? 'Unlock cover' : 'Lock cover'"
tooltipPosition="top"
>
<i [class]="metadataForm.get('audiobookCoverLocked')?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
</div>
</div>
@if (isAudibleProvider()) {
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved('audiobookThumbnailUrl')"
[class.copied]="isValueCopied('audiobookThumbnailUrl') && !hoveredFields['audiobookThumbnailUrl']"
[class.reset]="isValueCopied('audiobookThumbnailUrl') && hoveredFields['audiobookThumbnailUrl']"
(click)="hoveredFields['audiobookThumbnailUrl'] && isValueCopied('audiobookThumbnailUrl') ? resetField('audiobookThumbnailUrl') : copyFetchedToCurrent('audiobookThumbnailUrl')"
(mouseenter)="onMouseEnter('audiobookThumbnailUrl')"
(mouseleave)="onMouseLeave('audiobookThumbnailUrl')"
>
<i [class]="isValueSaved('audiobookThumbnailUrl') ? 'pi pi-check' : (hoveredFields['audiobookThumbnailUrl'] && isValueCopied('audiobookThumbnailUrl') ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
} @else {
<div class="transfer-btn-placeholder"></div>
}
<div class="field-side fetched cover-side">
<span class="cover-label mobile-only">Fetched</span>
<div class="cover-wrapper">
@if (isAudibleProvider()) {
<p-image
class="cover-image square-cover"
[src]="fetchedMetadata.thumbnailUrl!"
alt="Fetched audiobook cover"
appendTo="body"
lazyLoad
[preview]="true"
/>
} @else {
<div class="no-cover-placeholder">
<i class="pi pi-image"></i>
<span>N/A</span>
</div>
}
</div>
</div>
</div>
</div>
}
</div>
</section>
@@ -261,16 +342,108 @@
</div>
</section>
<!-- Additional Details Section -->
@if (metadataFieldsBottom.length > 0) {
<!-- Series Information Section -->
<section class="form-section">
<div class="section-header">
<i class="pi pi-book"></i>
<span>Series Information</span>
</div>
<div class="section-content">
@for (field of metadataSeriesFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
</div>
</div>
</div>
}
</div>
</section>
<!-- Book Details Section -->
<section class="form-section">
<div class="section-header">
<i class="pi pi-id-card"></i>
<span>Book Details</span>
</div>
<div class="section-content">
@for (field of metadataBookDetailsFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
<input pInputText [value]="fetchedMetadata[field.fetchedKey] ?? ''" class="field-input" readonly/>
</div>
</div>
</div>
}
</div>
</section>
<!-- Provider Metadata Section -->
@if (metadataProviderFields.length > 0) {
<section class="form-section">
<div class="section-header">
<i class="pi pi-list"></i>
<span>Additional Details</span>
<i class="pi pi-cloud"></i>
<span>Provider Metadata</span>
</div>
<div class="section-content">
@for (field of metadataFieldsBottom; track field) {
@for (field of metadataProviderFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
@@ -308,6 +481,72 @@
</div>
</section>
}
<!-- Audiobook Details Section -->
@if (currentBook && hasAudiobookFormat(currentBook)) {
<section class="form-section">
<div class="section-header">
<i class="pi pi-headphones"></i>
<span>Audiobook Details</span>
</div>
<div class="section-content">
@for (field of audiobookMetadataFields; track field) {
<div class="field-row">
<label class="field-label">{{ field.label }}</label>
<div class="field-content">
<div class="field-side current">
<button
type="button"
class="lock-btn"
[class.locked]="metadataForm.get(field.lockedKey)?.value"
(click)="toggleLock(field.controlName)"
>
<i [class]="metadataForm.get(field.lockedKey)?.value ? 'pi pi-lock' : 'pi pi-lock-open'"></i>
</button>
@if (field.type === 'boolean') {
<p-checkbox
formControlName="{{field.controlName}}"
[binary]="true"
class="field-checkbox"
/>
} @else {
<input pInputText formControlName="{{field.controlName}}" class="field-input"/>
}
</div>
<button
type="button"
class="transfer-btn"
[class.saved]="isValueSaved(field.controlName)"
[class.copied]="isValueCopied(field.controlName) && !hoveredFields[field.controlName]"
[class.reset]="isValueCopied(field.controlName) && hoveredFields[field.controlName]"
(click)="hoveredFields[field.controlName] && isValueCopied(field.controlName) ? resetField(field.controlName) : copyFetchedToCurrent(field.controlName)"
(mouseenter)="onMouseEnter(field.controlName)"
(mouseleave)="onMouseLeave(field.controlName)"
>
<i [class]="isValueSaved(field.controlName) ? 'pi pi-check' : (hoveredFields[field.controlName] && isValueCopied(field.controlName) ? 'pi pi-times' : 'pi pi-arrow-left')"></i>
</button>
<div class="field-side fetched">
@if (field.type === 'boolean') {
<p-checkbox
[ngModel]="getFetchedAudiobookValue(field.fetchedKey)"
[ngModelOptions]="{ standalone: true }"
[binary]="true"
[disabled]="true"
class="field-checkbox"
/>
} @else {
<input pInputText [value]="getFetchedAudiobookValue(field.fetchedKey) ?? ''" class="field-input" readonly/>
}
</div>
</div>
</div>
}
</div>
</section>
}
</div>
@if (!reviewMode) {
@@ -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;
@@ -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<Book | null>;
@Output() goBack = new EventEmitter<boolean>();
currentBook: Book | null = null;
private allItems: Record<string, string[]> = {};
filteredItems: Record<string, string[]> = {};
@@ -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<string, unknown> = {};
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<unknown>[] = [
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<string, boolean> = {};
@@ -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);
}
}
@@ -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 `<a href="https://comicvine.gamespot.com/volume/${metadata.comicvineId}" target="_blank">Comicvine</a>`;
} else if (metadata.ranobedbId) {
return `<a href="https://ranobedb.org/book/${metadata.ranobedbId}" target="_blank">RanobeDB</a>`;
} else if (metadata.audibleId) {
return `<a href="https://www.audible.com/pd/${metadata.audibleId}" target="_blank">Audible</a>`;
}
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) {
@@ -8,6 +8,11 @@
<p-tab value="similar">
<i class="pi pi-bookmark"></i> Similar Books
</p-tab>
@if (supportsDualCovers()) {
<p-tab value="covers">
<i class="pi pi-images"></i> Covers
</p-tab>
}
<p-tab value="files">
<i class="pi pi-folder-open"></i> Files
</p-tab>
@@ -54,6 +59,39 @@
</div>
</ng-template>
</p-tabpanel>
<p-tabpanel value="covers">
<ng-template #content>
<div class="covers-tab-content">
<div class="covers-grid">
<div class="cover-item">
<div class="cover-label">
<i class="pi pi-book"></i> Ebook Cover
</div>
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
alt="Ebook Cover"
width="200"
appendTo="body"
[preview]="true">
</p-image>
</div>
<div class="cover-item">
<div class="cover-label audiobook">
<i class="pi pi-headphones"></i> Audiobook Cover
</div>
<p-image
[src]="urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)"
alt="Audiobook Cover"
width="200"
appendTo="body"
[preview]="true"
styleClass="square-cover">
</p-image>
</div>
</div>
</div>
</ng-template>
</p-tabpanel>
<p-tabpanel value="notes">
<ng-template #content>
<app-book-notes-component [bookId]="book.id"></app-book-notes-component>
@@ -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);
}
}
@@ -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<ReadEvent>();
@Output() downloadBook = new EventEmitter<DownloadEvent>();
@Output() downloadFile = new EventEmitter<DownloadAdditionalFileEvent>();
@@ -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);
}
}
@@ -6,7 +6,7 @@
<div class="cover-wrapper">
<p-image
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
[src]="getBookCoverUrl(book)"
alt="Image"
width="250"
appendTo="body"
@@ -96,12 +96,12 @@
<div class="title-group">
@if (book?.metadata?.seriesName) {
<p class="series-link" (click)="goToSeries(book?.metadata?.seriesName!)">
<div class="series-link" (click)="goToSeries(book?.metadata?.seriesName!)">
{{ book?.metadata?.seriesName }}
@if (book?.metadata?.seriesNumber) {
#{{ book?.metadata?.seriesNumber }}
}
</p>
</div>
}
<div class="title-wrapper">
@@ -154,7 +154,7 @@
</p-button>
</div>
@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) {
<div class="gradient-divider"></div>
}
@@ -229,6 +229,20 @@
</a>
}
@if (book?.metadata?.audibleRating) {
<a
class="rating-link"
[href]="'https://www.audible.com/pd/' + (book.metadata?.audibleId ?? '')"
target="_blank"
rel="noopener noreferrer"
[pTooltip]="getRatingTooltip(book, 'audible')"
tooltipPosition="top"
>
<img src="https://www.audible.com/favicon.ico" alt="Audible" class="rating-favicon"/>
<span class="rating-value">{{ getRatingPercent(book.metadata!.audibleRating) }}%</span>
</a>
}
@if (book?.metadata?.googleId) {
<a
class="rating-link"
@@ -1078,7 +1078,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return p != null ? Math.round(p * 10) / 10 : null;
}
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover' | 'lubimyczytac' | 'ranobedb'): string {
getRatingTooltip(book: Book, source: 'amazon' | 'goodreads' | 'hardcover' | 'lubimyczytac' | 'ranobedb' | 'audible'): string {
const meta = book?.metadata;
if (!meta) return '';
@@ -1103,6 +1103,10 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return meta.ranobedbRating != null
? `★ ${meta.ranobedbRating}`
: '';
case 'audible':
return meta.audibleRating != null
? `★ ${meta.audibleRating} | ${meta.audibleReviewCount?.toLocaleString() ?? '0'} reviews`
: '';
default:
return '';
}
@@ -1231,4 +1235,11 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
isPhysicalBook(book: Book): boolean {
return !this.hasAnyFiles(book);
}
getBookCoverUrl(book: Book): string {
const isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
return isAudiobook
? this.urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)
: this.urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn);
}
}
@@ -1,10 +1,10 @@
<div class="cover-search-container">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-image header-icon"></i>
<i class="pi {{ coverType === 'audiobook' ? 'pi-headphones' : 'pi-image' }} header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Search Cover Images</h2>
<h2 class="panel-title">Search {{ coverType === 'audiobook' ? 'Audiobook' : 'Ebook' }} Cover</h2>
<p class="panel-description">Find and select a cover for your book</p>
</div>
<p-button
@@ -31,7 +31,7 @@ export class CoverSearchComponent implements OnInit {
coverImages: CoverImage[] = [];
loading = false;
hasSearched = false;
isAudiobook = false;
coverType: 'ebook' | 'audiobook' = 'ebook';
private fb = inject(FormBuilder);
private bookCoverService = inject(BookCoverService);
@@ -51,8 +51,16 @@ export class CoverSearchComponent implements OnInit {
this.bookId = this.dynamicDialogConfig.data.bookId;
const book = this.bookService.getBookByIdFromState(this.bookId);
// Use explicitly provided coverType, or auto-detect based on primary file
if (this.dynamicDialogConfig.data.coverType) {
this.coverType = this.dynamicDialogConfig.data.coverType;
} else if (book?.primaryFile?.bookType === 'AUDIOBOOK') {
this.coverType = 'audiobook';
} else {
this.coverType = 'ebook';
}
if (book) {
this.isAudiobook = book.primaryFile?.bookType === 'AUDIOBOOK';
this.searchForm.patchValue({
title: book.metadata?.title || '',
author: book.metadata?.authors && book.metadata?.authors.length > 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() {
@@ -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)'
};

Some files were not shown because too many files have changed in this diff Show More