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:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user