fix(reader): add fetchFreshBookDetail method to ensure up-to-date reading position across devices (#358)

* fix(reader): add fetchFreshBookDetail method to ensure up-to-date reading position across devices

* test(audiobook): enhance tests to verify queryClient interactions for progress updates

* fix(audiobook): include audiobookProgress and fileProgress in progress payload
This commit is contained in:
brios
2026-04-22 17:27:06 -04:00
committed by Zach Yale
parent cf7999044f
commit 4527d43e84
9 changed files with 76 additions and 23 deletions
@@ -56,6 +56,9 @@ describe('BookPatchService', () => {
}, },
}); });
request.flush(null); request.flush(null);
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 11]});
}); });
it('deduplicates identical EPUB progress updates before posting', () => { it('deduplicates identical EPUB progress updates before posting', () => {
@@ -80,6 +83,8 @@ describe('BookPatchService', () => {
request.flush(null); request.flush(null);
httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books/progress')); httpTestingController.expectNone(req => req.url.endsWith('/api/v1/books/progress'));
expect(queryClient.setQueryData).toHaveBeenCalledWith(BOOKS_QUERY_KEY, expect.any(Function));
expect(queryClient.invalidateQueries).toHaveBeenCalledWith({queryKey: ['books', 'detail', 7]});
}); });
it('patches cached progress fields when resetting kobo progress', () => { it('patches cached progress fields when resetting kobo progress', () => {
@@ -79,7 +79,14 @@ export class BookPatchService {
progressPercent: payload.percentage progressPercent: payload.percentage
}; };
} }
return this.http.post<void>(`${this.url}/progress`, body); return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
patchBookFieldsInCache(this.queryClient, [{
bookId: payload.bookId,
fields: {epubProgress: {cfi: payload.cfi, percentage: payload.percentage}}
}]);
})
);
}), }),
share() share()
); );
@@ -127,7 +134,14 @@ export class BookPatchService {
progressPercent: percentage progressPercent: percentage
}; };
} }
return this.http.post<void>(`${this.url}/progress`, body); return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
patchBookFieldsInCache(this.queryClient, [{
bookId,
fields: {pdfProgress: {page, percentage}}
}]);
})
);
} }
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void { saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number, bookFileId?: number): void {
@@ -160,7 +174,14 @@ export class BookPatchService {
progressPercent: percentage progressPercent: percentage
}; };
} }
return this.http.post<void>(`${this.url}/progress`, body); return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
patchBookFieldsInCache(this.queryClient, [{
bookId,
fields: {cbxProgress: {page, percentage}}
}]);
})
);
} }
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> { saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
@@ -121,6 +121,20 @@ export class BookService {
return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription)); return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription));
} }
/**
* Always fetches book detail from the server, bypassing the cache.
*
* Used by reader components on initialization to guarantee the latest reading position.
* While optimistic cache updates keep progress current within a single session,
* this network request is necessary to pick up progress saved on another device or browser.
*/
fetchFreshBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
return this.queryClient.fetchQuery({
...this.bookDetailQueryOptions(bookId, withDescription),
staleTime: 0,
});
}
private getBookRecommendationsQueryOptions(bookId: number, limit: number) { private getBookRecommendationsQueryOptions(bookId: number, limit: number) {
return queryOptions({ return queryOptions({
queryKey: bookRecommendationsQueryKey(bookId, limit), queryKey: bookRecommendationsQueryKey(bookId, limit),
@@ -179,7 +179,7 @@ export class AudiobookPlayerComponent implements OnInit, OnDestroy {
this.loadBookmarks(); this.loadBookmarks();
}), }),
switchMap(info => switchMap(info =>
from(this.bookService.ensureBookDetail(bookId, false)).pipe( from(this.bookService.fetchFreshBookDetail(bookId, false)).pipe(
tap(book => this.applyBookDetails(book, info)), tap(book => this.applyBookDetails(book, info)),
map(() => void 0), map(() => void 0),
catchError(() => of(void 0)) catchError(() => of(void 0))
@@ -1,6 +1,7 @@
import {provideHttpClient} from '@angular/common/http'; import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {TestBed} from '@angular/core/testing'; import {TestBed} from '@angular/core/testing';
import {QueryClient} from '@tanstack/angular-query-experimental';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {AuthService} from '../../../shared/service/auth.service'; import {AuthService} from '../../../shared/service/auth.service';
@@ -10,20 +11,22 @@ import {AudiobookService} from './audiobook.service';
describe('AudiobookService', () => { describe('AudiobookService', () => {
let service: AudiobookService; let service: AudiobookService;
let httpTestingController: HttpTestingController; let httpTestingController: HttpTestingController;
let queryClient: QueryClient;
let getInternalAccessToken: ReturnType<typeof vi.fn>; let getInternalAccessToken: ReturnType<typeof vi.fn>;
beforeEach(() => { beforeEach(() => {
getInternalAccessToken = vi.fn(() => 'token 123'); getInternalAccessToken = vi.fn(() => 'token 123');
queryClient = new QueryClient();
vi.spyOn(queryClient, 'setQueryData');
vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue();
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
provideHttpClient(), provideHttpClient(),
provideHttpClientTesting(), provideHttpClientTesting(),
AudiobookService, AudiobookService,
{ {provide: AuthService, useValue: {getInternalAccessToken}},
provide: AuthService, {provide: QueryClient, useValue: queryClient},
useValue: {getInternalAccessToken},
},
], ],
}); });
@@ -33,6 +36,7 @@ describe('AudiobookService', () => {
afterEach(() => { afterEach(() => {
httpTestingController.verify(); httpTestingController.verify();
queryClient.clear();
TestBed.resetTestingModule(); TestBed.resetTestingModule();
vi.restoreAllMocks(); vi.restoreAllMocks();
}); });
@@ -85,9 +89,10 @@ describe('AudiobookService', () => {
request.flush(null); request.flush(null);
expect(completed).toBe(true); expect(completed).toBe(true);
expect(queryClient.setQueryData).toHaveBeenCalledWith(['books'], expect.any(Function));
}); });
it('maps audiobook progress into a file progress payload when a book file id is present', () => { it('includes both audiobookProgress and fileProgress in the payload when a book file id is present', () => {
const progress: AudiobookProgress = { const progress: AudiobookProgress = {
positionMs: 75_000, positionMs: 75_000,
trackIndex: 5, trackIndex: 5,
@@ -100,6 +105,7 @@ describe('AudiobookService', () => {
expect(request.request.method).toBe('POST'); expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({ expect(request.request.body).toEqual({
bookId: 12, bookId: 12,
audiobookProgress: progress,
fileProgress: { fileProgress: {
bookFileId: 99, bookFileId: 99,
positionData: '75000', positionData: '75000',
@@ -108,5 +114,7 @@ describe('AudiobookService', () => {
}, },
}); });
request.flush(null); request.flush(null);
expect(queryClient.setQueryData).toHaveBeenCalledWith(['books'], expect.any(Function));
}); });
}); });
@@ -1,10 +1,13 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { API_CONFIG } from '../../../core/config/api-config'; import { API_CONFIG } from '../../../core/config/api-config';
import { AudiobookInfo, AudiobookProgress } from './audiobook.model'; import { AudiobookInfo, AudiobookProgress } from './audiobook.model';
import { AuthService } from '../../../shared/service/auth.service'; import { AuthService } from '../../../shared/service/auth.service';
import { BookFileProgress } from '../../book/model/book.model'; import { BookFileProgress } from '../../book/model/book.model';
import { QueryClient } from '@tanstack/angular-query-experimental';
import { patchBookFieldsInCache } from '../../book/service/book-query-cache';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
@@ -15,6 +18,7 @@ export class AudiobookService {
private http = inject(HttpClient); private http = inject(HttpClient);
private authService = inject(AuthService); private authService = inject(AuthService);
private queryClient = inject(QueryClient);
getAudiobookInfo(bookId: number, bookType?: string): Observable<AudiobookInfo> { getAudiobookInfo(bookId: number, bookType?: string): Observable<AudiobookInfo> {
const params: Record<string, string> = {}; const params: Record<string, string> = {};
@@ -44,21 +48,22 @@ export class AudiobookService {
} }
saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable<void> { saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable<void> {
const body: {bookId: number; audiobookProgress: AudiobookProgress; fileProgress?: BookFileProgress} = {
bookId,
audiobookProgress: progress,
};
if (bookFileId) { if (bookFileId) {
const fileProgress: BookFileProgress = { body.fileProgress = {
bookFileId: bookFileId, bookFileId,
positionData: progress.positionMs.toString(), positionData: progress.positionMs.toString(),
positionHref: progress.trackIndex?.toString(), positionHref: progress.trackIndex?.toString(),
progressPercent: progress.percentage progressPercent: progress.percentage,
}; };
return this.http.post<void>(`${this.booksUrl}/progress`, {
bookId,
fileProgress
});
} }
return this.http.post<void>(`${this.booksUrl}/progress`, { return this.http.post<void>(`${this.booksUrl}/progress`, body).pipe(
bookId, tap(() => {
audiobookProgress: progress patchBookFieldsInCache(this.queryClient, [{bookId, fields: {audiobookProgress: progress}}]);
}); })
);
} }
} }
@@ -243,7 +243,7 @@ export class CbxReaderComponent implements OnInit, OnDestroy {
this.nextBookInSeries = null; this.nextBookInSeries = null;
this.currentBook = null; this.currentBook = null;
return from(this.bookService.ensureBookDetail(this.bookId, false)).pipe( return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe(
switchMap((book) => { switchMap((book) => {
// Use alternative bookType from query param if provided, otherwise use primary // Use alternative bookType from query param if provided, otherwise use primary
const resolvedBookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType; const resolvedBookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType;
@@ -230,7 +230,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.bookId = +this.route.snapshot.paramMap.get('bookId')!; this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined; this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
return from(this.bookService.ensureBookDetail(this.bookId, false)).pipe( return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe(
switchMap((book) => { switchMap((book) => {
this.book = book; this.book = book;
@@ -126,7 +126,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
this.bookId = +params.get('bookId')!; this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined; this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
return from(this.bookService.ensureBookDetail(this.bookId, false)).pipe( return from(this.bookService.fetchFreshBookDetail(this.bookId, false)).pipe(
switchMap((book) => { switchMap((book) => {
if (this.altBookType) { if (this.altBookType) {
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType); const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);