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) {
|
||||
|
||||
+19
-19
@@ -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
|
||||
|
||||
@@ -83,10 +83,10 @@
|
||||
@if (audiobookInfo.folderBased && currentTrack) {
|
||||
<span class="track-title">{{ currentTrack.title }}</span>
|
||||
<span class="track-number">{{ t('trackInfo.trackOf', { current: currentTrackIndex + 1, total: audiobookInfo.tracks?.length }) }}</span>
|
||||
} @else if (getCurrentChapter()) {
|
||||
<span class="track-title">{{ getCurrentChapter()?.title }}</span>
|
||||
} @else if (currentChapter) {
|
||||
<span class="track-title">{{ currentChapter.title }}</span>
|
||||
@if (hasMultipleChapters()) {
|
||||
<span class="track-number">{{ t('trackInfo.chapterOf', { current: getCurrentChapterIndex() + 1, total: audiobookInfo.chapters?.length }) }}</span>
|
||||
<span class="track-number">{{ t('trackInfo.chapterOf', { current: currentChapterIdx + 1, total: audiobookInfo.chapters?.length }) }}</span>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
@@ -329,7 +329,7 @@
|
||||
@for (chapter of audiobookInfo.chapters; track chapter.index) {
|
||||
<li
|
||||
class="track-item"
|
||||
[class.active]="getCurrentChapter()?.index === chapter.index"
|
||||
[class.active]="currentChapter?.index === chapter.index"
|
||||
(click)="selectChapter(chapter)"
|
||||
(keydown.enter)="selectChapter(chapter)"
|
||||
role="button"
|
||||
@@ -340,7 +340,7 @@
|
||||
<span class="track-name">{{ chapter.title }}</span>
|
||||
<span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
|
||||
</div>
|
||||
@if (getCurrentChapter()?.index === chapter.index && isPlaying) {
|
||||
@if (currentChapter?.index === chapter.index && isPlaying) {
|
||||
<i class="pi pi-volume-up playing-indicator"></i>
|
||||
}
|
||||
</li>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, ElementRef, inject, OnDestroy, OnInit, ViewChild} from '@angular/core';
|
||||
import {Location} from '@angular/common';
|
||||
import {ActivatedRoute} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {from, Observable, of, Subject} from 'rxjs';
|
||||
import {catchError, filter, map, switchMap, takeUntil, tap} from 'rxjs/operators';
|
||||
import {from, Observable, of} from 'rxjs';
|
||||
import {catchError, filter, map, switchMap, tap} from 'rxjs/operators';
|
||||
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
|
||||
|
||||
import {Button} from 'primeng/button';
|
||||
import {Slider, SliderChangeEvent} from 'primeng/slider';
|
||||
@@ -38,12 +39,13 @@ import {API_CONFIG} from '../../../core/config/api-config';
|
||||
TranslocoDirective
|
||||
],
|
||||
templateUrl: './audiobook-player.component.html',
|
||||
styleUrls: ['./audiobook-player.component.scss']
|
||||
styleUrls: ['./audiobook-player.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
@ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>;
|
||||
|
||||
private destroy$ = new Subject<void>();
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private audiobookService = inject(AudiobookService);
|
||||
private bookService = inject(BookService);
|
||||
private bookMarkService = inject(BookMarkService);
|
||||
@@ -54,7 +56,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
private audiobookSessionService = inject(AudiobookSessionService);
|
||||
private pageTitle = inject(PageTitleService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
private readonly cdr = inject(ChangeDetectorRef);
|
||||
isLoading = true;
|
||||
audioLoading = false;
|
||||
audioInitialized = false;
|
||||
@@ -76,6 +78,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
private savedPosition = 0;
|
||||
|
||||
currentTrackIndex = 0;
|
||||
currentChapter?: AudiobookChapter;
|
||||
currentChapterIdx = 0;
|
||||
audioSrc = '';
|
||||
|
||||
showTrackList = false;
|
||||
@@ -117,7 +121,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
];
|
||||
|
||||
this.route.paramMap.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
map(params => Number(params.get('bookId'))),
|
||||
filter(bookId => !Number.isNaN(bookId)),
|
||||
switchMap(bookId => this.loadAudiobook(bookId))
|
||||
@@ -125,9 +129,6 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
|
||||
if (this.progressSaveInterval) {
|
||||
clearInterval(this.progressSaveInterval);
|
||||
}
|
||||
@@ -153,10 +154,15 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.isLoading = true;
|
||||
|
||||
return this.audiobookService.getAudiobookInfo(bookId).pipe(
|
||||
tap((info) => {
|
||||
switchMap(info =>
|
||||
from(this.bookService.fetchFreshBookDetail(bookId, false)).pipe(
|
||||
map(book => ({info, book})),
|
||||
catchError(() => of({info, book: null as Book | null}))
|
||||
)
|
||||
),
|
||||
tap(({info, book}) => {
|
||||
this.audiobookInfo = info;
|
||||
if (info.folderBased && info.tracks && info.tracks.length > 0) {
|
||||
// Prepare the source URL but don't load it yet
|
||||
this.audioSrc = this.audiobookService.getTrackStreamUrl(bookId, 0);
|
||||
const track = info.tracks[0];
|
||||
if (track?.durationMs) {
|
||||
@@ -169,21 +175,24 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
// Load cover URLs - prefer stored audiobook cover, fall back to embedded, then book cover
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${bookId}/cover?token=${encodeURIComponent(token || '')}`;
|
||||
this.coverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${bookId}/audiobook-cover?token=${encodeURIComponent(token || '')}`;
|
||||
|
||||
this.isLoading = false;
|
||||
if (book) {
|
||||
this.applyBookDetails(book, info);
|
||||
}
|
||||
|
||||
this.loadBookmarks();
|
||||
|
||||
// Defer the branch flip to a new macrotask so Angular's CD cycle
|
||||
// sees a consistent @if state (prevents NG0100).
|
||||
setTimeout(() => {
|
||||
this.isLoading = false;
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}),
|
||||
switchMap(info =>
|
||||
from(this.bookService.fetchFreshBookDetail(bookId, false)).pipe(
|
||||
tap(book => this.applyBookDetails(book, info)),
|
||||
map(() => void 0),
|
||||
catchError(() => of(void 0))
|
||||
)
|
||||
),
|
||||
map(() => void 0),
|
||||
catchError(() => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
@@ -192,6 +201,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
this.isLoading = false;
|
||||
this.audioLoading = false;
|
||||
this.cdr.markForCheck();
|
||||
return of(void 0);
|
||||
})
|
||||
);
|
||||
@@ -229,6 +239,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
if (this.savedPosition > 0) {
|
||||
this.currentTime = this.savedPosition;
|
||||
}
|
||||
this.updateCurrentChapter();
|
||||
}
|
||||
|
||||
private loadTrack(index: number, showLoading = true): void {
|
||||
@@ -290,16 +301,19 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.setupMediaSession();
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onTimeUpdate(): void {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio) {
|
||||
const previousChapterIndex = this.getCurrentChapterIndex();
|
||||
const previousChapterIndex = this.currentChapterIdx;
|
||||
if (!this.isSeeking) {
|
||||
this.currentTime = audio.currentTime;
|
||||
}
|
||||
|
||||
this.updateCurrentChapter();
|
||||
|
||||
this.audiobookSessionService.updatePosition(
|
||||
Math.round(this.currentTime * 1000),
|
||||
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
|
||||
@@ -309,11 +323,12 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.updateMediaSessionPositionState();
|
||||
}
|
||||
|
||||
if (!this.audiobookInfo.folderBased && this.getCurrentChapterIndex() !== previousChapterIndex) {
|
||||
if (!this.audiobookInfo.folderBased && this.currentChapterIdx !== previousChapterIndex) {
|
||||
this.updateMediaSessionMetadata();
|
||||
}
|
||||
|
||||
this.checkSleepTimerEndOfChapter();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,6 +336,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
const audio = this.audioElement?.nativeElement;
|
||||
if (audio && audio.buffered.length > 0) {
|
||||
this.buffered = audio.buffered.end(audio.buffered.length - 1);
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,6 +358,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.updateMediaSessionPlaybackState();
|
||||
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onAudioError(): void {
|
||||
@@ -351,6 +368,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
summary: this.t.translate('common.error'),
|
||||
detail: this.t.translate('readerAudiobook.toast.audioLoadFailed')
|
||||
});
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
private setupMediaSession(): void {
|
||||
@@ -395,7 +413,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
if (!('mediaSession' in navigator)) return;
|
||||
|
||||
const chapters = this.audiobookInfo.chapters;
|
||||
const chapterTitle = chapters && chapters.length > 1 ? this.getCurrentChapter()?.title : null;
|
||||
const chapterTitle = chapters && chapters.length > 1 ? this.currentChapter?.title : null;
|
||||
|
||||
const title = this.audiobookInfo.folderBased
|
||||
? this.currentTrack?.title
|
||||
@@ -460,6 +478,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
|
||||
);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
};
|
||||
audio.addEventListener('canplay', playWhenReady);
|
||||
return;
|
||||
@@ -487,6 +506,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
this.isPlaying = !this.isPlaying;
|
||||
this.updateMediaSessionPlaybackState();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
seek(event: SliderChangeEvent): void {
|
||||
@@ -494,6 +514,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
const seekTime = event.value as number;
|
||||
this.isSeeking = true;
|
||||
this.currentTime = seekTime;
|
||||
this.updateCurrentChapter();
|
||||
|
||||
if (this.seekDebounceTimeout) {
|
||||
clearTimeout(this.seekDebounceTimeout);
|
||||
@@ -514,6 +535,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
const newTime = Math.max(0, Math.min(this.duration, audio.currentTime + seconds));
|
||||
audio.currentTime = newTime;
|
||||
this.currentTime = newTime;
|
||||
this.updateCurrentChapter();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -564,6 +586,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.updateMediaSessionMetadata();
|
||||
this.cdr.markForCheck();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
@@ -578,6 +601,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
setTimeout(() => {
|
||||
this.audioElement?.nativeElement?.play();
|
||||
this.updateMediaSessionMetadata();
|
||||
this.cdr.markForCheck();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
@@ -617,6 +641,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.audiobookInfo?.bookFileId, track.index
|
||||
);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
@@ -635,6 +660,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
audio.removeEventListener('canplay', seekAndPlay);
|
||||
audio.currentTime = chapter.startTimeMs / 1000;
|
||||
this.currentTime = chapter.startTimeMs / 1000;
|
||||
this.updateCurrentChapter();
|
||||
audio.play();
|
||||
this.isPlaying = true;
|
||||
this.startProgressSaveInterval();
|
||||
@@ -648,6 +674,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.audiobookInfo?.bookFileId
|
||||
);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
};
|
||||
audio.addEventListener('canplay', seekAndPlay);
|
||||
this.showTrackList = false;
|
||||
@@ -656,6 +683,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
|
||||
audio.currentTime = chapter.startTimeMs / 1000;
|
||||
this.currentTime = chapter.startTimeMs / 1000;
|
||||
this.updateCurrentChapter();
|
||||
this.showTrackList = false;
|
||||
this.updateMediaSessionMetadata();
|
||||
if (!this.isPlaying) {
|
||||
@@ -674,17 +702,17 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
getCurrentChapter(): AudiobookChapter | undefined {
|
||||
if (!this.audiobookInfo?.chapters) return undefined;
|
||||
private updateCurrentChapter(): void {
|
||||
if (!this.audiobookInfo?.chapters) {
|
||||
this.currentChapter = undefined;
|
||||
this.currentChapterIdx = 0;
|
||||
return;
|
||||
}
|
||||
const currentMs = this.currentTime * 1000;
|
||||
return this.audiobookInfo.chapters.find(
|
||||
this.currentChapter = this.audiobookInfo.chapters.find(
|
||||
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
|
||||
);
|
||||
}
|
||||
|
||||
getCurrentChapterIndex(): number {
|
||||
const chapter = this.getCurrentChapter();
|
||||
return chapter?.index ?? 0;
|
||||
this.currentChapterIdx = this.currentChapter?.index ?? 0;
|
||||
}
|
||||
|
||||
hasMultipleChapters(): boolean {
|
||||
@@ -692,22 +720,21 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
canGoPreviousChapter(): boolean {
|
||||
return this.getCurrentChapterIndex() > 0;
|
||||
return this.currentChapterIdx > 0;
|
||||
}
|
||||
|
||||
canGoNextChapter(): boolean {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return false;
|
||||
return this.getCurrentChapterIndex() < chapters.length - 1;
|
||||
return this.currentChapterIdx < chapters.length - 1;
|
||||
}
|
||||
|
||||
previousChapter(): void {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return;
|
||||
|
||||
const currentIndex = this.getCurrentChapterIndex();
|
||||
if (currentIndex > 0) {
|
||||
const prevChapter = chapters[currentIndex - 1];
|
||||
if (this.currentChapterIdx > 0) {
|
||||
const prevChapter = chapters[this.currentChapterIdx - 1];
|
||||
this.selectChapter(prevChapter);
|
||||
}
|
||||
}
|
||||
@@ -716,9 +743,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
const chapters = this.audiobookInfo?.chapters;
|
||||
if (!chapters) return;
|
||||
|
||||
const currentIndex = this.getCurrentChapterIndex();
|
||||
if (currentIndex < chapters.length - 1) {
|
||||
const nextChapter = chapters[currentIndex + 1];
|
||||
if (this.currentChapterIdx < chapters.length - 1) {
|
||||
const nextChapter = chapters[this.currentChapterIdx + 1];
|
||||
this.selectChapter(nextChapter);
|
||||
}
|
||||
}
|
||||
@@ -861,6 +887,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
if (this.sleepTimerRemaining <= 0) {
|
||||
this.triggerSleepTimerStop();
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}, 1000);
|
||||
|
||||
this.messageService.add({
|
||||
@@ -945,10 +972,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
private checkSleepTimerEndOfChapter(): void {
|
||||
if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return;
|
||||
|
||||
const currentChapter = this.getCurrentChapter();
|
||||
if (currentChapter) {
|
||||
if (this.currentChapter) {
|
||||
const currentMs = this.currentTime * 1000;
|
||||
if (currentMs >= currentChapter.endTimeMs - 1000) {
|
||||
if (currentMs >= this.currentChapter.endTimeMs - 1000) {
|
||||
this.triggerSleepTimerStop();
|
||||
}
|
||||
}
|
||||
@@ -956,9 +982,10 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
|
||||
loadBookmarks(): void {
|
||||
this.bookMarkService.getBookmarksForBook(this.bookId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(bookmarks => {
|
||||
this.bookmarks = bookmarks;
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -970,14 +997,13 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
addBookmark(): void {
|
||||
const currentChapter = this.getCurrentChapter();
|
||||
const currentTrack = this.currentTrack;
|
||||
|
||||
let title: string;
|
||||
if (this.audiobookInfo.folderBased && currentTrack) {
|
||||
title = `${currentTrack.title} - ${this.formatTime(this.currentTime)}`;
|
||||
} else if (currentChapter) {
|
||||
title = `${currentChapter.title} - ${this.formatTime(this.currentTime)}`;
|
||||
} else if (this.currentChapter) {
|
||||
title = `${this.currentChapter.title} - ${this.formatTime(this.currentTime)}`;
|
||||
} else {
|
||||
title = this.t.translate('readerAudiobook.bookmarks.bookmarkAt', {time: this.formatTime(this.currentTime)});
|
||||
}
|
||||
@@ -990,7 +1016,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
};
|
||||
|
||||
this.bookMarkService.createBookmark(request)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (bookmark) => {
|
||||
this.bookmarks = [...this.bookmarks, bookmark];
|
||||
@@ -999,6 +1025,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
summary: this.t.translate('readerAudiobook.toast.bookmarkAdded'),
|
||||
detail: title
|
||||
});
|
||||
this.cdr.markForCheck();
|
||||
},
|
||||
error: (err) => {
|
||||
const isDuplicate = err?.status === 409;
|
||||
@@ -1046,6 +1073,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
|
||||
);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
};
|
||||
audio.addEventListener('canplay', seekAndPlay);
|
||||
this.showBookmarkList = false;
|
||||
@@ -1082,6 +1110,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
|
||||
);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
@@ -1089,13 +1118,14 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
|
||||
deleteBookmark(event: MouseEvent, bookmarkId: number): void {
|
||||
event.stopPropagation();
|
||||
this.bookMarkService.deleteBookmark(bookmarkId)
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
|
||||
this.messageService.add({
|
||||
severity: 'info',
|
||||
summary: this.t.translate('readerAudiobook.toast.bookmarkDeleted')
|
||||
});
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, effect, ElementRef, HostListener, inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
|
||||
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, effect, ElementRef, HostListener, inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { forkJoin, from, Subject } from 'rxjs';
|
||||
import { debounceTime, map, switchMap, takeUntil, tap } from 'rxjs/operators';
|
||||
@@ -62,7 +62,8 @@ import {
|
||||
CbxQuickSettingsService
|
||||
],
|
||||
templateUrl: './cbx-reader.component.html',
|
||||
styleUrl: './cbx-reader.component.scss'
|
||||
styleUrl: './cbx-reader.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
private static readonly PRELOAD_PAGE_WINDOW = 5;
|
||||
@@ -230,6 +231,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
protected readonly cbxQuickSettingsState = this.quickSettingsService.state;
|
||||
private pageDimensionService = inject(CbxPageDimensionService);
|
||||
private wakeLockService = inject(WakeLockService);
|
||||
private cdr = inject(ChangeDetectorRef);
|
||||
private readerPreferencesService = inject(ReaderPreferencesService);
|
||||
|
||||
protected readonly CbxScrollMode = CbxScrollMode;
|
||||
@@ -252,7 +254,10 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
/** Run after the browser has applied layout (two frames — common Angular/DOM pattern). */
|
||||
private afterNextPaint(fn: () => void): void {
|
||||
requestAnimationFrame(() => requestAnimationFrame(fn));
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => {
|
||||
fn();
|
||||
this.cdr.markForCheck();
|
||||
}));
|
||||
}
|
||||
|
||||
constructor() {
|
||||
@@ -425,11 +430,13 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
const percentage = this.pages.length > 0 ? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10 : 0;
|
||||
this.readingSessionService.startSession(this.bookId, "CBX", (this.currentPage + 1).toString(), percentage);
|
||||
this.cdr.markForCheck();
|
||||
},
|
||||
error: (err) => {
|
||||
const errorMessage = err?.error?.message || this.t.translate('shared.reader.failedToLoadPages');
|
||||
this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: errorMessage });
|
||||
this.isLoading = false;
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -437,6 +444,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
const errorMessage = err?.error?.message || this.t.translate('shared.reader.failedToLoadBook');
|
||||
this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: errorMessage });
|
||||
this.isLoading = false;
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -486,6 +494,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe(() => {
|
||||
this.showShortcutsHelp = true;
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -580,6 +589,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.brightness = value;
|
||||
this.quickSettingsService.setBrightness(value);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
|
||||
this.quickSettingsService.emulateBookChange$
|
||||
@@ -588,6 +598,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.emulateBook = value;
|
||||
this.quickSettingsService.setEmulateBook(value);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
|
||||
this.quickSettingsService.clickToPaginateChange$
|
||||
@@ -596,6 +607,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.clickToPaginate = value;
|
||||
this.quickSettingsService.setClickToPaginate(value);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
|
||||
this.quickSettingsService.autoCloseMenuChange$
|
||||
@@ -604,6 +616,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.autoCloseMenu = value;
|
||||
this.quickSettingsService.setAutoCloseMenu(value);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
});
|
||||
|
||||
this.quickSettingsService.stripMaxWidthChange$
|
||||
@@ -864,7 +877,9 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
setTimeout(() => {
|
||||
this.isPageTransitioning = false;
|
||||
this.previousImageUrls = [];
|
||||
this.cdr.markForCheck();
|
||||
}, 150);
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
};
|
||||
img.onerror = () => {
|
||||
@@ -874,6 +889,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.imagesLoaded = true;
|
||||
this.isPageTransitioning = false;
|
||||
this.previousImageUrls = [];
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
};
|
||||
img.src = url;
|
||||
@@ -882,6 +898,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
onImageLoad(): void {
|
||||
this.imagesLoaded = true;
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
get isTwoPageView(): boolean {
|
||||
@@ -1029,6 +1046,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
if (this.isSlideshowActive && this.currentPage >= this.pages.length - 1) {
|
||||
this.stopSlideshow();
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
private getPageStep(): number {
|
||||
@@ -1059,6 +1077,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.fitMode = mode;
|
||||
this.quickSettingsService.setFitMode(mode);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onScrollModeChange(mode: CbxScrollMode): void {
|
||||
@@ -1093,6 +1112,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.updateCurrentImageUrls();
|
||||
this.preloadAdjacentPages();
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onPageViewModeChange(mode: CbxPageViewMode): void {
|
||||
@@ -1104,6 +1124,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.preloadAdjacentPages();
|
||||
this.footerService.setTwoPageView(this.isTwoPageView);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onPageSpreadChange(spread: CbxPageSpread): void {
|
||||
@@ -1113,12 +1134,14 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.updateCurrentImageUrls();
|
||||
this.preloadAdjacentPages();
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
onBackgroundColorChange(color: CbxBackgroundColor): void {
|
||||
this.backgroundColor = color;
|
||||
this.quickSettingsService.setBackgroundColor(color);
|
||||
this.updateViewerSetting();
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
private initializeInfiniteScroll(): void {
|
||||
@@ -1350,6 +1373,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
if (this.longStripIntersectionObserver) {
|
||||
this.longStripIntersectionObserver.observe(img);
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1384,6 +1408,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.longStripAllImagesLoaded = true;
|
||||
this.longStripDoScroll(this.currentPage, 'instant', layoutGen);
|
||||
this.longStripInitFinished = true;
|
||||
this.cdr.markForCheck();
|
||||
};
|
||||
|
||||
if (img.complete) {
|
||||
@@ -1446,6 +1471,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
private longStripHandleIntersection(entries: IntersectionObserverEntry[]): void {
|
||||
if (!this.longStripAllImagesLoaded || this.longStripIsScrolling) return;
|
||||
|
||||
let changed = false;
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
const pageAttr = entry.target.getAttribute('data-page');
|
||||
@@ -1453,9 +1479,13 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
const page = parseInt(pageAttr, 10);
|
||||
// Prefetch more images when a page enters the viewport
|
||||
this.longStripPrefetchAround(page);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
}
|
||||
|
||||
private longStripAttachScrollListeners(): void {
|
||||
@@ -1466,6 +1496,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
if (this.longStripScrollDebounceTimer) clearTimeout(this.longStripScrollDebounceTimer);
|
||||
this.longStripScrollDebounceTimer = setTimeout(() => {
|
||||
this.longStripOnScroll(container);
|
||||
this.cdr.markForCheck();
|
||||
}, 20);
|
||||
};
|
||||
|
||||
@@ -1474,6 +1505,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
if (this.longStripScrollEndDebounceTimer) clearTimeout(this.longStripScrollEndDebounceTimer);
|
||||
this.longStripScrollEndDebounceTimer = setTimeout(() => {
|
||||
this.longStripOnScrollEnd(container);
|
||||
this.cdr.markForCheck();
|
||||
}, supportsScrollEnd ? 20 : 100);
|
||||
};
|
||||
|
||||
@@ -1638,6 +1670,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
this.updateSessionProgress();
|
||||
this.updateFooterPage();
|
||||
}
|
||||
this.cdr.markForCheck();
|
||||
}
|
||||
|
||||
firstPage(): void {
|
||||
@@ -1970,6 +2003,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
|
||||
|
||||
this.footerService.setSeriesBooks(this.previousBookInSeries, this.nextBookInSeries);
|
||||
this.footerService.setHasSeries(true);
|
||||
this.cdr.markForCheck();
|
||||
},
|
||||
error: (err) => {
|
||||
console.error('[SeriesNav] Failed to load series information:', err);
|
||||
|
||||
Reference in New Issue
Block a user