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 io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; 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.http.*;
import org.springframework.web.bind.annotation.*; 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; import java.nio.file.Path;
@Slf4j @Slf4j
@@ -46,13 +45,15 @@ public class AudiobookReaderController {
@ApiResponse(responseCode = "416", description = "Range not satisfiable") @ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId") @CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/stream") @GetMapping("/{bookId}/stream")
public ResponseEntity<? extends Resource> streamAudiobook( public void streamAudiobook(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@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,
@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); 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.") @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") @ApiResponse(responseCode = "416", description = "Range not satisfiable")
@CheckBookAccess(bookIdParam = "bookId") @CheckBookAccess(bookIdParam = "bookId")
@GetMapping("/{bookId}/track/{trackIndex}/stream") @GetMapping("/{bookId}/track/{trackIndex}/stream")
public ResponseEntity<? extends Resource> streamTrack( public void streamTrack(
@Parameter(description = "ID of the book") @PathVariable Long bookId, @Parameter(description = "ID of the book") @PathVariable Long bookId,
@Parameter(description = "Track index (0-indexed)") @PathVariable Integer trackIndex, @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); Path audioPath = audiobookReaderService.getAudioFilePath(bookId, bookType, trackIndex);
return getFile(audioPath); audiobookReaderService.streamWithRangeSupport(audioPath, request, response);
} }
@Operation(summary = "Get embedded cover art", @Operation(summary = "Get embedded cover art",
@@ -94,18 +97,4 @@ public class AudiobookReaderController {
return new ResponseEntity<>(coverData, headers, HttpStatus.OK); 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> { public interface BookRepository extends JpaRepository<BookEntity, Long>, JpaSpecificationExecutor<BookEntity> {
Optional<BookEntity> findBookByIdAndLibraryId(long id, long libraryId); 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" }) @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)") @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); Optional<BookEntity> findByIdWithBookFiles(@Param("id") Long id);
@@ -9,6 +9,8 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -45,61 +47,73 @@ public class AudioFileUtilityService {
* Check if a file is an audio file based on its extension. * Check if a file is an audio file based on its extension.
*/ */
public boolean isAudioFile(Path path) { 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); return AUDIO_EXTENSIONS.stream().anyMatch(fileName::endsWith);
} }
/** /**
* Get the MIME content type for an audio file using content-based detection via Apache Tika. * Get the supported audio file extensions.
*/
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.
*/ */
public Set<String> getSupportedExtensions() { public Set<String> getSupportedExtensions() {
return AUDIO_EXTENSIONS; return AUDIO_EXTENSIONS;
} }
private int naturalCompare(Path p1, Path p2) { private static final Map<String, String> AUDIO_MIME = Map.of(
return naturalCompare(p1.getFileName().toString(), p2.getFileName().toString()); ".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. * Extract a track title from a filename by removing extensions, track numbers, and separators.
* Handles filenames like "Track 1.mp3", "Track 2.mp3", ..., "Track 10.mp3" correctly.
*/ */
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; int i1 = 0, i2 = 0;
while (i1 < s1.length() && i2 < s2.length()) { while (i1 < s1.length() && i2 < s2.length()) {
char c1 = s1.charAt(i1); char c1 = s1.charAt(i1);
char c2 = s2.charAt(i2); char c2 = s2.charAt(i2);
if (Character.isDigit(c1) && Character.isDigit(c2)) { if (Character.isDigit(c1) && Character.isDigit(c2)) {
StringBuilder num1 = new StringBuilder(); StringBuilder b1 = new StringBuilder();
StringBuilder num2 = new StringBuilder();
while (i1 < s1.length() && Character.isDigit(s1.charAt(i1))) { 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))) { 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 { } else {
int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2)); int cmp = Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2));
if (cmp != 0) return cmp; if (cmp != 0) return cmp;
@@ -5,7 +5,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.Locale;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.AudiobookMetadata; import org.booklore.model.dto.AudiobookMetadata;
@@ -28,7 +28,7 @@ import org.springframework.transaction.annotation.Transactional;
@Slf4j @Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Transactional(readOnly = true) @Transactional
public class AudioMetadataService { public class AudioMetadataService {
private final AudioFileUtilityService audioFileUtility; private final AudioFileUtilityService audioFileUtility;
@@ -76,7 +76,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs()) .endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs()) .durationMs(ch.getDurationMs())
.build()) .build())
.collect(Collectors.toList()); .toList();
builder.chapters(chapters); builder.chapters(chapters);
} else { } else {
backfillChapters(bookFile, audioPath, builder); backfillChapters(bookFile, audioPath, builder);
@@ -218,7 +218,14 @@ public class AudioMetadataService {
long totalSizeBytes = tracks.stream() long totalSizeBytes = tracks.stream()
.mapToLong(t -> t.getFileSizeBytes() != null ? t.getFileSizeBytes() : 0) .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( private AudiobookInfo extractSingleFileMetadata(
@@ -268,7 +275,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs()) .endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs()) .durationMs(ch.getDurationMs())
.build()) .build())
.collect(Collectors.toList()); .toList();
bookFile.setChapters(entityChapters); bookFile.setChapters(entityChapters);
bookFile.setChapterCount(entityChapters.size()); bookFile.setChapterCount(entityChapters.size());
bookFileRepository.save(bookFile); bookFileRepository.save(bookFile);
@@ -298,7 +305,7 @@ public class AudioMetadataService {
.endTimeMs(ch.getEndTimeMs()) .endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs()) .durationMs(ch.getDurationMs())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
List<AudiobookChapter> fallback = new ArrayList<>(); List<AudiobookChapter> fallback = new ArrayList<>();
@@ -372,8 +379,8 @@ public class AudioMetadataService {
private Integer parseChannels(String channels) { private Integer parseChannels(String channels) {
if (channels == null) return null; if (channels == null) return null;
if (channels.toLowerCase().contains("stereo")) return 2; if (channels.toLowerCase(Locale.ROOT).contains("stereo")) return 2;
if (channels.toLowerCase().contains("mono")) return 1; if (channels.toLowerCase(Locale.ROOT).contains("mono")) return 1;
try { try {
return Integer.parseInt(channels.replaceAll("[^0-9]", "")); return Integer.parseInt(channels.replaceAll("[^0-9]", ""));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@@ -12,6 +12,7 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path; import java.nio.file.Path;
@@ -34,6 +35,7 @@ public class AudiobookReaderService {
/** /**
* Get audiobook information including metadata, chapters, and tracks. * Get audiobook information including metadata, chapters, and tracks.
*/ */
@Transactional
public AudiobookInfo getAudiobookInfo(Long bookId, String bookType) { public AudiobookInfo getAudiobookInfo(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType); BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.getFullFilePath(); Path audioPath = bookFile.getFullFilePath();
@@ -50,6 +52,7 @@ public class AudiobookReaderService {
* Get the path to an audio file for streaming. * Get the path to an audio file for streaming.
* For folder-based audiobooks, returns the path to a specific track. * For folder-based audiobooks, returns the path to a specific track.
*/ */
@Transactional(readOnly = true)
public Path getAudioFilePath(Long bookId, String bookType, Integer trackIndex) { public Path getAudioFilePath(Long bookId, String bookType, Integer trackIndex) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType); BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
@@ -78,6 +81,7 @@ public class AudiobookReaderService {
/** /**
* Get embedded cover art from an audiobook file. * Get embedded cover art from an audiobook file.
*/ */
@Transactional(readOnly = true)
public byte[] getEmbeddedCoverArt(Long bookId, String bookType) { public byte[] getEmbeddedCoverArt(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType); BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath(); Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath();
@@ -87,6 +91,7 @@ public class AudiobookReaderService {
/** /**
* Get the MIME type of embedded cover art. * Get the MIME type of embedded cover art.
*/ */
@Transactional(readOnly = true)
public String getCoverArtMimeType(Long bookId, String bookType) { public String getCoverArtMimeType(Long bookId, String bookType) {
BookFileEntity bookFile = getAudiobookFile(bookId, bookType); BookFileEntity bookFile = getAudiobookFile(bookId, bookType);
Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath(); Path audioPath = bookFile.isFolderBased() ? bookFile.getFirstAudioFile() : bookFile.getFullFilePath();
@@ -100,8 +105,9 @@ public class AudiobookReaderService {
return audioFileUtility.getContentType(audioPath); return audioFileUtility.getContentType(audioPath);
} }
private BookFileEntity getAudiobookFile(Long bookId, String bookType) { @Transactional(readOnly = true)
BookEntity bookEntity = bookRepository.findByIdWithBookFiles(bookId) protected BookFileEntity getAudiobookFile(Long bookId, String bookType) {
BookEntity bookEntity = bookRepository.findByIdForAudiobook(bookId)
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
if (bookType != null) { if (bookType != null) {
@@ -102,7 +102,7 @@ class AudiobookReaderServiceTest {
.durationMs(3600000L) .durationMs(3600000L)
.build(); .build();
when(bookRepository.findByIdWithBookFiles(1L)).thenReturn(Optional.of(bookEntity)); when(bookRepository.findByIdForAudiobook(1L)).thenReturn(Optional.of(bookEntity));
when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo); when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null); AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
@@ -124,7 +124,7 @@ class AudiobookReaderServiceTest {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); 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); when(audioMetadataService.getMetadata(audiobookFileEntity, audioPath)).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, "AUDIOBOOK"); AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, "AUDIOBOOK");
@@ -135,7 +135,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getAudiobookInfo_throwsExceptionWhenBookNotFound() { void getAudiobookInfo_throwsExceptionWhenBookNotFound() {
when(bookRepository.findByIdWithBookFiles(999L)).thenReturn(Optional.empty()); when(bookRepository.findByIdForAudiobook(999L)).thenReturn(Optional.empty());
assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(), assertThrows(ApiError.BOOK_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(999L, null)); () -> audiobookReaderService.getAudiobookInfo(999L, null));
@@ -150,7 +150,7 @@ class AudiobookReaderServiceTest {
bookFiles.add(epubFile); bookFiles.add(epubFile);
when(bookEntity.getBookFiles()).thenReturn(bookFiles); 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(), assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(1L, null)); () -> audiobookReaderService.getAudiobookInfo(1L, null));
@@ -158,7 +158,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getAudiobookInfo_throwsExceptionWhenRequestedTypeNotFound() { 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(), assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
() -> audiobookReaderService.getAudiobookInfo(1L, "EPUB")); () -> audiobookReaderService.getAudiobookInfo(1L, "EPUB"));
@@ -166,7 +166,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getAudiobookInfo_wrapsMetadataServiceException() throws Exception { 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")); when(audioMetadataService.getMetadata(any(), any())).thenThrow(new RuntimeException("Parse error"));
assertThrows(ApiError.FILE_READ_ERROR.createException().getClass(), assertThrows(ApiError.FILE_READ_ERROR.createException().getClass(),
@@ -177,7 +177,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getAudioFilePath_singleFile_returnsFilePath() { 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); Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
@@ -186,7 +186,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getAudioFilePath_singleFile_ignoresTrackIndex() { 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); Path result = audiobookReaderService.getAudioFilePath(1L, null, 5);
@@ -204,7 +204,7 @@ class AudiobookReaderServiceTest {
Files.createFile(track1); Files.createFile(track1);
Files.createFile(track2); 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)); when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1, track2));
Path result = audiobookReaderService.getAudioFilePath(1L, null, 1); Path result = audiobookReaderService.getAudioFilePath(1L, null, 1);
@@ -221,7 +221,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3"); Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1); 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)); when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
Path result = audiobookReaderService.getAudioFilePath(1L, null, null); Path result = audiobookReaderService.getAudioFilePath(1L, null, null);
@@ -238,7 +238,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3"); Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1); 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)); when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
@@ -254,7 +254,7 @@ class AudiobookReaderServiceTest {
Path track1 = folderPath.resolve("track1.mp3"); Path track1 = folderPath.resolve("track1.mp3");
Files.createFile(track1); 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)); when(audioFileUtility.listAudioFiles(folderPath)).thenReturn(List.of(track1));
assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(), assertThrows(ApiError.FILE_NOT_FOUND.createException().getClass(),
@@ -297,7 +297,7 @@ class AudiobookReaderServiceTest {
void getEmbeddedCoverArt_delegatesToMetadataService() { void getEmbeddedCoverArt_delegatesToMetadataService() {
byte[] expectedData = new byte[]{0x01, 0x02, 0x03}; 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); when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(expectedData);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -318,7 +318,7 @@ class AudiobookReaderServiceTest {
byte[] expectedData = new byte[]{0x04, 0x05}; 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); when(audioMetadataService.getEmbeddedCoverArt(track1)).thenReturn(expectedData);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -329,7 +329,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getEmbeddedCoverArt_returnsNullWhenNoCoverArt() { 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); when(audioMetadataService.getEmbeddedCoverArt(audioPath)).thenReturn(null);
byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null); byte[] result = audiobookReaderService.getEmbeddedCoverArt(1L, null);
@@ -341,7 +341,7 @@ class AudiobookReaderServiceTest {
@Test @Test
void getCoverArtMimeType_delegatesToMetadataService() { 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"); when(audioMetadataService.getCoverArtMimeType(audioPath)).thenReturn("image/png");
String result = audiobookReaderService.getCoverArtMimeType(1L, null); String result = audiobookReaderService.getCoverArtMimeType(1L, null);
@@ -360,7 +360,7 @@ class AudiobookReaderServiceTest {
Files.createFile(track1); Files.createFile(track1);
when(folderAudiobookFileEntity.getFirstAudioFile()).thenReturn(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"); when(audioMetadataService.getCoverArtMimeType(track1)).thenReturn("image/jpeg");
String result = audiobookReaderService.getCoverArtMimeType(1L, null); String result = audiobookReaderService.getCoverArtMimeType(1L, null);
@@ -396,7 +396,7 @@ class AudiobookReaderServiceTest {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); 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); when(audioMetadataService.getMetadata(eq(audiobookFileEntity), any())).thenReturn(expectedInfo);
AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null); AudiobookInfo result = audiobookReaderService.getAudiobookInfo(1L, null);
@@ -409,7 +409,7 @@ class AudiobookReaderServiceTest {
void getAudiobookInfo_bookTypeIsCaseInsensitive() throws Exception { void getAudiobookInfo_bookTypeIsCaseInsensitive() throws Exception {
AudiobookInfo expectedInfo = AudiobookInfo.builder().bookId(1L).build(); 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); when(audioMetadataService.getMetadata(any(), any())).thenReturn(expectedInfo);
// Test lowercase // Test lowercase
@@ -83,10 +83,10 @@
@if (audiobookInfo.folderBased && currentTrack) { @if (audiobookInfo.folderBased && currentTrack) {
<span class="track-title">{{ currentTrack.title }}</span> <span class="track-title">{{ currentTrack.title }}</span>
<span class="track-number">{{ t('trackInfo.trackOf', { current: currentTrackIndex + 1, total: audiobookInfo.tracks?.length }) }}</span> <span class="track-number">{{ t('trackInfo.trackOf', { current: currentTrackIndex + 1, total: audiobookInfo.tracks?.length }) }}</span>
} @else if (getCurrentChapter()) { } @else if (currentChapter) {
<span class="track-title">{{ getCurrentChapter()?.title }}</span> <span class="track-title">{{ currentChapter.title }}</span>
@if (hasMultipleChapters()) { @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> </div>
@@ -329,7 +329,7 @@
@for (chapter of audiobookInfo.chapters; track chapter.index) { @for (chapter of audiobookInfo.chapters; track chapter.index) {
<li <li
class="track-item" class="track-item"
[class.active]="getCurrentChapter()?.index === chapter.index" [class.active]="currentChapter?.index === chapter.index"
(click)="selectChapter(chapter)" (click)="selectChapter(chapter)"
(keydown.enter)="selectChapter(chapter)" (keydown.enter)="selectChapter(chapter)"
role="button" role="button"
@@ -340,7 +340,7 @@
<span class="track-name">{{ chapter.title }}</span> <span class="track-name">{{ chapter.title }}</span>
<span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span> <span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
</div> </div>
@if (getCurrentChapter()?.index === chapter.index && isPlaying) { @if (currentChapter?.index === chapter.index && isPlaying) {
<i class="pi pi-volume-up playing-indicator"></i> <i class="pi pi-volume-up playing-indicator"></i>
} }
</li> </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 {Location} from '@angular/common';
import {ActivatedRoute} from '@angular/router'; import {ActivatedRoute} from '@angular/router';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {from, Observable, of, Subject} from 'rxjs'; import {from, Observable, of} from 'rxjs';
import {catchError, filter, map, switchMap, takeUntil, tap} from 'rxjs/operators'; import {catchError, filter, map, switchMap, tap} from 'rxjs/operators';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {Slider, SliderChangeEvent} from 'primeng/slider'; import {Slider, SliderChangeEvent} from 'primeng/slider';
@@ -38,12 +39,13 @@ import {API_CONFIG} from '../../../core/config/api-config';
TranslocoDirective TranslocoDirective
], ],
templateUrl: './audiobook-player.component.html', templateUrl: './audiobook-player.component.html',
styleUrls: ['./audiobook-player.component.scss'] styleUrls: ['./audiobook-player.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class AudiobookPlayerComponent implements OnInit, OnDestroy { export class AudiobookPlayerComponent implements OnInit, OnDestroy {
@ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>; @ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>;
private destroy$ = new Subject<void>(); private readonly destroyRef = inject(DestroyRef);
private audiobookService = inject(AudiobookService); private audiobookService = inject(AudiobookService);
private bookService = inject(BookService); private bookService = inject(BookService);
private bookMarkService = inject(BookMarkService); private bookMarkService = inject(BookMarkService);
@@ -54,7 +56,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
private audiobookSessionService = inject(AudiobookSessionService); private audiobookSessionService = inject(AudiobookSessionService);
private pageTitle = inject(PageTitleService); private pageTitle = inject(PageTitleService);
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private readonly cdr = inject(ChangeDetectorRef);
isLoading = true; isLoading = true;
audioLoading = false; audioLoading = false;
audioInitialized = false; audioInitialized = false;
@@ -76,6 +78,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
private savedPosition = 0; private savedPosition = 0;
currentTrackIndex = 0; currentTrackIndex = 0;
currentChapter?: AudiobookChapter;
currentChapterIdx = 0;
audioSrc = ''; audioSrc = '';
showTrackList = false; showTrackList = false;
@@ -117,7 +121,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
]; ];
this.route.paramMap.pipe( this.route.paramMap.pipe(
takeUntil(this.destroy$), takeUntilDestroyed(this.destroyRef),
map(params => Number(params.get('bookId'))), map(params => Number(params.get('bookId'))),
filter(bookId => !Number.isNaN(bookId)), filter(bookId => !Number.isNaN(bookId)),
switchMap(bookId => this.loadAudiobook(bookId)) switchMap(bookId => this.loadAudiobook(bookId))
@@ -125,9 +129,6 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
} }
ngOnDestroy(): void { ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
if (this.progressSaveInterval) { if (this.progressSaveInterval) {
clearInterval(this.progressSaveInterval); clearInterval(this.progressSaveInterval);
} }
@@ -153,10 +154,15 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.isLoading = true; this.isLoading = true;
return this.audiobookService.getAudiobookInfo(bookId).pipe( 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; this.audiobookInfo = info;
if (info.folderBased && info.tracks && info.tracks.length > 0) { 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); this.audioSrc = this.audiobookService.getTrackStreamUrl(bookId, 0);
const track = info.tracks[0]; const track = info.tracks[0];
if (track?.durationMs) { 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(); const token = this.authService.getInternalAccessToken();
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book/${bookId}/cover?token=${encodeURIComponent(token || '')}`; 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.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(); 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 => map(() => void 0),
from(this.bookService.fetchFreshBookDetail(bookId, false)).pipe(
tap(book => this.applyBookDetails(book, info)),
map(() => void 0),
catchError(() => of(void 0))
)
),
catchError(() => { catchError(() => {
this.messageService.add({ this.messageService.add({
severity: 'error', severity: 'error',
@@ -192,6 +201,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
}); });
this.isLoading = false; this.isLoading = false;
this.audioLoading = false; this.audioLoading = false;
this.cdr.markForCheck();
return of(void 0); return of(void 0);
}) })
); );
@@ -229,6 +239,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
if (this.savedPosition > 0) { if (this.savedPosition > 0) {
this.currentTime = this.savedPosition; this.currentTime = this.savedPosition;
} }
this.updateCurrentChapter();
} }
private loadTrack(index: number, showLoading = true): void { private loadTrack(index: number, showLoading = true): void {
@@ -290,16 +301,19 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.setupMediaSession(); this.setupMediaSession();
} }
this.cdr.markForCheck();
} }
onTimeUpdate(): void { onTimeUpdate(): void {
const audio = this.audioElement?.nativeElement; const audio = this.audioElement?.nativeElement;
if (audio) { if (audio) {
const previousChapterIndex = this.getCurrentChapterIndex(); const previousChapterIndex = this.currentChapterIdx;
if (!this.isSeeking) { if (!this.isSeeking) {
this.currentTime = audio.currentTime; this.currentTime = audio.currentTime;
} }
this.updateCurrentChapter();
this.audiobookSessionService.updatePosition( this.audiobookSessionService.updatePosition(
Math.round(this.currentTime * 1000), Math.round(this.currentTime * 1000),
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
@@ -309,11 +323,12 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.updateMediaSessionPositionState(); this.updateMediaSessionPositionState();
} }
if (!this.audiobookInfo.folderBased && this.getCurrentChapterIndex() !== previousChapterIndex) { if (!this.audiobookInfo.folderBased && this.currentChapterIdx !== previousChapterIndex) {
this.updateMediaSessionMetadata(); this.updateMediaSessionMetadata();
} }
this.checkSleepTimerEndOfChapter(); this.checkSleepTimerEndOfChapter();
this.cdr.markForCheck();
} }
} }
@@ -321,6 +336,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
const audio = this.audioElement?.nativeElement; const audio = this.audioElement?.nativeElement;
if (audio && audio.buffered.length > 0) { if (audio && audio.buffered.length > 0) {
this.buffered = audio.buffered.end(audio.buffered.length - 1); 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.updateMediaSessionPlaybackState();
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000)); this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
} }
this.cdr.markForCheck();
} }
onAudioError(): void { onAudioError(): void {
@@ -351,6 +368,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
summary: this.t.translate('common.error'), summary: this.t.translate('common.error'),
detail: this.t.translate('readerAudiobook.toast.audioLoadFailed') detail: this.t.translate('readerAudiobook.toast.audioLoadFailed')
}); });
this.cdr.markForCheck();
} }
private setupMediaSession(): void { private setupMediaSession(): void {
@@ -395,7 +413,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
if (!('mediaSession' in navigator)) return; if (!('mediaSession' in navigator)) return;
const chapters = this.audiobookInfo.chapters; 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 const title = this.audiobookInfo.folderBased
? this.currentTrack?.title ? this.currentTrack?.title
@@ -460,6 +478,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
); );
} }
this.cdr.markForCheck();
}; };
audio.addEventListener('canplay', playWhenReady); audio.addEventListener('canplay', playWhenReady);
return; return;
@@ -487,6 +506,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
} }
this.isPlaying = !this.isPlaying; this.isPlaying = !this.isPlaying;
this.updateMediaSessionPlaybackState(); this.updateMediaSessionPlaybackState();
this.cdr.markForCheck();
} }
seek(event: SliderChangeEvent): void { seek(event: SliderChangeEvent): void {
@@ -494,6 +514,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
const seekTime = event.value as number; const seekTime = event.value as number;
this.isSeeking = true; this.isSeeking = true;
this.currentTime = seekTime; this.currentTime = seekTime;
this.updateCurrentChapter();
if (this.seekDebounceTimeout) { if (this.seekDebounceTimeout) {
clearTimeout(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)); const newTime = Math.max(0, Math.min(this.duration, audio.currentTime + seconds));
audio.currentTime = newTime; audio.currentTime = newTime;
this.currentTime = newTime; this.currentTime = newTime;
this.updateCurrentChapter();
} }
} }
@@ -564,6 +586,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
setTimeout(() => { setTimeout(() => {
this.audioElement?.nativeElement?.play(); this.audioElement?.nativeElement?.play();
this.updateMediaSessionMetadata(); this.updateMediaSessionMetadata();
this.cdr.markForCheck();
}, 100); }, 100);
} }
} }
@@ -578,6 +601,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
setTimeout(() => { setTimeout(() => {
this.audioElement?.nativeElement?.play(); this.audioElement?.nativeElement?.play();
this.updateMediaSessionMetadata(); this.updateMediaSessionMetadata();
this.cdr.markForCheck();
}, 100); }, 100);
} }
} }
@@ -617,6 +641,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.audiobookInfo?.bookFileId, track.index this.audiobookInfo?.bookFileId, track.index
); );
} }
this.cdr.markForCheck();
}, 100); }, 100);
} }
@@ -635,6 +660,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
audio.removeEventListener('canplay', seekAndPlay); audio.removeEventListener('canplay', seekAndPlay);
audio.currentTime = chapter.startTimeMs / 1000; audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000; this.currentTime = chapter.startTimeMs / 1000;
this.updateCurrentChapter();
audio.play(); audio.play();
this.isPlaying = true; this.isPlaying = true;
this.startProgressSaveInterval(); this.startProgressSaveInterval();
@@ -648,6 +674,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.audiobookInfo?.bookFileId this.audiobookInfo?.bookFileId
); );
} }
this.cdr.markForCheck();
}; };
audio.addEventListener('canplay', seekAndPlay); audio.addEventListener('canplay', seekAndPlay);
this.showTrackList = false; this.showTrackList = false;
@@ -656,6 +683,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
audio.currentTime = chapter.startTimeMs / 1000; audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000; this.currentTime = chapter.startTimeMs / 1000;
this.updateCurrentChapter();
this.showTrackList = false; this.showTrackList = false;
this.updateMediaSessionMetadata(); this.updateMediaSessionMetadata();
if (!this.isPlaying) { if (!this.isPlaying) {
@@ -674,17 +702,17 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
} }
} }
getCurrentChapter(): AudiobookChapter | undefined { private updateCurrentChapter(): void {
if (!this.audiobookInfo?.chapters) return undefined; if (!this.audiobookInfo?.chapters) {
this.currentChapter = undefined;
this.currentChapterIdx = 0;
return;
}
const currentMs = this.currentTime * 1000; const currentMs = this.currentTime * 1000;
return this.audiobookInfo.chapters.find( this.currentChapter = this.audiobookInfo.chapters.find(
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
); );
} this.currentChapterIdx = this.currentChapter?.index ?? 0;
getCurrentChapterIndex(): number {
const chapter = this.getCurrentChapter();
return chapter?.index ?? 0;
} }
hasMultipleChapters(): boolean { hasMultipleChapters(): boolean {
@@ -692,22 +720,21 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
} }
canGoPreviousChapter(): boolean { canGoPreviousChapter(): boolean {
return this.getCurrentChapterIndex() > 0; return this.currentChapterIdx > 0;
} }
canGoNextChapter(): boolean { canGoNextChapter(): boolean {
const chapters = this.audiobookInfo?.chapters; const chapters = this.audiobookInfo?.chapters;
if (!chapters) return false; if (!chapters) return false;
return this.getCurrentChapterIndex() < chapters.length - 1; return this.currentChapterIdx < chapters.length - 1;
} }
previousChapter(): void { previousChapter(): void {
const chapters = this.audiobookInfo?.chapters; const chapters = this.audiobookInfo?.chapters;
if (!chapters) return; if (!chapters) return;
const currentIndex = this.getCurrentChapterIndex(); if (this.currentChapterIdx > 0) {
if (currentIndex > 0) { const prevChapter = chapters[this.currentChapterIdx - 1];
const prevChapter = chapters[currentIndex - 1];
this.selectChapter(prevChapter); this.selectChapter(prevChapter);
} }
} }
@@ -716,9 +743,8 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
const chapters = this.audiobookInfo?.chapters; const chapters = this.audiobookInfo?.chapters;
if (!chapters) return; if (!chapters) return;
const currentIndex = this.getCurrentChapterIndex(); if (this.currentChapterIdx < chapters.length - 1) {
if (currentIndex < chapters.length - 1) { const nextChapter = chapters[this.currentChapterIdx + 1];
const nextChapter = chapters[currentIndex + 1];
this.selectChapter(nextChapter); this.selectChapter(nextChapter);
} }
} }
@@ -861,6 +887,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
if (this.sleepTimerRemaining <= 0) { if (this.sleepTimerRemaining <= 0) {
this.triggerSleepTimerStop(); this.triggerSleepTimerStop();
} }
this.cdr.markForCheck();
}, 1000); }, 1000);
this.messageService.add({ this.messageService.add({
@@ -945,10 +972,9 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
private checkSleepTimerEndOfChapter(): void { private checkSleepTimerEndOfChapter(): void {
if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return; if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return;
const currentChapter = this.getCurrentChapter(); if (this.currentChapter) {
if (currentChapter) {
const currentMs = this.currentTime * 1000; const currentMs = this.currentTime * 1000;
if (currentMs >= currentChapter.endTimeMs - 1000) { if (currentMs >= this.currentChapter.endTimeMs - 1000) {
this.triggerSleepTimerStop(); this.triggerSleepTimerStop();
} }
} }
@@ -956,9 +982,10 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
loadBookmarks(): void { loadBookmarks(): void {
this.bookMarkService.getBookmarksForBook(this.bookId) this.bookMarkService.getBookmarksForBook(this.bookId)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(bookmarks => { .subscribe(bookmarks => {
this.bookmarks = bookmarks; this.bookmarks = bookmarks;
this.cdr.markForCheck();
}); });
} }
@@ -970,14 +997,13 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
} }
addBookmark(): void { addBookmark(): void {
const currentChapter = this.getCurrentChapter();
const currentTrack = this.currentTrack; const currentTrack = this.currentTrack;
let title: string; let title: string;
if (this.audiobookInfo.folderBased && currentTrack) { if (this.audiobookInfo.folderBased && currentTrack) {
title = `${currentTrack.title} - ${this.formatTime(this.currentTime)}`; title = `${currentTrack.title} - ${this.formatTime(this.currentTime)}`;
} else if (currentChapter) { } else if (this.currentChapter) {
title = `${currentChapter.title} - ${this.formatTime(this.currentTime)}`; title = `${this.currentChapter.title} - ${this.formatTime(this.currentTime)}`;
} else { } else {
title = this.t.translate('readerAudiobook.bookmarks.bookmarkAt', {time: this.formatTime(this.currentTime)}); 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) this.bookMarkService.createBookmark(request)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({ .subscribe({
next: (bookmark) => { next: (bookmark) => {
this.bookmarks = [...this.bookmarks, bookmark]; this.bookmarks = [...this.bookmarks, bookmark];
@@ -999,6 +1025,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
summary: this.t.translate('readerAudiobook.toast.bookmarkAdded'), summary: this.t.translate('readerAudiobook.toast.bookmarkAdded'),
detail: title detail: title
}); });
this.cdr.markForCheck();
}, },
error: (err) => { error: (err) => {
const isDuplicate = err?.status === 409; const isDuplicate = err?.status === 409;
@@ -1046,6 +1073,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
); );
} }
this.cdr.markForCheck();
}; };
audio.addEventListener('canplay', seekAndPlay); audio.addEventListener('canplay', seekAndPlay);
this.showBookmarkList = false; this.showBookmarkList = false;
@@ -1082,6 +1110,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
); );
} }
this.cdr.markForCheck();
}, 100); }, 100);
} }
} }
@@ -1089,13 +1118,14 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
deleteBookmark(event: MouseEvent, bookmarkId: number): void { deleteBookmark(event: MouseEvent, bookmarkId: number): void {
event.stopPropagation(); event.stopPropagation();
this.bookMarkService.deleteBookmark(bookmarkId) this.bookMarkService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => { .subscribe(() => {
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId); this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
this.messageService.add({ this.messageService.add({
severity: 'info', severity: 'info',
summary: this.t.translate('readerAudiobook.toast.bookmarkDeleted') 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 { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, from, Subject } from 'rxjs'; import { forkJoin, from, Subject } from 'rxjs';
import { debounceTime, map, switchMap, takeUntil, tap } from 'rxjs/operators'; import { debounceTime, map, switchMap, takeUntil, tap } from 'rxjs/operators';
@@ -62,7 +62,8 @@ import {
CbxQuickSettingsService CbxQuickSettingsService
], ],
templateUrl: './cbx-reader.component.html', templateUrl: './cbx-reader.component.html',
styleUrl: './cbx-reader.component.scss' styleUrl: './cbx-reader.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush
}) })
export class CbxReaderComponent implements OnInit, OnDestroy { export class CbxReaderComponent implements OnInit, OnDestroy {
private static readonly PRELOAD_PAGE_WINDOW = 5; private static readonly PRELOAD_PAGE_WINDOW = 5;
@@ -230,6 +231,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
protected readonly cbxQuickSettingsState = this.quickSettingsService.state; protected readonly cbxQuickSettingsState = this.quickSettingsService.state;
private pageDimensionService = inject(CbxPageDimensionService); private pageDimensionService = inject(CbxPageDimensionService);
private wakeLockService = inject(WakeLockService); private wakeLockService = inject(WakeLockService);
private cdr = inject(ChangeDetectorRef);
private readerPreferencesService = inject(ReaderPreferencesService); private readerPreferencesService = inject(ReaderPreferencesService);
protected readonly CbxScrollMode = CbxScrollMode; 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). */ /** Run after the browser has applied layout (two frames — common Angular/DOM pattern). */
private afterNextPaint(fn: () => void): void { private afterNextPaint(fn: () => void): void {
requestAnimationFrame(() => requestAnimationFrame(fn)); requestAnimationFrame(() => requestAnimationFrame(() => {
fn();
this.cdr.markForCheck();
}));
} }
constructor() { 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; 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.readingSessionService.startSession(this.bookId, "CBX", (this.currentPage + 1).toString(), percentage);
this.cdr.markForCheck();
}, },
error: (err) => { error: (err) => {
const errorMessage = err?.error?.message || this.t.translate('shared.reader.failedToLoadPages'); 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.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: errorMessage });
this.isLoading = false; 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'); 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.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: errorMessage });
this.isLoading = false; this.isLoading = false;
this.cdr.markForCheck();
} }
}); });
} }
@@ -486,6 +494,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
.pipe(takeUntil(this.destroy$)) .pipe(takeUntil(this.destroy$))
.subscribe(() => { .subscribe(() => {
this.showShortcutsHelp = true; this.showShortcutsHelp = true;
this.cdr.markForCheck();
}); });
} }
@@ -580,6 +589,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.brightness = value; this.brightness = value;
this.quickSettingsService.setBrightness(value); this.quickSettingsService.setBrightness(value);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
}); });
this.quickSettingsService.emulateBookChange$ this.quickSettingsService.emulateBookChange$
@@ -588,6 +598,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.emulateBook = value; this.emulateBook = value;
this.quickSettingsService.setEmulateBook(value); this.quickSettingsService.setEmulateBook(value);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
}); });
this.quickSettingsService.clickToPaginateChange$ this.quickSettingsService.clickToPaginateChange$
@@ -596,6 +607,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.clickToPaginate = value; this.clickToPaginate = value;
this.quickSettingsService.setClickToPaginate(value); this.quickSettingsService.setClickToPaginate(value);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
}); });
this.quickSettingsService.autoCloseMenuChange$ this.quickSettingsService.autoCloseMenuChange$
@@ -604,6 +616,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.autoCloseMenu = value; this.autoCloseMenu = value;
this.quickSettingsService.setAutoCloseMenu(value); this.quickSettingsService.setAutoCloseMenu(value);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
}); });
this.quickSettingsService.stripMaxWidthChange$ this.quickSettingsService.stripMaxWidthChange$
@@ -864,7 +877,9 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
setTimeout(() => { setTimeout(() => {
this.isPageTransitioning = false; this.isPageTransitioning = false;
this.previousImageUrls = []; this.previousImageUrls = [];
this.cdr.markForCheck();
}, 150); }, 150);
this.cdr.markForCheck();
} }
}; };
img.onerror = () => { img.onerror = () => {
@@ -874,6 +889,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.imagesLoaded = true; this.imagesLoaded = true;
this.isPageTransitioning = false; this.isPageTransitioning = false;
this.previousImageUrls = []; this.previousImageUrls = [];
this.cdr.markForCheck();
} }
}; };
img.src = url; img.src = url;
@@ -882,6 +898,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
onImageLoad(): void { onImageLoad(): void {
this.imagesLoaded = true; this.imagesLoaded = true;
this.cdr.markForCheck();
} }
get isTwoPageView(): boolean { get isTwoPageView(): boolean {
@@ -1029,6 +1046,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.isSlideshowActive && this.currentPage >= this.pages.length - 1) { if (this.isSlideshowActive && this.currentPage >= this.pages.length - 1) {
this.stopSlideshow(); this.stopSlideshow();
} }
this.cdr.markForCheck();
} }
private getPageStep(): number { private getPageStep(): number {
@@ -1059,6 +1077,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.fitMode = mode; this.fitMode = mode;
this.quickSettingsService.setFitMode(mode); this.quickSettingsService.setFitMode(mode);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
} }
onScrollModeChange(mode: CbxScrollMode): void { onScrollModeChange(mode: CbxScrollMode): void {
@@ -1093,6 +1112,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.updateCurrentImageUrls(); this.updateCurrentImageUrls();
this.preloadAdjacentPages(); this.preloadAdjacentPages();
} }
this.cdr.markForCheck();
} }
onPageViewModeChange(mode: CbxPageViewMode): void { onPageViewModeChange(mode: CbxPageViewMode): void {
@@ -1104,6 +1124,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.preloadAdjacentPages(); this.preloadAdjacentPages();
this.footerService.setTwoPageView(this.isTwoPageView); this.footerService.setTwoPageView(this.isTwoPageView);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
} }
onPageSpreadChange(spread: CbxPageSpread): void { onPageSpreadChange(spread: CbxPageSpread): void {
@@ -1113,12 +1134,14 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.updateCurrentImageUrls(); this.updateCurrentImageUrls();
this.preloadAdjacentPages(); this.preloadAdjacentPages();
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
} }
onBackgroundColorChange(color: CbxBackgroundColor): void { onBackgroundColorChange(color: CbxBackgroundColor): void {
this.backgroundColor = color; this.backgroundColor = color;
this.quickSettingsService.setBackgroundColor(color); this.quickSettingsService.setBackgroundColor(color);
this.updateViewerSetting(); this.updateViewerSetting();
this.cdr.markForCheck();
} }
private initializeInfiniteScroll(): void { private initializeInfiniteScroll(): void {
@@ -1350,6 +1373,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.longStripIntersectionObserver) { if (this.longStripIntersectionObserver) {
this.longStripIntersectionObserver.observe(img); this.longStripIntersectionObserver.observe(img);
} }
this.cdr.markForCheck();
} }
/** /**
@@ -1384,6 +1408,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.longStripAllImagesLoaded = true; this.longStripAllImagesLoaded = true;
this.longStripDoScroll(this.currentPage, 'instant', layoutGen); this.longStripDoScroll(this.currentPage, 'instant', layoutGen);
this.longStripInitFinished = true; this.longStripInitFinished = true;
this.cdr.markForCheck();
}; };
if (img.complete) { if (img.complete) {
@@ -1446,6 +1471,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
private longStripHandleIntersection(entries: IntersectionObserverEntry[]): void { private longStripHandleIntersection(entries: IntersectionObserverEntry[]): void {
if (!this.longStripAllImagesLoaded || this.longStripIsScrolling) return; if (!this.longStripAllImagesLoaded || this.longStripIsScrolling) return;
let changed = false;
for (const entry of entries) { for (const entry of entries) {
if (entry.isIntersecting) { if (entry.isIntersecting) {
const pageAttr = entry.target.getAttribute('data-page'); const pageAttr = entry.target.getAttribute('data-page');
@@ -1453,9 +1479,13 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
const page = parseInt(pageAttr, 10); const page = parseInt(pageAttr, 10);
// Prefetch more images when a page enters the viewport // Prefetch more images when a page enters the viewport
this.longStripPrefetchAround(page); this.longStripPrefetchAround(page);
changed = true;
} }
} }
} }
if (changed) {
this.cdr.markForCheck();
}
} }
private longStripAttachScrollListeners(): void { private longStripAttachScrollListeners(): void {
@@ -1466,6 +1496,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.longStripScrollDebounceTimer) clearTimeout(this.longStripScrollDebounceTimer); if (this.longStripScrollDebounceTimer) clearTimeout(this.longStripScrollDebounceTimer);
this.longStripScrollDebounceTimer = setTimeout(() => { this.longStripScrollDebounceTimer = setTimeout(() => {
this.longStripOnScroll(container); this.longStripOnScroll(container);
this.cdr.markForCheck();
}, 20); }, 20);
}; };
@@ -1474,6 +1505,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
if (this.longStripScrollEndDebounceTimer) clearTimeout(this.longStripScrollEndDebounceTimer); if (this.longStripScrollEndDebounceTimer) clearTimeout(this.longStripScrollEndDebounceTimer);
this.longStripScrollEndDebounceTimer = setTimeout(() => { this.longStripScrollEndDebounceTimer = setTimeout(() => {
this.longStripOnScrollEnd(container); this.longStripOnScrollEnd(container);
this.cdr.markForCheck();
}, supportsScrollEnd ? 20 : 100); }, supportsScrollEnd ? 20 : 100);
}; };
@@ -1638,6 +1670,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.updateSessionProgress(); this.updateSessionProgress();
this.updateFooterPage(); this.updateFooterPage();
} }
this.cdr.markForCheck();
} }
firstPage(): void { firstPage(): void {
@@ -1970,6 +2003,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.footerService.setSeriesBooks(this.previousBookInSeries, this.nextBookInSeries); this.footerService.setSeriesBooks(this.previousBookInSeries, this.nextBookInSeries);
this.footerService.setHasSeries(true); this.footerService.setHasSeries(true);
this.cdr.markForCheck();
}, },
error: (err) => { error: (err) => {
console.error('[SeriesNav] Failed to load series information:', err); console.error('[SeriesNav] Failed to load series information:', err);