fix(audiobook): improve audiobook streaming and player UI (#513)

This commit is contained in:
brios
2026-04-22 17:27:34 -04:00
committed by Zach Yale
parent 649c485c2d
commit 3e988077e0
9 changed files with 226 additions and 142 deletions
@@ -9,13 +9,12 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.util.FileUtils;
import org.booklore.util.MimeDetector;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Path;
@Slf4j
@@ -46,13 +45,15 @@ public class AudiobookReaderController {
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/stream")
public ResponseEntity<? extends Resource> streamAudiobook(
public void streamAudiobook(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex) {
@Parameter(description = "Track index for folder-based audiobooks (0-indexed)") @RequestParam(required = false) Integer trackIndex,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
return getFile(audioPath);
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
}
@Operation(summary = "Stream specific track", description = "Stream a specific track from a folder-based audiobook.")
@@ -61,13 +62,15 @@ public class AudiobookReaderController {
@ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/track/{trackIndex}/stream")
public ResponseEntity<? extends Resource> streamTrack(
public void streamTrack(
@Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex,
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType) {
@Parameter(description = "Optional book type for alternative format") @RequestParam(required = false) String bookType,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
return getFile(audioPath);
audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
}
@Operation(summary = "Get embedded cover art",
@@ -94,18 +97,4 @@ public class AudiobookReaderController {
return new ResponseEntity<>(coverData, headers, HttpStatus.OK);
}
private ResponseEntity<FileSystemResource> getFile(Path filePath) {
Long lastModified = FileUtils.getFileLastModified(filePath);
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
if (lastModified != null) {
builder.lastModified(lastModified);
}
return builder
.cacheControl(CacheControl.noCache().cachePrivate())
.contentType(MediaType.parseMediaType(MimeDetector.detectSafe(filePath)))
.body(new FileSystemResource(filePath));
}
}
@@ -22,6 +22,10 @@ import java.util.Set;
public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId);
@EntityGraph(attributePaths = { "metadata", "metadata.authors", "bookFiles", "libraryPath" })
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdForAudiobook(@Param("id") Long id);
@EntityGraph(attributePaths = { "metadata", "metadata.comicMetadata", "shelves", "libraryPath", "library", "bookFiles" })
@Query("SELECT b FROM BookEntity b WHERE b.id = :id AND (b.deleted IS NULL OR b.deleted = false)")
Optional<BookEntity> findByIdWithBookFiles(@Param("id") Long id);
@@ -9,6 +9,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -45,61 +47,73 @@ public class AudioFileUtilityService {
* Check if a file is an audio file based on its extension.
*/
public boolean isAudioFile(Path path) {
String fileName = path.getFileName().toString().toLowerCase();
String fileName = path.getFileName().toString().toLowerCase(Locale.ROOT);
return AUDIO_EXTENSIONS.stream().anyMatch(fileName::endsWith);
}
/**
* Get the MIME content type for an audio file using content-based detection via Apache Tika.
*/
public String getContentType(Path audioPath) {
return MimeDetector.detectSafe(audioPath);
}
/**
* Extract a readable track title from a filename.
* Removes extension and replaces underscores/hyphens with spaces.
*/
public String getTrackTitleFromFilename(String filename) {
int lastDot = filename.lastIndexOf('.');
if (lastDot > 0) {
filename = filename.substring(0, lastDot);
}
return SEPARATOR_PATTERN.matcher(filename).replaceAll(" ").trim();
}
/**
* Get the set of supported audio file extensions.
* Get the supported audio file extensions.
*/
public Set<String> getSupportedExtensions() {
return AUDIO_EXTENSIONS;
}
private int naturalCompare(Path p1, Path p2) {
return naturalCompare(p1.getFileName().toString(), p2.getFileName().toString());
private static final Map<String, String> AUDIO_MIME = Map.of(
".mp3", "audio/mpeg", ".m4a", "audio/mp4",
".m4b", "audio/mp4", ".opus", "audio/opus");
/**
* Get the MIME content type for an audio file using extension-based detection,
* falling back to Apache Tika for unknown extensions.
*/
public String getContentType(Path audioPath) {
String name = audioPath.getFileName().toString().toLowerCase(Locale.ROOT);
int dot = name.lastIndexOf('.');
if (dot >= 0) {
String mime = AUDIO_MIME.get(name.substring(dot));
if (mime != null) return mime;
}
return MimeDetector.detectSafe(audioPath);
}
/**
* Natural alphanumeric sort comparison.
* Handles filenames like "Track 1.mp3", "Track 2.mp3", ..., "Track 10.mp3" correctly.
* Extract a track title from a filename by removing extensions, track numbers, and separators.
*/
private int naturalCompare(String s1, String s2) {
public String getTrackTitleFromFilename(String filename) {
int dot = filename.lastIndexOf('.');
String name = dot >= 0 ? filename.substring(0, dot) : filename;
// Replace separators with spaces
name = SEPARATOR_PATTERN.matcher(name).replaceAll(" ");
return name.trim();
}
/**
* Natural sort comparator for strings that may contain numbers.
*/
private int naturalCompare(Path p1, Path p2) {
String s1 = p1.getFileName().toString();
String s2 = p2.getFileName().toString();
int i1 = 0, i2 = 0;
while (i1 < s1.length() && i2 < s2.length()) {
char c1 = s1.charAt(i1);
char c2 = s2.charAt(i2);
if (Character.isDigit(c1) && Character.isDigit(c2)) {
StringBuilder num1 = new StringBuilder();
StringBuilder num2 = new StringBuilder();
StringBuilder b1 = new StringBuilder();
while (i1 < s1.length() && Character.isDigit(s1.charAt(i1))) {
num1.append(s1.charAt(i1++));
b1.append(s1.charAt(i1++));
}
StringBuilder b2 = new StringBuilder();
while (i2 < s2.length() && Character.isDigit(s2.charAt(i2))) {
num2.append(s2.charAt(i2++));
b2.append(s2.charAt(i2++));
}
int cmp = Long.compare(Long.parseLong(num1.toString()), Long.parseLong(num2.toString()));
if (cmp != 0) return cmp;
long v1 = Long.parseLong(b1.toString());
long v2 = Long.parseLong(b2.toString());
if (v1 != v2) return Long.compare(v1, v2);
} else {
int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2));
if (cmp != 0) return cmp;
@@ -5,7 +5,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Locale;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.AudiobookMetadata;
@@ -28,7 +28,7 @@ import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
@Transactional
public class AudioMetadataService {
private final AudioFileUtilityService audioFileUtility;
@@ -76,7 +76,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs())
.build())
.collect(Collectors.toList());
.toList();
builder.chapters(chapters);
} else {
backfillChapters(bookFile, audioPath, builder);
@@ -218,7 +218,14 @@ public class AudioMetadataService {
long totalSizeBytes = tracks.stream()
.mapToLong(t -> t.getFileSizeBytes() != null ? t.getFileSizeBytes() : 0)
.sum();return builder.title(title).author(author).durationMs(totalDurationMs).totalSizeBytes(totalSizeBytes > 0 ? totalSizeBytes : null).tracks(tracks).build();
.sum();
return builder
.title(title)
.author(author)
.durationMs(totalDurationMs)
.totalSizeBytes(totalSizeBytes > 0 ? totalSizeBytes : null)
.tracks(tracks)
.build();
}
private AudiobookInfo extractSingleFileMetadata(
@@ -268,7 +275,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs())
.build())
.collect(Collectors.toList());
.toList();
bookFile.setChapters(entityChapters);
bookFile.setChapterCount(entityChapters.size());
bookFileRepository.save(bookFile);
@@ -298,7 +305,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs())
.build())
.collect(Collectors.toList());
.toList();
}
List<AudiobookChapter> fallback = new ArrayList<>();
@@ -372,8 +379,8 @@ public class AudioMetadataService {
private Integer parseChannels(String channels) {
if (channels == null) return null;
if (channels.toLowerCase().contains("stereo")) return 2;
if (channels.toLowerCase().contains("mono")) return 1;
if (channels.toLowerCase(Locale.ROOT).contains("stereo")) return 2;
if (channels.toLowerCase(Locale.ROOT).contains("mono")) return 1;
try {
return Integer.parseInt(channels.replaceAll("[^0-9]", ""));
} catch (NumberFormatException e) {
@@ -12,6 +12,7 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.nio.file.Path;
@@ -34,6 +35,7 @@ public class AudiobookReaderService {
/**
* Get audiobook information including metadata, chapters, and tracks.
*/
@Transactional
public AudiobookInfo getAudiobookInfo(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.getFullFilePath();
@@ -50,6 +52,7 @@ public class AudiobookReaderService {
* Get the path to an audio file for streaming.
* For folder-based audiobooks, returns the path to a specific track.
*/
@Transactional(readOnly = true)
public Path getAudioFilePath(Long bookId, String bookType, Integer trackIndex) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
@@ -78,6 +81,7 @@ public class AudiobookReaderService {
/**
* Get embedded cover art from an audiobook file.
*/
@Transactional(readOnly = true)
public byte[] getEmbeddedCoverArt(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath();
@@ -87,6 +91,7 @@ public class AudiobookReaderService {
/**
* Get the MIME type of embedded cover art.
*/
@Transactional(readOnly = true)
public String getCoverArtMimeType(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath();
@@ -100,8 +105,9 @@ public class AudiobookReaderService {
return audioFileUtility.getContentType(audioPath);
}
private BookFileEntity getAudiobookFile(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId)
@Transactional(readOnly = true)
protected BookFileEntity getAudiobookFile(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdForAudiobook(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) {
@@ -102,7 +102,7 @@ class AudiobookReaderServiceTest {
.durationMs(3600000L)
.build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
@@ -124,7 +124,7 @@ class AudiobookReaderServiceTest {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, "AUDIOBOOK");
@@ -135,7 +135,7 @@ class AudiobookReaderServiceTest {
@Test
void getAudiobookInfo_throwsExceptionWhenBookNotFound() {
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty());
when(bookRepository.findByIdForAudiobook(999L)).thenReturn(Optional.empty());
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(999L, null));
@@ -150,7 +150,7 @@ class AudiobookReaderServiceTest {
bookFiles.add(epubFile);
when(bookEntity.getBookFiles()).thenReturn(bookFiles);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(1L, null));
@@ -158,7 +158,7 @@ class AudiobookReaderServiceTest {
@Test
void getAudiobookInfo_throwsExceptionWhenRequestedTypeNotFound() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(1L, "EPUB"));
@@ -166,7 +166,7 @@ class AudiobookReaderServiceTest {
@Test
void getAudiobookInfo_wrapsMetadataServiceException() throws Exception {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(any(), any())).thenThrow(new RuntimeException("Parse error"));
assertThrows(ApiError.FILE_READ_ERROR.createException().getClass(),
@@ -177,7 +177,7 @@ class AudiobookReaderServiceTest {
@Test
void getAudioFilePath_singleFile_returnsFilePath() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
@@ -186,7 +186,7 @@ class AudiobookReaderServiceTest {
@Test
void getAudioFilePath_singleFile_ignoresTrackIndex() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
Path result = audiobookReaderService.getAudioFilePath(1L, null, 5);
@@ -204,7 +204,7 @@ class AudiobookReaderServiceTest {
Files.createFile(track1);
Files.createFile(track2);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2));
Path result = audiobookReaderService.getAudioFilePath(1L, null, 1);
@@ -221,7 +221,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
@@ -238,7 +238,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
@@ -254,7 +254,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
@@ -297,7 +297,7 @@ class AudiobookReaderServiceTest {
void getEmbeddedCoverArt_delegatesToMetadataService() {
byte[] expectedData = new byte[]{0x01, 0x02, 0x03};
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(expectedData);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -318,7 +318,7 @@ class AudiobookReaderServiceTest {
byte[] expectedData = new byte[]{0x04, 0x05};
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getEmbeddedCoverArt(track1)).thenReturn(expectedData);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -329,7 +329,7 @@ class AudiobookReaderServiceTest {
@Test
void getEmbeddedCoverArt_returnsNullWhenNoCoverArt() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(null);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -341,7 +341,7 @@ class AudiobookReaderServiceTest {
@Test
void getCoverArtMimeType_delegatesToMetadataService() {
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getCoverArtMimeType(audioPath)).thenReturn("image/png");
String result = audiobookReaderService.getCoverArtMimeType(1L, null);
@@ -360,7 +360,7 @@ class AudiobookReaderServiceTest {
Files.createFile(track1);
when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(track1);
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getCoverArtMimeType(track1)).thenReturn("image/jpeg");
String result = audiobookReaderService.getCoverArtMimeType(1L, null);
@@ -396,7 +396,7 @@ class AudiobookReaderServiceTest {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(eq(audiobookFileEntity), any())).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
@@ -409,7 +409,7 @@ class AudiobookReaderServiceTest {
void getAudiobookInfo_bookTypeIsCaseInsensitive() throws Exception {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity));
when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(any(), any())).thenReturn(expectedInfo);
// Test lowercase