Introduce multi-format book support, including audiobooks (#2486)

* fix: support reading alternative book formats using bookType query param

* feat: add streaming reader support for alternative EPUB formats

* refactor: extract tabs section into MetadataTabsComponent

* feat: implement per-file reading progress tracking

* feat: add configurable format priority with cascading fallback

* refactor: redesign library creator with single-page layout

* refactor: unify reading progress into ReadingProgressService

* refactor: improve delete options with clearer file format and book deletion

* refactor: improve book format matching with normalization and fuzzy fallback

* feat: add folder-based audiobook support with ZIP downloads and preparing state

* fix: display unique format types in metadata viewer

* refactor: auto-attach files to single book in folder during rescan

* feat: implement folder-centric book file grouping with fuzzy matching

* refactor: consolidate book grouping with organization mode support

* fix: use folder hash for folder-based audiobooks in auto-attach

* fix: delete only BookFileEntity on file removal, not entire book

* fix: set folderBased flag and correct file size for auto-attached audiobook folders

* fix: use count query to avoid lazy initialization in file delete handler

* fix: preserve book metadata when file is moved by detecting hash match

* fix: skip books with no files in restoration to avoid NPE

* fix: round all progress percentages to one decimal place before sending to UI

* style: improve library creator dialog spacing and layout

* fix: migrate FOLDER_AS_BOOK to BOOK_PER_FOLDER for backwards compatibility

* fix: FileMoveService now handles multi-file BookEntity properly

* style: redesign metadata-picker and file-mover UI components

* style: redesign file-naming-pattern UI and improve theme contrast

* style: relax spacing in library-creator component

* style: tighten directory-picker layout for consistency

* fix: PathPatternResolver now respects folderBased flag for audiobooks

* style: move checkmark column to left side and add pending status in file-mover

* refactor: consolidate BookFileType into BookType and add audiobook styling

* feat: show 'Continue Reading' button for in-progress books

* fix: preserve dots in folder names during grouping and prevent duplicate attachments

* style: reduce gap between download-all button and primary file section

* style: shorten 'Continue Reading' button to 'Read' on mobile

* feat: add DISK_TYPE config to disable file moves on network storage

* style: standardize settings pages with shared styles and consistent spacing

* style: revamp settings pages with modern card-based layouts

* style: revamp OPDS, auth, and task management settings layouts

* fix: update FileMoveService tests to include AppProperties parameter

* fix: derive BookFileType from extension when uploading additional book files

* feat: show format type and size in download button with dropdown for alternatives

* feat: add audiobook streaming player with HTTP Range support

* feat: add M4B chapter extraction and chapter navigation

* feat: add audiobook bookmarks and sleep timer

* refactor: split AudiobookReaderService into focused services

* feat: add Media Session API for background audio playback

* feat: display file extensions in format tags with distinct colors and add audiobook upload support

* feat: require bookFileId for viewer settings API

* fix: show split button for audiobooks with readable alternatives

* feat: improve reading sessions table with book type badges and better formatting

* feat: add audiobook play button in files tab

* feat: use file extension for format display and meaningful tab values

* feat: add extension field to BookFile DTO

* feat: use extension field for book card format pill

* fix: use mixed orientation for format priority drag-drop to support multi-line layout

* feat: add attach book files feature to consolidate single-file books

* fix: increase drag handle size for format priority chips

* fix: add missing BookFileRepository mock to BookServiceDeleteTests

* feat: add delete buttons to files tab and move shelf to other items menu

* feat: add physical books support for cataloging books without digital files

* refactor: redesign icon-picker component with improved styling

* refactor: redesign metadata-picker component with improved layout and alignment

* refactor: move Add Physical Book to top of library menu

* refactor: use p-autoComplete for authors/categories in add-physical-book dialog

* feat: add square cover search and display support for audiobooks

* fix: navigate to first page when opening unread ebooks

* fix: exclude API requests from service worker interception

* feat: support fileless books with automatic file attachment

* fix: bypass service worker for audiobook streaming requests

* refactor: remove alphabetical filter sorting, default to count, limit filters to 100

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-27 10:12:50 -07:00
committed by GitHub
co-authored by acx10
parent c23e38b5a5
commit 3f334202b6
340 changed files with 23225 additions and 20727 deletions
@@ -0,0 +1,399 @@
@if (isLoading) {
<div class="loading-container">
<p-progressSpinner strokeWidth="3" />
<span class="loading-text">Loading audiobook...</span>
</div>
} @else {
<div class="audiobook-reader">
<!-- Hidden audio element -->
<audio
#audioElement
[src]="audioSrc"
(loadedmetadata)="onAudioLoaded()"
(timeupdate)="onTimeUpdate()"
(progress)="onProgress()"
(ended)="onAudioEnded()"
(error)="onAudioError()"
preload="metadata"
></audio>
<!-- Header -->
<header class="reader-header">
<p-button
icon="pi pi-arrow-left"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="closeReader()"
pTooltip="Back"
tooltipPosition="bottom"
/>
<div class="header-info">
<h1 class="book-title">{{ audiobookInfo.title || 'Untitled' }}</h1>
<span class="book-author">{{ audiobookInfo.author || 'Unknown Author' }}</span>
</div>
<div class="header-actions">
<p-button
icon="pi pi-bookmark"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleBookmarkList()"
pTooltip="Bookmarks"
tooltipPosition="bottom"
/>
<p-button
icon="pi pi-list"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleTrackList()"
pTooltip="Chapters/Tracks"
tooltipPosition="bottom"
/>
</div>
</header>
<!-- Main content -->
<main class="reader-main">
<!-- Cover art -->
<div class="cover-container">
<div class="cover-wrapper">
@if (coverUrl) {
<img
[src]="coverUrl"
(error)="onCoverError()"
alt="Cover"
class="cover-image"
/>
} @else {
<div class="cover-placeholder">
<i class="pi pi-headphones"></i>
</div>
}
@if (audioLoading) {
<div class="cover-loading">
<p-progressSpinner strokeWidth="3" />
</div>
}
</div>
</div>
<!-- Track/Chapter info -->
<div class="track-info">
@if (audiobookInfo.folderBased && currentTrack) {
<span class="track-title">{{ currentTrack.title }}</span>
<span class="track-number">Track {{ currentTrackIndex + 1 }} of {{ audiobookInfo.tracks?.length }}</span>
} @else if (getCurrentChapter()) {
<span class="track-title">{{ getCurrentChapter()?.title }}</span>
@if (hasMultipleChapters()) {
<span class="track-number">Chapter {{ getCurrentChapterIndex() + 1 }} of {{ audiobookInfo.chapters?.length }}</span>
}
}
</div>
<!-- Progress bar -->
<div class="progress-container">
<div class="time-display">
<span class="current-time">{{ formatTime(currentTime) }}</span>
<span class="duration">{{ formatTime(duration) }}</span>
</div>
<div class="progress-bar-wrapper">
<div class="buffered-bar" [style.width.%]="getBufferedPercent()"></div>
<p-slider
[(ngModel)]="currentTime"
[min]="0"
[max]="duration || 100"
[step]="1"
(onChange)="seek($event)"
styleClass="progress-slider"
/>
</div>
</div>
<!-- Playback controls -->
<div class="playback-controls">
@if (audiobookInfo.folderBased) {
<p-button
icon="pi pi-step-backward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="previousTrack()"
[disabled]="currentTrackIndex === 0"
pTooltip="Previous Track"
tooltipPosition="top"
size="large"
/>
} @else if (hasMultipleChapters()) {
<p-button
icon="pi pi-step-backward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="previousChapter()"
[disabled]="!canGoPreviousChapter()"
pTooltip="Previous Chapter"
tooltipPosition="top"
size="large"
/>
}
<p-button
icon="pi pi-replay"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="seekRelative(-30)"
pTooltip="-30s"
tooltipPosition="top"
size="large"
/>
<p-button
[icon]="isPlaying ? 'pi pi-pause' : 'pi pi-play'"
[rounded]="true"
severity="contrast"
(onClick)="togglePlay()"
[disabled]="audioLoading"
styleClass="play-button"
size="large"
/>
<p-button
icon="pi pi-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="seekRelative(30)"
pTooltip="+30s"
tooltipPosition="top"
size="large"
/>
@if (audiobookInfo.folderBased) {
<p-button
icon="pi pi-step-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="nextTrack()"
[disabled]="!audiobookInfo.tracks || currentTrackIndex >= audiobookInfo.tracks.length - 1"
pTooltip="Next Track"
tooltipPosition="top"
size="large"
/>
} @else if (hasMultipleChapters()) {
<p-button
icon="pi pi-step-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="nextChapter()"
[disabled]="!canGoNextChapter()"
pTooltip="Next Chapter"
tooltipPosition="top"
size="large"
/>
}
</div>
<!-- Secondary controls -->
<div class="secondary-controls">
<!-- Volume -->
<div class="volume-control">
<p-button
[icon]="getVolumeIcon()"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleMute()"
size="small"
/>
<p-slider
[(ngModel)]="volume"
[min]="0"
[max]="1"
[step]="0.01"
(onChange)="setVolume($event)"
styleClass="volume-slider"
/>
</div>
<!-- Playback speed -->
<div class="speed-control">
<p-selectButton
[options]="playbackRates"
[ngModel]="playbackRate"
(ngModelChange)="setPlaybackRate($event)"
optionLabel="label"
optionValue="value"
size="small"
/>
</div>
</div>
<!-- Extra controls row -->
<div class="extra-controls">
<!-- Add bookmark button -->
<p-button
icon="pi pi-bookmark-fill"
label="Add Bookmark"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="addBookmark()"
size="small"
/>
<!-- Sleep timer -->
<p-button
#sleepTimerBtn
icon="pi pi-moon"
[label]="sleepTimerActive ? formatSleepTimerRemaining() : 'Sleep Timer'"
[rounded]="true"
[text]="true"
severity="secondary"
[styleClass]="sleepTimerActive ? 'sleep-timer-active' : ''"
(onClick)="sleepTimerMenu.toggle($event)"
size="small"
/>
<p-menu
#sleepTimerMenu
[model]="sleepTimerOptions"
[popup]="true"
appendTo="body"
/>
</div>
<!-- Audio details -->
<div class="audio-details">
@if (audiobookInfo.narrator) {
<span class="detail-item">
<i class="pi pi-user"></i>
Narrated by {{ audiobookInfo.narrator }}
</span>
}
@if (audiobookInfo.bitrate) {
<span class="detail-item">
<i class="pi pi-sliders-h"></i>
{{ audiobookInfo.bitrate }} kbps
</span>
}
@if (audiobookInfo.durationMs) {
<span class="detail-item">
<i class="pi pi-clock"></i>
{{ formatDuration(audiobookInfo.durationMs) }} total
</span>
}
</div>
</main>
<!-- Track/Chapter list sidebar -->
@if (showTrackList) {
<aside class="track-list-sidebar">
<div class="sidebar-header">
<h2>{{ audiobookInfo.folderBased ? 'Tracks' : 'Chapters' }}</h2>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleTrackList()"
/>
</div>
<div class="sidebar-content">
@if (audiobookInfo.folderBased && audiobookInfo.tracks) {
<ul class="track-list">
@for (track of audiobookInfo.tracks; track track.index) {
<li
class="track-item"
[class.active]="track.index === currentTrackIndex"
(click)="selectTrack(track)"
>
<span class="track-index">{{ track.index + 1 }}</span>
<div class="track-details">
<span class="track-name">{{ track.title }}</span>
<span class="track-duration">{{ formatDuration(track.durationMs) }}</span>
</div>
@if (track.index === currentTrackIndex && isPlaying) {
<i class="pi pi-volume-up playing-indicator"></i>
}
</li>
}
</ul>
} @else if (audiobookInfo.chapters) {
<ul class="track-list">
@for (chapter of audiobookInfo.chapters; track chapter.index) {
<li
class="track-item"
[class.active]="getCurrentChapter()?.index === chapter.index"
(click)="selectChapter(chapter)"
>
<span class="track-index">{{ chapter.index + 1 }}</span>
<div class="track-details">
<span class="track-name">{{ chapter.title }}</span>
<span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
</div>
@if (getCurrentChapter()?.index === chapter.index && isPlaying) {
<i class="pi pi-volume-up playing-indicator"></i>
}
</li>
}
</ul>
}
</div>
</aside>
}
<!-- Bookmark list sidebar -->
@if (showBookmarkList) {
<aside class="track-list-sidebar bookmark-sidebar">
<div class="sidebar-header">
<h2>Bookmarks</h2>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleBookmarkList()"
/>
</div>
<div class="sidebar-content">
@if (bookmarks.length === 0) {
<div class="empty-bookmarks">
<i class="pi pi-bookmark"></i>
<p>No bookmarks yet</p>
<span>Add a bookmark to save your place</span>
</div>
} @else {
<ul class="track-list">
@for (bookmark of bookmarks; track bookmark.id) {
<li
class="track-item bookmark-item"
(click)="goToBookmark(bookmark)"
>
<i class="pi pi-bookmark-fill bookmark-icon"></i>
<div class="track-details">
<span class="track-name">{{ bookmark.title }}</span>
<span class="track-duration">{{ formatBookmarkPosition(bookmark) }}</span>
</div>
<p-button
icon="pi pi-trash"
[rounded]="true"
[text]="true"
severity="danger"
size="small"
(onClick)="deleteBookmark($event, bookmark.id)"
pTooltip="Delete"
tooltipPosition="left"
/>
</li>
}
</ul>
}
</div>
</aside>
}
</div>
}
@@ -0,0 +1,805 @@
@use 'sass:color';
// Variables - More vibrant color palette
$bg-primary: #0f0f1a;
$bg-secondary: #1a1a2e;
$bg-tertiary: #252542;
$bg-darker: #0a0a12;
$text-primary: #ffffff;
$text-secondary: rgba(255, 255, 255, 0.8);
$text-tertiary: rgba(255, 255, 255, 0.5);
$accent-secondary: #ec4899;
$accent-tertiary: #06b6d4;
$border-color: rgba(255, 255, 255, 0.1);
// CSS variable for primary color from theme
:host {
--accent-color: var(--primary-color, #8b5cf6);
--accent-hover: var(--primary-hover-color, #a78bfa);
}
// Gradient mixins
@mixin gradient-bg {
background: linear-gradient(135deg, $bg-secondary 0%, $bg-primary 50%, $bg-darker 100%);
}
@mixin accent-gradient {
background: linear-gradient(135deg, var(--accent-color) 0%, $accent-secondary 100%);
}
@mixin glow-effect($color, $intensity: 0.4) {
box-shadow: 0 0 40px rgba($color, $intensity),
0 0 80px rgba($color, $intensity * 0.5);
}
// Loading container
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
@include gradient-bg;
gap: 1rem;
.loading-text {
color: $text-secondary;
font-size: 0.9rem;
}
::ng-deep .p-progress-spinner-circle {
stroke: var(--accent-color) !important;
}
}
// Main container
.audiobook-reader {
display: flex;
flex-direction: column;
height: 100vh;
@include gradient-bg;
color: $text-primary;
overflow: hidden;
position: relative;
// Subtle animated gradient overlay
&::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: radial-gradient(ellipse at 20% 0%, color-mix(in srgb, var(--accent-color) 15%, transparent) 0%, transparent 50%),
radial-gradient(ellipse at 80% 100%, rgba($accent-secondary, 0.1) 0%, transparent 50%);
pointer-events: none;
z-index: 0;
}
}
// Header
.reader-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 1.5rem;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(20px);
border-bottom: 1px solid $border-color;
z-index: 10;
position: relative;
.header-info {
flex: 1;
text-align: center;
padding: 0 1rem;
overflow: hidden;
.book-title {
font-size: 1.1rem;
font-weight: 600;
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background: linear-gradient(90deg, $text-primary, var(--accent-color));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.book-author {
font-size: 0.85rem;
color: $text-secondary;
}
}
.header-actions {
display: flex;
gap: 0.25rem;
}
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
}
}
}
}
// Main content
.reader-main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem 1.5rem;
overflow-y: auto;
gap: 1.5rem;
position: relative;
z-index: 1;
}
// Cover art
.cover-container {
flex-shrink: 0;
width: 100%;
max-width: 480px;
aspect-ratio: 1;
margin-top: 1.5rem;
.cover-wrapper {
position: relative;
width: 100%;
height: 100%;
border-radius: 16px;
overflow: hidden;
box-shadow:
0 25px 60px -12px rgba(0, 0, 0, 0.6),
0 0 0 1px rgba(255, 255, 255, 0.1),
0 0 60px color-mix(in srgb, var(--accent-color) 20%, transparent),
0 0 100px rgba($accent-secondary, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
&:hover {
transform: scale(1.02);
box-shadow:
0 30px 70px -12px rgba(0, 0, 0, 0.7),
0 0 0 1px rgba(255, 255, 255, 0.15),
0 0 80px color-mix(in srgb, var(--accent-color) 30%, transparent),
0 0 120px rgba($accent-secondary, 0.15);
}
.cover-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.cover-loading {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(4px);
}
.cover-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
@include accent-gradient;
opacity: 0.8;
i {
font-size: 5rem;
color: rgba(255, 255, 255, 0.9);
text-shadow: 0 0 30px rgba(255, 255, 255, 0.5);
}
}
}
}
// Track info
.track-info {
text-align: center;
min-height: 3rem;
.track-title {
display: block;
font-size: 1.1rem;
font-weight: 600;
color: $text-primary;
margin-bottom: 0.25rem;
}
.track-number {
font-size: 0.85rem;
color: var(--accent-color);
font-weight: 500;
}
}
// Progress bar
.progress-container {
width: 100%;
max-width: 500px;
.time-display {
display: flex;
justify-content: space-between;
margin-bottom: 0.75rem;
font-size: 0.85rem;
color: $text-secondary;
font-variant-numeric: tabular-nums;
font-weight: 500;
}
.progress-bar-wrapper {
position: relative;
height: 8px;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
overflow: visible;
.buffered-bar {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: rgba(255, 255, 255, 0.15);
border-radius: 4px;
transition: width 0.3s ease;
}
::ng-deep .progress-slider {
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
.p-slider {
background: transparent;
height: 8px;
.p-slider-range {
@include accent-gradient;
border-radius: 4px;
box-shadow: 0 0 10px color-mix(in srgb, var(--accent-color) 50%, transparent);
}
.p-slider-handle {
width: 18px;
height: 18px;
background: $text-primary;
border: 3px solid var(--accent-color);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4),
0 0 15px color-mix(in srgb, var(--accent-color) 40%, transparent);
transition: transform 0.15s ease, box-shadow 0.15s ease;
&:hover {
transform: scale(1.2);
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.5),
0 0 25px color-mix(in srgb, var(--accent-color) 60%, transparent);
}
}
}
}
}
}
// Playback controls
.playback-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
::ng-deep .play-button {
.p-button {
width: 72px;
height: 72px;
font-size: 1.75rem;
@include accent-gradient;
border: none;
box-shadow: 0 8px 30px color-mix(in srgb, var(--accent-color) 40%, transparent),
0 0 50px color-mix(in srgb, var(--accent-color) 20%, transparent);
transition: transform 0.2s ease, box-shadow 0.2s ease;
&:hover {
transform: scale(1.05);
box-shadow: 0 10px 40px color-mix(in srgb, var(--accent-color) 50%, transparent),
0 0 70px color-mix(in srgb, var(--accent-color) 30%, transparent);
}
&:active {
transform: scale(0.98);
}
.p-button-icon {
font-size: 1.75rem;
}
}
}
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
transition: all 0.2s ease;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
transform: scale(1.1);
}
&:disabled {
color: $text-tertiary;
opacity: 0.4;
transform: none;
}
}
&.p-button-lg {
width: 48px;
height: 48px;
}
}
}
// Secondary controls
.secondary-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 2rem;
width: 100%;
max-width: 500px;
padding: 1rem 0;
}
.volume-control {
display: flex;
align-items: center;
gap: 0.75rem;
::ng-deep .p-button.p-button-text {
color: $text-secondary;
&:hover {
color: var(--accent-color);
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
}
}
::ng-deep .volume-slider {
width: 100px;
.p-slider {
background: rgba(255, 255, 255, 0.15);
height: 5px;
border-radius: 3px;
.p-slider-range {
background: $accent-tertiary;
border-radius: 3px;
}
.p-slider-handle {
width: 14px;
height: 14px;
background: $text-primary;
border: 2px solid $accent-tertiary;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
}
}
}
.speed-control {
::ng-deep .p-selectbutton {
.p-button {
padding: 0.5rem 0.75rem;
font-size: 0.8rem;
font-weight: 600;
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.1);
color: $text-secondary;
transition: all 0.2s ease;
&:hover {
background: rgba(255, 255, 255, 0.12);
color: $text-primary;
border-color: rgba(255, 255, 255, 0.2);
}
&.p-highlight {
@include accent-gradient;
color: $text-primary;
border-color: transparent;
box-shadow: 0 4px 15px color-mix(in srgb, var(--accent-color) 30%, transparent);
}
}
}
}
// Audio details
.audio-details {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 1.25rem;
padding: 1rem 1rem 0;
color: $text-tertiary;
font-size: 0.8rem;
background: rgba(255, 255, 255, 0.03);
border-radius: 12px;
margin-top: 0.5rem;
.detail-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
white-space: nowrap;
i {
font-size: 0.9rem;
color: $accent-tertiary;
}
}
}
// Extra controls (bookmark, sleep timer)
.extra-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
padding-top: 0.5rem;
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
font-size: 0.85rem;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
}
.p-button-icon {
font-size: 1rem;
}
}
&.sleep-timer-active {
color: #fbbf24 !important;
&:hover {
background: rgba(251, 191, 36, 0.15) !important;
}
}
}
}
// Empty bookmarks
.empty-bookmarks {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem 1.5rem;
text-align: center;
color: $text-tertiary;
i {
font-size: 3rem;
margin-bottom: 1rem;
opacity: 0.5;
}
p {
margin: 0 0 0.5rem;
font-size: 1rem;
font-weight: 500;
color: $text-secondary;
}
span {
font-size: 0.85rem;
}
}
// Bookmark item
.bookmark-item {
.bookmark-icon {
color: var(--accent-color);
font-size: 1.1rem;
flex-shrink: 0;
}
::ng-deep .p-button {
opacity: 0;
transition: opacity 0.2s ease;
}
&:hover {
::ng-deep .p-button {
opacity: 1;
}
}
}
// Track list sidebar
.track-list-sidebar {
position: fixed;
top: 0;
right: 0;
width: 100%;
max-width: 400px;
height: 100vh;
background: linear-gradient(180deg, $bg-tertiary 0%, $bg-secondary 100%);
border-left: 1px solid color-mix(in srgb, var(--accent-color) 20%, transparent);
z-index: 100;
display: flex;
flex-direction: column;
animation: slideIn 0.25s ease-out;
box-shadow: -10px 0 40px rgba(0, 0, 0, 0.5);
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0.5;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.25rem 1.5rem;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
h2 {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
background: linear-gradient(90deg, $text-primary, var(--accent-color));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
::ng-deep .p-button.p-button-text {
color: $text-secondary;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
}
}
}
.sidebar-content {
flex: 1;
overflow-y: auto;
padding: 0.5rem 0;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--accent-color) 30%, transparent);
border-radius: 3px;
&:hover {
background: color-mix(in srgb, var(--accent-color) 50%, transparent);
}
}
}
}
.track-list {
list-style: none;
margin: 0;
padding: 0;
.track-item {
display: flex;
align-items: center;
padding: 1rem 1.5rem;
cursor: pointer;
transition: all 0.2s ease;
gap: 1rem;
border-left: 3px solid transparent;
&:hover {
background: color-mix(in srgb, var(--accent-color) 10%, transparent);
border-left-color: color-mix(in srgb, var(--accent-color) 50%, transparent);
}
&.active {
background: linear-gradient(90deg, color-mix(in srgb, var(--accent-color) 20%, transparent) 0%, transparent 100%);
border-left-color: var(--accent-color);
.track-index {
color: var(--accent-color);
font-weight: 700;
}
.track-name {
color: var(--accent-color);
}
}
.track-index {
width: 2rem;
text-align: center;
font-size: 0.9rem;
color: $text-tertiary;
flex-shrink: 0;
font-weight: 600;
}
.track-details {
flex: 1;
min-width: 0;
.track-name {
display: block;
font-size: 0.95rem;
color: $text-primary;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-weight: 500;
}
.track-duration {
font-size: 0.8rem;
color: $text-tertiary;
margin-top: 0.2rem;
}
}
.playing-indicator {
color: var(--accent-color);
animation: pulse 1.5s ease-in-out infinite;
font-size: 1.1rem;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.6;
transform: scale(0.95);
}
}
}
}
// Responsive adjustments
@media (max-width: 768px) {
.reader-main {
padding: 1rem;
gap: 1rem;
}
.cover-container {
max-width: 360px;
margin-top: 1rem;
}
.secondary-controls {
flex-direction: column;
gap: 1rem;
}
.volume-control {
::ng-deep .volume-slider {
width: 150px;
}
}
.track-list-sidebar {
max-width: 75%;
}
.audio-details {
gap: 0.75rem;
padding: 0.75rem;
.detail-item {
padding: 0.4rem 0.6rem;
font-size: 0.75rem;
i {
font-size: 0.8rem;
}
}
}
}
@media (max-width: 480px) {
.cover-container {
max-width: 300px;
margin-top: 0.5rem;
}
.playback-controls {
gap: 0.5rem;
::ng-deep .play-button {
.p-button {
width: 64px;
height: 64px;
}
}
::ng-deep .p-button.p-button-lg {
width: 40px;
height: 40px;
}
}
.audio-details {
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
gap: 0.5rem;
.detail-item {
flex: 0 1 auto;
}
}
}
// Landscape mode optimization
@media (max-height: 600px) and (orientation: landscape) {
.reader-main {
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
gap: 1rem;
}
.cover-container {
max-width: 180px;
}
.track-info,
.progress-container,
.playback-controls,
.secondary-controls {
width: auto;
}
.audio-details {
flex-direction: row;
}
}
@@ -0,0 +1,966 @@
import { Component, ElementRef, inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { CommonModule, Location } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { forkJoin, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Button } from 'primeng/button';
import { Slider, SliderChangeEvent } from 'primeng/slider';
import { ProgressSpinner } from 'primeng/progressspinner';
import { Tooltip } from 'primeng/tooltip';
import { MessageService } from 'primeng/api';
import { SelectButton } from 'primeng/selectbutton';
import { Menu } from 'primeng/menu';
import { MenuItem } from 'primeng/api';
import { AudiobookService } from './audiobook.service';
import { AudiobookInfo, AudiobookChapter, AudiobookTrack, AudiobookProgress } from './audiobook.model';
import { BookService } from '../../book/service/book.service';
import { BookMarkService, BookMark, CreateBookMarkRequest } from '../../../shared/service/book-mark.service';
import { AudiobookSessionService } from '../../../shared/service/audiobook-session.service';
import { PageTitleService } from '../../../shared/service/page-title.service';
import { AuthService } from '../../../shared/service/auth.service';
import { API_CONFIG } from '../../../core/config/api-config';
@Component({
selector: 'app-audiobook-reader',
standalone: true,
imports: [
CommonModule,
FormsModule,
Button,
Slider,
ProgressSpinner,
Tooltip,
SelectButton,
Menu
],
templateUrl: './audiobook-reader.component.html',
styleUrls: ['./audiobook-reader.component.scss']
})
export class AudiobookReaderComponent implements OnInit, OnDestroy {
@ViewChild('audioElement') audioElement!: ElementRef<HTMLAudioElement>;
private destroy$ = new Subject<void>();
private audiobookService = inject(AudiobookService);
private bookService = inject(BookService);
private bookMarkService = inject(BookMarkService);
private authService = inject(AuthService);
private route = inject(ActivatedRoute);
private router = inject(Router);
private location = inject(Location);
private messageService = inject(MessageService);
private audiobookSessionService = inject(AudiobookSessionService);
private pageTitle = inject(PageTitleService);
// Loading state
isLoading = true;
audioLoading = true;
// Book data
bookId!: number;
audiobookInfo!: AudiobookInfo;
coverUrl?: string;
bookCoverUrl?: string;
// Audio state
isPlaying = false;
currentTime = 0;
duration = 0;
volume = 1;
previousVolume = 1;
isMuted = false;
playbackRate = 1;
buffered = 0;
// Saved position to restore after audio loads
private savedPosition = 0;
// Track state (for folder-based audiobooks)
currentTrackIndex = 0;
audioSrc = '';
// UI state
showTrackList = false;
showBookmarkList = false;
// Sleep timer
sleepTimerActive = false;
sleepTimerRemaining = 0; // seconds remaining
sleepTimerEndOfChapter = false;
private sleepTimerInterval?: ReturnType<typeof setInterval>;
private originalVolume = 1;
sleepTimerOptions: MenuItem[] = [
{ label: '15 minutes', command: () => this.setSleepTimer(15) },
{ label: '30 minutes', command: () => this.setSleepTimer(30) },
{ label: '45 minutes', command: () => this.setSleepTimer(45) },
{ label: '60 minutes', command: () => this.setSleepTimer(60) },
{ label: 'End of chapter', command: () => this.setSleepTimerEndOfChapter() },
{ separator: true },
{ label: 'Cancel timer', command: () => this.cancelSleepTimer(), visible: false }
];
// Bookmarks
bookmarks: BookMark[] = [];
// Playback speed options
playbackRates = [
{ label: '0.5x', value: 0.5 },
{ label: '0.75x', value: 0.75 },
{ label: '1x', value: 1 },
{ label: '1.25x', value: 1.25 },
{ label: '1.5x', value: 1.5 },
{ label: '2x', value: 2 }
];
// Progress save interval
private progressSaveInterval?: ReturnType<typeof setInterval>;
ngOnInit(): void {
this.route.paramMap.pipe(takeUntil(this.destroy$)).subscribe(params => {
this.bookId = +params.get('bookId')!;
this.loadAudiobook();
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
if (this.progressSaveInterval) {
clearInterval(this.progressSaveInterval);
}
if (this.sleepTimerInterval) {
clearInterval(this.sleepTimerInterval);
}
this.saveProgress();
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000));
}
}
private loadAudiobook(): void {
// Reset all state when loading a new audiobook
this.resetState();
this.isLoading = true;
const audiobookInfo$ = this.audiobookService.getAudiobookInfo(this.bookId);
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
forkJoin([audiobookInfo$, book$]).subscribe({
next: ([info, book]) => {
this.audiobookInfo = info;
this.pageTitle.setBookPageTitle(book);
// Set cover URL with auth token
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
this.bookCoverUrl = `${API_CONFIG.BASE_URL}/api/v1/media/cover/${this.bookId}?token=${encodeURIComponent(token || '')}`;
this.coverUrl = this.audiobookService.getEmbeddedCoverUrl(this.bookId);
// Restore progress and load audio
if (book.audiobookProgress) {
// Store saved position - will be applied when audio loads
this.savedPosition = book.audiobookProgress.positionMs
? book.audiobookProgress.positionMs / 1000
: 0;
}
if (info.folderBased && info.tracks && info.tracks.length > 0) {
// Folder-based audiobook
const trackIndex = book.audiobookProgress?.trackIndex ?? 0;
this.currentTrackIndex = trackIndex;
this.loadTrack(trackIndex);
} else {
// Single-file audiobook
this.audioSrc = this.audiobookService.getStreamUrl(this.bookId);
}
this.isLoading = false;
// Load bookmarks
this.loadBookmarks();
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to load audiobook'
});
this.isLoading = false;
}
});
}
private loadTrack(index: number): void {
if (!this.audiobookInfo.tracks || index < 0 || index >= this.audiobookInfo.tracks.length) {
return;
}
this.currentTrackIndex = index;
this.audioSrc = this.audiobookService.getTrackStreamUrl(this.bookId, index);
this.audioLoading = true;
// Reset buffered since it's a new track
this.buffered = 0;
}
private resetState(): void {
// Stop any existing intervals
this.stopProgressSaveInterval();
// Reset audio state
this.isPlaying = false;
this.currentTime = 0;
this.duration = 0;
this.buffered = 0;
this.savedPosition = 0;
this.currentTrackIndex = 0;
this.audioSrc = '';
this.audioLoading = true;
// Reset UI state
this.showTrackList = false;
this.coverUrl = undefined;
this.bookCoverUrl = undefined;
}
// Audio event handlers
onAudioLoaded(): void {
this.audioLoading = false;
const audio = this.audioElement?.nativeElement;
if (audio) {
this.duration = audio.duration;
audio.volume = this.volume;
audio.playbackRate = this.playbackRate;
// Apply saved position now that we know the duration
if (this.savedPosition > 0 && this.savedPosition < this.duration) {
audio.currentTime = this.savedPosition;
this.currentTime = this.savedPosition;
}
// Setup Media Session for background playback
this.setupMediaSession();
// Note: Session will be started when user presses play, not on load
}
}
onTimeUpdate(): void {
const audio = this.audioElement?.nativeElement;
if (audio) {
const previousChapterIndex = this.getCurrentChapterIndex();
this.currentTime = audio.currentTime;
// Update audiobook session position
this.audiobookSessionService.updatePosition(
Math.round(this.currentTime * 1000),
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
);
// Update Media Session position state (throttled to every 5 seconds)
if (Math.floor(this.currentTime) % 5 === 0) {
this.updateMediaSessionPositionState();
}
// Update metadata if chapter changed (for single-file audiobooks)
if (!this.audiobookInfo.folderBased && this.getCurrentChapterIndex() !== previousChapterIndex) {
this.updateMediaSessionMetadata();
}
// Check sleep timer end of chapter
this.checkSleepTimerEndOfChapter();
}
}
onProgress(): void {
const audio = this.audioElement?.nativeElement;
if (audio && audio.buffered.length > 0) {
this.buffered = audio.buffered.end(audio.buffered.length - 1);
}
}
onAudioEnded(): void {
// For folder-based audiobooks, play next track
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
if (this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) {
this.nextTrack();
} else {
this.isPlaying = false;
this.stopProgressSaveInterval();
this.saveProgress();
this.updateMediaSessionPlaybackState();
// Pause session when audiobook ends
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
}
} else {
this.isPlaying = false;
this.stopProgressSaveInterval();
this.saveProgress();
this.updateMediaSessionPlaybackState();
// Pause session when audiobook ends
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
}
}
onAudioError(): void {
this.audioLoading = false;
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to load audio'
});
}
// Media Session API for background playback
private setupMediaSession(): void {
if (!('mediaSession' in navigator)) return;
this.updateMediaSessionMetadata();
navigator.mediaSession.setActionHandler('play', () => {
if (!this.isPlaying) this.togglePlay();
});
navigator.mediaSession.setActionHandler('pause', () => {
if (this.isPlaying) this.togglePlay();
});
navigator.mediaSession.setActionHandler('seekbackward', () => this.seekRelative(-30));
navigator.mediaSession.setActionHandler('seekforward', () => this.seekRelative(30));
navigator.mediaSession.setActionHandler('previoustrack', () => {
this.audiobookInfo.folderBased ? this.previousTrack() : this.previousChapter();
});
navigator.mediaSession.setActionHandler('nexttrack', () => {
this.audiobookInfo.folderBased ? this.nextTrack() : this.nextChapter();
});
navigator.mediaSession.setActionHandler('seekto', (details) => {
if (details.seekTime !== undefined) {
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.currentTime = details.seekTime;
this.currentTime = details.seekTime;
}
}
});
}
private updateMediaSessionMetadata(): void {
if (!('mediaSession' in navigator)) return;
const title = this.audiobookInfo.folderBased
? this.currentTrack?.title
: this.getCurrentChapter()?.title || this.audiobookInfo.title;
navigator.mediaSession.metadata = new MediaMetadata({
title: title || 'Untitled',
artist: this.audiobookInfo.author || 'Unknown Author',
album: this.audiobookInfo.title,
artwork: this.coverUrl
? [{ src: this.coverUrl, sizes: '512x512', type: 'image/png' }]
: []
});
}
private updateMediaSessionPlaybackState(): void {
if ('mediaSession' in navigator) {
navigator.mediaSession.playbackState = this.isPlaying ? 'playing' : 'paused';
}
}
private updateMediaSessionPositionState(): void {
if ('mediaSession' in navigator && 'setPositionState' in navigator.mediaSession) {
try {
navigator.mediaSession.setPositionState({
duration: this.duration,
playbackRate: this.playbackRate,
position: this.currentTime
});
} catch {
// Ignore errors from invalid position state
}
}
}
// Playback controls
togglePlay(): void {
const audio = this.audioElement?.nativeElement;
if (!audio) return;
if (this.isPlaying) {
audio.pause();
this.stopProgressSaveInterval();
this.saveProgress();
// Pause the listening session
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
} else {
audio.play();
this.startProgressSaveInterval();
// Start or resume the listening session
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(Math.round(this.currentTime * 1000));
} else {
this.audiobookSessionService.startSession(
this.bookId,
Math.round(this.currentTime * 1000),
this.playbackRate,
this.audiobookInfo?.bookFileId,
this.audiobookInfo?.folderBased ? this.currentTrackIndex : undefined
);
}
}
this.isPlaying = !this.isPlaying;
this.updateMediaSessionPlaybackState();
}
seek(event: SliderChangeEvent): void {
const audio = this.audioElement?.nativeElement;
if (audio && this.duration > 0 && event.value !== undefined) {
audio.currentTime = event.value as number;
this.currentTime = event.value as number;
}
}
seekRelative(seconds: number): void {
const audio = this.audioElement?.nativeElement;
if (audio) {
const newTime = Math.max(0, Math.min(this.duration, audio.currentTime + seconds));
audio.currentTime = newTime;
this.currentTime = newTime;
}
}
// Volume controls
setVolume(event: SliderChangeEvent): void {
const audio = this.audioElement?.nativeElement;
if (event.value !== undefined) {
this.volume = event.value as number;
this.isMuted = this.volume === 0;
if (audio) {
audio.volume = this.volume;
}
}
}
toggleMute(): void {
const audio = this.audioElement?.nativeElement;
if (!audio) return;
if (this.isMuted) {
this.volume = this.previousVolume || 0.5;
audio.volume = this.volume;
this.isMuted = false;
} else {
this.previousVolume = this.volume;
this.volume = 0;
audio.volume = 0;
this.isMuted = true;
}
}
// Playback rate
setPlaybackRate(rate: number): void {
if (rate === undefined || rate === null) return;
const audio = this.audioElement?.nativeElement;
this.playbackRate = rate;
if (audio) {
audio.playbackRate = rate;
}
this.updateMediaSessionPositionState();
// Update session with new playback rate
this.audiobookSessionService.updatePlaybackRate(rate);
}
// Track navigation (folder-based)
previousTrack(): void {
if (this.currentTrackIndex > 0) {
this.loadTrack(this.currentTrackIndex - 1);
this.currentTime = 0;
this.savedPosition = 0; // Reset saved position for new track
if (this.isPlaying) {
setTimeout(() => {
this.audioElement?.nativeElement?.play();
this.updateMediaSessionMetadata();
}, 100);
}
}
}
nextTrack(): void {
if (this.audiobookInfo.tracks && this.currentTrackIndex < this.audiobookInfo.tracks.length - 1) {
this.loadTrack(this.currentTrackIndex + 1);
this.currentTime = 0;
this.savedPosition = 0; // Reset saved position for new track
if (this.isPlaying) {
setTimeout(() => {
this.audioElement?.nativeElement?.play();
this.updateMediaSessionMetadata();
}, 100);
}
}
}
selectTrack(track: AudiobookTrack): void {
this.loadTrack(track.index);
this.currentTime = 0;
this.savedPosition = 0; // Reset saved position for new track
this.showTrackList = false;
setTimeout(() => {
this.audioElement?.nativeElement?.play();
this.isPlaying = true;
this.startProgressSaveInterval();
this.updateMediaSessionMetadata();
this.updateMediaSessionPlaybackState();
// Start or resume listening session
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(0);
} else {
this.audiobookSessionService.startSession(
this.bookId, 0, this.playbackRate,
this.audiobookInfo?.bookFileId, track.index
);
}
}, 100);
}
// Chapter navigation (single-file)
selectChapter(chapter: AudiobookChapter): void {
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.currentTime = chapter.startTimeMs / 1000;
this.currentTime = chapter.startTimeMs / 1000;
this.showTrackList = false;
this.updateMediaSessionMetadata();
if (!this.isPlaying) {
audio.play();
this.isPlaying = true;
this.startProgressSaveInterval();
this.updateMediaSessionPlaybackState();
// Start or resume listening session
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(chapter.startTimeMs);
} else {
this.audiobookSessionService.startSession(
this.bookId, chapter.startTimeMs, this.playbackRate,
this.audiobookInfo?.bookFileId
);
}
}
}
}
getCurrentChapter(): AudiobookChapter | undefined {
if (!this.audiobookInfo?.chapters) return undefined;
const currentMs = this.currentTime * 1000;
return this.audiobookInfo.chapters.find(
ch => currentMs >= ch.startTimeMs && currentMs < ch.endTimeMs
);
}
getCurrentChapterIndex(): number {
const chapter = this.getCurrentChapter();
return chapter?.index ?? 0;
}
hasMultipleChapters(): boolean {
return (this.audiobookInfo?.chapters?.length ?? 0) > 1;
}
canGoPreviousChapter(): boolean {
return this.getCurrentChapterIndex() > 0;
}
canGoNextChapter(): boolean {
const chapters = this.audiobookInfo?.chapters;
if (!chapters) return false;
return this.getCurrentChapterIndex() < 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];
this.selectChapter(prevChapter);
}
}
nextChapter(): void {
const chapters = this.audiobookInfo?.chapters;
if (!chapters) return;
const currentIndex = this.getCurrentChapterIndex();
if (currentIndex < chapters.length - 1) {
const nextChapter = chapters[currentIndex + 1];
this.selectChapter(nextChapter);
}
}
// Progress management - save every 5 seconds while playing
private startProgressSaveInterval(): void {
if (this.progressSaveInterval) return; // Already running
this.progressSaveInterval = setInterval(() => {
if (this.isPlaying) {
this.saveProgress();
}
}, 5000);
}
private stopProgressSaveInterval(): void {
if (this.progressSaveInterval) {
clearInterval(this.progressSaveInterval);
this.progressSaveInterval = undefined;
}
}
private saveProgress(): void {
if (!this.audiobookInfo) return;
const totalDuration = this.getTotalDuration();
const currentPosition = this.getCurrentTotalPosition();
const percentage = totalDuration > 0 ? (currentPosition / totalDuration) * 100 : 0;
// For folder-based: positionMs = track position (for seeking within track)
// For single-file: positionMs = absolute position
const positionMs = this.audiobookInfo.folderBased
? Math.round(this.currentTime * 1000) // Track position
: Math.round(currentPosition * 1000); // Absolute position
const progress: AudiobookProgress = {
positionMs: positionMs,
trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined,
percentage: Math.round(percentage * 10) / 10
};
this.audiobookService.saveProgress(
this.bookId,
progress,
this.audiobookInfo.bookFileId
).subscribe();
}
private getTotalDuration(): number {
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
return this.audiobookInfo.tracks.reduce((sum, t) => sum + t.durationMs, 0) / 1000;
}
return this.duration;
}
private getCurrentTotalPosition(): number {
if (this.audiobookInfo.folderBased && this.audiobookInfo.tracks) {
const currentTrack = this.audiobookInfo.tracks[this.currentTrackIndex];
return (currentTrack?.cumulativeStartMs || 0) / 1000 + this.currentTime;
}
return this.currentTime;
}
// Utility methods
formatTime(seconds: number): string {
if (!seconds || !isFinite(seconds)) return '0:00';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
if (h > 0) {
return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
}
return `${m}:${s.toString().padStart(2, '0')}`;
}
formatDuration(ms: number): string {
return this.formatTime(ms / 1000);
}
getProgressPercent(): number {
return this.duration > 0 ? (this.currentTime / this.duration) * 100 : 0;
}
getBufferedPercent(): number {
return this.duration > 0 ? (this.buffered / this.duration) * 100 : 0;
}
onCoverError(): void {
// Fallback to book cover if embedded cover fails
// Only fallback once to prevent infinite loop
if (this.coverUrl !== this.bookCoverUrl) {
this.coverUrl = this.bookCoverUrl;
} else {
// Both covers failed, use a placeholder
this.coverUrl = undefined;
}
}
toggleTrackList(): void {
this.showTrackList = !this.showTrackList;
}
closeReader(): void {
this.saveProgress();
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.endSession(Math.round(this.currentTime * 1000));
}
this.location.back();
}
getVolumeIcon(): string {
if (this.isMuted || this.volume === 0) return 'pi pi-volume-off';
if (this.volume < 0.5) return 'pi pi-volume-down';
return 'pi pi-volume-up';
}
get currentTrack(): AudiobookTrack | undefined {
return this.audiobookInfo?.tracks?.[this.currentTrackIndex];
}
// ==================== SLEEP TIMER ====================
setSleepTimer(minutes: number): void {
this.cancelSleepTimer();
this.sleepTimerRemaining = minutes * 60;
this.sleepTimerActive = true;
this.sleepTimerEndOfChapter = false;
this.originalVolume = this.volume;
this.updateSleepTimerMenuVisibility();
this.sleepTimerInterval = setInterval(() => {
this.sleepTimerRemaining--;
// Fade out volume in last 30 seconds
if (this.sleepTimerRemaining <= 30 && this.sleepTimerRemaining > 0) {
const fadeRatio = this.sleepTimerRemaining / 30;
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.volume = this.originalVolume * fadeRatio;
}
}
if (this.sleepTimerRemaining <= 0) {
this.triggerSleepTimerStop();
}
}, 1000);
this.messageService.add({
severity: 'info',
summary: 'Sleep Timer',
detail: `Playback will stop in ${minutes} minutes`
});
}
setSleepTimerEndOfChapter(): void {
this.cancelSleepTimer();
this.sleepTimerActive = true;
this.sleepTimerEndOfChapter = true;
this.sleepTimerRemaining = 0;
this.originalVolume = this.volume;
this.updateSleepTimerMenuVisibility();
this.messageService.add({
severity: 'info',
summary: 'Sleep Timer',
detail: 'Playback will stop at end of chapter'
});
}
cancelSleepTimer(): void {
if (this.sleepTimerInterval) {
clearInterval(this.sleepTimerInterval);
this.sleepTimerInterval = undefined;
}
// Restore original volume if we were fading
if (this.sleepTimerActive && this.originalVolume > 0) {
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.volume = this.originalVolume;
this.volume = this.originalVolume;
}
}
this.sleepTimerActive = false;
this.sleepTimerRemaining = 0;
this.sleepTimerEndOfChapter = false;
this.updateSleepTimerMenuVisibility();
}
private triggerSleepTimerStop(): void {
const audio = this.audioElement?.nativeElement;
if (audio) {
audio.pause();
audio.volume = this.originalVolume;
this.volume = this.originalVolume;
}
this.isPlaying = false;
this.stopProgressSaveInterval();
this.saveProgress();
this.cancelSleepTimer();
this.updateMediaSessionPlaybackState();
// Pause the listening session
this.audiobookSessionService.pauseSession(Math.round(this.currentTime * 1000));
this.messageService.add({
severity: 'info',
summary: 'Sleep Timer',
detail: 'Playback stopped by sleep timer'
});
}
private updateSleepTimerMenuVisibility(): void {
// Show/hide cancel option based on timer state
const cancelItem = this.sleepTimerOptions.find(item => item.label === 'Cancel timer');
if (cancelItem) {
cancelItem.visible = this.sleepTimerActive;
}
}
formatSleepTimerRemaining(): string {
if (this.sleepTimerEndOfChapter) {
return 'End of chapter';
}
const minutes = Math.floor(this.sleepTimerRemaining / 60);
const seconds = this.sleepTimerRemaining % 60;
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
// Check for end of chapter in onTimeUpdate for sleep timer
private checkSleepTimerEndOfChapter(): void {
if (!this.sleepTimerEndOfChapter || !this.sleepTimerActive) return;
const currentChapter = this.getCurrentChapter();
if (currentChapter) {
const currentMs = this.currentTime * 1000;
// If we're within 1 second of chapter end, trigger stop
if (currentMs >= currentChapter.endTimeMs - 1000) {
this.triggerSleepTimerStop();
}
}
}
// ==================== BOOKMARKS ====================
loadBookmarks(): void {
this.bookMarkService.getBookmarksForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarks => {
this.bookmarks = bookmarks;
});
}
toggleBookmarkList(): void {
this.showBookmarkList = !this.showBookmarkList;
if (this.showBookmarkList && this.bookmarks.length === 0) {
this.loadBookmarks();
}
}
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 {
title = `Bookmark at ${this.formatTime(this.currentTime)}`;
}
const request: CreateBookMarkRequest = {
bookId: this.bookId,
title: title,
positionMs: Math.round(this.currentTime * 1000),
trackIndex: this.audiobookInfo.folderBased ? this.currentTrackIndex : undefined
};
this.bookMarkService.createBookmark(request)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: (bookmark) => {
this.bookmarks = [...this.bookmarks, bookmark];
this.messageService.add({
severity: 'success',
summary: 'Bookmark Added',
detail: title
});
},
error: (err) => {
const isDuplicate = err?.status === 409;
this.messageService.add({
severity: isDuplicate ? 'warn' : 'error',
summary: isDuplicate ? 'Bookmark Exists' : 'Error',
detail: isDuplicate ? 'A bookmark already exists at this position' : 'Failed to add bookmark'
});
}
});
}
goToBookmark(bookmark: BookMark): void {
// Handle track switching for folder-based audiobooks
if (this.audiobookInfo.folderBased && bookmark.trackIndex !== undefined && bookmark.trackIndex !== null) {
if (bookmark.trackIndex !== this.currentTrackIndex) {
this.loadTrack(bookmark.trackIndex);
// Wait for track to load, then seek
this.savedPosition = (bookmark.positionMs || 0) / 1000;
} else {
// Same track, just seek
const audio = this.audioElement?.nativeElement;
if (audio && bookmark.positionMs) {
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
}
} else {
// Single-file audiobook
const audio = this.audioElement?.nativeElement;
if (audio && bookmark.positionMs) {
audio.currentTime = bookmark.positionMs / 1000;
this.currentTime = bookmark.positionMs / 1000;
}
}
this.showBookmarkList = false;
if (!this.isPlaying) {
setTimeout(() => {
this.audioElement?.nativeElement?.play();
this.isPlaying = true;
this.startProgressSaveInterval();
// Start or resume listening session
const positionMs = bookmark.positionMs || 0;
if (this.audiobookSessionService.isSessionActive()) {
this.audiobookSessionService.resumeSession(positionMs);
} else {
this.audiobookSessionService.startSession(
this.bookId, positionMs, this.playbackRate,
this.audiobookInfo?.bookFileId,
this.audiobookInfo?.folderBased ? bookmark.trackIndex : undefined
);
}
}, 100);
}
}
deleteBookmark(event: MouseEvent, bookmarkId: number): void {
event.stopPropagation();
this.bookMarkService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.bookmarks = this.bookmarks.filter(b => b.id !== bookmarkId);
this.messageService.add({
severity: 'info',
summary: 'Bookmark Deleted'
});
});
}
formatBookmarkPosition(bookmark: BookMark): string {
if (bookmark.positionMs) {
return this.formatTime(bookmark.positionMs / 1000);
}
return '';
}
}
@@ -0,0 +1,39 @@
export interface AudiobookInfo {
bookId: number;
bookFileId: number;
title?: string;
author?: string;
narrator?: string;
durationMs: number;
bitrate?: number;
codec?: string;
sampleRate?: number;
channels?: number;
folderBased: boolean;
chapters?: AudiobookChapter[];
tracks?: AudiobookTrack[];
}
export interface AudiobookChapter {
index: number;
title: string;
startTimeMs: number;
endTimeMs: number;
durationMs: number;
}
export interface AudiobookTrack {
index: number;
fileName: string;
title: string;
durationMs: number;
fileSizeBytes: number;
cumulativeStartMs: number;
}
export interface AudiobookProgress {
positionMs: number;
trackIndex?: number;
trackPositionMs?: number;
percentage: number;
}
@@ -0,0 +1,64 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { API_CONFIG } from '../../../core/config/api-config';
import { AudiobookInfo, AudiobookProgress } from './audiobook.model';
import { AuthService } from '../../../shared/service/auth.service';
import { BookFileProgress } from '../../book/model/book.model';
@Injectable({
providedIn: 'root'
})
export class AudiobookService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobook`;
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private authService = inject(AuthService);
getAudiobookInfo(bookId: number, bookType?: string): Observable<AudiobookInfo> {
const params: Record<string, string> = {};
if (bookType) {
params['bookType'] = bookType;
}
return this.http.get<AudiobookInfo>(`${this.baseUrl}/${bookId}/info`, { params });
}
getStreamUrl(bookId: number, trackIndex?: number): string {
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
if (trackIndex !== undefined && trackIndex !== null) {
url += `&trackIndex=${trackIndex}`;
}
return url;
}
getTrackStreamUrl(bookId: number, trackIndex: number): string {
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
}
getEmbeddedCoverUrl(bookId: number): string {
const token = this.authService.getInternalAccessToken() || this.authService.getOidcAccessToken();
return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
}
saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable<void> {
if (bookFileId) {
const fileProgress: BookFileProgress = {
bookFileId: bookFileId,
positionData: progress.positionMs.toString(),
positionHref: progress.trackIndex?.toString(),
progressPercent: progress.percentage
};
return this.http.post<void>(`${this.booksUrl}/progress`, {
bookId,
fileProgress
});
}
return this.http.post<void>(`${this.booksUrl}/progress`, {
bookId,
audiobookProgress: progress
});
}
}
@@ -0,0 +1,3 @@
export * from './audiobook-reader.component';
export * from './audiobook.service';
export * from './audiobook.model';
@@ -2,7 +2,7 @@ import {Component, HostListener, inject, OnDestroy, OnInit} from '@angular/core'
import {ActivatedRoute, Router} from '@angular/router';
import {CommonModule} from '@angular/common';
import {forkJoin, Subject} from 'rxjs';
import {filter, first, takeUntil, timeout} from 'rxjs/operators';
import {filter, first, map, switchMap, takeUntil, timeout} from 'rxjs/operators';
import {PageTitleService} from "../../../shared/service/page-title.service";
import {CbxReaderService} from '../../book/service/cbx-reader.service';
import {BookService} from '../../book/service/book.service';
@@ -55,6 +55,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
bookType!: BookType;
bookId!: number;
bookFileId?: number;
altBookType?: string;
pages: number[] = [];
currentPage = 0;
isLoading = true;
@@ -129,34 +131,48 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.route.paramMap.subscribe((params) => {
this.isLoading = true;
this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
this.previousBookInSeries = null;
this.nextBookInSeries = null;
this.currentBook = null;
forkJoin([
this.bookService.getBookByIdFromAPI(this.bookId, false),
this.bookService.getBookSetting(this.bookId),
this.userService.getMyself()
]).subscribe({
next: ([book, bookSettings, myself]) => {
const userSettings = myself.userSettings;
this.bookType = book.bookType;
this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
switchMap((book) => {
// Use alternative bookType from query param if provided, otherwise use primary
this.bookType = (this.altBookType as BookType) ?? book.primaryFile?.bookType!;
this.currentBook = book;
// Determine which file ID to use for progress tracking
if (this.altBookType) {
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
this.bookFileId = altFile?.id;
} else {
this.bookFileId = book.primaryFile?.id;
}
return forkJoin([
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
this.userService.getMyself()
]).pipe(map(([bookSettings, myself]) => ({ book, bookSettings, myself })));
})
).subscribe({
next: ({ book, bookSettings, myself }) => {
const userSettings = myself.userSettings;
this.pageTitle.setBookPageTitle(book);
const title = book.metadata?.title || book.fileName;
this.headerService.initialize(this.bookId, title, this.destroy$);
this.sidebarService.initialize(this.bookId, book, this.destroy$);
this.sidebarService.initialize(this.bookId, book, this.destroy$, this.altBookType);
if (book.metadata?.seriesName) {
this.loadSeriesNavigationAsync(book);
}
const pagesObservable = this.bookType === CbxReaderComponent.TYPE_PDF
? this.pdfReaderService.getAvailablePages(this.bookId)
: this.cbxReaderService.getAvailablePages(this.bookId);
? this.pdfReaderService.getAvailablePages(this.bookId, this.altBookType)
: this.cbxReaderService.getAvailablePages(this.bookId, this.altBookType);
pagesObservable.subscribe({
next: (pages) => {
@@ -728,8 +744,8 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
private getPageImageUrl(pageIndex: number): string {
return this.bookType === CbxReaderComponent.TYPE_PDF
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex])
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]);
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType)
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex], this.altBookType);
}
get infiniteScrollImageUrls(): string[] {
@@ -765,10 +781,10 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
: 0;
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe();
}
if (this.bookType === CbxReaderComponent.TYPE_PDF) {
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage, this.bookFileId).subscribe();
}
}
@@ -109,7 +109,7 @@
@if (bookmarks.length > 0) {
<ul class="item-list">
@for (bookmark of bookmarks; track bookmark.id) {
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi)">
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
<div class="item-content">
<span class="item-title">{{ bookmark.title }}</span>
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
@@ -27,6 +27,7 @@ export class CbxSidebarService {
private destroy$ = new Subject<void>();
private bookId!: number;
private altBookType?: string;
private bookType!: BookType;
private _isOpen = new BehaviorSubject<boolean>(false);
@@ -66,9 +67,10 @@ export class CbxSidebarService {
return this.bookType === 'PDF';
}
initialize(bookId: number, book: Book, destroy$: Subject<void>): void {
initialize(bookId: number, book: Book, destroy$: Subject<void>, altBookType?: string): void {
this.bookId = bookId;
this.bookType = book.bookType;
this.altBookType = altBookType;
this.bookType = (altBookType as BookType) ?? book.primaryFile?.bookType!;
this.destroy$ = destroy$;
this._bookInfo.next({
@@ -85,7 +87,7 @@ export class CbxSidebarService {
private loadPageInfo(): void {
if (this.bookType === 'PDF') {
this.pdfReaderService.getPageInfo(this.bookId)
this.pdfReaderService.getPageInfo(this.bookId, this.altBookType)
.pipe(takeUntil(this.destroy$))
.subscribe(pdfInfo => {
this._pdfPageCount.next(pdfInfo.pageCount);
@@ -99,7 +101,7 @@ export class CbxSidebarService {
}
});
} else {
this.cbxReaderService.getPageInfo(this.bookId)
this.cbxReaderService.getPageInfo(this.bookId, this.altBookType)
.pipe(takeUntil(this.destroy$))
.subscribe(pages => this._pages.next(pages));
}
@@ -43,7 +43,10 @@ export class EpubStreamingService {
private http = inject(HttpClient);
private authService = inject(AuthService);
getBookInfo(bookId: number): Observable<EpubBookInfo> {
getBookInfo(bookId: number, bookType?: string): Observable<EpubBookInfo> {
if (bookType) {
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`, { params: { bookType } });
}
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`);
}
@@ -79,26 +79,26 @@ export class ReaderViewManagerService {
);
}
loadEpubStreaming(bookId: number): Observable<void> {
loadEpubStreaming(bookId: number, bookType?: string): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return this.epubStreamingService.getBookInfo(bookId).pipe(
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo))),
return this.epubStreamingService.getBookInfo(bookId, bookType).pipe(
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo, bookType))),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo): Promise<void> {
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo, bookType?: string): Promise<void> {
const makeStreamingBook = (window as any).makeStreamingBook;
if (!makeStreamingBook) {
throw new Error('makeStreamingBook not available - Foliate script may not be loaded');
}
const baseUrl = this.epubStreamingService.getBaseUrl();
const authToken = this.epubStreamingService.getAuthToken();
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken);
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken, bookType);
await this.view.open(book);
}
@@ -1,7 +1,7 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {forkJoin, Observable, of, Subject, throwError} from 'rxjs';
import {catchError, switchMap, takeUntil, tap} from 'rxjs/operators';
import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators';
import {MessageService} from 'primeng/api';
import {ReaderLoaderService} from './core/loader.service';
import {ReaderViewManagerService} from './core/view-manager.service';
@@ -17,7 +17,7 @@ import {ReaderHeaderService} from './layout/header/header.service';
import {ReaderNoteService} from './features/notes/note.service';
import {BookService} from '../../book/service/book.service';
import {ActivatedRoute} from '@angular/router';
import {Book} from '../../book/model/book.model';
import {Book, BookType} from '../../book/model/book.model';
import {ReaderHeaderComponent} from './layout/header/header.component';
import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component';
import {ReaderLeftSidebarComponent} from './layout/panel/panel.component';
@@ -83,6 +83,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
public stateService = inject(ReaderStateService);
protected bookId!: number;
protected altBookType?: string;
private hasLoadedOnce = false;
private _fileUrl: string | null = null;
@@ -207,23 +208,39 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
private loadBookFromAPI(): Observable<void> {
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
return this.stateService.initializeState(this.bookId).pipe(
switchMap(() => forkJoin({
state: this.stateService.initializeState(this.bookId),
book: this.bookService.getBookByIdFromAPI(this.bookId, false)
})),
switchMap(({book}) => {
return this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
switchMap((book) => {
this.book = book;
this.progressService.initialize(this.bookId, book.bookType!);
// Use alternative bookType from query param if provided, otherwise use primary
const bookType = (this.altBookType as BookType) ?? book.primaryFile?.bookType!;
// Determine which file ID to use for progress tracking
let bookFileId: number | undefined;
if (this.altBookType) {
// Look for the alternative format file with matching type
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
bookFileId = altFile?.id;
} else {
// Use the primary file
bookFileId = book.primaryFile?.id;
}
return this.stateService.initializeState(this.bookId, bookFileId!).pipe(
map(() => ({ book, bookType, bookFileId }))
);
}),
switchMap(({book, bookType, bookFileId}) => {
this.progressService.initialize(this.bookId, bookType, bookFileId);
this.selectionService.initialize(this.bookId, this.destroy$);
this.headerService.initialize(this.bookId, book.metadata?.title || '', this.destroy$);
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
const loadBook$ = book.bookType === 'EPUB' && useStreaming
? this.viewManager.loadEpubStreaming(this.bookId)
const loadBook$ = bookType === 'EPUB' && useStreaming
? this.viewManager.loadEpubStreaming(this.bookId, this.altBookType)
: this.loadBookBlob();
return loadBook$.pipe(
@@ -237,7 +254,12 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
switchMap(() => {
if (!this.hasLoadedOnce) {
this.hasLoadedOnce = true;
return this.viewManager.goTo(book.epubProgress!.cfi);
// Navigate to saved position if progress exists, otherwise go to first page
if (book.epubProgress?.cfi) {
return this.viewManager.goTo(book.epubProgress.cfi);
} else {
return this.viewManager.goTo(0);
}
}
return of(undefined);
})
@@ -247,7 +269,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
}
private loadBookBlob(): Observable<void> {
return this.bookService.getFileContent(this.bookId).pipe(
return this.bookService.getFileContent(this.bookId, this.altBookType).pipe(
switchMap(fileBlob => {
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
@@ -96,7 +96,7 @@
@if (bookmarks.length > 0) {
<ul class="item-list">
@for (bookmark of bookmarks; track bookmark.id) {
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi)">
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
<div class="item-content">
<span class="item-title">{{ bookmark.title }}</span>
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
@@ -30,6 +30,7 @@ export class ReaderProgressService {
private bookId!: number;
private bookType!: BookType;
private bookFileId?: number;
private hasStartedSession = false;
private _currentCfi: string | null = null;
@@ -61,9 +62,10 @@ export class ReaderProgressService {
return this._currentPageInfo;
}
initialize(bookId: number, bookType: BookType): void {
initialize(bookId: number, bookType: BookType, bookFileId?: number): void {
this.bookId = bookId;
this.bookType = bookType;
this.bookFileId = bookFileId;
this.hasStartedSession = false;
}
@@ -80,7 +82,7 @@ export class ReaderProgressService {
}
if (cfi && percentage !== null) {
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage);
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage, this.bookFileId);
this.readingSessionService.updateProgress(cfi, percentage);
}
@@ -93,10 +93,10 @@ export class ReaderStateService {
this.loadCustomFontsIntoList();
}
initializeState(bookId: number): Observable<void> {
initializeState(bookId: number, bookFileId: number): Observable<void> {
return forkJoin([
this.userService.getMyself(),
this.bookService.getBookSetting(bookId)
this.bookService.getBookSetting(bookId, bookFileId)
]).pipe(
tap(([myself, bookSetting]) => {
const settingScope = myself.userSettings.perBookSetting.epub;
@@ -4,6 +4,7 @@ import {NgxExtendedPdfViewerModule, ZoomType} from 'ngx-extended-pdf-viewer';
import {PageTitleService} from "../../../shared/service/page-title.service";
import {BookService} from '../../book/service/book.service';
import {forkJoin, Subscription} from 'rxjs';
import {map, switchMap} from 'rxjs/operators';
import {BookSetting} from '../../book/model/book.model';
import {UserService} from '../../settings/user-management/user.service';
@@ -31,6 +32,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
bookData!: string | Blob;
bookId!: number;
bookFileId?: number;
private appSettingsSubscription!: Subscription;
private bookService = inject(BookService);
@@ -46,17 +48,21 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.isLoading = true;
this.bookId = +params.get('bookId')!;
const myself$ = this.userService.getMyself();
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
const bookSetting$ = this.bookService.getBookSetting(this.bookId);
const pdfData$ = this.bookService.getFileContent(this.bookId);
this.bookService.getBookByIdFromAPI(this.bookId, false).pipe(
switchMap((book) => {
// Set the book file ID for progress tracking
this.bookFileId = book.primaryFile?.id;
forkJoin([book$, bookSetting$, pdfData$, myself$]).subscribe({
next: (results) => {
const pdfMeta = results[0];
const pdfPrefs = results[1];
const pdfData = results[2];
const myself = results[3];
return forkJoin([
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
this.bookService.getFileContent(this.bookId),
this.userService.getMyself()
]).pipe(map(([bookSetting, pdfData, myself]) => ({ book, bookSetting, pdfData, myself })));
})
).subscribe({
next: ({ book, bookSetting, pdfData, myself }) => {
const pdfMeta = book;
const pdfPrefs = bookSetting;
this.pageTitle.setBookPageTitle(pdfMeta);
@@ -115,7 +121,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
updateProgress(): void {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.bookService.savePdfProgress(this.bookId, this.page, percentage).subscribe();
this.bookService.savePdfProgress(this.bookId, this.page, percentage, this.bookFileId).subscribe();
}
onPdfPagesLoaded(event: { pagesCount: number }): void {