fix(audiobook): improve audiobook streaming and player UI (#513)
This commit is contained in:
@@ -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);
|
||||
|
||||
+46
-32
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user