Fix audiobook chapter extraction for M4B/M4A formats (#2976)

* Fix audiobook chapter extraction for M4B/M4A formats

* Add unit tests for ffprobe service, chapter backfill, and audiobook rescan

* Add collapsible chapter list to audiobook details section
This commit is contained in:
ACX
2026-02-25 18:35:46 -07:00
committed by GitHub
parent bc844fc57e
commit e53c545dcb
17 changed files with 626 additions and 13 deletions
+3
View File
@@ -35,3 +35,6 @@ out/
### VS Code ###
.vscode/
### Local scripts ###
local/
@@ -233,7 +233,7 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil
setAudiobookTechnicalMetadata(bookEntity, audioMetadata);
}
private void setAudiobookTechnicalMetadata(BookEntity bookEntity, BookMetadata audioMetadata) {
public void setAudiobookTechnicalMetadata(BookEntity bookEntity, BookMetadata audioMetadata) {
AudiobookMetadata audiobookDto = audioMetadata.getAudiobookMetadata();
if (audiobookDto == null) {
return;
@@ -11,11 +11,13 @@ import org.booklore.model.websocket.Topic;
import org.booklore.repository.LibraryRepository;
import org.booklore.repository.BookRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.fileprocessor.AudiobookProcessor;
import org.booklore.service.metadata.BookMetadataUpdater;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.task.options.RescanLibraryContext;
import org.booklore.task.TaskCancellationManager;
import org.booklore.task.TaskStatus;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.TaskType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
@@ -34,14 +36,16 @@ public class LibraryRescanHelper {
private final NotificationService notificationService;
private final TaskCancellationManager cancellationManager;
private final BookRepository bookRepository;
private final AudiobookProcessor audiobookProcessor;
public LibraryRescanHelper(LibraryRepository libraryRepository, MetadataExtractorFactory metadataExtractorFactory, @Lazy BookMetadataUpdater bookMetadataUpdater, NotificationService notificationService, TaskCancellationManager cancellationManager, BookRepository bookRepository) {
public LibraryRescanHelper(LibraryRepository libraryRepository, MetadataExtractorFactory metadataExtractorFactory, @Lazy BookMetadataUpdater bookMetadataUpdater, NotificationService notificationService, TaskCancellationManager cancellationManager, BookRepository bookRepository, AudiobookProcessor audiobookProcessor) {
this.libraryRepository = libraryRepository;
this.metadataExtractorFactory = metadataExtractorFactory;
this.bookMetadataUpdater = bookMetadataUpdater;
this.notificationService = notificationService;
this.cancellationManager = cancellationManager;
this.bookRepository = bookRepository;
this.audiobookProcessor = audiobookProcessor;
}
@Transactional
@@ -105,6 +109,10 @@ public class LibraryRescanHelper {
.mergeTags(true)
.build();
bookMetadataUpdater.setBookMetadata(metadataUpdateContext);
if (bookEntity.getPrimaryBookFile().getBookType() == BookFileType.AUDIOBOOK && bookMetadata.getAudiobookMetadata() != null) {
audiobookProcessor.setAudiobookTechnicalMetadata(bookEntity, bookMetadata);
}
} catch (Exception e) {
log.error("Failed to update metadata for book id={} path={}: {}", bookEntity.getId(), bookEntity.getFullFilePath(), e.getMessage(), e);
} finally {
@@ -1,10 +1,12 @@
package org.booklore.service.metadata.extractor;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.booklore.model.dto.AudiobookMetadata;
import org.booklore.model.dto.BookMetadata;
import org.booklore.service.reader.FfprobeService;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
@@ -22,6 +24,7 @@ import tools.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
@@ -32,8 +35,11 @@ import java.util.logging.Logger;
@Slf4j
@Component
@AllArgsConstructor
public class AudiobookMetadataExtractor implements FileMetadataExtractor {
private final FfprobeService ffprobeService;
static {
Logger.getLogger("org.jaudiotagger").setLevel(Level.WARNING);
}
@@ -210,6 +216,16 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor {
}
}
public List<AudiobookMetadata.ChapterInfo> extractChaptersFromFile(File audioFile) {
try {
AudioFile f = AudioFileIO.read(audioFile);
return extractChapters(audioFile, f, f.getAudioHeader());
} catch (Exception e) {
log.warn("Failed to extract chapters from {}: {}", audioFile.getName(), e.getMessage());
return null;
}
}
private List<AudiobookMetadata.ChapterInfo> extractChapters(File audioFile, AudioFile taggedFile, AudioHeader header) {
List<AudiobookMetadata.ChapterInfo> chapters = extractId3v2Chapters(taggedFile);
if (chapters != null && !chapters.isEmpty()) {
@@ -322,8 +338,14 @@ public class AudiobookMetadataExtractor implements FileMetadataExtractor {
List<AudiobookMetadata.ChapterInfo> chapters = new ArrayList<>();
try {
Path ffprobeBinary = ffprobeService.getFfprobeBinary();
if (ffprobeBinary == null) {
log.debug("ffprobe binary not available, skipping chapter extraction for {}", audioFile.getName());
return null;
}
ProcessBuilder pb = new ProcessBuilder(
"ffprobe",
ffprobeBinary.toAbsolutePath().toString(),
"-v", "quiet",
"-print_format", "json",
"-show_chapters",
@@ -1,10 +1,13 @@
package org.booklore.service.reader;
import org.booklore.model.dto.AudiobookMetadata;
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 org.booklore.model.entity.BookMetadataEntity;
import org.booklore.repository.BookFileRepository;
import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jaudiotagger.audio.AudioFile;
@@ -15,6 +18,7 @@ import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.images.Artwork;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -27,6 +31,8 @@ import java.util.stream.Collectors;
public class AudioMetadataService {
private final AudioFileUtilityService audioFileUtility;
private final AudiobookMetadataExtractor audiobookMetadataExtractor;
private final BookFileRepository bookFileRepository;
public AudiobookInfo getMetadata(BookFileEntity bookFile, Path audioPath) throws Exception {
if (bookFile.isFolderBased()) {
@@ -64,6 +70,8 @@ public class AudioMetadataService {
.build())
.collect(Collectors.toList());
builder.chapters(chapters);
} else {
backfillChapters(bookFile, audioPath, builder);
}
if (metadata != null) {
@@ -222,19 +230,63 @@ public class AudioMetadataService {
.narrator(getTagValue(tag, FieldKey.COMPOSER));
}
List<AudiobookChapter> chapters = new ArrayList<>();
chapters.add(AudiobookChapter.builder()
.index(0)
.title("Full Audiobook")
.startTimeMs(0L)
.endTimeMs(durationMs)
.durationMs(durationMs)
.build());
List<AudiobookChapter> chapters = extractChaptersFromFile(audioPath.toFile(), durationMs);
builder.chapters(chapters);
return builder.build();
}
private void backfillChapters(BookFileEntity bookFile, Path audioPath, AudiobookInfo.AudiobookInfoBuilder builder) {
try {
List<AudiobookChapter> chapters = extractChaptersFromFile(
audioPath.toFile(),
bookFile.getDurationSeconds() != null ? bookFile.getDurationSeconds() * 1000 : 0
);
builder.chapters(chapters);
List<BookFileEntity.AudioFileChapter> entityChapters = 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());
bookFile.setChapters(entityChapters);
bookFile.setChapterCount(entityChapters.size());
bookFileRepository.save(bookFile);
log.info("Backfilled {} chapters for audiobook file id={}", entityChapters.size(), bookFile.getId());
} catch (Exception e) {
log.debug("Failed to backfill chapters for audiobook file id={}: {}", bookFile.getId(), e.getMessage());
}
}
private List<AudiobookChapter> extractChaptersFromFile(File audioFile, long fallbackDurationMs) {
List<AudiobookMetadata.ChapterInfo> extracted = audiobookMetadataExtractor.extractChaptersFromFile(audioFile);
if (extracted != null && !extracted.isEmpty()) {
return extracted.stream()
.map(ch -> AudiobookChapter.builder()
.index(ch.getIndex())
.title(ch.getTitle())
.startTimeMs(ch.getStartTimeMs())
.endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs())
.build())
.collect(Collectors.toList());
}
List<AudiobookChapter> fallback = new ArrayList<>();
fallback.add(AudiobookChapter.builder()
.index(0)
.title("Full Audiobook")
.startTimeMs(0L)
.endTimeMs(fallbackDurationMs)
.durationMs(fallbackDurationMs)
.build());
return fallback;
}
public byte[] getEmbeddedCoverArt(Path audioPath) {
try {
AudioFile audioFile = AudioFileIO.read(audioPath.toFile());
@@ -0,0 +1,85 @@
package org.booklore.service.reader;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.util.FileService;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Slf4j
@Service
@AllArgsConstructor
public class FfprobeService {
private static final String FFPROBE_GITHUB_BASE_URL = "https://github.com/booklore-app/booklore-tools/raw/main/ffprobe/";
private static final String BIN_DARWIN_ARM64 = "ffprobe-darwin-arm64";
private static final String BIN_DARWIN_X64 = "ffprobe-darwin-64";
private static final String BIN_LINUX_X64 = "ffprobe-linux-64";
private static final String BIN_LINUX_ARM64 = "ffprobe-linux-arm64";
private final FileService fileService;
public Path getFfprobeBinary() {
try {
return setupFfprobeBinary();
} catch (Exception e) {
log.warn("Failed to set up ffprobe binary: {}", e.getMessage());
return null;
}
}
private Path setupFfprobeBinary() throws Exception {
String binaryName = getFfprobeBinaryName();
Path toolsDir = Paths.get(fileService.getToolsFfprobePath());
if (!Files.exists(toolsDir)) {
Files.createDirectories(toolsDir);
}
Path binaryPath = toolsDir.resolve(binaryName);
if (!Files.exists(binaryPath)) {
String downloadUrl = FFPROBE_GITHUB_BASE_URL + binaryName;
log.info("Downloading ffprobe binary '{}' from {}", binaryName, downloadUrl);
try (InputStream in = java.net.URI.create(downloadUrl).toURL().openStream()) {
Files.copy(in, binaryPath, StandardCopyOption.REPLACE_EXISTING);
}
if (!binaryPath.toFile().setExecutable(true)) {
log.warn("Failed to set executable permission for '{}'", binaryPath.toAbsolutePath());
}
log.info("Downloaded ffprobe binary to {}", binaryPath.toAbsolutePath());
} else {
if (!binaryPath.toFile().setExecutable(true)) {
log.warn("Failed to set executable permission for '{}'", binaryPath.toAbsolutePath());
}
log.debug("Using existing ffprobe binary at {}", binaryPath.toAbsolutePath());
}
return binaryPath;
}
private String getFfprobeBinaryName() {
String osName = System.getProperty("os.name").toLowerCase();
String osArch = System.getProperty("os.arch").toLowerCase();
log.debug("Detected OS: {} ({})", osName, osArch);
if (osName.contains("mac") || osName.contains("darwin")) {
if (osArch.contains("arm") || osArch.contains("aarch64")) {
return BIN_DARWIN_ARM64;
} else {
return BIN_DARWIN_X64;
}
} else if (osName.contains("linux")) {
if (osArch.contains("arm64") || osArch.contains("aarch64")) {
return BIN_LINUX_ARM64;
} else if (osArch.contains("64")) {
return BIN_LINUX_X64;
}
}
throw new IllegalStateException("Unsupported operating system or architecture: " + osName + " / " + osArch);
}
}
@@ -170,6 +170,10 @@ public class FileService {
return Paths.get(appProperties.getPathConfig(), "tools", "kepubify").toString();
}
public String getToolsFfprobePath() {
return Paths.get(appProperties.getPathConfig(), "tools", "ffprobe").toString();
}
// ========================================
// VALIDATION
@@ -1,6 +1,7 @@
package org.booklore.service.library;
import org.booklore.model.MetadataUpdateContext;
import org.booklore.model.dto.AudiobookMetadata;
import org.booklore.model.dto.BookMetadata;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookEntity;
@@ -14,6 +15,7 @@ import org.booklore.model.websocket.Topic;
import org.booklore.repository.BookRepository;
import org.booklore.repository.LibraryRepository;
import org.booklore.service.NotificationService;
import org.booklore.service.fileprocessor.AudiobookProcessor;
import org.booklore.service.metadata.BookMetadataUpdater;
import org.booklore.service.metadata.extractor.MetadataExtractorFactory;
import org.booklore.task.options.RescanLibraryContext;
@@ -46,6 +48,7 @@ class LibraryRescanHelperTest {
@Mock private NotificationService notificationService;
@Mock private TaskCancellationManager cancellationManager;
@Mock private BookRepository bookRepository;
@Mock private AudiobookProcessor audiobookProcessor;
@InjectMocks private LibraryRescanHelper libraryRescanHelper;
@Captor private ArgumentCaptor<TaskProgressPayload> payloadCaptor;
@@ -306,6 +309,71 @@ class LibraryRescanHelperTest {
verify(bookMetadataUpdater).setBookMetadata(any(MetadataUpdateContext.class));
}
@Test
void handleRescanOptions_shouldUpdateAudiobookTechnicalMetadata() {
BookEntity audiobookEntity = createBookEntity(3L, "audiobook.m4b", BookFileType.AUDIOBOOK);
AudiobookMetadata audiobookMeta = AudiobookMetadata.builder()
.durationSeconds(3600L)
.bitrate(128)
.sampleRate(44100)
.channels(2)
.codec("AAC")
.chapterCount(5)
.build();
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Test Audiobook");
metadata.setAudiobookMetadata(audiobookMeta);
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
when(bookRepository.findAllWithMetadataByLibraryId(1L)).thenReturn(List.of(audiobookEntity));
when(metadataExtractorFactory.extractMetadata(eq(BookFileType.AUDIOBOOK), any(File.class))).thenReturn(metadata);
when(cancellationManager.isTaskCancelled(taskId)).thenReturn(false);
libraryRescanHelper.handleRescanOptions(rescanContext, taskId);
verify(bookMetadataUpdater).setBookMetadata(any(MetadataUpdateContext.class));
verify(audiobookProcessor).setAudiobookTechnicalMetadata(audiobookEntity, metadata);
}
@Test
void handleRescanOptions_shouldNotUpdateTechnicalMetadata_forNonAudiobooks() {
BookEntity epubBook = createBookEntity(1L, "book.epub", BookFileType.EPUB);
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Epub Book");
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
when(bookRepository.findAllWithMetadataByLibraryId(1L)).thenReturn(List.of(epubBook));
when(metadataExtractorFactory.extractMetadata(eq(BookFileType.EPUB), any(File.class))).thenReturn(metadata);
when(cancellationManager.isTaskCancelled(taskId)).thenReturn(false);
libraryRescanHelper.handleRescanOptions(rescanContext, taskId);
verify(bookMetadataUpdater).setBookMetadata(any(MetadataUpdateContext.class));
verify(audiobookProcessor, never()).setAudiobookTechnicalMetadata(any(), any());
}
@Test
void handleRescanOptions_shouldSkipTechnicalMetadata_whenAudiobookMetadataNull() {
BookEntity audiobookEntity = createBookEntity(3L, "audiobook.m4b", BookFileType.AUDIOBOOK);
BookMetadata metadata = new BookMetadata();
metadata.setTitle("Audiobook Without Tech Meta");
metadata.setAudiobookMetadata(null);
when(libraryRepository.findById(1L)).thenReturn(Optional.of(library));
when(bookRepository.findAllWithMetadataByLibraryId(1L)).thenReturn(List.of(audiobookEntity));
when(metadataExtractorFactory.extractMetadata(eq(BookFileType.AUDIOBOOK), any(File.class))).thenReturn(metadata);
when(cancellationManager.isTaskCancelled(taskId)).thenReturn(false);
libraryRescanHelper.handleRescanOptions(rescanContext, taskId);
verify(bookMetadataUpdater).setBookMetadata(any(MetadataUpdateContext.class));
verify(audiobookProcessor, never()).setAudiobookTechnicalMetadata(any(), any());
}
private BookEntity createBookEntity(Long id, String fileName, BookFileType bookType) {
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/test/path");
@@ -1,11 +1,14 @@
package org.booklore.service.reader;
import org.booklore.model.dto.AudiobookMetadata;
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.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookMetadataEntity;
import org.booklore.repository.BookFileRepository;
import org.booklore.service.metadata.extractor.AudiobookMetadataExtractor;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
@@ -23,6 +26,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -37,6 +41,12 @@ class AudioMetadataServiceTest {
@Mock
AudioFileUtilityService audioFileUtility;
@Mock
AudiobookMetadataExtractor audiobookMetadataExtractor;
@Mock
BookFileRepository bookFileRepository;
@InjectMocks
AudioMetadataService audioMetadataService;
@@ -558,4 +568,124 @@ class AudioMetadataServiceTest {
assertNull(info.getBitrate());
}
}
@Test
void getMetadata_backfillsChapters_whenDbHasMetadataButNoChapters() throws Exception {
bookFileEntity.setDurationSeconds(3600L);
bookFileEntity.setBitrate(192);
bookFileEntity.setChapters(null);
var bookMetadata = new BookMetadataEntity();
bookMetadata.setTitle("Test Book");
bookEntity.setMetadata(bookMetadata);
List<AudiobookMetadata.ChapterInfo> extractedChapters = List.of(
AudiobookMetadata.ChapterInfo.builder()
.index(0).title("Chapter 1").startTimeMs(0L).endTimeMs(1800000L).durationMs(1800000L).build(),
AudiobookMetadata.ChapterInfo.builder()
.index(1).title("Chapter 2").startTimeMs(1800000L).endTimeMs(3600000L).durationMs(1800000L).build()
);
when(audiobookMetadataExtractor.extractChaptersFromFile(any(File.class))).thenReturn(extractedChapters);
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
assertNotNull(info.getChapters());
assertEquals(2, info.getChapters().size());
assertEquals("Chapter 1", info.getChapters().get(0).getTitle());
assertEquals("Chapter 2", info.getChapters().get(1).getTitle());
verify(bookFileRepository).save(bookFileEntity);
assertNotNull(bookFileEntity.getChapters());
assertEquals(2, bookFileEntity.getChapters().size());
assertEquals(2, bookFileEntity.getChapterCount());
}
@Test
void getMetadata_backfillFallsBackToFullAudiobook_whenExtractorReturnsNull() throws Exception {
bookFileEntity.setDurationSeconds(7200L);
bookFileEntity.setChapters(null);
var bookMetadata = new BookMetadataEntity();
bookEntity.setMetadata(bookMetadata);
when(audiobookMetadataExtractor.extractChaptersFromFile(any(File.class))).thenReturn(null);
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
assertNotNull(info.getChapters());
assertEquals(1, info.getChapters().size());
assertEquals("Full Audiobook", info.getChapters().get(0).getTitle());
assertEquals(7200000L, info.getChapters().get(0).getEndTimeMs());
verify(bookFileRepository).save(bookFileEntity);
}
@Test
void getMetadata_extractSingleFile_usesRealChapterExtraction() throws Exception {
AudioFile audioFile = mock(AudioFile.class);
AudioHeader header = mock(AudioHeader.class);
when(audioFile.getAudioHeader()).thenReturn(header);
when(audioFile.getTag()).thenReturn(null);
when(header.getPreciseTrackLength()).thenReturn(3600.0);
List<AudiobookMetadata.ChapterInfo> extractedChapters = List.of(
AudiobookMetadata.ChapterInfo.builder()
.index(0).title("Intro").startTimeMs(0L).endTimeMs(600000L).durationMs(600000L).build(),
AudiobookMetadata.ChapterInfo.builder()
.index(1).title("Part One").startTimeMs(600000L).endTimeMs(3600000L).durationMs(3000000L).build()
);
when(audiobookMetadataExtractor.extractChaptersFromFile(any(File.class))).thenReturn(extractedChapters);
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
assertNotNull(info.getChapters());
assertEquals(2, info.getChapters().size());
assertEquals("Intro", info.getChapters().get(0).getTitle());
assertEquals("Part One", info.getChapters().get(1).getTitle());
}
}
@Test
void getMetadata_extractSingleFile_fallsBackWhenExtractionReturnsEmpty() throws Exception {
AudioFile audioFile = mock(AudioFile.class);
AudioHeader header = mock(AudioHeader.class);
when(audioFile.getAudioHeader()).thenReturn(header);
when(audioFile.getTag()).thenReturn(null);
when(header.getPreciseTrackLength()).thenReturn(5400.0);
when(audiobookMetadataExtractor.extractChaptersFromFile(any(File.class))).thenReturn(List.of());
try (MockedStatic<AudioFileIO> audioFileIOMock = mockStatic(AudioFileIO.class)) {
audioFileIOMock.when(() -> AudioFileIO.read(audioPath.toFile())).thenReturn(audioFile);
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
assertNotNull(info.getChapters());
assertEquals(1, info.getChapters().size());
assertEquals("Full Audiobook", info.getChapters().get(0).getTitle());
assertEquals(5400000L, info.getChapters().get(0).getDurationMs());
}
}
@Test
void getMetadata_backfillSurvivesExtractionException() throws Exception {
bookFileEntity.setDurationSeconds(1800L);
bookFileEntity.setChapters(null);
var bookMetadata = new BookMetadataEntity();
bookEntity.setMetadata(bookMetadata);
when(audiobookMetadataExtractor.extractChaptersFromFile(any(File.class)))
.thenThrow(new RuntimeException("ffprobe failed"));
AudiobookInfo info = audioMetadataService.getMetadata(bookFileEntity, audioPath);
assertNotNull(info);
verify(bookFileRepository, never()).save(any());
}
}
@@ -0,0 +1,108 @@
package org.booklore.service.reader;
import org.booklore.util.FileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class FfprobeServiceTest {
@Mock
FileService fileService;
@InjectMocks
FfprobeService ffprobeService;
@TempDir
Path tempDir;
@BeforeEach
void setUp() {
when(fileService.getToolsFfprobePath()).thenReturn(tempDir.resolve("tools/ffprobe").toString());
}
@Test
void getFfprobeBinary_returnsExistingBinary() throws IOException {
Path toolsDir = tempDir.resolve("tools/ffprobe");
Files.createDirectories(toolsDir);
String expectedName = getExpectedBinaryName();
Path binaryPath = toolsDir.resolve(expectedName);
Files.writeString(binaryPath, "fake-binary");
Path result = ffprobeService.getFfprobeBinary();
assertThat(result).isNotNull();
assertThat(result.getFileName().toString()).isEqualTo(expectedName);
assertThat(result).exists();
}
@Test
void getFfprobeBinary_createsDirectoryIfMissing() throws IOException {
Path toolsDir = tempDir.resolve("tools/ffprobe");
String expectedName = getExpectedBinaryName();
Path binaryPath = toolsDir.resolve(expectedName);
Files.createDirectories(toolsDir);
Files.writeString(binaryPath, "fake-binary");
Path result = ffprobeService.getFfprobeBinary();
assertThat(result).isNotNull();
assertThat(toolsDir).exists();
}
@Test
void getFfprobeBinary_returnsNullOnFailure() {
when(fileService.getToolsFfprobePath()).thenReturn("/nonexistent\0path");
Path result = ffprobeService.getFfprobeBinary();
assertThat(result).isNull();
}
@Test
void getFfprobeBinary_setsExecutablePermission() throws IOException {
Path toolsDir = tempDir.resolve("tools/ffprobe");
Files.createDirectories(toolsDir);
String expectedName = getExpectedBinaryName();
Path binaryPath = toolsDir.resolve(expectedName);
Files.writeString(binaryPath, "fake-binary");
Path result = ffprobeService.getFfprobeBinary();
assertThat(result).isNotNull();
assertThat(result.toFile().canExecute()).isTrue();
}
private String getExpectedBinaryName() {
String osName = System.getProperty("os.name").toLowerCase();
String osArch = System.getProperty("os.arch").toLowerCase();
if (osName.contains("mac") || osName.contains("darwin")) {
if (osArch.contains("arm") || osArch.contains("aarch64")) {
return "ffprobe-darwin-arm64";
}
return "ffprobe-darwin-64";
} else if (osName.contains("linux")) {
if (osArch.contains("arm64") || osArch.contains("aarch64")) {
return "ffprobe-linux-arm64";
}
return "ffprobe-linux-64";
}
throw new IllegalStateException("Unsupported OS for test: " + osName);
}
}
@@ -97,6 +97,14 @@ export interface BookFileProgress {
progressPercent: number;
}
export interface AudiobookChapterInfo {
index?: number;
title?: string;
startTimeMs?: number;
endTimeMs?: number;
durationMs?: number;
}
export interface AudiobookMetadata {
narrator?: string;
abridged?: boolean | null;
@@ -106,6 +114,7 @@ export interface AudiobookMetadata {
channels?: number;
codec?: string;
chapterCount?: number;
chapters?: AudiobookChapterInfo[];
narratorLocked?: boolean;
abridgedLocked?: boolean;
}
@@ -978,6 +978,27 @@
</span>
</div>
}
@if (audio.chapters?.length) {
<div class="audiobook-chapters-section">
<div class="audiobook-chapters-header clickable" (click)="isChapterListExpanded = !isChapterListExpanded">
<span class="audiobook-chapters-toggle-label">
<i class="pi pi-list"></i>
{{ t('audiobookChapterList') }}
</span>
<i class="pi section-toggle-icon" [ngClass]="isChapterListExpanded ? 'pi-chevron-up' : 'pi-chevron-down'"></i>
</div>
<div class="audiobook-chapters-list" [ngClass]="{'collapsed': !isChapterListExpanded}">
@for (chapter of audio.chapters; track chapter.index) {
<div class="audiobook-chapter-row">
<span class="audiobook-chapter-index">{{ chapter.index! + 1 }}</span>
<span class="audiobook-chapter-title">{{ chapter.title }}</span>
<span class="audiobook-chapter-duration">{{ formatDurationMs(chapter.durationMs!) }}</span>
</div>
}
</div>
</div>
}
</div>
</div>
}
@@ -1019,7 +1019,7 @@
display: flex;
flex-direction: column;
gap: 1rem;
max-height: 500px;
max-height: 2000px;
overflow: hidden;
transition: max-height 0.3s ease, padding 0.3s ease, opacity 0.3s ease;
opacity: 1;
@@ -1099,3 +1099,88 @@
color: white;
}
}
.audiobook-chapters-section {
border-top: 1px solid var(--border-color);
padding-top: 0.75rem;
}
.audiobook-chapters-header {
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
user-select: none;
padding: 0.375rem 0;
&:hover .audiobook-chapters-toggle-label {
color: var(--primary-hover-color);
}
}
.audiobook-chapters-toggle-label {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.85rem;
font-weight: 600;
color: var(--text-color);
transition: color 0.2s ease;
i {
font-size: 0.9rem;
color: var(--primary-color);
}
}
.audiobook-chapters-list {
display: flex;
flex-direction: column;
gap: 0;
max-height: 500px;
overflow-y: auto;
transition: max-height 0.3s ease, opacity 0.3s ease;
opacity: 1;
&.collapsed {
max-height: 0;
opacity: 0;
overflow: hidden;
}
}
.audiobook-chapter-row {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 0.25rem;
border-bottom: 1px solid var(--surface-border);
font-size: 0.875rem;
&:last-child {
border-bottom: none;
}
}
.audiobook-chapter-index {
flex: 0 0 1.75rem;
text-align: center;
font-weight: 600;
color: var(--text-color-secondary);
font-size: 0.8rem;
}
.audiobook-chapter-title {
flex: 1;
color: var(--text-color);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.audiobook-chapter-duration {
flex-shrink: 0;
color: var(--text-color-secondary);
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
}
@@ -78,6 +78,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
isOverflowing = false;
isComicSectionExpanded = true;
isAudiobookSectionExpanded = true;
isChapterListExpanded = false;
showFilePath = false;
isAutoFetching = false;
private metadataCenterViewMode: 'route' | 'dialog' = 'route';
@@ -1372,6 +1373,18 @@ export class MetadataViewerComponent implements OnInit, OnChanges, AfterViewChec
return `${minutes}m`;
}
formatDurationMs(ms: number): string {
if (!ms) return '-';
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
formatSampleRate(sampleRate: number): string {
if (!sampleRate) return '-';
return `${(sampleRate / 1000).toFixed(1)} kHz`;
@@ -388,9 +388,12 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
private updateMediaSessionMetadata(): void {
if (!('mediaSession' in navigator)) return;
const chapters = this.audiobookInfo.chapters;
const chapterTitle = chapters && chapters.length > 1 ? this.getCurrentChapter()?.title : null;
const title = this.audiobookInfo.folderBased
? this.currentTrack?.title
: this.getCurrentChapter()?.title || this.audiobookInfo.title;
: chapterTitle || this.audiobookInfo.title;
navigator.mediaSession.metadata = new MediaMetadata({
title: title || this.t.translate('readerAudiobook.untitled'),
+1
View File
@@ -286,6 +286,7 @@
"audiobookSampleRate": "Sample Rate",
"audiobookChannels": "Channels",
"audiobookCodec": "Codec",
"audiobookChapterList": "Chapter List",
"abridged": "Abridged",
"unabridged": "Unabridged",
"readBtn": "Read",
+1
View File
@@ -286,6 +286,7 @@
"audiobookSampleRate": "Frecuencia de muestreo",
"audiobookChannels": "Canales",
"audiobookCodec": "Códec",
"audiobookChapterList": "Lista de capítulos",
"abridged": "Abreviado",
"unabridged": "Íntegro",
"readBtn": "Leer",