refactor(books): add reader navigation, book permission checks, and additional commands (#2350)
This commit is contained in:
+2
-1
@@ -3,6 +3,7 @@ import {DynamicDialogRef} from '@openng/optimus-ui/dynamicdialog';
|
||||
import {DialogLauncherService, DialogSize, DialogStyle} from '../../../../shared/services/dialog-launcher.service';
|
||||
import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {type BookSenderSource} from '../book-sender/book-sender.component';
|
||||
|
||||
interface MetadataRefreshDialogContext {
|
||||
metadataRefreshType: MetadataRefreshType;
|
||||
@@ -139,7 +140,7 @@ export class BookDialogHelperService {
|
||||
});
|
||||
}
|
||||
|
||||
async openCustomSendDialog(book: Book): Promise<DynamicDialogRef | null> {
|
||||
async openCustomSendDialog(book: BookSenderSource): Promise<DynamicDialogRef | null> {
|
||||
return this.dialogLauncherService.launchLazyDialog(async () => {
|
||||
const {BookSenderComponent} = await import('../book-sender/book-sender.component');
|
||||
return this.openDialog(BookSenderComponent, {
|
||||
|
||||
@@ -9,10 +9,15 @@ import {DynamicDialogConfig, DynamicDialogRef} from '@openng/optimus-ui/dynamicd
|
||||
import {MessageService} from '@openng/optimus-ui/api';
|
||||
import {EmailV2ProviderService} from '../../../settings/email-v2/email-v2-provider/email-v2-provider.service';
|
||||
import {EmailV2RecipientService} from '../../../settings/email-v2/email-v2-recipient/email-v2-recipient.service';
|
||||
import {Book} from '../../model/book.model';
|
||||
import {RadioButton} from '@openng/optimus-ui/radiobutton';
|
||||
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
export interface BookSenderSource {
|
||||
id: number;
|
||||
primaryFile?: {id: number; bookType?: string; fileSizeKb?: number};
|
||||
alternativeFormats?: readonly {id: number; bookType?: string; fileSizeKb?: number}[];
|
||||
}
|
||||
|
||||
interface EmailableFile {
|
||||
id: number;
|
||||
bookType?: string;
|
||||
@@ -44,7 +49,7 @@ export class BookSenderComponent implements OnInit {
|
||||
dynamicDialogRef = inject(DynamicDialogRef);
|
||||
private dynamicDialogConfig = inject(DynamicDialogConfig);
|
||||
|
||||
book: Book = this.dynamicDialogConfig.data.book;
|
||||
book: BookSenderSource = this.dynamicDialogConfig.data.book;
|
||||
|
||||
emailProviders: { label: string, value: EmailProvider }[] = [];
|
||||
emailRecipients: { label: string, value: EmailRecipient }[] = [];
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import {type User} from '../../settings/user-management/user.service';
|
||||
import {type BookFileResponse, type BookSummary} from './book-response.models';
|
||||
|
||||
type BookActionPermissionSource = Pick<
|
||||
User['permissions'],
|
||||
| 'admin'
|
||||
| 'canDownload'
|
||||
| 'canEmailBook'
|
||||
| 'canEditMetadata'
|
||||
| 'canDeleteBook'
|
||||
| 'canBulkResetGrimmoryReadProgress'
|
||||
| 'canBulkResetKoReaderReadProgress'
|
||||
| 'canMoveOrganizeFiles'
|
||||
>;
|
||||
|
||||
interface BookActionPermissions {
|
||||
readonly canDownload: boolean;
|
||||
readonly canEmailBook: boolean;
|
||||
readonly canEditMetadata: boolean;
|
||||
readonly canDeleteBook: boolean;
|
||||
readonly canResetGrimmoryProgress: boolean;
|
||||
readonly canResetKoreaderProgress: boolean;
|
||||
readonly canOrganizeFiles: boolean;
|
||||
}
|
||||
|
||||
export function bookActionPermissions(
|
||||
permissions: BookActionPermissionSource | null | undefined,
|
||||
): BookActionPermissions {
|
||||
const admin = !!permissions?.admin;
|
||||
return {
|
||||
canDownload: admin || !!permissions?.canDownload,
|
||||
canEmailBook: admin || !!permissions?.canEmailBook,
|
||||
canEditMetadata: admin || !!permissions?.canEditMetadata,
|
||||
canDeleteBook: admin || !!permissions?.canDeleteBook,
|
||||
canResetGrimmoryProgress: admin || !!permissions?.canBulkResetGrimmoryReadProgress,
|
||||
canResetKoreaderProgress: admin || !!permissions?.canBulkResetKoReaderReadProgress,
|
||||
canOrganizeFiles: admin || !!permissions?.canMoveOrganizeFiles,
|
||||
};
|
||||
}
|
||||
|
||||
export type BookReadAction = 'read' | 'continueReading' | 'play' | 'continueListening';
|
||||
|
||||
export function bookGrimmoryProgress(
|
||||
book: BookSummary,
|
||||
file: BookFileResponse | undefined = book.primaryFile,
|
||||
): number | null {
|
||||
switch (file?.bookType) {
|
||||
case 'EPUB':
|
||||
case 'FB2':
|
||||
case 'MOBI':
|
||||
case 'AZW3':
|
||||
return book.epubProgress?.percentage ?? null;
|
||||
case 'PDF':
|
||||
return book.pdfProgress?.percentage ?? null;
|
||||
case 'CBX':
|
||||
return book.cbxProgress?.percentage ?? null;
|
||||
case 'AUDIOBOOK':
|
||||
return book.audiobookProgress?.percentage ?? null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function bookProgressPercentage(
|
||||
book: BookSummary,
|
||||
file: BookFileResponse | undefined = book.primaryFile,
|
||||
): number | null {
|
||||
const progress = bookGrimmoryProgress(book, file);
|
||||
if (file?.bookType === 'AUDIOBOOK') {
|
||||
return progress;
|
||||
}
|
||||
return progress ?? book.koreaderProgress?.percentage ?? book.koboProgress?.percentage ?? null;
|
||||
}
|
||||
|
||||
function bookPartlyRead(book: BookSummary, file: BookFileResponse | undefined): boolean {
|
||||
const progress = bookProgressPercentage(book, file);
|
||||
return progress !== null && progress > 0 && progress < 100;
|
||||
}
|
||||
|
||||
export function bookReadAction(
|
||||
book: BookSummary,
|
||||
file: BookFileResponse | undefined = book.primaryFile,
|
||||
): BookReadAction {
|
||||
const audiobook = file?.bookType === 'AUDIOBOOK';
|
||||
if (bookPartlyRead(book, file)) {
|
||||
return audiobook ? 'continueListening' : 'continueReading';
|
||||
}
|
||||
return audiobook ? 'play' : 'read';
|
||||
}
|
||||
@@ -2,4 +2,5 @@ import {bookCommandKeys} from './book-command-keys';
|
||||
|
||||
export const bookBackgroundSubmissionKeys = {
|
||||
changeCovers: () => [...bookCommandKeys.all(), 'background-submission', 'change-covers'] as const,
|
||||
quickSend: () => [...bookCommandKeys.all(), 'background-submission', 'quick-send'] as const,
|
||||
};
|
||||
|
||||
@@ -2,3 +2,7 @@ export interface ChangeCoversVariables {
|
||||
readonly kind: 'regenerate' | 'generate';
|
||||
readonly bookIds: readonly number[];
|
||||
}
|
||||
|
||||
export interface QuickSendBookVariables {
|
||||
readonly bookId: number;
|
||||
}
|
||||
|
||||
@@ -5,12 +5,13 @@ import {lastValueFrom} from 'rxjs';
|
||||
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {bookBackgroundSubmissionKeys} from './book-background-submission-keys';
|
||||
import {ChangeCoversVariables} from './book-background-submission.models';
|
||||
import {ChangeCoversVariables, QuickSendBookVariables} from './book-background-submission.models';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookBackgroundSubmissionService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
private readonly emailUrl = `${API_CONFIG.BASE_URL}/api/v1/email`;
|
||||
|
||||
changeCovers() {
|
||||
return mutationOptions({
|
||||
@@ -19,6 +20,14 @@ export class BookBackgroundSubmissionService {
|
||||
});
|
||||
}
|
||||
|
||||
quickSend() {
|
||||
return mutationOptions({
|
||||
mutationKey: bookBackgroundSubmissionKeys.quickSend(),
|
||||
mutationFn: ({bookId}: QuickSendBookVariables) =>
|
||||
lastValueFrom(this.http.post<void>(`${this.emailUrl}/book/${bookId}`, {})),
|
||||
});
|
||||
}
|
||||
|
||||
private requestCoverChanges(
|
||||
variables: ChangeCoversVariables,
|
||||
): Promise<void> {
|
||||
|
||||
@@ -2,6 +2,7 @@ export const bookCommandKeys = {
|
||||
all: () => ['books', 'command'] as const,
|
||||
readStatus: () => [...bookCommandKeys.all(), 'read-status'] as const,
|
||||
deleteBooks: () => [...bookCommandKeys.all(), 'delete'] as const,
|
||||
deleteAdditionalFile: () => [...bookCommandKeys.all(), 'delete-additional-file'] as const,
|
||||
resetProgress: () => [...bookCommandKeys.all(), 'reset-progress'] as const,
|
||||
metadataAllLocks: () => [...bookCommandKeys.all(), 'metadata', 'all-locks'] as const,
|
||||
};
|
||||
|
||||
@@ -23,6 +23,16 @@ export interface DeleteBooksResult {
|
||||
readonly fileCleanupFailedBookIds: readonly number[];
|
||||
}
|
||||
|
||||
export interface DeleteAdditionalFileVariables {
|
||||
readonly bookId: number;
|
||||
readonly fileId: number;
|
||||
}
|
||||
|
||||
export interface DeleteAdditionalFileResult {
|
||||
readonly bookId: number;
|
||||
readonly fileId: number;
|
||||
}
|
||||
|
||||
export type BookProgressSource = 'GRIMMORY' | 'KOREADER' | 'KOBO';
|
||||
|
||||
export interface ResetBookProgressVariables {
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
ResetBookProgressPartialError,
|
||||
ResetBookProgressResult,
|
||||
DeleteBooksVariables,
|
||||
DeleteAdditionalFileVariables,
|
||||
DeleteAdditionalFileResult,
|
||||
ResetBookProgressVariables,
|
||||
SetAllBookMetadataLocksVariables,
|
||||
SetBookReadStatusVariables,
|
||||
@@ -71,6 +73,21 @@ export class BookCommandService {
|
||||
});
|
||||
}
|
||||
|
||||
deleteAdditionalFile() {
|
||||
return reconcilingMutationOptions({
|
||||
mutationKey: bookCommandKeys.deleteAdditionalFile(),
|
||||
scope: bookCommandScopes.deletion,
|
||||
mutationFn: (variables: DeleteAdditionalFileVariables) =>
|
||||
this.deleteAdditionalFileRecord(variables),
|
||||
reconcile: (outcome, variables, client) => applyBookQueryChangeSet(
|
||||
client,
|
||||
bookCommandChangeSet(outcome, [variables.bookId], result => ({
|
||||
changedBookIds: [result.bookId],
|
||||
})),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
resetProgress() {
|
||||
return reconcilingMutationOptions({
|
||||
mutationKey: bookCommandKeys.resetProgress(),
|
||||
@@ -111,6 +128,13 @@ export class BookCommandService {
|
||||
));
|
||||
}
|
||||
|
||||
private async deleteAdditionalFileRecord(
|
||||
{bookId, fileId}: DeleteAdditionalFileVariables,
|
||||
): Promise<DeleteAdditionalFileResult> {
|
||||
await lastValueFrom(this.http.delete<void>(`${this.baseUrl}/${bookId}/files/${fileId}`));
|
||||
return {bookId, fileId};
|
||||
}
|
||||
|
||||
private async deleteBookRecords(
|
||||
bookIds: readonly number[],
|
||||
): Promise<DeleteBooksResult> {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {
|
||||
DeleteAdditionalFileResult,
|
||||
DeleteBooksResult,
|
||||
ResetBookProgressResult,
|
||||
SetAllBookMetadataLocksResult,
|
||||
@@ -76,6 +77,17 @@ export const legacyBookCachePatches = {
|
||||
client: QueryClient,
|
||||
result: DeleteBooksResult,
|
||||
): Promise<void> => removeListOnlyBooks(client, result.removedBookIds),
|
||||
deleteAdditionalFile: (
|
||||
client: QueryClient,
|
||||
result: DeleteAdditionalFileResult,
|
||||
): Promise<void> => patchListOnlyBooksWith(client, [{
|
||||
bookId: result.bookId,
|
||||
updater: book => ({
|
||||
...book,
|
||||
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== result.fileId),
|
||||
supplementaryFiles: book.supplementaryFiles?.filter(file => file.id !== result.fileId),
|
||||
}),
|
||||
}]),
|
||||
resetProgress: (
|
||||
client: QueryClient,
|
||||
results: readonly ResetBookProgressResult[],
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Router} from '@angular/router';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import {BookNavigationService} from './book-navigation.service';
|
||||
|
||||
const navigate = vi.fn(() => Promise.resolve(true));
|
||||
|
||||
function createService(): BookNavigationService {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [{provide: Router, useValue: {navigate}}],
|
||||
});
|
||||
return TestBed.inject(BookNavigationService);
|
||||
}
|
||||
|
||||
describe('BookNavigationService', () => {
|
||||
beforeEach(() => navigate.mockClear());
|
||||
|
||||
it('tracks navigation context and derived positions', () => {
|
||||
const service = new BookNavigationService();
|
||||
const service = createService();
|
||||
|
||||
expect(service.navigationState()).toBeNull();
|
||||
expect(service.canNavigatePrevious()).toBe(false);
|
||||
@@ -36,7 +49,7 @@ describe('BookNavigationService', () => {
|
||||
});
|
||||
|
||||
it('clears invalid navigation context and ignores unknown book ids', () => {
|
||||
const service = new BookNavigationService();
|
||||
const service = createService();
|
||||
|
||||
service.setNavigationContext([1, 2, 3], 99);
|
||||
expect(service.navigationState()).toBeNull();
|
||||
@@ -49,4 +62,26 @@ describe('BookNavigationService', () => {
|
||||
|
||||
expect(service.navigationState()).toEqual({bookIds: [1, 2, 3], currentIndex: 0});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['PDF', '/pdf-reader/book/7'],
|
||||
['EPUB', '/ebook-reader/book/7'],
|
||||
['FB2', '/ebook-reader/book/7'],
|
||||
['MOBI', '/ebook-reader/book/7'],
|
||||
['AZW3', '/ebook-reader/book/7'],
|
||||
['CBX', '/cbx-reader/book/7'],
|
||||
['AUDIOBOOK', '/audiobook-player/book/7'],
|
||||
] as const)('opens %s books in the matching reader', (bookType, route) => {
|
||||
const service = createService();
|
||||
|
||||
service.readBook({
|
||||
id: 7,
|
||||
libraryId: 1,
|
||||
libraryName: 'Library',
|
||||
primaryFile: {id: 70, bookId: 7, book: true, folderBased: false, bookType},
|
||||
});
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith([route]);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
import {computed, inject, Injectable, signal} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
import {type BookFileResponse, type BookFileType, type BookSummary} from '../data/book-response.models';
|
||||
|
||||
export interface BookNavigationState {
|
||||
bookIds: number[];
|
||||
@@ -9,6 +12,8 @@ export interface BookNavigationState {
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookNavigationService {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
private readonly _navigationState = signal<BookNavigationState | null>(null);
|
||||
readonly navigationState = this._navigationState.asReadonly();
|
||||
|
||||
@@ -53,6 +58,21 @@ export class BookNavigationService {
|
||||
this._availableBookIds.set(bookIds);
|
||||
}
|
||||
|
||||
readBook(book: BookSummary, file: BookFileResponse | undefined = book.primaryFile): void {
|
||||
const baseUrl = this.readerRoute(file?.bookType);
|
||||
if (!baseUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const path = [`/${baseUrl}/book/${book.id}`];
|
||||
if (file?.bookType !== book.primaryFile?.bookType) {
|
||||
void this.router.navigate(path, {queryParams: {bookType: file?.bookType}});
|
||||
return;
|
||||
}
|
||||
|
||||
void this.router.navigate(path);
|
||||
}
|
||||
|
||||
setNavigationContext(bookIds: number[], currentBookId: number): void {
|
||||
const currentIndex = bookIds.indexOf(currentBookId);
|
||||
if (currentIndex !== -1) {
|
||||
@@ -74,4 +94,22 @@ export class BookNavigationService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readerRoute(bookType: BookFileType | undefined): string | null {
|
||||
switch (bookType) {
|
||||
case 'PDF':
|
||||
return 'pdf-reader';
|
||||
case 'EPUB':
|
||||
case 'FB2':
|
||||
case 'MOBI':
|
||||
case 'AZW3':
|
||||
return 'ebook-reader';
|
||||
case 'CBX':
|
||||
return 'cbx-reader';
|
||||
case 'AUDIOBOOK':
|
||||
return 'audiobook-player';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user