refactor(frontend): rename booklore-ui to frontend
- Frontend path: - rename the tracked Angular app tree from `booklore-ui/` to `frontend/` - preserve file contents during the move so this commit stays focused on the path change itself - Frontend docs: - update the moved frontend README and contribution guide where they refer to the renamed folder - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
@@ -0,0 +1,211 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable, throwError} from 'rxjs';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {catchError, tap} from 'rxjs/operators';
|
||||
import {AdditionalFile, AdditionalFileType, Book, DetachBookFileResponse, DuplicateDetectionRequest, DuplicateGroup} from '../model/book.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {FileDownloadService} from '../../../shared/service/file-download.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {patchBookInCacheWith, patchBooksInCache, removeBooksFromCache} from './book-query-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookFileService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private fileDownloadService = inject(FileDownloadService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
getFileContent(bookId: number, bookType?: string): Observable<Blob> {
|
||||
let url = `${this.url}/${bookId}/content`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<Blob>(url, {responseType: 'blob' as 'json'});
|
||||
}
|
||||
|
||||
downloadFile(book: Book): void {
|
||||
const downloadUrl = `${this.url}/${book.id}/download`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, book.primaryFile?.fileName ?? 'book');
|
||||
}
|
||||
|
||||
downloadAllFiles(book: Book): void {
|
||||
const downloadUrl = `${this.url}/${book.id}/download-all`;
|
||||
const filename = book.metadata?.title
|
||||
? `${book.metadata.title.replace(/[^a-zA-Z0-9\-_]/g, '_')}.zip`
|
||||
: `book-${book.id}.zip`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, filename);
|
||||
}
|
||||
|
||||
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
|
||||
tap(() => {
|
||||
patchBookInCacheWith(this.queryClient, bookId, book => ({
|
||||
...book,
|
||||
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
|
||||
supplementaryFiles: book.supplementaryFiles?.filter(f => f.id !== fileId),
|
||||
}));
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.additionalFileDeletedDetail')
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.fileDeleteFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.fileDeleteFailedDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteBookFile(bookId: number, fileId: number, isPrimary: boolean): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${bookId}/files/${fileId}`).pipe(
|
||||
tap(() => {
|
||||
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||
if (isPrimary) {
|
||||
const remaining = book.alternativeFormats?.filter(f => f.id !== fileId) || [];
|
||||
const [newPrimary, ...rest] = remaining;
|
||||
return {...book, primaryFile: newPrimary, alternativeFormats: rest};
|
||||
}
|
||||
return {
|
||||
...book,
|
||||
alternativeFormats: book.alternativeFormats?.filter(f => f.id !== fileId),
|
||||
};
|
||||
});
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.fileDeletedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.bookFileDeletedDetail')
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.fileDeleteFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.fileDeleteFailedDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType): Observable<AdditionalFile> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const isBook = fileType === AdditionalFileType.ALTERNATIVE_FORMAT;
|
||||
formData.append('isBook', String(isBook));
|
||||
|
||||
if (isBook) {
|
||||
const lower = (file?.name || '').toLowerCase();
|
||||
const ext = lower.includes('.') ? lower.substring(lower.lastIndexOf('.') + 1) : '';
|
||||
const EXTENSION_TO_BOOK_TYPE: Record<string, string> = {
|
||||
pdf: 'PDF',
|
||||
epub: 'EPUB',
|
||||
cbz: 'CBX', cbr: 'CBX', cb7: 'CBX',
|
||||
mobi: 'MOBI',
|
||||
azw3: 'AZW3', azw: 'AZW3',
|
||||
fb2: 'FB2',
|
||||
m4b: 'AUDIOBOOK', m4a: 'AUDIOBOOK', mp3: 'AUDIOBOOK', opus: 'AUDIOBOOK',
|
||||
};
|
||||
const bookType = EXTENSION_TO_BOOK_TYPE[ext] ?? null;
|
||||
|
||||
if (bookType) {
|
||||
formData.append('bookType', bookType);
|
||||
}
|
||||
}
|
||||
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
|
||||
tap(newFile => {
|
||||
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
|
||||
return {...book, alternativeFormats: [...(book.alternativeFormats || []), newFile]};
|
||||
}
|
||||
return {...book, supplementaryFiles: [...(book.supplementaryFiles || []), newFile]};
|
||||
});
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.fileUploadedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.fileUploadedDetail')
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.uploadFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.uploadFailedDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
downloadAdditionalFile(book: Book, fileId: number): void {
|
||||
const additionalFile = [
|
||||
...(book.alternativeFormats || []),
|
||||
...(book.supplementaryFiles || [])
|
||||
].find((f: AdditionalFile) => f.id === fileId);
|
||||
const downloadUrl = `${this.url}/${book.id}/files/${fileId}/download`;
|
||||
this.fileDownloadService.downloadFile(downloadUrl, additionalFile?.fileName ?? 'file');
|
||||
}
|
||||
|
||||
detachBookFile(bookId: number, fileId: number, copyMetadata: boolean): Observable<DetachBookFileResponse> {
|
||||
return this.http.post<DetachBookFileResponse>(`${this.url}/${bookId}/files/${fileId}/detach`, {copyMetadata}).pipe(
|
||||
tap(response => {
|
||||
patchBooksInCache(this.queryClient, [response.sourceBook, response.newBook]);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('metadata.viewer.toast.detachFileSuccessSummary'),
|
||||
detail: this.t.translate('metadata.viewer.toast.detachFileSuccessDetail')
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('metadata.viewer.toast.detachFileErrorSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('metadata.viewer.toast.detachFileErrorDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
findDuplicates(request: DuplicateDetectionRequest): Observable<DuplicateGroup[]> {
|
||||
return this.http.post<DuplicateGroup[]>(`${this.url}/duplicates`, request);
|
||||
}
|
||||
|
||||
attachBookFiles(targetBookId: number, sourceBookIds: number[], moveFiles: boolean): Observable<{updatedBook: Book, deletedSourceBookIds: number[]}> {
|
||||
return this.http.post<{updatedBook: Book, deletedSourceBookIds: number[]}>(`${this.url}/${targetBookId}/attach-file`, {
|
||||
sourceBookIds,
|
||||
moveFiles
|
||||
}).pipe(
|
||||
tap(response => {
|
||||
patchBooksInCache(this.queryClient, [response.updatedBook]);
|
||||
removeBooksFromCache(this.queryClient, response.deletedSourceBookIds);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.filesAttachedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.filesAttachedDetail', {count: sourceBookIds.length})
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.attachmentFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.attachmentFailedDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {BookService} from './book.service';
|
||||
import {BookMetadataManageService} from './book-metadata-manage.service';
|
||||
import {AGE_RATING_OPTIONS, CONTENT_RATING_LABELS, readStatusLabels} from '../components/book-browser/book-filter/book-filter.config';
|
||||
import {ReadStatus} from '../model/book.model';
|
||||
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {finalize} from 'rxjs';
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {User} from '../../settings/user-management/user.service';
|
||||
import {APIException} from '../../../shared/models/api-exception.model';
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookMenuService {
|
||||
|
||||
confirmationService = inject(ConfirmationService);
|
||||
messageService = inject(MessageService);
|
||||
bookService = inject(BookService);
|
||||
bookMetadataManageService = inject(BookMetadataManageService);
|
||||
loadingService = inject(LoadingService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
getMetadataMenuItems(
|
||||
autoFetchMetadata: () => void,
|
||||
fetchMetadata: () => void,
|
||||
bulkEditMetadata: () => void,
|
||||
multiBookEditMetadata: () => void,
|
||||
regenerateCovers: () => void,
|
||||
generateCustomCovers: () => void,
|
||||
user: User | null): MenuItem[] {
|
||||
|
||||
const permissions = user?.permissions;
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
if (permissions?.canBulkAutoFetchMetadata) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.autoFetchMetadata'),
|
||||
icon: 'pi pi-bolt',
|
||||
command: autoFetchMetadata
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkCustomFetchMetadata) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.customFetchMetadata'),
|
||||
icon: 'pi pi-sync',
|
||||
command: fetchMetadata
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkEditMetadata) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.bulkMetadataEditor'),
|
||||
icon: 'pi pi-table',
|
||||
command: bulkEditMetadata
|
||||
});
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.multiBookMetadataEditor'),
|
||||
icon: 'pi pi-clone',
|
||||
command: multiBookEditMetadata
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkRegenerateCover) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.regenerateCovers'),
|
||||
icon: 'pi pi-image',
|
||||
command: regenerateCovers
|
||||
});
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.generateCustomCovers'),
|
||||
icon: 'pi pi-palette',
|
||||
command: generateCustomCovers
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
getMoreActionsMenu(selectedBooks: Set<number>, user: User | null): MenuItem[] {
|
||||
const count = selectedBooks.size;
|
||||
const permissions = user?.permissions;
|
||||
const items: MenuItem[] = [];
|
||||
|
||||
if (permissions?.canBulkResetBookReadStatus) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.updateReadStatus'),
|
||||
icon: 'pi pi-book',
|
||||
items: Object.entries(readStatusLabels).map(([status, label]) => ({
|
||||
label,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.readStatusMessage', {count, label}),
|
||||
header: this.t.translate('book.menuService.confirm.readStatusHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
acceptButtonProps: {
|
||||
label: this.t.translate('common.yes'),
|
||||
severity: 'success'
|
||||
},
|
||||
rejectButtonProps: {
|
||||
label: this.t.translate('common.no'),
|
||||
severity: 'secondary'
|
||||
},
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.updatingReadStatus', {count}));
|
||||
|
||||
this.bookService.updateBookReadStatus(Array.from(selectedBooks), status as ReadStatus)
|
||||
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.readStatusUpdatedSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.readStatusUpdatedDetail', {label}),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.updateFailedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.readStatusFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkEditMetadata) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.setAgeRating'),
|
||||
icon: 'pi pi-user',
|
||||
items: [
|
||||
...AGE_RATING_OPTIONS.map(option => ({
|
||||
label: option.label,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.ageRatingMessage', {label: option.label, count}),
|
||||
header: this.t.translate('book.menuService.confirm.ageRatingHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.settingAgeRating', {count}));
|
||||
this.bookMetadataManageService.updateBooksMetadata({
|
||||
bookIds: Array.from(selectedBooks),
|
||||
ageRating: option.id
|
||||
}).pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.ageRatingUpdatedSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.ageRatingUpdatedDetail', {label: option.label}),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.updateFailedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.ageRatingFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
})),
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.menuService.menu.clearAgeRating'),
|
||||
icon: 'pi pi-times',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.clearAgeRatingMessage', {count}),
|
||||
header: this.t.translate('book.menuService.confirm.clearAgeRatingHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.clearingAgeRating', {count}));
|
||||
this.bookMetadataManageService.updateBooksMetadata({
|
||||
bookIds: Array.from(selectedBooks),
|
||||
clearAgeRating: true
|
||||
}).pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.ageRatingClearedSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.ageRatingClearedDetail'),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.updateFailedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.clearAgeRatingFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.setContentRating'),
|
||||
icon: 'pi pi-shield',
|
||||
items: [
|
||||
...Object.entries(CONTENT_RATING_LABELS).map(([value, label]) => ({
|
||||
label: label,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.contentRatingMessage', {label, count}),
|
||||
header: this.t.translate('book.menuService.confirm.contentRatingHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.settingContentRating', {count}));
|
||||
this.bookMetadataManageService.updateBooksMetadata({
|
||||
bookIds: Array.from(selectedBooks),
|
||||
contentRating: value
|
||||
}).pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.contentRatingUpdatedSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.contentRatingUpdatedDetail', {label}),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.updateFailedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.contentRatingFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
})),
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.menuService.menu.clearContentRating'),
|
||||
icon: 'pi pi-times',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.clearContentRatingMessage', {count}),
|
||||
header: this.t.translate('book.menuService.confirm.clearContentRatingHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.clearingContentRating', {count}));
|
||||
this.bookMetadataManageService.updateBooksMetadata({
|
||||
bookIds: Array.from(selectedBooks),
|
||||
clearContentRating: true
|
||||
}).pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.contentRatingClearedSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.contentRatingClearedDetail'),
|
||||
life: 2000
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.updateFailedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.clearContentRatingFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
// Shelf Actions
|
||||
if (permissions?.canManageLibrary || permissions?.admin) { // Assuming these permissions cover shelf management for books
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.removeFromAllShelves'),
|
||||
icon: 'pi pi-bookmark-fill', // Or bookmark-slash
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.unshelveMessage', {count}),
|
||||
header: this.t.translate('book.menuService.confirm.unshelveHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.removingFromShelves', {count}));
|
||||
const books = this.bookService.getBooksByIds(Array.from(selectedBooks));
|
||||
const allShelfIds = new Set<number>();
|
||||
books.forEach(b => b.shelves?.forEach(s => {
|
||||
if (s.id) allShelfIds.add(s.id);
|
||||
}));
|
||||
|
||||
if (allShelfIds.size === 0) {
|
||||
this.loadingService.hide(loader);
|
||||
this.messageService.add({ severity: 'info', summary: this.t.translate('common.info'), detail: this.t.translate('book.menuService.toast.noBooksOnShelvesDetail') });
|
||||
return;
|
||||
}
|
||||
|
||||
this.bookService.updateBookShelves(selectedBooks, new Set(), allShelfIds)
|
||||
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.menuService.toast.unshelveSuccessDetail')});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('book.menuService.toast.unshelveFailedDetail')});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkResetGrimmoryReadProgress ?? permissions?.canBulkResetBookloreReadProgress) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.resetGrimmoryProgress'),
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.resetGrimmoryMessage', {count}),
|
||||
header: this.t.translate('book.menuService.confirm.resetHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.resettingGrimmoryProgress', {count}));
|
||||
|
||||
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.GRIMMORY)
|
||||
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.progressResetSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.grimmoryProgressResetDetail'),
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.failedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.progressResetFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (permissions?.canBulkResetKoReaderReadProgress) {
|
||||
items.push({
|
||||
label: this.t.translate('book.menuService.menu.resetKOReaderProgress'),
|
||||
icon: 'pi pi-undo',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.menuService.confirm.resetKOReaderMessage', {count}),
|
||||
header: this.t.translate('book.menuService.confirm.resetHeader'),
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.no'),
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.menuService.loading.resettingKOReaderProgress', {count}));
|
||||
|
||||
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.KOREADER)
|
||||
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.menuService.toast.progressResetSummary'),
|
||||
detail: this.t.translate('book.menuService.toast.koreaderProgressResetDetail'),
|
||||
life: 1500
|
||||
});
|
||||
},
|
||||
error: (err: HttpErrorResponse) => {
|
||||
const apiError = err.error as APIException;
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.menuService.toast.failedSummary'),
|
||||
detail: apiError?.message || this.t.translate('book.menuService.toast.progressResetFailedDetail'),
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, map, tap} from 'rxjs/operators';
|
||||
import {Book, BookMetadata, BulkMetadataUpdateRequest, MetadataUpdateWrapper} from '../model/book.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {invalidateBookQueries, invalidateBooksQuery, patchBookInCacheWith, patchBookMetadataInCache} from './book-query-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookMetadataManageService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean, replaceMode: 'REPLACE_ALL' | 'REPLACE_WHEN_PROVIDED' = 'REPLACE_ALL'): Observable<BookMetadata> {
|
||||
const params = new HttpParams().set('mergeCategories', mergeCategories.toString()).set('replaceMode', replaceMode);
|
||||
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
|
||||
tap(updatedMetadata => {
|
||||
if (bookId != null) {
|
||||
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateBooksMetadata(request: BulkMetadataUpdateRequest): Observable<void> {
|
||||
return this.http.put(`${this.url}/bulk-edit-metadata`, request).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
}),
|
||||
map(() => void 0)
|
||||
);
|
||||
}
|
||||
|
||||
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
|
||||
const requestBody = {
|
||||
bookIds: Array.from(bookIds),
|
||||
lock
|
||||
};
|
||||
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
|
||||
tap(updatedMetadataList => {
|
||||
updatedMetadataList.forEach(metadata => {
|
||||
if (metadata.bookId != null) {
|
||||
patchBookMetadataInCache(this.queryClient, metadata.bookId, metadata);
|
||||
}
|
||||
});
|
||||
}),
|
||||
map(() => void 0),
|
||||
catchError((error) => {
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
|
||||
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
|
||||
|
||||
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, {
|
||||
bookIds: Array.from(bookIdSet),
|
||||
fieldActions
|
||||
}).pipe(
|
||||
tap(() => {
|
||||
for (const bookId of bookIdSet) {
|
||||
patchBookInCacheWith(this.queryClient, bookId, book => {
|
||||
if (!book.metadata) return book;
|
||||
const updatedMetadata = {...book.metadata} as Record<string, unknown>;
|
||||
for (const [field, action] of Object.entries(fieldActions)) {
|
||||
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
|
||||
if (lockField in updatedMetadata) {
|
||||
updatedMetadata[lockField] = action === 'LOCK';
|
||||
}
|
||||
}
|
||||
return {...book, metadata: updatedMetadata as BookMetadata};
|
||||
});
|
||||
}
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.fieldLockFailedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.fieldLockFailedDetail'),
|
||||
});
|
||||
throw error;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<unknown> {
|
||||
return this.http.post(`${this.url}/metadata/manage/consolidate`, {metadataType, targetValues, valuesToMerge}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<unknown> {
|
||||
return this.http.post(`${this.url}/metadata/manage/delete`, {metadataType, valuesToDelete}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getUploadCoverUrl(bookId: number): string {
|
||||
return this.url + '/' + bookId + '/metadata/cover/upload';
|
||||
}
|
||||
|
||||
uploadCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
|
||||
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/cover/from-url`, {url}).pipe(
|
||||
tap(updatedMetadata => {
|
||||
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
regenerateCovers(missingOnly = false): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/regenerate-covers?missingOnly=${missingOnly}`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
regenerateCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getFileMetadata(bookId: number): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/${bookId}/file-metadata`);
|
||||
}
|
||||
|
||||
generateCustomCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
generateCustomCoversForBooks(bookIds: number[]): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/bulk-generate-custom-covers`, {bookIds}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
regenerateCoversForBooks(bookIds: number[]): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/bulk-regenerate-covers`, {bookIds}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
uploadAudiobookCoverFromUrl(bookId: number, url: string): Observable<BookMetadata> {
|
||||
return this.http.post<BookMetadata>(`${this.url}/${bookId}/metadata/audiobook-cover/from-url`, {url}).pipe(
|
||||
tap(updatedMetadata => {
|
||||
patchBookMetadataInCache(this.queryClient, bookId, updatedMetadata);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
uploadAudiobookCoverFromFile(bookId: number, file: File): Observable<void> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
return this.http.post<void>(`${this.url}/${bookId}/metadata/audiobook-cover/upload`, formData).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getUploadAudiobookCoverUrl(bookId: number): string {
|
||||
return this.url + '/' + bookId + '/metadata/audiobook-cover/upload';
|
||||
}
|
||||
|
||||
regenerateAudiobookCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/regenerate-audiobook-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
generateCustomAudiobookCover(bookId: number): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${bookId}/generate-custom-audiobook-cover`, {}).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, [bookId]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
supportsDualCovers(book: Book): boolean {
|
||||
const allFiles = [book.primaryFile, ...(book.alternativeFormats || [])].filter(f => f?.bookType);
|
||||
const hasAudiobook = allFiles.some(f => f!.bookType === 'AUDIOBOOK');
|
||||
const hasEbook = allFiles.some(f => f!.bookType !== 'AUDIOBOOK');
|
||||
return hasAudiobook && hasEbook;
|
||||
}
|
||||
|
||||
bulkUploadCover(bookIds: number[], file: File): Observable<void> {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('bookIds', bookIds.join(','));
|
||||
return this.http.post<void>(`${this.url}/bulk-upload-cover`, formData).pipe(
|
||||
tap(() => {
|
||||
invalidateBookQueries(this.queryClient, bookIds);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
|
||||
import {BookMetadata} from '../model/book.model';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {SseClient} from 'ngx-sse-client';
|
||||
import {HttpClient, HttpHeaders} from '@angular/common/http';
|
||||
import {map} from 'rxjs/operators';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class BookMetadataService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
private http = inject(HttpClient);
|
||||
private authService = inject(AuthService);
|
||||
private sseClient = inject(SseClient);
|
||||
|
||||
fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable<BookMetadata> {
|
||||
const token = this.authService.getInternalAccessToken();
|
||||
|
||||
if (!token) {
|
||||
throw new Error('No authentication token available');
|
||||
}
|
||||
|
||||
const headers = new HttpHeaders()
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
return this.sseClient.stream(
|
||||
`${this.url}/${bookId}/metadata/prospective`,
|
||||
{
|
||||
keepAlive: false,
|
||||
reconnectionDelay: 1000,
|
||||
responseType: 'event'
|
||||
},
|
||||
{
|
||||
headers,
|
||||
body: request,
|
||||
withCredentials: true
|
||||
},
|
||||
'POST'
|
||||
).pipe(
|
||||
map((event) => {
|
||||
if (event.type === 'error') {
|
||||
const errorEvent = event as ErrorEvent;
|
||||
throw new Error(errorEvent.message);
|
||||
} else {
|
||||
const messageEvent = event as MessageEvent;
|
||||
return JSON.parse(messageEvent.data) as BookMetadata;
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fetchMetadataDetail(provider: string, providerItemId: string): Observable<BookMetadata> {
|
||||
return this.http.get<BookMetadata>(`${this.url}/metadata/detail/${provider}/${providerItemId}`);
|
||||
}
|
||||
|
||||
lookupByIsbn(isbn: string): Observable<BookMetadata> {
|
||||
return this.http.post<BookMetadata>(`${this.url}/metadata/isbn-lookup`, {isbn});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import {computed, Injectable, signal} from '@angular/core';
|
||||
|
||||
export interface BookNavigationState {
|
||||
bookIds: number[];
|
||||
currentIndex: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookNavigationService {
|
||||
private readonly _navigationState = signal<BookNavigationState | null>(null);
|
||||
readonly navigationState = this._navigationState.asReadonly();
|
||||
|
||||
private readonly _availableBookIds = signal<number[]>([]);
|
||||
readonly availableBookIds = this._availableBookIds.asReadonly();
|
||||
|
||||
readonly canNavigatePrevious = computed(() => {
|
||||
const state = this.navigationState();
|
||||
return state !== null && state.currentIndex > 0;
|
||||
});
|
||||
|
||||
readonly canNavigateNext = computed(() => {
|
||||
const state = this.navigationState();
|
||||
return state !== null && state.currentIndex < state.bookIds.length - 1;
|
||||
});
|
||||
|
||||
readonly previousBookId = computed<number | null>(() => {
|
||||
const state = this.navigationState();
|
||||
return state && state.currentIndex > 0
|
||||
? state.bookIds[state.currentIndex - 1]
|
||||
: null;
|
||||
});
|
||||
|
||||
readonly nextBookId = computed<number | null>(() => {
|
||||
const state = this.navigationState();
|
||||
return state && state.currentIndex < state.bookIds.length - 1
|
||||
? state.bookIds[state.currentIndex + 1]
|
||||
: null;
|
||||
});
|
||||
|
||||
readonly currentPosition = computed<{ current: number; total: number } | null>(() => {
|
||||
const state = this.navigationState();
|
||||
return state
|
||||
? {
|
||||
current: state.currentIndex + 1,
|
||||
total: state.bookIds.length
|
||||
}
|
||||
: null;
|
||||
});
|
||||
|
||||
setAvailableBookIds(bookIds: number[]): void {
|
||||
this._availableBookIds.set(bookIds);
|
||||
}
|
||||
|
||||
setNavigationContext(bookIds: number[], currentBookId: number): void {
|
||||
const currentIndex = bookIds.indexOf(currentBookId);
|
||||
if (currentIndex !== -1) {
|
||||
this._navigationState.set({bookIds, currentIndex});
|
||||
} else {
|
||||
this._navigationState.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
updateCurrentBook(bookId: number): void {
|
||||
const state = this.navigationState();
|
||||
if (state) {
|
||||
const newIndex = state.bookIds.indexOf(bookId);
|
||||
if (newIndex !== -1) {
|
||||
this._navigationState.set({
|
||||
...state,
|
||||
currentIndex: newIndex
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
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 {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
|
||||
import {BookStatusUpdateResponse, PersonalRatingUpdateResponse} from '../model/book.model';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {
|
||||
patchBooksInCache,
|
||||
patchBookFieldsInCache,
|
||||
} from './book-query-cache';
|
||||
|
||||
function getResetProgressFields(type: ResetProgressType): Partial<Book> {
|
||||
if (type === ResetProgressTypes.KOREADER) {
|
||||
return {koreaderProgress: undefined};
|
||||
}
|
||||
|
||||
if (type === ResetProgressTypes.KOBO) {
|
||||
return {koboProgress: undefined};
|
||||
}
|
||||
|
||||
return {
|
||||
epubProgress: undefined,
|
||||
pdfProgress: undefined,
|
||||
cbxProgress: undefined,
|
||||
audiobookProgress: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookPatchService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
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: {
|
||||
bookId: number;
|
||||
epubProgress: {
|
||||
cfi: string;
|
||||
href: string;
|
||||
percentage: number;
|
||||
};
|
||||
fileProgress?: {
|
||||
bookFileId: number;
|
||||
positionData: string;
|
||||
positionHref: string;
|
||||
progressPercent: number;
|
||||
};
|
||||
} = {
|
||||
bookId: payload.bookId,
|
||||
epubProgress: {
|
||||
cfi: payload.cfi,
|
||||
href: payload.href,
|
||||
percentage: payload.percentage
|
||||
}
|
||||
};
|
||||
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 => {
|
||||
patchBooksInCache(this.queryClient, updatedBooks);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
const body: {
|
||||
bookId: number;
|
||||
pdfProgress: {
|
||||
page: number;
|
||||
percentage: number;
|
||||
};
|
||||
fileProgress?: {
|
||||
bookFileId: number;
|
||||
positionData: string;
|
||||
progressPercent: number;
|
||||
};
|
||||
} = {
|
||||
bookId,
|
||||
pdfProgress: {
|
||||
page,
|
||||
percentage
|
||||
}
|
||||
};
|
||||
if (bookFileId) {
|
||||
body.fileProgress = {
|
||||
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: {
|
||||
bookId: number;
|
||||
cbxProgress: {
|
||||
page: number;
|
||||
percentage: number;
|
||||
};
|
||||
fileProgress?: {
|
||||
bookFileId: number;
|
||||
positionData: string;
|
||||
progressPercent: number;
|
||||
};
|
||||
} = {
|
||||
bookId,
|
||||
cbxProgress: {
|
||||
page,
|
||||
percentage
|
||||
}
|
||||
};
|
||||
if (bookFileId) {
|
||||
body.fileProgress = {
|
||||
bookFileId,
|
||||
positionData: String(page),
|
||||
progressPercent: percentage
|
||||
};
|
||||
}
|
||||
return this.http.post<void>(`${this.url}/progress`, body);
|
||||
}
|
||||
|
||||
saveFileProgress(bookId: number, fileProgress: BookFileProgress): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/progress`, {
|
||||
bookId,
|
||||
fileProgress
|
||||
});
|
||||
}
|
||||
|
||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/progress`, {
|
||||
bookId,
|
||||
dateFinished
|
||||
}).pipe(
|
||||
tap(() => {
|
||||
patchBookFieldsInCache(this.queryClient, [{bookId, fields: {dateFinished: dateFinished || undefined}}]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<BookStatusUpdateResponse[]> {
|
||||
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
|
||||
const params = new HttpParams().set('type', type);
|
||||
|
||||
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
|
||||
tap(responses => {
|
||||
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||
bookId: r.bookId,
|
||||
fields: {
|
||||
...getResetProgressFields(type),
|
||||
readStatus: r.readStatus,
|
||||
readStatusModifiedTime: r.readStatusModifiedTime,
|
||||
dateFinished: r.dateFinished
|
||||
}
|
||||
})));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
|
||||
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
|
||||
|
||||
return this.http.post<BookStatusUpdateResponse[]>(`${this.url}/status`, {
|
||||
bookIds: ids,
|
||||
status
|
||||
}).pipe(
|
||||
tap(responses => {
|
||||
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||
bookId: r.bookId,
|
||||
fields: {readStatus: r.readStatus, readStatusModifiedTime: r.readStatusModifiedTime, dateFinished: r.dateFinished}
|
||||
})));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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 => {
|
||||
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||
bookId: r.bookId,
|
||||
fields: {personalRating: r.personalRating}
|
||||
})));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
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 => {
|
||||
patchBookFieldsInCache(this.queryClient, responses.map(r => ({
|
||||
bookId: r.bookId,
|
||||
fields: {personalRating: r.personalRating}
|
||||
})));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLastReadTime(bookId: number): void {
|
||||
const timestamp = new Date().toISOString();
|
||||
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book =>
|
||||
book.id === bookId ? {...book, lastReadTime: timestamp} : book
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Book} from '../model/book.model';
|
||||
import {
|
||||
addBookToCache,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
removeBooksFromCache
|
||||
} from './book-query-cache';
|
||||
import {
|
||||
BOOKS_QUERY_KEY,
|
||||
bookDetailQueryKey,
|
||||
bookDetailQueryPrefix,
|
||||
bookRecommendationsQueryKey
|
||||
} from './book-query-keys';
|
||||
|
||||
function makeBook(id: number, overrides: Partial<Book> = {}): Book {
|
||||
return {
|
||||
id,
|
||||
libraryId: 1,
|
||||
libraryName: 'Test Library',
|
||||
metadata: {
|
||||
bookId: id,
|
||||
title: `Book ${id}`
|
||||
},
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
describe('book-query-cache', () => {
|
||||
let queryClient: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient();
|
||||
});
|
||||
|
||||
it('adds new books and replaces existing entries by id', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
const updatedSecondBook = makeBook(2, {
|
||||
libraryName: 'Updated Library',
|
||||
metadata: {
|
||||
bookId: 2,
|
||||
title: 'Updated Book 2'
|
||||
}
|
||||
});
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook]);
|
||||
|
||||
addBookToCache(queryClient, secondBook);
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, secondBook]);
|
||||
|
||||
addBookToCache(queryClient, updatedSecondBook);
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
|
||||
});
|
||||
|
||||
it('patches list entries and invalidates matching detail queries', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
const updatedSecondBook = makeBook(2, {
|
||||
libraryName: 'Updated Library'
|
||||
});
|
||||
const invalidateQueriesSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
|
||||
|
||||
patchBooksInCache(queryClient, [updatedSecondBook]);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([firstBook, updatedSecondBook]);
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledWith({queryKey: bookDetailQueryPrefix(2)});
|
||||
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('removes detail and recommendation queries for deleted books', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, true), firstBook);
|
||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
|
||||
queryClient.setQueryData(bookDetailQueryKey(2, false), secondBook);
|
||||
|
||||
removeBookQueries(queryClient, [1]);
|
||||
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, true))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(2, false))).toEqual(secondBook);
|
||||
});
|
||||
|
||||
it('removes deleted books from the list cache and associated queries', () => {
|
||||
const firstBook = makeBook(1);
|
||||
const secondBook = makeBook(2);
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, [firstBook, secondBook]);
|
||||
queryClient.setQueryData(bookDetailQueryKey(1, false), firstBook);
|
||||
queryClient.setQueryData(bookRecommendationsQueryKey(1, 20), [secondBook]);
|
||||
|
||||
removeBooksFromCache(queryClient, [1]);
|
||||
|
||||
expect(queryClient.getQueryData<Book[]>(BOOKS_QUERY_KEY)).toEqual([secondBook]);
|
||||
expect(queryClient.getQueryData(bookDetailQueryKey(1, false))).toBeUndefined();
|
||||
expect(queryClient.getQueryData(bookRecommendationsQueryKey(1, 20))).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Book, BookMetadata} from '../model/book.model';
|
||||
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
|
||||
|
||||
// --- Full invalidation (refetches from server) ---
|
||||
|
||||
export function invalidateBooksQuery(queryClient: QueryClient): void {
|
||||
void queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
}
|
||||
|
||||
export function invalidateBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
invalidateBooksQuery(queryClient);
|
||||
invalidateBookDetailQueries(queryClient, bookIds);
|
||||
}
|
||||
|
||||
export function invalidateBookDetailQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
for (const bookId of new Set(bookIds)) {
|
||||
void queryClient.invalidateQueries({queryKey: bookDetailQueryPrefix(bookId)});
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBookQueries(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
for (const bookId of new Set(bookIds)) {
|
||||
queryClient.removeQueries({queryKey: bookDetailQueryPrefix(bookId)});
|
||||
queryClient.removeQueries({queryKey: bookRecommendationsQueryPrefix(bookId)});
|
||||
}
|
||||
}
|
||||
|
||||
export function removeBooksFromCache(queryClient: QueryClient, bookIds: Iterable<number>): void {
|
||||
const removedIds = new Set(bookIds);
|
||||
if (removedIds.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).filter(book => !removedIds.has(book.id))
|
||||
);
|
||||
removeBookQueries(queryClient, removedIds);
|
||||
}
|
||||
|
||||
// --- Surgical patches (updates cache directly, no list refetch) ---
|
||||
|
||||
export function addBookToCache(queryClient: QueryClient, book: Book): void {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current => {
|
||||
const books = current ?? [];
|
||||
const exists = books.some(b => b.id === book.id);
|
||||
return exists ? books.map(b => b.id === book.id ? book : b) : [...books, book];
|
||||
});
|
||||
}
|
||||
|
||||
export function patchBooksInCache(queryClient: QueryClient, updatedBooks: Book[]): void {
|
||||
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => updatedMap.get(book.id) ?? book)
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, updatedBooks.map(b => b.id));
|
||||
}
|
||||
|
||||
export function patchBookMetadataInCache(queryClient: QueryClient, bookId: number, metadata: BookMetadata): void {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book =>
|
||||
book.id === bookId ? {...book, metadata} : book
|
||||
)
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, [bookId]);
|
||||
}
|
||||
|
||||
export function patchBookInCacheWith(queryClient: QueryClient, bookId: number, updater: (book: Book) => Book): void {
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => book.id === bookId ? updater(book) : book)
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, [bookId]);
|
||||
}
|
||||
|
||||
export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookId: number; fields: Partial<Book>}[]): void {
|
||||
const updateMap = new Map(updates.map(u => [u.bookId, u.fields]));
|
||||
queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => {
|
||||
const fields = updateMap.get(book.id);
|
||||
return fields ? {...book, ...fields} : book;
|
||||
})
|
||||
);
|
||||
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export const BOOKS_QUERY_KEY = ['books'] as const;
|
||||
|
||||
export const bookDetailQueryKey = (bookId: number, withDescription: boolean) =>
|
||||
['books', 'detail', bookId, withDescription] as const;
|
||||
|
||||
export const bookDetailQueryPrefix = (bookId: number) =>
|
||||
['books', 'detail', bookId] as const;
|
||||
|
||||
export const bookRecommendationsQueryKey = (bookId: number, limit: number) =>
|
||||
['books', 'recommendations', bookId, limit] as const;
|
||||
|
||||
export const bookRecommendationsQueryPrefix = (bookId: number) =>
|
||||
['books', 'recommendations', bookId] as const;
|
||||
@@ -0,0 +1,54 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {Book} from '../model/book.model';
|
||||
import {QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {
|
||||
addBookToCache,
|
||||
invalidateBookDetailQueries,
|
||||
invalidateBooksQuery,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
} from './book-query-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookSocketService {
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
handleNewlyCreatedBook(book: Book): void {
|
||||
addBookToCache(this.queryClient, book);
|
||||
}
|
||||
|
||||
handleRemovedBookIds(removedBookIds: number[]): void {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
removeBookQueries(this.queryClient, removedBookIds);
|
||||
}
|
||||
|
||||
handleBookUpdate(updatedBook: Book): void {
|
||||
patchBooksInCache(this.queryClient, [updatedBook]);
|
||||
}
|
||||
|
||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
||||
patchBooksInCache(this.queryClient, updatedBooks);
|
||||
}
|
||||
|
||||
handleBookMetadataUpdate(bookId: number): void {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
invalidateBookDetailQueries(this.queryClient, [bookId]);
|
||||
}
|
||||
|
||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
||||
if (!patches || patches.length === 0) return;
|
||||
const patchMap = new Map(patches.map(p => [p.id, p.coverUpdatedOn]));
|
||||
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => {
|
||||
const coverUpdatedOn = patchMap.get(book.id);
|
||||
return coverUpdatedOn && book.metadata
|
||||
? {...book, metadata: {...book.metadata, coverUpdatedOn}}
|
||||
: book;
|
||||
})
|
||||
);
|
||||
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {first, from, lastValueFrom, Observable, throwError} from 'rxjs';
|
||||
import {HttpClient, HttpParams} from '@angular/common/http';
|
||||
import {catchError, map, tap} from 'rxjs/operators';
|
||||
import {Book, BookDeletionResponse, BookRecommendation, BookSetting, BookStatusUpdateResponse, BookType, CreatePhysicalBookRequest, PersonalRatingUpdateResponse, ReadStatus} from '../model/book.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {ResetProgressType} from '../../../shared/constants/reset-progress-type';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {BookSocketService} from './book-socket.service';
|
||||
import {BookPatchService} from './book-patch.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
import {
|
||||
BOOKS_QUERY_KEY,
|
||||
bookDetailQueryKey,
|
||||
bookRecommendationsQueryKey,
|
||||
} from './book-query-keys';
|
||||
import {
|
||||
invalidateBooksQuery,
|
||||
patchBooksInCache,
|
||||
removeBookQueries,
|
||||
} from './book-query-cache';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BookService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`;
|
||||
|
||||
private http = inject(HttpClient);
|
||||
private messageService = inject(MessageService);
|
||||
private authService = inject(AuthService);
|
||||
private router = inject(Router);
|
||||
private bookSocketService = inject(BookSocketService);
|
||||
private bookPatchService = inject(BookPatchService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly t = inject(TranslocoService);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private booksQuery = injectQuery(() => ({
|
||||
...this.getBooksQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
books = computed(() => this.booksQuery.data() ?? []);
|
||||
|
||||
/** Pre-computed unique metadata values for autocomplete across the app. */
|
||||
readonly uniqueMetadata = computed(() => {
|
||||
const books = this.books();
|
||||
const authors = new Set<string>();
|
||||
const categories = new Set<string>();
|
||||
const moods = new Set<string>();
|
||||
const tags = new Set<string>();
|
||||
const publishers = new Set<string>();
|
||||
const series = new Set<string>();
|
||||
|
||||
for (const book of books) {
|
||||
const m = book.metadata;
|
||||
if (!m) continue;
|
||||
m.authors?.forEach(v => authors.add(v));
|
||||
m.categories?.forEach(v => categories.add(v));
|
||||
m.moods?.forEach(v => moods.add(v));
|
||||
m.tags?.forEach(v => tags.add(v));
|
||||
if (m.publisher) publishers.add(m.publisher);
|
||||
if (m.seriesName) series.add(m.seriesName);
|
||||
}
|
||||
|
||||
return {
|
||||
authors: Array.from(authors),
|
||||
categories: Array.from(categories),
|
||||
moods: Array.from(moods),
|
||||
tags: Array.from(tags),
|
||||
publishers: Array.from(publishers),
|
||||
series: Array.from(series),
|
||||
};
|
||||
});
|
||||
|
||||
booksError = computed<string | null>(() => {
|
||||
if (!this.token() || !this.booksQuery.isError()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const error = this.booksQuery.error();
|
||||
return error instanceof Error ? error.message : 'Failed to load books';
|
||||
});
|
||||
|
||||
isBooksLoading = computed(() => !!this.token() && this.booksQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: BOOKS_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getBooksQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: BOOKS_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Book[]>(this.url))
|
||||
});
|
||||
}
|
||||
|
||||
bookDetailQueryOptions(bookId: number, withDescription: boolean) {
|
||||
return queryOptions({
|
||||
queryKey: bookDetailQueryKey(bookId, withDescription),
|
||||
queryFn: () => lastValueFrom(this.http.get<Book>(`${this.url}/${bookId}`, {
|
||||
params: {
|
||||
withDescription: withDescription.toString()
|
||||
}
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
ensureBookDetail(bookId: number, withDescription: boolean): Promise<Book> {
|
||||
return this.queryClient.ensureQueryData(this.bookDetailQueryOptions(bookId, withDescription));
|
||||
}
|
||||
|
||||
private getBookRecommendationsQueryOptions(bookId: number, limit: number) {
|
||||
return queryOptions({
|
||||
queryKey: bookRecommendationsQueryKey(bookId, limit),
|
||||
queryFn: () => lastValueFrom(this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
|
||||
params: {limit: limit.toString()}
|
||||
}))
|
||||
});
|
||||
}
|
||||
|
||||
removeBooksFromShelf(shelfId: number): void {
|
||||
this.queryClient.setQueryData<Book[]>(BOOKS_QUERY_KEY, current =>
|
||||
(current ?? []).map(book => ({
|
||||
...book,
|
||||
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
/*------------------ Book Retrieval ------------------*/
|
||||
|
||||
findBookById(bookId: number): Book | undefined {
|
||||
return this.books().find(book => +book.id === +bookId);
|
||||
}
|
||||
|
||||
getBooksByIds(bookIds: number[]): Book[] {
|
||||
if (bookIds.length === 0) return [];
|
||||
const idSet = new Set(bookIds.map(id => +id));
|
||||
return this.books().filter(book => idSet.has(+book.id));
|
||||
}
|
||||
|
||||
getBooksInSeries(bookId: number): Observable<Book[]> {
|
||||
return from(this.queryClient.ensureQueryData(this.getBooksQueryOptions())).pipe(
|
||||
map(books => {
|
||||
const currentBook = books.find(book => book.id === bookId);
|
||||
if (!currentBook?.metadata?.seriesName) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const seriesName = currentBook.metadata.seriesName.toLowerCase();
|
||||
return books.filter(book => book.metadata?.seriesName?.toLowerCase() === seriesName);
|
||||
}),
|
||||
first()
|
||||
);
|
||||
}
|
||||
|
||||
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
|
||||
return from(this.queryClient.ensureQueryData(this.getBookRecommendationsQueryOptions(bookId, limit)));
|
||||
}
|
||||
|
||||
/*------------------ Book Operations ------------------*/
|
||||
|
||||
deleteBooks(ids: Set<number>): Observable<BookDeletionResponse> {
|
||||
const idList = Array.from(ids);
|
||||
const params = new HttpParams().set('ids', idList.join(','));
|
||||
|
||||
return this.http.delete<BookDeletionResponse>(this.url, {params}).pipe(
|
||||
tap(response => {
|
||||
const deletedIds = response.deleted.length > 0 ? response.deleted : idList;
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
removeBookQueries(this.queryClient, deletedIds);
|
||||
|
||||
if (response.failedFileDeletions?.length > 0) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: this.t.translate('book.bookService.toast.someFilesNotDeletedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.someFilesNotDeletedDetail', {fileNames: response.failedFileDeletions.join(', ')}),
|
||||
});
|
||||
} else {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.booksDeletedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.booksDeletedDetail', {count: idList.length}),
|
||||
});
|
||||
}
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.deleteFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.deleteFailedDetail'),
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
|
||||
return this.bookPatchService.updateBookShelves(bookIds, shelvesToAssign, shelvesToUnassign);
|
||||
}
|
||||
|
||||
createPhysicalBook(request: CreatePhysicalBookRequest): Observable<Book> {
|
||||
return this.http.post<Book>(`${this.url}/physical`, request).pipe(
|
||||
tap(newBook => {
|
||||
invalidateBooksQuery(this.queryClient);
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: this.t.translate('book.bookService.toast.physicalBookCreatedSummary'),
|
||||
detail: this.t.translate('book.bookService.toast.physicalBookCreatedDetail', {title: newBook.metadata?.title || 'Book'})
|
||||
});
|
||||
}),
|
||||
catchError(error => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.bookService.toast.creationFailedSummary'),
|
||||
detail: error?.error?.message || error?.message || this.t.translate('book.bookService.toast.creationFailedDetail')
|
||||
});
|
||||
return throwError(() => error);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
togglePhysicalFlag(bookId: number, physical: boolean): Observable<Book> {
|
||||
return this.http.patch<Book>(`${this.url}/${bookId}/physical`, null, {params: {physical}}).pipe(
|
||||
tap(updatedBook => {
|
||||
patchBooksInCache(this.queryClient, [updatedBook]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/*------------------ Reading & Viewer Settings ------------------*/
|
||||
|
||||
readBook(bookId: number, reader?: 'epub-streaming', explicitBookType?: BookType): void {
|
||||
const book = this.findBookById(bookId);
|
||||
|
||||
if (!book) {
|
||||
console.error('Book not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const bookType: BookType | undefined = explicitBookType ?? book.primaryFile?.bookType;
|
||||
const isAlternativeFormat = explicitBookType && explicitBookType !== book.primaryFile?.bookType;
|
||||
|
||||
let baseUrl: string | null = null;
|
||||
const queryParams: Partial<{streaming: true; bookType: BookType}> = {};
|
||||
|
||||
switch (bookType) {
|
||||
case 'PDF':
|
||||
baseUrl = 'pdf-reader';
|
||||
break;
|
||||
|
||||
case 'EPUB':
|
||||
baseUrl = 'ebook-reader';
|
||||
if (reader === 'epub-streaming') {
|
||||
queryParams['streaming'] = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'FB2':
|
||||
case 'MOBI':
|
||||
case 'AZW3':
|
||||
baseUrl = 'ebook-reader';
|
||||
break;
|
||||
|
||||
case 'CBX':
|
||||
baseUrl = 'cbx-reader';
|
||||
break;
|
||||
|
||||
case 'AUDIOBOOK':
|
||||
baseUrl = 'audiobook-player';
|
||||
break;
|
||||
}
|
||||
|
||||
if (!baseUrl) {
|
||||
console.error('Unsupported book type:', bookType);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAlternativeFormat) {
|
||||
queryParams['bookType'] = bookType;
|
||||
}
|
||||
|
||||
const hasQueryParams = Object.keys(queryParams).length > 0;
|
||||
this.router.navigate([`/${baseUrl}/book/${book.id}`], hasQueryParams ? {queryParams} : undefined);
|
||||
|
||||
this.updateLastReadTime(book.id);
|
||||
}
|
||||
|
||||
getBookSetting(bookId: number, bookFileId: number): Observable<BookSetting> {
|
||||
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting?bookFileId=${bookFileId}`);
|
||||
}
|
||||
|
||||
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, bookSetting);
|
||||
}
|
||||
|
||||
/*------------------ Progress & Status Tracking ------------------*/
|
||||
|
||||
updateLastReadTime(bookId: number): void {
|
||||
this.bookPatchService.updateLastReadTime(bookId);
|
||||
}
|
||||
|
||||
savePdfProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
return this.bookPatchService.savePdfProgress(bookId, page, percentage, bookFileId);
|
||||
}
|
||||
|
||||
saveCbxProgress(bookId: number, page: number, percentage: number, bookFileId?: number): Observable<void> {
|
||||
return this.bookPatchService.saveCbxProgress(bookId, page, percentage, bookFileId);
|
||||
}
|
||||
|
||||
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
|
||||
return this.bookPatchService.updateDateFinished(bookId, dateFinished);
|
||||
}
|
||||
|
||||
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<BookStatusUpdateResponse[]> {
|
||||
return this.bookPatchService.resetProgress(bookIds, type);
|
||||
}
|
||||
|
||||
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<BookStatusUpdateResponse[]> {
|
||||
return this.bookPatchService.updateBookReadStatus(bookIds, status);
|
||||
}
|
||||
|
||||
/*------------------ Personal Rating ------------------*/
|
||||
|
||||
resetPersonalRating(bookIds: number | number[]): Observable<PersonalRatingUpdateResponse[]> {
|
||||
return this.bookPatchService.resetPersonalRating(bookIds);
|
||||
}
|
||||
|
||||
updatePersonalRating(bookIds: number | number[], rating: number): Observable<PersonalRatingUpdateResponse[]> {
|
||||
return this.bookPatchService.updatePersonalRating(bookIds, rating);
|
||||
}
|
||||
|
||||
/*------------------ Websocket Handlers ------------------*/
|
||||
|
||||
handleNewlyCreatedBook(book: Book): void {
|
||||
this.bookSocketService.handleNewlyCreatedBook(book);
|
||||
}
|
||||
|
||||
handleRemovedBookIds(removedBookIds: number[]): void {
|
||||
this.bookSocketService.handleRemovedBookIds(removedBookIds);
|
||||
}
|
||||
|
||||
handleBookUpdate(updatedBook: Book): void {
|
||||
this.bookSocketService.handleBookUpdate(updatedBook);
|
||||
}
|
||||
|
||||
handleMultipleBookUpdates(updatedBooks: Book[]): void {
|
||||
this.bookSocketService.handleMultipleBookUpdates(updatedBooks);
|
||||
}
|
||||
|
||||
handleBookMetadataUpdate(bookId: number): void {
|
||||
this.bookSocketService.handleBookMetadataUpdate(bookId);
|
||||
}
|
||||
|
||||
handleMultipleBookCoverPatches(patches: { id: number; coverUpdatedOn: string }[]): void {
|
||||
this.bookSocketService.handleMultipleBookCoverPatches(patches);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Injectable, inject} from '@angular/core';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
export interface CbxPageInfo {
|
||||
pageNumber: number;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class CbxReaderService {
|
||||
|
||||
private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/cbx`;
|
||||
private readonly imageUrl = `${API_CONFIG.BASE_URL}/api/v1/media/book`;
|
||||
private authService = inject(AuthService);
|
||||
private http = inject(HttpClient);
|
||||
|
||||
private getToken(): string | null {
|
||||
return this.authService.getInternalAccessToken();
|
||||
}
|
||||
|
||||
private appendToken(url: string): string {
|
||||
const token = this.getToken();
|
||||
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
|
||||
}
|
||||
|
||||
getAvailablePages(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/pages`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<number[]>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageInfo(bookId: number, bookType?: string) {
|
||||
let url = `${this.pagesUrl}/${bookId}/page-info`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.http.get<CbxPageInfo[]>(this.appendToken(url));
|
||||
}
|
||||
|
||||
getPageImageUrl(bookId: number, page: number, bookType?: string): string {
|
||||
let url = `${this.imageUrl}/${bookId}/cbx/pages/${page}`;
|
||||
if (bookType) {
|
||||
url += `?bookType=${bookType}`;
|
||||
}
|
||||
return this.appendToken(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {of, Subject} from 'rxjs';
|
||||
import {IMessage} from '@stomp/rx-stomp';
|
||||
import {provideTanStackQuery, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {LibraryHealthService} from './library-health.service';
|
||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||
|
||||
describe('LibraryHealthService', () => {
|
||||
let service: LibraryHealthService;
|
||||
let queryClient: QueryClient;
|
||||
let httpGetSpy: ReturnType<typeof vi.fn>;
|
||||
let wsSubject: Subject<IMessage>;
|
||||
|
||||
beforeEach(() => {
|
||||
httpGetSpy = vi.fn().mockReturnValue(of({}));
|
||||
wsSubject = new Subject<IMessage>();
|
||||
queryClient = new QueryClient();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideTanStackQuery(queryClient),
|
||||
LibraryHealthService,
|
||||
{provide: HttpClient, useValue: {get: httpGetSpy}},
|
||||
{provide: RxStompService, useValue: {watch: vi.fn(() => wsSubject.asObservable())}},
|
||||
]
|
||||
});
|
||||
|
||||
service = TestBed.inject(LibraryHealthService);
|
||||
});
|
||||
|
||||
async function initializeService(): Promise<void> {
|
||||
const fetchQuerySpy = vi.spyOn(queryClient, 'fetchQuery');
|
||||
service.initialize();
|
||||
await fetchQuerySpy.mock.results[0]?.value;
|
||||
}
|
||||
|
||||
it('fetches initial health on initialize', async () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||
|
||||
await initializeService();
|
||||
|
||||
expect(httpGetSpy).toHaveBeenCalledOnce();
|
||||
expect(service.health()).toEqual({1: true, 2: false});
|
||||
});
|
||||
|
||||
it('reports unhealthy for a library with false health', async () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true, 2: false}));
|
||||
|
||||
await initializeService();
|
||||
|
||||
expect(service.isUnhealthy(2)).toBe(true);
|
||||
});
|
||||
|
||||
it('reports healthy for a library with true health', async () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true}));
|
||||
|
||||
await initializeService();
|
||||
|
||||
expect(service.isUnhealthy(1)).toBe(false);
|
||||
});
|
||||
|
||||
it('reports false for an unknown library', async () => {
|
||||
httpGetSpy.mockReturnValue(of({}));
|
||||
|
||||
await initializeService();
|
||||
|
||||
expect(service.isUnhealthy(99)).toBe(false);
|
||||
});
|
||||
|
||||
it('updates state from websocket messages', async () => {
|
||||
httpGetSpy.mockReturnValue(of({1: true}));
|
||||
|
||||
await initializeService();
|
||||
wsSubject.next({body: JSON.stringify({libraryHealth: {1: false}})} as IMessage);
|
||||
|
||||
expect(service.isUnhealthy(1)).toBe(true);
|
||||
expect(service.health()).toEqual({1: false});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import {computed, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {lastValueFrom} from 'rxjs';
|
||||
import {RxStompService} from '../../../shared/websocket/rx-stomp.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
const LIBRARY_HEALTH_QUERY_KEY = ['libraryHealth'] as const;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryHealthService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries/health`;
|
||||
private http = inject(HttpClient);
|
||||
private rxStompService = inject(RxStompService);
|
||||
private queryClient = inject(QueryClient);
|
||||
|
||||
private healthQuery = injectQuery(() => ({
|
||||
...this.getHealthQueryOptions(),
|
||||
enabled: false, // manually triggered via initialize()
|
||||
}));
|
||||
|
||||
health = computed(() => this.healthQuery.data() ?? {});
|
||||
|
||||
private getHealthQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: LIBRARY_HEALTH_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Record<number, boolean>>(this.url))
|
||||
});
|
||||
}
|
||||
|
||||
initialize(): void {
|
||||
void this.queryClient.fetchQuery(this.getHealthQueryOptions());
|
||||
|
||||
this.rxStompService.watch('/topic/library-health').subscribe(msg => {
|
||||
const payload = JSON.parse(msg.body);
|
||||
this.queryClient.setQueryData(LIBRARY_HEALTH_QUERY_KEY, payload.libraryHealth);
|
||||
});
|
||||
}
|
||||
|
||||
isUnhealthy(libraryId: number): boolean {
|
||||
return this.health()[libraryId] === false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export const LIBRARIES_QUERY_KEY = ['libraries'] as const;
|
||||
|
||||
export const libraryFormatCountsQueryKey = (libraryId: number) =>
|
||||
['libraries', 'format-counts', libraryId] as const;
|
||||
@@ -0,0 +1,308 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||
import {Router} from '@angular/router';
|
||||
import {LibraryService} from './library.service';
|
||||
import {ShelfService} from './shelf.service';
|
||||
import {Library} from '../model/library.model';
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
|
||||
import {TaskHelperService} from '../../settings/task-management/task-helper.service';
|
||||
import {UserService} from "../../settings/user-management/user.service";
|
||||
import {LoadingService} from '../../../core/services/loading.service';
|
||||
import {finalize} from 'rxjs';
|
||||
import {DialogLauncherService} from '../../../shared/services/dialog-launcher.service';
|
||||
import {BookDialogHelperService} from '../components/book-browser/book-dialog-helper.service';
|
||||
import {TranslocoService} from '@jsverse/transloco';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class LibraryShelfMenuService {
|
||||
|
||||
private confirmationService = inject(ConfirmationService);
|
||||
private messageService = inject(MessageService);
|
||||
private libraryService = inject(LibraryService);
|
||||
private shelfService = inject(ShelfService);
|
||||
private taskHelperService = inject(TaskHelperService);
|
||||
private router = inject(Router);
|
||||
private dialogLauncherService = inject(DialogLauncherService);
|
||||
private magicShelfService = inject(MagicShelfService);
|
||||
private userService = inject(UserService);
|
||||
private loadingService = inject(LoadingService);
|
||||
private bookDialogHelperService = inject(BookDialogHelperService);
|
||||
private readonly t = inject(TranslocoService);
|
||||
|
||||
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
|
||||
return [
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.optionsLabel'),
|
||||
items: [
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.addPhysicalBook'),
|
||||
icon: 'pi pi-book',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openAddPhysicalBookDialog(entity?.id as number);
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.bulkIsbnImport'),
|
||||
icon: 'pi pi-barcode',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openBulkIsbnImportDialog(entity?.id as number);
|
||||
}
|
||||
},
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.editLibrary'),
|
||||
icon: 'pi pi-pen-to-square',
|
||||
command: () => {
|
||||
this.dialogLauncherService.openLibraryEditDialog((entity?.id as number));
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.rescanLibrary'),
|
||||
icon: 'pi pi-refresh',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.shelfMenuService.confirm.rescanLibraryMessage', {name: entity?.name}),
|
||||
header: this.t.translate('book.shelfMenuService.confirm.header'),
|
||||
icon: undefined,
|
||||
acceptLabel: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptIcon: undefined,
|
||||
rejectIcon: undefined,
|
||||
acceptButtonStyleClass: undefined,
|
||||
rejectButtonStyleClass: undefined,
|
||||
rejectButtonProps: {
|
||||
label: this.t.translate('common.cancel'),
|
||||
severity: 'secondary',
|
||||
},
|
||||
acceptButtonProps: {
|
||||
label: this.t.translate('book.shelfMenuService.confirm.rescanLabel'),
|
||||
severity: 'success',
|
||||
},
|
||||
accept: () => {
|
||||
this.libraryService.refreshLibrary(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshSuccessDetail')});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
|
||||
detail: this.t.translate('book.shelfMenuService.toast.libraryRefreshFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.customFetchMetadata'),
|
||||
icon: 'pi pi-sync',
|
||||
command: () => {
|
||||
this.dialogLauncherService.openLibraryMetadataFetchDialog((entity?.id as number));
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.autoFetchMetadata'),
|
||||
icon: 'pi pi-bolt',
|
||||
command: () => {
|
||||
this.taskHelperService.refreshMetadataTask({
|
||||
refreshType: MetadataRefreshType.LIBRARY,
|
||||
libraryId: entity?.id ?? undefined
|
||||
}).subscribe();
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.findDuplicates'),
|
||||
icon: 'pi pi-copy',
|
||||
command: () => {
|
||||
this.bookDialogHelperService.openDuplicateMergerDialog(entity?.id as number);
|
||||
}
|
||||
},
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.library.deleteLibrary'),
|
||||
icon: 'pi pi-trash',
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.shelfMenuService.confirm.deleteLibraryMessage', {name: entity?.name}),
|
||||
header: this.t.translate('book.shelfMenuService.confirm.header'),
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
rejectButtonProps: {
|
||||
label: this.t.translate('common.cancel'),
|
||||
severity: 'secondary',
|
||||
},
|
||||
acceptButtonProps: {
|
||||
label: this.t.translate('common.yes'),
|
||||
severity: 'danger',
|
||||
},
|
||||
accept: () => {
|
||||
const loader = this.loadingService.show(this.t.translate('book.shelfMenuService.loading.deletingLibrary', {name: entity?.name}));
|
||||
|
||||
this.libraryService.deleteLibrary(entity?.id!)
|
||||
.pipe(finalize(() => this.loadingService.hide(loader)))
|
||||
.subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.libraryDeletedDetail')});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
|
||||
detail: this.t.translate('book.shelfMenuService.toast.libraryDeleteFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
initializeShelfMenuItems(entity: any): MenuItem[] {
|
||||
const user = this.userService.getCurrentUser();
|
||||
const isOwner = entity?.userId === user?.id;
|
||||
const isPublicShelf = entity?.publicShelf ?? false;
|
||||
const disableOptions = !isOwner;
|
||||
|
||||
return [
|
||||
{
|
||||
label: (isPublicShelf ? this.t.translate('book.shelfMenuService.shelf.publicShelfPrefix') : '') + (disableOptions ? this.t.translate('book.shelfMenuService.shelf.readOnly') : this.t.translate('book.shelfMenuService.shelf.optionsLabel')),
|
||||
items: [
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.shelf.editShelf'),
|
||||
icon: 'pi pi-pen-to-square',
|
||||
disabled: disableOptions,
|
||||
command: () => {
|
||||
this.dialogLauncherService.openShelfEditDialog((entity?.id as number));
|
||||
}
|
||||
},
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.shelf.deleteShelf'),
|
||||
icon: 'pi pi-trash',
|
||||
disabled: disableOptions,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.shelfMenuService.confirm.deleteShelfMessage', {name: entity?.name}),
|
||||
header: this.t.translate('book.shelfMenuService.confirm.header'),
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonProps: {
|
||||
label: this.t.translate('common.yes'),
|
||||
severity: 'danger'
|
||||
},
|
||||
rejectButtonProps: {
|
||||
label: this.t.translate('common.cancel'),
|
||||
severity: 'secondary'
|
||||
},
|
||||
accept: () => {
|
||||
this.shelfService.deleteShelf(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.shelfDeletedDetail')});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
|
||||
detail: this.t.translate('book.shelfMenuService.toast.shelfDeleteFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
initializeMagicShelfMenuItems(entity: MagicShelf | null): MenuItem[] {
|
||||
const isAdmin = this.userService.getCurrentUser()?.permissions.admin ?? false;
|
||||
const isPublicShelf = entity?.isPublic ?? false;
|
||||
const disableOptions = isPublicShelf && !isAdmin;
|
||||
|
||||
return [
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.magicShelf.optionsLabel'),
|
||||
items: [
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.magicShelf.editMagicShelf'),
|
||||
icon: 'pi pi-pen-to-square',
|
||||
disabled: disableOptions,
|
||||
command: () => {
|
||||
this.dialogLauncherService.openMagicShelfEditDialog((entity?.id as number));
|
||||
}
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.magicShelf.exportJson'),
|
||||
icon: 'pi pi-copy',
|
||||
command: () => {
|
||||
if (entity?.filterJson) {
|
||||
navigator.clipboard.writeText(entity.filterJson).then(() => {
|
||||
this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfJsonCopiedDetail')});
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
separator: true
|
||||
},
|
||||
{
|
||||
label: this.t.translate('book.shelfMenuService.magicShelf.deleteMagicShelf'),
|
||||
icon: 'pi pi-trash',
|
||||
disabled: disableOptions,
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: this.t.translate('book.shelfMenuService.confirm.deleteMagicShelfMessage', {name: entity?.name}),
|
||||
header: this.t.translate('book.shelfMenuService.confirm.header'),
|
||||
acceptLabel: this.t.translate('common.yes'),
|
||||
rejectLabel: this.t.translate('common.cancel'),
|
||||
acceptButtonProps: {
|
||||
label: this.t.translate('common.yes'),
|
||||
severity: 'danger'
|
||||
},
|
||||
rejectButtonProps: {
|
||||
label: this.t.translate('common.cancel'),
|
||||
severity: 'secondary'
|
||||
},
|
||||
accept: () => {
|
||||
this.magicShelfService.deleteShelf(entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.router.navigate(['/']);
|
||||
this.messageService.add({severity: 'info', summary: this.t.translate('common.success'), detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeletedDetail')});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: this.t.translate('book.shelfMenuService.toast.failedSummary'),
|
||||
detail: this.t.translate('book.shelfMenuService.toast.magicShelfDeleteFailedDetail'),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import {computed, effect, inject, Injectable, signal} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {from, lastValueFrom, Observable} from 'rxjs';
|
||||
import {tap} from 'rxjs/operators';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Library} from '../model/library.model';
|
||||
import {BookService} from './book.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
import {BOOKS_QUERY_KEY} from './book-query-keys';
|
||||
import {LIBRARIES_QUERY_KEY, libraryFormatCountsQueryKey} from './library-query-keys';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class LibraryService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/libraries`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private authService = inject(AuthService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
readonly largeLibraryLoading = signal<{ isLoading: boolean; expectedCount: number }>({
|
||||
isLoading: false,
|
||||
expectedCount: 0
|
||||
});
|
||||
|
||||
private librariesQuery = injectQuery(() => ({
|
||||
...this.getLibrariesQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
libraries = computed(() => this.librariesQuery.data() ?? []);
|
||||
|
||||
librariesError = computed<string | null>(() => {
|
||||
if (!this.token() || !this.librariesQuery.isError()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const error = this.librariesQuery.error();
|
||||
return error instanceof Error ? error.message : 'Failed to load libraries';
|
||||
});
|
||||
|
||||
isLibrariesLoading = computed(() => !!this.token() && this.librariesQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: LIBRARIES_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getLibrariesQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: LIBRARIES_QUERY_KEY,
|
||||
queryFn: async () => {
|
||||
const libraries = await lastValueFrom(this.http.get<Library[]>(this.url));
|
||||
return this.sortLibraries(libraries);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getLibraryFormatCountsQueryOptions(libraryId: number) {
|
||||
return queryOptions({
|
||||
queryKey: libraryFormatCountsQueryKey(libraryId),
|
||||
queryFn: () => lastValueFrom(this.http.get<Record<string, number>>(`${this.url}/${libraryId}/format-counts`))
|
||||
});
|
||||
}
|
||||
|
||||
scanLibraryPaths(lib: Library): Observable<number> {
|
||||
return this.http.post<number>(`${this.url}/scan`, lib);
|
||||
}
|
||||
|
||||
createLibrary(lib: Library): Observable<Library> {
|
||||
return this.http.post<Library>(this.url, lib).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLibrary(lib: Library, id?: number): Observable<Library> {
|
||||
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteLibrary(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
void this.queryClient.invalidateQueries({queryKey: BOOKS_QUERY_KEY, exact: true});
|
||||
this.queryClient.removeQueries({queryKey: libraryFormatCountsQueryKey(id), exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
refreshLibrary(id: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
|
||||
return this.http
|
||||
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
|
||||
.pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: LIBRARIES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
doesLibraryExistByName(name: string): boolean {
|
||||
return this.libraries().some(library => library.name === name);
|
||||
}
|
||||
|
||||
findLibraryById(id: number): Library | undefined {
|
||||
return this.libraries().find(library => library.id === id);
|
||||
}
|
||||
|
||||
getBookCountValue(libraryId: number): number {
|
||||
return this.bookService.books().filter(book => book.libraryId === libraryId).length;
|
||||
}
|
||||
|
||||
setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void {
|
||||
this.largeLibraryLoading.set({ isLoading, expectedCount });
|
||||
}
|
||||
|
||||
getBookCountsByFormat(libraryId: number): Observable<Record<string, number>> {
|
||||
return from(this.queryClient.ensureQueryData(this.getLibraryFormatCountsQueryOptions(libraryId)));
|
||||
}
|
||||
|
||||
private sortLibraries(libraries: Library[]): Library[] {
|
||||
return [...libraries].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import {inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable, map} from 'rxjs';
|
||||
import {BookMetadata} from '../model/book.model';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {MetadataBatchProgressNotification} from '../../../shared/model/metadata-batch-progress.model';
|
||||
|
||||
export enum FetchedMetadataProposalStatus {
|
||||
FETCHED = 'FETCHED',
|
||||
ACCEPTED = 'ACCEPTED',
|
||||
REJECTED = 'REJECTED',
|
||||
}
|
||||
|
||||
export interface FetchedProposal {
|
||||
proposalId: number;
|
||||
taskId: string;
|
||||
bookId: number;
|
||||
fetchedAt: string;
|
||||
reviewedAt: string | null;
|
||||
reviewerUserId: string | null;
|
||||
status: FetchedMetadataProposalStatus;
|
||||
metadataJson: BookMetadata;
|
||||
}
|
||||
|
||||
export interface MetadataFetchTask {
|
||||
id: string;
|
||||
status: string;
|
||||
completed: number;
|
||||
totalBooks: number;
|
||||
startedAt: string;
|
||||
completedAt: string | null;
|
||||
initiatedBy: string;
|
||||
errorMessage: string | null;
|
||||
|
||||
proposals: FetchedProposal[];
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class MetadataTaskService {
|
||||
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/metadata/tasks`;
|
||||
private http = inject(HttpClient);
|
||||
|
||||
getTaskWithProposals(taskId: string): Observable<MetadataFetchTask> {
|
||||
return this.http.get<{ task: MetadataFetchTask }>(`${this.url}/${taskId}`)
|
||||
.pipe(
|
||||
map(response => response.task)
|
||||
);
|
||||
}
|
||||
|
||||
deleteTask(taskId: string): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${taskId}`);
|
||||
}
|
||||
|
||||
updateProposalStatus(taskId: string, proposalId: number, status: string): Observable<void> {
|
||||
return this.http.post<void>(`${this.url}/${taskId}/proposals/${proposalId}/status`, null, {
|
||||
params: {status}
|
||||
});
|
||||
}
|
||||
|
||||
getActiveTasks(): Observable<MetadataBatchProgressNotification[]> {
|
||||
return this.http.get<MetadataBatchProgressNotification[]>(`${this.url}/active`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import {computed, effect, inject, Injectable} from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {lastValueFrom, Observable} from 'rxjs';
|
||||
import {tap} from 'rxjs/operators';
|
||||
import {injectQuery, queryOptions, QueryClient} from '@tanstack/angular-query-experimental';
|
||||
|
||||
import {Shelf} from '../model/shelf.model';
|
||||
import {BookService} from './book.service';
|
||||
import {API_CONFIG} from '../../../core/config/api-config';
|
||||
import {Book} from '../model/book.model';
|
||||
import {UserService} from '../../settings/user-management/user.service';
|
||||
import {AuthService} from '../../../shared/service/auth.service';
|
||||
|
||||
const SHELVES_QUERY_KEY = ['shelves'] as const;
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
export class ShelfService {
|
||||
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/shelves`;
|
||||
private http = inject(HttpClient);
|
||||
private bookService = inject(BookService);
|
||||
private userService = inject(UserService);
|
||||
private authService = inject(AuthService);
|
||||
private queryClient = inject(QueryClient);
|
||||
private readonly token = this.authService.token;
|
||||
|
||||
private shelvesQuery = injectQuery(() => ({
|
||||
...this.getShelvesQueryOptions(),
|
||||
enabled: !!this.token(),
|
||||
}));
|
||||
|
||||
shelves = computed(() => this.shelvesQuery.data() ?? []);
|
||||
|
||||
shelvesError = computed<string | null>(() => {
|
||||
if (!this.token() || !this.shelvesQuery.isError()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const error = this.shelvesQuery.error();
|
||||
return error instanceof Error ? error.message : 'Failed to load shelves';
|
||||
});
|
||||
|
||||
isShelvesLoading = computed(() => !!this.token() && this.shelvesQuery.isPending());
|
||||
|
||||
constructor() {
|
||||
effect(() => {
|
||||
const token = this.token();
|
||||
if (token === null) {
|
||||
this.queryClient.removeQueries({queryKey: SHELVES_QUERY_KEY});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getShelvesQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: SHELVES_QUERY_KEY,
|
||||
queryFn: () => lastValueFrom(this.http.get<Shelf[]>(this.url))
|
||||
});
|
||||
}
|
||||
|
||||
reloadShelves(): void {
|
||||
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||
}
|
||||
|
||||
createShelf(shelf: Shelf): Observable<Shelf> {
|
||||
return this.http.post<Shelf>(this.url, shelf).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
|
||||
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
|
||||
tap(() => {
|
||||
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
deleteShelf(id: number): Observable<void> {
|
||||
return this.http.delete<void>(`${this.url}/${id}`).pipe(
|
||||
tap(() => {
|
||||
this.bookService.removeBooksFromShelf(id);
|
||||
void this.queryClient.invalidateQueries({queryKey: SHELVES_QUERY_KEY, exact: true});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getBookCountValue(shelfId: number): number {
|
||||
const shelf = this.shelves().find(currentShelf => currentShelf.id === shelfId);
|
||||
if (!shelf) return 0;
|
||||
|
||||
const currentUserId = this.userService.getCurrentUser()?.id;
|
||||
const isOwner = currentUserId === shelf.userId;
|
||||
|
||||
if (isOwner) {
|
||||
return this.bookService.books().filter(book =>
|
||||
book.shelves?.some(currentShelf => currentShelf.id === shelfId)
|
||||
).length;
|
||||
}
|
||||
|
||||
return shelf.bookCount || 0;
|
||||
}
|
||||
|
||||
getBooksOnShelf(shelfId: number): Observable<Book[]> {
|
||||
return this.http.get<Book[]>(`${this.url}/${shelfId}/books`);
|
||||
}
|
||||
|
||||
getUnshelvedBookCountValue(): number {
|
||||
return this.bookService.books().filter(book => !book.shelves || book.shelves.length === 0).length;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Book, ReadStatus} from '../model/book.model';
|
||||
import {SortDirection, SortOption} from "../model/sort.model";
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class SortService {
|
||||
|
||||
private naturalCompare(a: string, b: string): number {
|
||||
if (a == null && b == null) return 0;
|
||||
if (a == null) return 1;
|
||||
if (b == null) return -1;
|
||||
|
||||
const aStr = a.toString();
|
||||
const bStr = b.toString();
|
||||
|
||||
const chunkRegex = /(\d+|\D+)/g;
|
||||
|
||||
const aChunks = aStr.match(chunkRegex) || [aStr];
|
||||
const bChunks = bStr.match(chunkRegex) || [bStr];
|
||||
|
||||
const maxLength = Math.max(aChunks.length, bChunks.length);
|
||||
|
||||
for (let i = 0; i < maxLength; i++) {
|
||||
const aChunk = aChunks[i] || '';
|
||||
const bChunk = bChunks[i] || '';
|
||||
|
||||
if (aChunk === '' && bChunk === '') continue;
|
||||
|
||||
const aIsNumeric = /^\d+$/.test(aChunk);
|
||||
const bIsNumeric = /^\d+$/.test(bChunk);
|
||||
|
||||
if (aIsNumeric && bIsNumeric) {
|
||||
const aNum = parseInt(aChunk, 10);
|
||||
const bNum = parseInt(bChunk, 10);
|
||||
if (aNum !== bNum) {
|
||||
return aNum - bNum;
|
||||
}
|
||||
} else {
|
||||
const comparison = aChunk.localeCompare(bChunk);
|
||||
if (comparison !== 0) {
|
||||
return comparison;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return aChunks.length - bChunks.length;
|
||||
}
|
||||
|
||||
private static readonly READ_STATUS_RANK: Record<string, number> = {
|
||||
[ReadStatus.UNSET]: 0,
|
||||
[ReadStatus.UNREAD]: 1,
|
||||
[ReadStatus.READING]: 2,
|
||||
[ReadStatus.RE_READING]: 3,
|
||||
[ReadStatus.PARTIALLY_READ]: 4,
|
||||
[ReadStatus.PAUSED]: 5,
|
||||
[ReadStatus.READ]: 6,
|
||||
[ReadStatus.ABANDONED]: 7,
|
||||
[ReadStatus.WONT_READ]: 8,
|
||||
};
|
||||
|
||||
private readonly fieldExtractors: Record<string, (book: Book) => unknown> = {
|
||||
title: (book) => book.metadata?.title?.toLowerCase() || null,
|
||||
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
|
||||
authorSurnameVorname: (book) => book.metadata?.authors?.map(a => {
|
||||
const parts = a.trim().split(/\s+/);
|
||||
if (parts.length < 2) return a.toLowerCase();
|
||||
const surname = parts.pop();
|
||||
const firstname = parts.join(" ");
|
||||
return `${surname}, ${firstname}`.toLowerCase();
|
||||
}).join(", ") || null,
|
||||
publishedDate: (book) => {
|
||||
const date = book.metadata?.publishedDate;
|
||||
return date === null || date === undefined ? null : new Date(date).getTime();
|
||||
},
|
||||
publisher: (book) => book.metadata?.publisher || null,
|
||||
pageCount: (book) => book.metadata?.pageCount || null,
|
||||
rating: (book) => book.metadata?.rating || null,
|
||||
personalRating: (book) => book.personalRating || null,
|
||||
reviewCount: (book) => book.metadata?.reviewCount || null,
|
||||
amazonRating: (book) => book.metadata?.amazonRating || null,
|
||||
amazonReviewCount: (book) => book.metadata?.amazonReviewCount || null,
|
||||
goodreadsRating: (book) => book.metadata?.goodreadsRating || null,
|
||||
goodreadsReviewCount: (book) => book.metadata?.goodreadsReviewCount || null,
|
||||
hardcoverRating: (book) => book.metadata?.hardcoverRating || null,
|
||||
hardcoverReviewCount: (book) => book.metadata?.hardcoverReviewCount || null,
|
||||
ranobedbRating: (book) => book.metadata?.ranobedbRating || null,
|
||||
locked: (book) => book.metadata?.allMetadataLocked ?? false,
|
||||
lastReadTime: (book) => book.lastReadTime ? new Date(book.lastReadTime).getTime() : null,
|
||||
addedOn: (book) => book.addedOn ? new Date(book.addedOn).getTime() : null,
|
||||
fileSizeKb: (book) => book.fileSizeKb || null,
|
||||
fileName: (book) => book.fileName,
|
||||
filePath: (book) => book.filePath,
|
||||
random: (book) => Math.random(),
|
||||
seriesName: (book) => book.metadata?.seriesName?.toLowerCase() || null,
|
||||
seriesNumber: (book) => book.metadata?.seriesNumber ?? null,
|
||||
readStatus: (book) => book.readStatus ? (SortService.READ_STATUS_RANK[book.readStatus] ?? null) : null,
|
||||
dateFinished: (book) => book.dateFinished ? new Date(book.dateFinished).getTime() : null,
|
||||
readingProgress: (book) =>
|
||||
book.epubProgress?.percentage
|
||||
?? book.pdfProgress?.percentage
|
||||
?? book.cbxProgress?.percentage
|
||||
?? book.audiobookProgress?.percentage
|
||||
?? book.koreaderProgress?.percentage
|
||||
?? book.koboProgress?.percentage
|
||||
?? null,
|
||||
bookType: (book) => book.primaryFile?.bookType || null,
|
||||
narrator: (book) => book.metadata?.narrator?.toLowerCase() || null,
|
||||
};
|
||||
|
||||
applySort(books: Book[], selectedSort: SortOption | null): Book[] {
|
||||
if (!selectedSort) return books;
|
||||
return this.applyMultiSort(books, [selectedSort]);
|
||||
}
|
||||
|
||||
applyMultiSort(books: Book[], sortCriteria: SortOption[]): Book[] {
|
||||
if (!sortCriteria || sortCriteria.length === 0) return books;
|
||||
|
||||
return books.slice().sort((a, b) => {
|
||||
for (const criterion of sortCriteria) {
|
||||
const result = this.compareByCriterion(a, b, criterion);
|
||||
if (result !== 0) return result;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
private compareByCriterion(a: Book, b: Book, criterion: SortOption): number {
|
||||
const extractor = this.fieldExtractors[criterion.field];
|
||||
|
||||
if (!extractor) {
|
||||
console.warn(`[SortService] No extractor for field: ${criterion.field}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const aValue = extractor(a);
|
||||
const bValue = extractor(b);
|
||||
|
||||
let result = this.compareValues(aValue, bValue);
|
||||
|
||||
return criterion.direction === SortDirection.ASCENDING ? result : -result;
|
||||
}
|
||||
|
||||
private compareValues(aValue: unknown, bValue: unknown): number {
|
||||
if (Array.isArray(aValue) && Array.isArray(bValue)) {
|
||||
return this.compareArrays(aValue, bValue);
|
||||
} else if (typeof aValue === 'string' && typeof bValue === 'string') {
|
||||
return this.naturalCompare(aValue, bValue);
|
||||
} else if (typeof aValue === 'number' && typeof bValue === 'number') {
|
||||
return aValue - bValue;
|
||||
} else {
|
||||
if (aValue == null && bValue != null) return 1;
|
||||
if (aValue != null && bValue == null) return -1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private compareArrays(aValue: unknown[], bValue: unknown[]): number {
|
||||
for (let i = 0; i < aValue.length; i++) {
|
||||
const valA = aValue[i];
|
||||
const valB = bValue[i];
|
||||
|
||||
if (typeof valA === 'string' && typeof valB === 'string') {
|
||||
const result = this.naturalCompare(valA, valB);
|
||||
if (result !== 0) return result;
|
||||
} else if (typeof valA === 'number' && typeof valB === 'number') {
|
||||
const result = valA - valB;
|
||||
if (result !== 0) return result;
|
||||
} else {
|
||||
if (valA == null && valB != null) return 1;
|
||||
if (valA != null && valB == null) return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user