Files
grimmory/booklore-ui/src/app/features/book/service/book-patch.service.ts
T
ACXandacx10 3f334202b6 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>
2026-01-27 10:12:50 -07:00

258 lines
9.0 KiB
TypeScript

import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
import {Book, BookFileProgress, ReadStatus} from '../model/book.model';
import {BookStateService} from './book-state.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from './book.service';
@Injectable({
providedIn: 'root',
})
export class BookPatchService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private bookStateService = inject(BookStateService);
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number; bookFileId?: number }>();
private epubProgress$ = this.epubProgressSubject.pipe(
distinctUntilChanged((prev, curr) =>
prev.bookId === curr.bookId &&
prev.cfi === curr.cfi &&
prev.href === curr.href &&
prev.percentage === curr.percentage &&
prev.bookFileId === curr.bookFileId
),
exhaustMap(payload => {
const body: any = {
bookId: payload.bookId,
epubProgress: {
cfi: payload.cfi,
href: payload.href,
percentage: payload.percentage
}
};
// Add file-level progress if bookFileId is provided
if (payload.bookFileId) {
body.fileProgress = {
bookFileId: payload.bookFileId,
positionData: payload.cfi,
positionHref: payload.href,
progressPercent: payload.percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}),
share()
);
constructor() {
this.epubProgress$.subscribe();
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
const requestPayload = {
bookIds: Array.from(bookIds),
shelvesToAssign: Array.from(shelvesToAssign),
shelvesToUnassign: Array.from(shelvesToUnassign),
};
return this.http.post<Book[]>(`${this.url}/shelves`, requestPayload).pipe(
tap(updatedBooks => {
const currentState = this.bookStateService.getCurrentBookState();
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => {
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (index !== -1) {
currentBooks[index] = updatedBook;
}
});
this.bookStateService.updateBookState({...currentState, books: [...currentBooks]});
})
);
}
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
positionData: String(page),
progressPercent: percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void {
this.epubProgressSubject.next({bookId, cfi, href, percentage, bookFileId});
}
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
const body: any = {
bookId: bookId,
cbxProgress: {
page: page,
percentage: percentage
}
};
// Add file-level progress if bookFileId is provided
if (bookFileId) {
body.fileProgress = {
bookFileId: bookFileId,
positionData: String(page),
progressPercent: percentage
};
}
return this.http.post<void>(`${this.url}/progress`, body);
}
/**
* Save file-level progress directly using the new API.
* This is the preferred method for per-file progress tracking.
*/
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
const body = {
bookId: bookId,
fileProgress: fileProgress
};
return this.http.post<void>(`${this.url}/progress`, body);
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
const body = {
bookId: bookId,
dateFinished: dateFinished
};
return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
const currentState = this.bookStateService.getCurrentBookState();
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});
this.bookStateService.updateBookState({
...currentState,
books: updatedBooks
});
}
})
);
}
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<BookStatusUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const params = new HttpParams().set('type', ResetProgressTypes[type]);
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const requestBody = {
bookIds: ids,
status: status
};
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/status`, requestBody).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
readStatus: response.readStatus,
readStatusModifiedTime: response.readStatusModifiedTime,
dateFinished: response.dateFinished
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
resetPersonalRating(bookIds: number | number[]): Observable<PersonalRatingUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.post<PersonalRatingUpdateResponse[]>(`${this.url}/reset-personal-rating`, ids).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updatePersonalRating(bookIds: number | number[], rating: number): Observable<PersonalRatingUpdateResponse[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<PersonalRatingUpdateResponse[]>(`${this.url}/personal-rating`, {ids, rating}).pipe(
tap(responses => {
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book => {
const response = responses.find(r => r.bookId === book.id);
if (response) {
return {
...book,
personalRating: response.personalRating
};
}
return book;
});
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
})
);
}
updateLastReadTime(bookId: number): void {
const timestamp = new Date().toISOString();
const currentState = this.bookStateService.getCurrentBookState();
const updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
);
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
}