import {Injectable} from '@angular/core'; import {BehaviorSubject, Observable, of} from 'rxjs'; import {HttpClient} from '@angular/common/http'; import {catchError, map, switchMap, tap} from 'rxjs/operators'; import {Book, BookMetadata, BookSetting, BookType} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; @Injectable({ providedIn: 'root', }) export class BookService { private readonly url = 'http://localhost:8080/v1/book'; private bookStateSubject = new BehaviorSubject({ books: null, loaded: false, error: null, }); bookState$ = this.bookStateSubject.asObservable(); constructor(private http: HttpClient) { this.loadBooks(); } private loadBooks(): void { this.http.get(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(); } updateBookShelves(bookIds: Set, shelvesToAssign: Set, shelvesToUnassign: Set): Observable { const requestPayload = { bookIds: Array.from(bookIds), shelvesToAssign: Array.from(shelvesToAssign), shelvesToUnassign: Array.from(shelvesToUnassign), }; return this.http.post(`${this.url}/assign-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}); } getBookById(bookId: number): Observable { return this.bookState$.pipe( map(state => state.books?.find(book => book.id === bookId)) ); } getBookSetting(bookId: number): Observable { return this.http.get(`${this.url}/${bookId}/viewer-setting`); } updateViewerSetting(viewerSetting: any, bookId: number): Observable { return this.http.put(`${this.url}/${bookId}/viewer-setting`, viewerSetting); } updateLastReadTime(bookId: number): Observable { return this.http.put(`${this.url}/${bookId}/update-last-read`, {}).pipe( switchMap(updatedBook => { const currentState = this.bookStateSubject.value; const updatedBooks = (currentState.books || []).map(book => book.id === updatedBook.id ? {...book, lastReadTime: updatedBook.lastReadTime} : book ); this.bookStateSubject.next({...currentState, books: updatedBooks}); return [updatedBook]; }) ); } readBook(book: Book): void { if (book.bookType === "PDF") { const url = `/pdf-viewer/book/${book.id}`; window.open(url, '_blank'); this.updateLastReadTime(book.id).subscribe({ next: () => console.log('Last read time updated successfully'), error: err => console.error('Failed to update last read time', err), }); } else if (book.bookType === "EPUB") { const url = `/epub-viewer/book/${book.id}`; window.open(url, '_blank'); } else { console.error('Unsupported book type:', book.bookType); return; } } searchBooks(query: string): Observable { if (query.length < 2) { return of([]); } return this.bookState$.pipe( map(state => (state.books || []).filter(book => book.metadata?.title?.toLowerCase().includes(query.toLowerCase()) ) ) ); } getBookData(bookId: number): Observable { console.log('Fetching book data...'); return this.http.get(`${this.url}/${bookId}/data`, { responseType: 'blob' as 'json' }); } getBookCoverUrl(bookId: number): string { return `${this.url}/${bookId}/cover`; } getBookByIdFromAPI(bookId: number, withDescription: boolean) { return this.http.get(`${this.url}/${bookId}`, { params: { withDescription: withDescription.toString() } }); } saveEpubProgress(bookId: number, progress: string): Observable { return this.http.post(`${this.url}/progress`, { bookId: bookId, epubProgress: progress }); } /*------------------ 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: Set): void { const currentState = this.bookStateSubject.value; const filteredBooks = (currentState.books || []).filter(book => !removedBookIds.has(book.id)); this.bookStateSubject.next({...currentState, books: filteredBooks}); } handleBookUpdate(updatedBook: Book) { const currentState = this.bookStateSubject.value; const updatedBooks = (currentState.books || []).map(book => { return book.id == updatedBook.id ? {...book, metadata: updatedBook.metadata} : book }); this.bookStateSubject.next({...currentState, books: updatedBooks}) } 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}) } }