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:
@@ -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);
|
||||
|
||||
+21
@@ -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;
|
||||
}
|
||||
|
||||
+3
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+7
@@ -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) {
|
||||
}
|
||||
}
|
||||
|
||||
+149
-25
@@ -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;
|
||||
|
||||
+6
-6
@@ -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());
|
||||
|
||||
+315
-17
@@ -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 {
|
||||
|
||||
+12
@@ -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;
|
||||
}
|
||||
}
|
||||
+346
@@ -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";
|
||||
}
|
||||
}
|
||||
+28
-6
@@ -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) {
|
||||
|
||||
+142
-257
@@ -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;
|
||||
+16
-1
@@ -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());
|
||||
}
|
||||
|
||||
+39
-35
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user