Improve Angular project structure and code organization (#1328)

This commit is contained in:
Aditya Chandel
2025-10-12 02:01:59 -06:00
committed by GitHub
parent 54a8bacccd
commit 7c9bd56f63
405 changed files with 463 additions and 727 deletions
@@ -0,0 +1,154 @@
import {inject, Injectable} from '@angular/core';
import {ConfirmationService, MessageService} from 'primeng/api';
import {MenuItem} from 'primeng/api';
import {BookService} from './book.service';
import {readStatusLabels} from '../components/book-browser/book-filter/book-filter.component';
import {ReadStatus} from '../model/book.model';
import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
@Injectable({
providedIn: 'root'
})
export class BookMenuService {
confirmationService = inject(ConfirmationService);
messageService = inject(MessageService);
bookService = inject(BookService);
getMetadataMenuItems(
autoFetchMetadata: () => void,
fetchMetadata: () => void,
bulkEditMetadata: () => void,
multiBookEditMetadata: () => void): MenuItem[] {
return [
{
label: 'Auto Fetch Metadata',
icon: 'pi pi-bolt',
command: autoFetchMetadata
},
{
label: 'Custom Fetch Metadata',
icon: 'pi pi-sync',
command: fetchMetadata
},
{
label: 'Bulk Metadata Editor',
icon: 'pi pi-table',
command: bulkEditMetadata
},
{
label: 'Multi-Book Metadata Editor',
icon: 'pi pi-clone',
command: multiBookEditMetadata
}
];
}
getTieredMenuItems(selectedBooks: Set<number>): MenuItem[] {
return [
{
label: 'Update Read Status',
icon: 'pi pi-book',
items: Object.entries(readStatusLabels).map(([status, label]) => ({
label,
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to mark selected books as "${label}"?`,
header: 'Confirm Read Status Update',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
this.bookService.updateBookReadStatus(Array.from(selectedBooks), status as ReadStatus).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Read Status Updated',
detail: `Marked as "${label}"`,
life: 2000
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Update Failed',
detail: 'Could not update read status.',
life: 3000
});
}
});
}
});
}
}))
},
{
label: 'Reset Booklore Progress',
icon: 'pi pi-undo',
command: () => {
this.confirmationService.confirm({
message: 'Are you sure you want to reset Booklore reading progress for selected books?',
header: 'Confirm Reset',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.BOOKLORE).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Progress Reset',
detail: 'Booklore reading progress has been reset.',
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not reset progress.',
life: 1500
});
}
});
}
});
}
},
{
label: 'Reset KOReader Progress',
icon: 'pi pi-undo',
command: () => {
this.confirmationService.confirm({
message: 'Are you sure you want to reset KOReader reading progress for selected books?',
header: 'Confirm Reset',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'Yes',
rejectLabel: 'No',
accept: () => {
this.bookService.resetProgress(Array.from(selectedBooks), ResetProgressTypes.KOREADER).subscribe({
next: () => {
this.messageService.add({
severity: 'success',
summary: 'Progress Reset',
detail: 'KOReader reading progress has been reset.',
life: 1500
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Could not reset progress.',
life: 1500
});
}
});
}
});
}
}
];
}
}
@@ -0,0 +1,683 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, first, Observable, of, throwError} from 'rxjs';
import {HttpClient, HttpParams} from '@angular/common/http';
import {catchError, filter, map, tap, shareReplay, finalize, distinctUntilChanged} from 'rxjs/operators';
import {Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus, AdditionalFileType, AdditionalFile} from '../model/book.model';
import {BookState} from '../model/state/book-state.model';
import {API_CONFIG} from '../../../core/config/api-config';
import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model';
import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model';
import {MessageService} from 'primeng/api';
import {ResetProgressType, ResetProgressTypes} from '../../../shared/constants/reset-progress-type';
import {AuthService} from '../../../shared/service/auth.service';
import {FileDownloadService} from '../../../shared/service/file-download.service';
@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 fileDownloadService = inject(FileDownloadService);
private bookStateSubject = new BehaviorSubject<BookState>({
books: null,
loaded: false,
error: null,
});
private loading$: Observable<Book[]> | null = null;
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.bookStateSubject.next({
books: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.bookStateSubject.value;
if (current.loaded && !current.books) {
this.bookStateSubject.next({
books: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
bookState$ = this.bookStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchBooks().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
getCurrentBookState(): BookState {
return this.bookStateSubject.value;
}
private fetchBooks(): Observable<Book[]> {
return this.http.get<Book[]>(this.url).pipe(
tap(books => {
this.bookStateSubject.next({
books: books || [],
loaded: true,
error: null,
});
}),
catchError(error => {
const curr = this.bookStateSubject.value;
this.bookStateSubject.next({
books: curr.books,
loaded: true,
error: error.message,
});
throw error;
})
);
}
refreshBooks(): void {
this.http.get<Book[]>(this.url).pipe(
tap(books => {
this.bookStateSubject.next({
books: books || [],
loaded: true,
error: null,
});
}),
catchError(error => {
this.bookStateSubject.next({
books: null,
loaded: true,
error: error.message,
});
return of(null);
})
).subscribe();
}
getBookByIdFromState(bookId: number): Book | undefined {
const currentState = this.bookStateSubject.value;
return currentState.books?.find(book => +book.id === +bookId);
}
getBooksByIdsFromState(bookIds: number[]): Book[] {
const currentState = this.bookStateSubject.value;
if (!currentState.books || bookIds.length === 0) return [];
const idSet = new Set(bookIds.map(id => +id));
return currentState.books.filter(book => idSet.has(+book.id));
}
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(
map(updatedBooks => {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
updatedBooks.forEach(updatedBook => {
const index = currentBooks.findIndex(b => b.id === updatedBook.id);
if (index !== -1) {
currentBooks[index] = updatedBook;
}
});
this.bookStateSubject.next({...currentState, books: [...currentBooks]});
return updatedBooks;
}),
catchError(error => {
const currentState = this.bookStateSubject.value;
this.bookStateSubject.next({...currentState, error: error.message});
throw error;
})
);
}
removeBooksByLibraryId(libraryId: number): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const filteredBooks = currentBooks.filter(book => book.libraryId !== libraryId);
this.bookStateSubject.next({...currentState, books: filteredBooks});
}
removeBooksFromShelf(shelfId: number): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const updatedBooks = currentBooks.map(book => ({
...book,
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
}));
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
getBookSetting(bookId: number): Observable<BookSetting> {
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
}
updateViewerSetting(bookSetting: BookSetting, bookId: number): Observable<void> {
return this.http.put<void>(`${this.url}/${bookId}/viewer-setting`, bookSetting);
}
updateLastReadTime(bookId: number) {
const timestamp = new Date().toISOString();
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book =>
book.id === bookId ? {...book, lastReadTime: timestamp} : book
);
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
readBook(bookId: number, reader?: "ngx" | "streaming"): void {
const book = this.bookStateSubject.value.books?.find(b => b.id === bookId);
if (!book) {
console.error('Book not found');
return;
}
let url: string | null = null;
switch (book.bookType) {
case "PDF":
url = !reader || reader === "ngx"
? `/pdf-viewer/book/${book.id}`
: `/cbx-viewer/book/${book.id}`;
break;
case "EPUB":
url = `/epub-viewer/book/${book.id}`;
break;
case "CBX":
url = `/cbx-viewer/book/${book.id}`;
break;
default:
console.error('Unsupported book type:', book.bookType);
return;
}
window.open(url, '_blank');
this.updateLastReadTime(book.id);
}
getFileContent(bookId: number): Observable<Blob> {
return this.http.get<Blob>(`${this.url}/${bookId}/content`, {responseType: 'blob' as 'json'});
}
getBookByIdFromAPI(bookId: number, withDescription: boolean) {
return this.http.get<Book>(`${this.url}/${bookId}`, {
params: {
withDescription: withDescription.toString()
}
});
}
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 currentState = this.bookStateSubject.value;
const remainingBooks = (currentState.books || []).filter(
book => !ids.has(book.id)
);
this.bookStateSubject.next({
books: remainingBooks,
loaded: true,
error: null,
});
if (response.failedFileDeletions?.length > 0) {
this.messageService.add({
severity: 'warn',
summary: 'Some files could not be deleted',
detail: `Books: ${response.failedFileDeletions.join(', ')}`,
});
} else {
this.messageService.add({
severity: 'success',
summary: 'Books Deleted',
detail: `${idList.length} book(s) deleted successfully.`,
});
}
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error?.error?.message || error?.message || 'An error occurred while deleting books.',
});
return throwError(() => error);
})
);
}
deleteAdditionalFile(bookId: number, fileId: number): Observable<void> {
const deleteUrl = `${this.url}/${bookId}/files/${fileId}`;
return this.http.delete<void>(deleteUrl).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
return {
...book,
alternativeFormats: book.alternativeFormats?.filter(file => file.id !== fileId),
supplementaryFiles: book.supplementaryFiles?.filter(file => file.id !== fileId)
};
}
return book;
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: 'File Deleted',
detail: 'Additional file deleted successfully.'
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: error?.error?.message || error?.message || 'An error occurred while deleting the file.'
});
return throwError(() => error);
})
);
}
uploadAdditionalFile(bookId: number, file: File, fileType: AdditionalFileType, description?: string): Observable<AdditionalFile> {
const formData = new FormData();
formData.append('file', file);
formData.append('additionalFileType', fileType);
if (description) {
formData.append('description', description);
}
return this.http.post<AdditionalFile>(`${this.url}/${bookId}/files`, formData).pipe(
tap((newFile) => {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
if (book.id === bookId) {
const updatedBook = {...book};
if (fileType === AdditionalFileType.ALTERNATIVE_FORMAT) {
updatedBook.alternativeFormats = [...(book.alternativeFormats || []), newFile];
} else {
updatedBook.supplementaryFiles = [...(book.supplementaryFiles || []), newFile];
}
return updatedBook;
}
return book;
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks
});
this.messageService.add({
severity: 'success',
summary: 'File Uploaded',
detail: 'Additional file uploaded successfully.'
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Upload Failed',
detail: error?.error?.message || error?.message || 'An error occurred while uploading the file.'
});
return throwError(() => error);
})
);
}
downloadFile(bookId: number): void {
const downloadUrl = `${this.url}/${bookId}/download`;
this.fileDownloadService.downloadFile(downloadUrl, `book_${bookId}`);
}
downloadAdditionalFile(bookId: number, fileId: number): void {
const downloadUrl = `${this.url}/${bookId}/files/${fileId}/download`;
this.fileDownloadService.downloadFile(downloadUrl, `additional_file_${fileId}`);
}
savePdfProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
pdfProgress: {
page: page,
percentage: percentage
}
}
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
const body = {
bookId: bookId,
epubProgress: {
cfi: cfi,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
const body = {
bookId: bookId,
cbxProgress: {
page: page,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}
updateDateFinished(bookId: number, dateFinished: string | null): Observable<void> {
const body = {
bookId: bookId,
dateFinished: dateFinished
};
return this.http.post<void>(`${this.url}/progress`, body).pipe(
tap(() => {
// Update the book in the state
const currentState = this.bookStateSubject.value;
if (currentState.books) {
const updatedBooks = currentState.books.map(book => {
if (book.id === bookId) {
return {...book, dateFinished: dateFinished || undefined};
}
return book;
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks
});
}
})
);
}
regenerateCovers(): Observable<void> {
return this.http.post<void>(`${this.url}/regenerate-covers`, {});
}
regenerateCover(bookId: number): Observable<void> {
return this.http.post<void>(`${this.url}/${bookId}/regenerate-cover`, {});
}
/*------------------ All the metadata related calls go here ------------------*/
fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable<BookMetadata[]> {
return this.http.post<BookMetadata[]>(`${this.url}/${bookId}/metadata/prospective`, request);
}
updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable<BookMetadata> {
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
return this.http.put<BookMetadata>(`${this.url}/${bookId}/metadata`, wrapper, {params}).pipe(
map(updatedMetadata => {
this.handleBookMetadataUpdate(bookId!, updatedMetadata);
return updatedMetadata;
})
);
}
updateBooksMetadata(request: BulkMetadataUpdateRequest, mergeCategories: boolean): Observable<BookMetadata[]> {
const params = new HttpParams().set('mergeCategories', mergeCategories.toString());
return this.http.put<BookMetadata[]>(`${this.url}/bulk-edit-metadata`, request, {params}).pipe(
map(updatedMetadataList => {
request.bookIds.forEach((id, index) => {
this.handleBookMetadataUpdate(id, updatedMetadataList[index]);
});
return updatedMetadataList;
})
);
}
toggleAllLock(bookIds: Set<number>, lock: string): Observable<void> {
const requestBody = {
bookIds: Array.from(bookIds),
lock: lock
};
return this.http.put<BookMetadata[]>(`${this.url}/metadata/toggle-all-lock`, requestBody).pipe(
tap((updatedMetadataList) => {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
});
this.bookStateSubject.next({...currentState, books: updatedBooks});
}),
map(() => void 0),
catchError((error) => {
throw error;
})
);
}
getComicInfoMetadata(bookId: number): Observable<BookMetadata> {
return this.http.get<BookMetadata>(`${this.url}/${bookId}/cbx/metadata/comicinfo`);
}
autoRefreshMetadata(metadataRefreshRequest: MetadataRefreshRequest): Observable<any> {
return this.http.put<void>(`${this.url}/metadata/refresh`, metadataRefreshRequest).pipe(
map(() => {
this.messageService.add({
severity: 'success',
summary: 'Metadata Update Scheduled',
detail: 'The metadata update for the selected books has been successfully scheduled.'
});
return {success: true};
}),
catchError((e) => {
if (e.status === 409) {
this.messageService.add({
severity: 'error',
summary: 'Task Already Running',
life: 5000,
detail: 'A metadata refresh task is already in progress. Please wait for it to complete before starting another one.'
});
} else {
this.messageService.add({
severity: 'error',
summary: 'Metadata Update Failed',
life: 5000,
detail: 'An unexpected error occurred while scheduling the metadata update. Please try again later or contact support if the issue persists.'
});
}
return of({success: false});
})
);
}
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 =>
this.handleBookMetadataUpdate(bookId, updatedMetadata)
)
);
}
getBookRecommendations(bookId: number, limit: number = 20): Observable<BookRecommendation[]> {
return this.http.get<BookRecommendation[]>(`${this.url}/${bookId}/recommendations`, {
params: {limit: limit.toString()}
});
}
getBooksInSeries(bookId: number): Observable<Book[]> {
return this.bookStateSubject.asObservable().pipe(
filter(state => state.loaded),
first(),
map(state => {
const allBooks = state.books || [];
const currentBook = allBooks.find(b => b.id === bookId);
if (!currentBook || !currentBook.metadata?.seriesName) {
return [];
}
const seriesName = currentBook.metadata.seriesName.toLowerCase();
return allBooks.filter(b => b.metadata?.seriesName?.toLowerCase() === seriesName);
})
);
}
resetProgress(bookIds: number | number[], type: ResetProgressType): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
const params = new HttpParams().set('type', ResetProgressTypes[type]);
return this.http.post<Book[]>(`${this.url}/reset-progress`, ids, {params}).pipe(
tap(updatedBooks => updatedBooks.forEach(book => this.handleBookUpdate(book)))
);
}
updateBookReadStatus(bookIds: number | number[], status: ReadStatus): Observable<Book[]> {
const ids = Array.isArray(bookIds) ? bookIds : [bookIds];
return this.http.put<Book[]>(`${this.url}/read-status`, {ids, status}).pipe(
tap(updatedBooks => {
updatedBooks.forEach(updatedBook => this.handleBookUpdate(updatedBook));
})
);
}
consolidateMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', targetValues: string[], valuesToMerge: string[]): Observable<any> {
const payload = {metadataType, targetValues, valuesToMerge};
return this.http.post(`${this.url}/metadata/manage/consolidate`, payload).pipe(
tap(() => {
this.refreshBooks();
})
);
}
deleteMetadata(metadataType: 'authors' | 'categories' | 'moods' | 'tags' | 'series' | 'publishers' | 'languages', valuesToDelete: string[]): Observable<any> {
const payload = {metadataType, valuesToDelete};
return this.http.post(`${this.url}/metadata/manage/delete`, payload).pipe(
tap(() => {
this.refreshBooks();
})
);
}
/*------------------ All the websocket handlers go below ------------------*/
handleNewlyCreatedBook(book: Book): void {
const currentState = this.bookStateSubject.value;
const updatedBooks = currentState.books ? [...currentState.books] : [];
const bookIndex = updatedBooks.findIndex(existingBook => existingBook.id === book.id);
if (bookIndex > -1) {
updatedBooks[bookIndex] = book;
} else {
updatedBooks.push(book);
}
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
handleRemovedBookIds(removedBookIds: number[]): void {
const currentState = this.bookStateSubject.value;
const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.includes(book.id));
this.bookStateSubject.next({...currentState, books: filteredBooks});
}
handleBookUpdate(updatedBook: Book) {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book =>
book.id === updatedBook.id ? updatedBook : book
);
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
handleMultipleBookUpdates(updatedBooks: Book[]): void {
const currentState = this.bookStateSubject.value;
const currentBooks = currentState.books || [];
const updatedMap = new Map(updatedBooks.map(book => [book.id, book]));
const mergedBooks = currentBooks.map(book =>
updatedMap.has(book.id) ? updatedMap.get(book.id)! : book
);
this.bookStateSubject.next({...currentState, books: mergedBooks});
}
handleBookMetadataUpdate(bookId: number, updatedMetadata: BookMetadata) {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
return book.id == bookId ? {...book, metadata: updatedMetadata} : book
});
this.bookStateSubject.next({...currentState, books: updatedBooks})
}
toggleFieldLocks(bookIds: number[] | Set<number>, fieldActions: Record<string, 'LOCK' | 'UNLOCK'>): Observable<void> {
const bookIdSet = bookIds instanceof Set ? bookIds : new Set(bookIds);
const requestBody = {
bookIds: Array.from(bookIdSet),
fieldActions
};
return this.http.put<void>(`${this.url}/metadata/toggle-field-locks`, requestBody).pipe(
tap(() => {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
if (!bookIdSet.has(book.id)) return book;
const updatedMetadata = {...book.metadata};
for (const [field, action] of Object.entries(fieldActions)) {
const lockField = field.endsWith('Locked') ? field : `${field}Locked`;
if (lockField in updatedMetadata) {
(updatedMetadata as any)[lockField] = action === 'LOCK';
}
}
return {
...book,
metadata: updatedMetadata
};
});
this.bookStateSubject.next({
...currentState,
books: updatedBooks as Book[]
});
}),
catchError(error => {
this.messageService.add({
severity: 'error',
summary: 'Field Lock Update Failed',
detail: 'Failed to update metadata field locks. Please try again.',
});
throw error;
})
);
}
}
@@ -0,0 +1,30 @@
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';
@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.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
private appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getAvailablePages(bookId: number) {
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
}
getPageImageUrl(bookId: number, page: number): string {
return this.appendToken(`${this.imageUrl}/${bookId}/cbx/pages/${page}`);
}
}
@@ -0,0 +1,251 @@
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 {BookService} from './book.service';
import {Library} from '../model/library.model';
import {Shelf} from '../model/shelf.model';
import {DialogService} from 'primeng/dynamicdialog';
import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum';
import {LibraryCreatorComponent} from '../../library-creator/library-creator.component';
import {ShelfEditDialogComponent} from '../components/shelf-edit-dialog/shelf-edit-dialog.component';
import {MagicShelf, MagicShelfService} from '../../magic-shelf/service/magic-shelf.service';
import {MetadataFetchOptionsComponent} from '../../metadata/component/metadata-options-dialog/metadata-fetch-options-component/metadata-fetch-options.component';
import {MagicShelfComponent} from '../../magic-shelf/component/magic-shelf-component';
@Injectable({
providedIn: 'root',
})
export class LibraryShelfMenuService {
private confirmationService = inject(ConfirmationService);
private messageService = inject(MessageService);
private libraryService = inject(LibraryService);
private shelfService = inject(ShelfService);
private bookService = inject(BookService);
private router = inject(Router);
private dialogService = inject(DialogService);
private magicShelfService = inject(MagicShelfService);
initializeLibraryMenuItems(entity: Library | Shelf | MagicShelf | null): MenuItem[] {
return [
{
label: 'Options',
items: [
{
label: 'Edit Library',
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogService.open(LibraryCreatorComponent, {
header: 'Edit Library',
modal: true,
closable: true,
style: {
position: 'absolute',
top: '15%',
},
data: {
mode: 'edit',
libraryId: entity?.id
}
});
}
},
{
label: 'Delete Library',
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to delete library: ${entity?.name}?`,
header: 'Confirmation',
rejectButtonProps: {
label: 'Cancel',
severity: 'secondary',
},
acceptButtonProps: {
label: 'Yes',
severity: 'success',
},
accept: () => {
this.libraryService.deleteLibrary(entity?.id!).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Library was deleted'});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete library',
});
}
});
}
});
}
},
{
label: 'Re-scan Library',
icon: 'pi pi-refresh',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to refresh library: ${entity?.name}?`,
header: 'Confirmation',
rejectButtonProps: {
label: 'Cancel',
severity: 'secondary',
},
acceptButtonProps: {
label: 'Yes',
severity: 'success',
},
accept: () => {
this.libraryService.refreshLibrary(entity?.id!).subscribe({
complete: () => {
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Library refresh scheduled'});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Failed to refresh library',
});
}
});
}
});
}
},
{
label: 'Custom Fetch Metadata',
icon: 'pi pi-sync',
command: () => {
this.dialogService.open(MetadataFetchOptionsComponent, {
header: 'Metadata Refresh Options',
modal: true,
closable: true,
data: {
libraryId: entity?.id,
metadataRefreshType: MetadataRefreshType.LIBRARY
}
})
}
},
{
label: 'Auto Fetch Metadata',
icon: 'pi pi-bolt',
command: () => {
this.bookService.autoRefreshMetadata({
refreshType: MetadataRefreshType.LIBRARY,
libraryId: entity?.id || undefined
}).subscribe();
}
}
]
}
];
}
initializeShelfMenuItems(entity: any): MenuItem[] {
return [
{
label: 'Options',
items: [
{
label: 'Edit Shelf',
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogService.open(ShelfEditDialogComponent, {
header: 'Edit Shelf',
modal: true,
closable: true,
data: {
shelfId: entity?.id
},
style: {
position: 'absolute',
top: '15%',
}
})
}
},
{
label: 'Delete Shelf',
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to delete shelf: ${entity?.name}?`,
header: 'Confirmation',
accept: () => {
this.shelfService.deleteShelf(entity?.id!).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf was deleted'});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete shelf',
});
}
});
}
});
}
}
]
}
];
}
initializeMagicShelfMenuItems(entity: any): MenuItem[] {
return [
{
label: 'Options',
items: [
{
label: 'Edit Magic Shelf',
icon: 'pi pi-pen-to-square',
command: () => {
this.dialogService.open(MagicShelfComponent, {
header: 'Edit Magic Shelf',
modal: true,
closable: true,
data: {
id: entity?.id
}
})
}
},
{
label: 'Delete Magic Shelf',
icon: 'pi pi-trash',
command: () => {
this.confirmationService.confirm({
message: `Are you sure you want to delete magic shelf: ${entity?.name}?`,
header: 'Confirmation',
accept: () => {
this.magicShelfService.deleteShelf(entity?.id!).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Magic shelf was deleted'});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Failed',
detail: 'Failed to delete shelf',
});
}
});
}
});
}
}
]
}
];
}
}
@@ -0,0 +1,160 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {catchError, distinctUntilChanged, finalize, map, shareReplay, tap} from 'rxjs/operators';
import {Library} from '../model/library.model';
import {LibraryState} from '../model/state/library-state.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config';
import {AuthService} from '../../../shared/service/auth.service';
@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 libraryStateSubject = new BehaviorSubject<LibraryState>({
libraries: null,
loaded: false,
error: null,
});
private loading$: Observable<Library[]> | null = null;
constructor() {
this.authService.token$.pipe(
distinctUntilChanged()
).subscribe(token => {
if (token === null) {
this.libraryStateSubject.next({
libraries: null,
loaded: true,
error: null,
});
this.loading$ = null;
} else {
const current = this.libraryStateSubject.value;
if (current.loaded && !current.libraries) {
this.libraryStateSubject.next({
libraries: null,
loaded: false,
error: null,
});
this.loading$ = null;
}
}
});
}
libraryState$ = this.libraryStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchLibraries().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchLibraries(): Observable<Library[]> {
return this.http.get<Library[]>(this.url).pipe(
tap(libs => this.libraryStateSubject.next({libraries: libs, loaded: true, error: null})),
catchError(err => {
const current = this.libraryStateSubject.value;
this.libraryStateSubject.next({libraries: current.libraries, loaded: true, error: err.message});
throw err;
})
);
}
createLibrary(lib: Library): Observable<Library> {
return this.http.post<Library>(this.url, lib).pipe(
map(created => {
const curr = this.libraryStateSubject.value;
const updated = curr.libraries ? [...curr.libraries, created] : [created];
this.libraryStateSubject.next({...curr, libraries: updated});
return created;
})
);
}
updateLibrary(lib: Library, id?: number): Observable<Library> {
return this.http.put<Library>(`${this.url}/${id}`, lib).pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
deleteLibrary(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksByLibraryId(id);
const curr = this.libraryStateSubject.value;
const filtered = curr.libraries?.filter(l => l.id !== id) || [];
this.libraryStateSubject.next({...curr, libraries: filtered});
}),
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
return of();
})
);
}
refreshLibrary(id: number): Observable<void> {
return this.http.put<void>(`${this.url}/${id}/refresh`, {}).pipe(
catchError(err => {
const curr = this.libraryStateSubject.value;
this.libraryStateSubject.next({...curr, error: err.message});
throw err;
})
);
}
updateLibraryFileNamingPattern(id: number, pattern: string): Observable<Library> {
return this.http
.patch<Library>(`${this.url}/${id}/file-naming-pattern`, {fileNamingPattern: pattern})
.pipe(
map(updated => {
const curr = this.libraryStateSubject.value;
const list = curr.libraries?.map(l => (l.id === updated.id ? updated : l)) || [updated];
this.libraryStateSubject.next({...curr, libraries: list});
return updated;
})
);
}
doesLibraryExistByName(name: string): boolean {
return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name);
}
findLibraryById(id: number): Library | undefined {
return this.libraryStateSubject.value.libraries?.find(l => l.id === id);
}
getLibrariesFromState(): Library[] {
return this.libraryStateSubject.value.libraries || [];
}
getLibraryPathById(pathId: number): string | undefined {
return this.libraryStateSubject.value.libraries
?.find(lib => lib.paths.some(p => p.id === pathId))
?.paths.find(p => p.id === pathId)?.path;
}
getBookCount(libraryId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state => (state.books || []).filter(b => b.libraryId === libraryId).length)
);
}
}
@@ -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,32 @@
import {Injectable, inject} from '@angular/core';
import {API_CONFIG} from '../../../core/config/api-config';
import {HttpClient} from '@angular/common/http';
import {AuthService} from '../../../shared/service/auth.service';
@Injectable({
providedIn: 'root'
})
export class NewPdfReaderService {
private readonly pagesUrl = `${API_CONFIG.BASE_URL}/api/v1/pdf`;
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.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
private appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
getAvailablePages(bookId: number) {
return this.http.get<number[]>(this.appendToken(`${this.pagesUrl}/${bookId}/pages`));
}
getPageImageUrl(bookId: number, page: number): string {
return this.appendToken(`${this.imageUrl}/${bookId}/pdf/pages/${page}`);
}
}
@@ -0,0 +1,114 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, of} from 'rxjs';
import {tap, catchError, map, shareReplay, finalize} from 'rxjs/operators';
import {Shelf} from '../model/shelf.model';
import {ShelfState} from '../model/state/shelf-state.model';
import {BookService} from './book.service';
import {API_CONFIG} from '../../../core/config/api-config';
@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 shelfStateSubject = new BehaviorSubject<ShelfState>({
shelves: null,
loaded: false,
error: null,
});
private loading$: Observable<Shelf[]> | null = null;
shelfState$ = this.shelfStateSubject.asObservable().pipe(
tap(state => {
if (!state.loaded && !state.error && !this.loading$) {
this.loading$ = this.fetchShelves().pipe(
shareReplay(1),
finalize(() => (this.loading$ = null))
);
this.loading$.subscribe();
}
})
);
private fetchShelves(): Observable<Shelf[]> {
return this.http.get<Shelf[]>(this.url).pipe(
tap(shelves => this.shelfStateSubject.next({shelves, loaded: true, error: null})),
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({shelves: curr.shelves, loaded: true, error: err.message});
throw err;
})
);
}
public reloadShelves(): void {
this.fetchShelves().subscribe({
next: () => {
},
error: () => {
}
});
}
createShelf(shelf: Shelf): Observable<Shelf> {
return this.http.post<Shelf>(this.url, shelf).pipe(
map(newShelf => {
const curr = this.shelfStateSubject.value;
const updated = curr.shelves ? [...curr.shelves, newShelf] : [newShelf];
this.shelfStateSubject.next({...curr, shelves: updated});
return newShelf;
})
);
}
updateShelf(shelf: Shelf, id?: number): Observable<Shelf> {
return this.http.put<Shelf>(`${this.url}/${id}`, shelf).pipe(
map(updated => {
const curr = this.shelfStateSubject.value;
const list = curr.shelves?.map(s => (s.id === updated.id ? updated : s)) || [updated];
this.shelfStateSubject.next({...curr, shelves: list});
return updated;
})
);
}
deleteShelf(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/${id}`).pipe(
tap(() => {
this.bookService.removeBooksFromShelf(id);
const curr = this.shelfStateSubject.value;
const filtered = curr.shelves?.filter(s => s.id !== id) || [];
this.shelfStateSubject.next({...curr, shelves: filtered});
}),
catchError(err => {
const curr = this.shelfStateSubject.value;
this.shelfStateSubject.next({...curr, error: err.message});
return of();
})
);
}
getShelfById(id: number): Shelf | undefined {
return this.shelfStateSubject.value.shelves?.find(s => s.id === id);
}
getBookCount(shelfId: number): Observable<number> {
return this.bookService.bookState$.pipe(
map(state =>
(state.books || []).filter(b => b.shelves?.some(s => s.id === shelfId)).length
)
);
}
getUnshelvedBookCount(): Observable<number> {
return this.bookService.bookState$.pipe(
map(state =>
(state.books || []).filter(b => !b.shelves || b.shelves.length === 0).length
)
);
}
}
@@ -0,0 +1,77 @@
import {Injectable} from '@angular/core';
import {Book} from '../model/book.model';
import {SortDirection, SortOption} from "../model/sort.model";
@Injectable({
providedIn: 'root',
})
export class SortService {
private readonly fieldExtractors: Record<string, (book: Book) => any> = {
title: (book) => (book.seriesCount ? (book.metadata?.seriesName?.toLowerCase() || null) : null)
?? (book.metadata?.title?.toLowerCase() || null),
titleSeries: (book) => {
const title = book.metadata?.title?.toLowerCase() || '';
const series = book.metadata?.seriesName?.toLowerCase();
const seriesNumber = book.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER;
if (series) {
return [series, seriesNumber];
}
return [title, Number.MAX_SAFE_INTEGER];
},
author: (book) => book.metadata?.authors?.map(a => a.toLowerCase()).join(", ") || null,
publishedDate: (book) => book.metadata?.publishedDate === null ? null : new Date(book.metadata?.publishedDate!).getTime(),
publisher: (book) => book.metadata?.publisher || null,
pageCount: (book) => book.metadata?.pageCount || null,
rating: (book) => book.metadata?.rating || 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,
locked: (book) =>
Object.keys(book.metadata ?? {})
.filter((key) => key.endsWith('Locked'))
.every((key) => book.metadata?.[key] === true),
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
};
applySort(books: Book[], selectedSort: SortOption | null): Book[] {
if (!selectedSort) return books;
const {field, direction} = selectedSort;
const extractor = this.fieldExtractors[field];
if (!extractor) {
console.warn(`[SortService] No extractor for field: ${field}`);
return books;
}
return books.slice().sort((a, b) => {
const aValue = extractor(a);
const bValue = extractor(b);
let result: number;
if (Array.isArray(aValue) && Array.isArray(bValue)) {
const nameCompare = aValue[0]?.localeCompare?.(bValue[0]) ?? 0;
result = nameCompare !== 0 ? nameCompare : (aValue[1] - bValue[1]);
} else if (typeof aValue === 'string' && typeof bValue === 'string') {
result = aValue.localeCompare(bValue);
} else if (typeof aValue === 'number' && typeof bValue === 'number') {
result = aValue - bValue;
} else {
// Handle nulls or mismatches
if (aValue == null && bValue != null) return 1;
if (aValue != null && bValue == null) return -1;
return 0;
}
return direction === SortDirection.ASCENDING ? result : -result;
});
}
}