diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java index 509eb27f9..429a0ecf9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java @@ -43,16 +43,12 @@ public class LibraryController { return libraryService.parseLibraryBooks(libraryId, force); } - - @DeleteMapping("/{libraryId}") public ResponseEntity deleteLibrary(@PathVariable long libraryId) { libraryService.deleteLibrary(libraryId); return ResponseEntity.noContent().build(); } - - @GetMapping("/{libraryId}/book/{bookId}/withNeighbors") public ResponseEntity getBookWithNeighbours(@PathVariable long libraryId, @PathVariable long bookId) { return ResponseEntity.ok(booksService.getBookWithNeighbours(libraryId, bookId)); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java index 0f8972fd1..7af50db53 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/BookRepository.java @@ -21,6 +21,8 @@ public interface BookRepository extends JpaRepository, JpaSpecificat Optional findBookByIdAndLibraryId(long id, long libraryId); + Optional findBookByFileNameAndLibraryId(String fileName, long libraryId); + @Query("SELECT b FROM Book b JOIN b.metadata bm WHERE LOWER(bm.title) LIKE LOWER(CONCAT('%', :title, '%'))") List findByTitleContainingIgnoreCase(@Param("title") String title); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfFileProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfFileProcessor.java index 4923d2f00..bc6e66709 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfFileProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/PdfFileProcessor.java @@ -40,7 +40,7 @@ public class PdfFileProcessor implements FileProcessor { File bookFile = new File(libraryFile.getFilePath()); String fileName = bookFile.getName(); if (!forceProcess) { - Optional bookOptional = bookRepository.findByFileName(fileName); + Optional bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibrary().getId()); if (bookOptional.isPresent()) { return FileProcessResult.builder() .libraryFile(libraryFile) diff --git a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.html b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.html index d98f7cecb..3fe4fce66 100644 --- a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.html +++ b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.html @@ -1,14 +1,20 @@ +
-

{{ title }}

+
+

{{ title }}

+
+

No books available.

+
+
- -
+
Cover of {{ book.metadata.title }}

{{ book.metadata.title }}

diff --git a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.scss b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.scss index 23d820827..ff71df0dd 100644 --- a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.scss +++ b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.scss @@ -2,6 +2,10 @@ margin-bottom: 20px; } +.last-read-title-container { + +} + .last-read-title { font-size: 1.5rem; color: var(--text-color); diff --git a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.ts b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.ts index 3b1f486c7..322efc95b 100644 --- a/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.ts +++ b/booklore-ui/src/app/book/component/dashboard-scroller/dashboard-scroller.component.ts @@ -1,31 +1,33 @@ -import {Component, OnInit, ViewChild, ElementRef, Input} from '@angular/core'; +import {Component, OnInit, ViewChild, ElementRef, Input, computed, signal} from '@angular/core'; import {Book} from '../../model/book.model'; import {BookService} from '../../service/book.service'; import {Button} from 'primeng/button'; import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; -import {NgForOf} from '@angular/common'; +import {NgForOf, NgIf} from '@angular/common'; import {Router} from '@angular/router'; @Component({ selector: 'app-dashboard-scroller', templateUrl: './dashboard-scroller.component.html', + styleUrls: ['./dashboard-scroller.component.scss'], imports: [ Button, InfiniteScrollDirective, - NgForOf + NgForOf, + NgIf ], - styleUrls: ['./dashboard-scroller.component.scss'] }) export class DashboardScrollerComponent implements OnInit { @Input() bookListType: 'lastRead' | 'latestAdded' = 'lastRead'; @Input() title: string = 'Last Read Books'; + @ViewChild('scrollContainer') scrollContainer!: ElementRef; - - books: Book[] = []; private currentPage: number = 0; - @ViewChild('scrollContainer') scrollContainer!: ElementRef; + booksSignal = computed(() => { + return this.bookListType === 'lastRead' ? this.bookService.lastReadBooks() : this.bookService.latestAddedBooks(); + }); constructor(private bookService: BookService, private router: Router) { } @@ -36,37 +38,17 @@ export class DashboardScrollerComponent implements OnInit { loadBooks(): void { if (this.bookListType === 'lastRead') { - this.bookService.loadLatestBooks(this.currentPage).subscribe({ - next: (response) => { - this.books = [...this.books, ...response.content]; - this.currentPage++; - }, - error: (err) => { - console.error('Error loading books:', err); - }, - }); + this.bookService.getLastReadBooks(this.currentPage); } else { - this.bookService.loadLatestAddedBooks(this.currentPage).subscribe({ - next: (response) => { - this.books = [...this.books, ...response.content]; - this.currentPage++; - }, - error: (err) => { - console.error('Error loading books:', err); - }, - }); + this.bookService.getLatestAddedBooks(this.currentPage); } + this.currentPage++; } coverImageSrc(bookId: number): string { return this.bookService.getBookCoverUrl(bookId); } - loadMore(): void { - console.log('Loading more books...'); - this.loadBooks(); - } - getAuthorNames(book: Book): string { return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available'; } @@ -76,13 +58,18 @@ export class DashboardScrollerComponent implements OnInit { window.open(url, '_blank'); } + loadMore() { + /*this.loadBooks(); + this.currentPage++;*/ + } onScroll(event: any): void { - const container = this.scrollContainer.nativeElement; + /*const container = this.scrollContainer.nativeElement; const scrollRight = container.scrollWidth - container.scrollLeft === container.clientWidth; if (scrollRight) { - this.loadMore(); - } + this.currentPage++; + this.loadBooks(); + }*/ } openBookInfo(bookId: number, libraryId: number) { diff --git a/booklore-ui/src/app/book/component/layout/app.menu.component.ts b/booklore-ui/src/app/book/component/layout/app.menu.component.ts index 9260c5f8d..3b71b2af8 100644 --- a/booklore-ui/src/app/book/component/layout/app.menu.component.ts +++ b/booklore-ui/src/app/book/component/layout/app.menu.component.ts @@ -12,22 +12,24 @@ import {Library} from '../../model/library.model'; }) export class AppMenuComponent implements OnInit { home: any[] = []; - libraries: Signal; - libraryMenu = computed(() => [ - { - label: 'Library', - separator: false, - items: this.libraries().map((lib: Library) => ({ - label: lib.name, - icon: 'pi pi-fw pi-home', - routerLink: [`/library/${lib.id}/books`] - })), - }, - ]); + libraryMenu = computed(() => { + const libraries = this.libraryService.libraries(); + return [ + { + label: 'Library', + separator: false, + items: libraries.map((lib) => ({ + label: lib.name, + icon: 'pi pi-fw pi-home', + routerLink: [`/library/${lib.id}/books`], + })), + }, + ]; + }); constructor(private libraryService: LibraryService) { - this.libraries = this.libraryService.libraries; + } ngOnInit() { diff --git a/booklore-ui/src/app/book/component/library-browser/library-browser.component.html b/booklore-ui/src/app/book/component/library-browser/library-browser.component.html index c7427e902..c440604c2 100644 --- a/booklore-ui/src/app/book/component/library-browser/library-browser.component.html +++ b/booklore-ui/src/app/book/component/library-browser/library-browser.component.html @@ -18,7 +18,7 @@ [ngClass]="coverSizeClass" [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" - (scrolled)="loadMore()"> + (scrolled)="loadBooks()">
Cover of {{ book.metadata.title }}
diff --git a/booklore-ui/src/app/book/component/library-browser/library-browser.component.ts b/booklore-ui/src/app/book/component/library-browser/library-browser.component.ts index 6d3bac231..f9744fcc0 100644 --- a/booklore-ui/src/app/book/component/library-browser/library-browser.component.ts +++ b/booklore-ui/src/app/book/component/library-browser/library-browser.component.ts @@ -1,15 +1,15 @@ -import {Component, computed, NgZone, OnChanges, OnInit, signal} from '@angular/core'; -import {ActivatedRoute, Router} from '@angular/router'; -import {BookProgressService} from '../../service/book-progress-service'; -import {BookService} from '../../service/book.service'; -import {Book, BookUpdateEvent} from '../../model/book.model'; -import {combineLatest} from 'rxjs'; -import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; -import {Button} from 'primeng/button'; -import {NgClass, NgForOf} from '@angular/common'; -import {FormsModule} from '@angular/forms'; -import {DropdownModule} from 'primeng/dropdown'; -import {LibraryService} from '../../service/library.service'; +import { Component, NgZone, OnDestroy, OnInit, signal, computed } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; +import { BookProgressService } from '../../service/book-progress-service'; +import { BookService } from '../../service/book.service'; +import { Book, BookUpdateEvent } from '../../model/book.model'; +import { combineLatest, Subscription } from 'rxjs'; +import { InfiniteScrollDirective } from 'ngx-infinite-scroll'; +import { Button } from 'primeng/button'; +import { NgClass, NgForOf } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { DropdownModule } from 'primeng/dropdown'; +import { LibraryService } from '../../service/library.service'; @Component({ selector: 'app-library-browser-v2', @@ -24,21 +24,22 @@ import {LibraryService} from '../../service/library.service'; NgClass ] }) -export class LibraryBrowserComponent implements OnInit { +export class LibraryBrowserComponent implements OnInit, OnDestroy { books: Book[] = []; - private libraryIdSignal = signal(1); private currentPage: number = 0; - cities: any[] | undefined; - selectedCity: any; + private progressSubscription?: Subscription; coverSizeClass = 'medium'; coverSizeClasses = ['small', 'medium', 'large', 'extra-large']; + private libraryIdSignal = signal(1); libraryNameSignal = computed(() => { const library = this.libraryService .libraries() .find((library) => library.id === this.libraryIdSignal()); return library ? library.name : 'Library not found'; }); + selectedCity: any; + cities: any[] | undefined; constructor( private bookService: BookService, @@ -53,27 +54,43 @@ export class LibraryBrowserComponent implements OnInit { combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap]) .subscribe(([params, queryParams]) => { const libraryId = params.get('libraryId'); - if (libraryId) { - this.libraryIdSignal.set(+libraryId); - this.resetState(); - this.loadBooks(); - } const watch = queryParams.get('watch'); - if (watch) { + if (libraryId) { + const libraryIdNum = +libraryId; + if (this.libraryIdSignal() !== libraryIdNum) { + this.libraryIdSignal.set(libraryIdNum); + this.resetState(); + this.loadBooks(); + } else if (this.books.length === 0) { + this.loadBooks(); + } + } + if (watch && !this.progressSubscription) { this.startListeningForProgress(); + } else if (!watch && this.progressSubscription) { + this.stopListeningForProgress(); } }); } startListeningForProgress(): void { - this.bookProgressService.connect(this.libraryIdSignal()).subscribe({ - next: (event: BookUpdateEvent) => this.addBookToCollection(event), - error: (error) => console.error('Error receiving progress updates:', error), - }); + this.progressSubscription = this.bookProgressService + .connect(this.libraryIdSignal()) + .subscribe({ + next: (event: BookUpdateEvent) => this.addBookToCollection(event), + error: (error) => console.error('Error receiving progress updates:', error), + }); + } + + stopListeningForProgress(): void { + if (this.progressSubscription) { + this.progressSubscription.unsubscribe(); + this.progressSubscription = undefined; + } } addBookToCollection(event: BookUpdateEvent): void { - if(event.parsingStatus === 'PARSED_NEW_BOOK') { + if (event.parsingStatus === 'PARSED_NEW_BOOK') { const newBook: Book = { id: event.book.id, libraryId: event.book.libraryId, @@ -85,16 +102,12 @@ export class LibraryBrowserComponent implements OnInit { } }); } else { - console.error('Status other than: PARSED_NEW_BOOK'); + console.warn('Status other than: PARSED_NEW_BOOK'); } } - resetState(): void { - this.books = []; - this.currentPage = 0; - } - loadBooks(): void { + console.log('loadBooks()') this.bookService.loadBooks(this.libraryIdSignal(), this.currentPage).subscribe({ next: (response) => { this.books = [...this.books, ...response.content]; @@ -108,10 +121,6 @@ export class LibraryBrowserComponent implements OnInit { return this.bookService.getBookCoverUrl(bookId); } - loadMore(): void { - this.loadBooks(); - } - getAuthorNames(book: Book): string { return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available'; } @@ -150,4 +159,15 @@ export class LibraryBrowserComponent implements OnInit { isDecreaseDisabled(): boolean { return this.coverSizeClass === this.coverSizeClasses[0]; } + + resetState(): void { + this.books = []; + this.currentPage = 0; + this.stopListeningForProgress(); + } + + ngOnDestroy(): void { + this.stopListeningForProgress(); + } + } diff --git a/booklore-ui/src/app/book/component/library-creator/library-creator.component.ts b/booklore-ui/src/app/book/component/library-creator/library-creator.component.ts index 5ff6c36b1..68b14527c 100644 --- a/booklore-ui/src/app/book/component/library-creator/library-creator.component.ts +++ b/booklore-ui/src/app/book/component/library-creator/library-creator.component.ts @@ -21,7 +21,7 @@ export class LibraryCreatorComponent { public dialogService: DialogService, private dynamicDialogRef: DynamicDialogRef, private messageService: MessageService, - private libraryServiceV2: LibraryService, + private libraryService: LibraryService, private router: Router, ) { } @@ -56,9 +56,8 @@ export class LibraryCreatorComponent { name: this.value, paths: this.folders, }; - this.libraryServiceV2.createLibrary(newLibrary).subscribe({ + this.libraryService.createLibrary(newLibrary).subscribe({ next: (createdLibrary) => { - console.log('Library successfully created:', createdLibrary); this.router.navigate( ['/library', createdLibrary.id, 'books'], {queryParams: {watch: true}} diff --git a/booklore-ui/src/app/book/component/theme-switcher/theme-switcher.component.ts b/booklore-ui/src/app/book/component/theme-switcher/theme-switcher.component.ts index 8c64d150a..7b67c842f 100644 --- a/booklore-ui/src/app/book/component/theme-switcher/theme-switcher.component.ts +++ b/booklore-ui/src/app/book/component/theme-switcher/theme-switcher.component.ts @@ -51,7 +51,6 @@ export class ThemeSwitcherComponent implements OnInit { const themeLink = document.getElementById('theme-link') as HTMLLinkElement; if (themeLink) { themeLink.href = `assets/layout/styles/theme/${theme}/theme.css`; - console.log(`Theme applied: ${theme}`); } else { console.error('Theme link element not found!'); } diff --git a/booklore-ui/src/app/book/service/book-progress-service.ts b/booklore-ui/src/app/book/service/book-progress-service.ts index beac9494a..7fd206025 100644 --- a/booklore-ui/src/app/book/service/book-progress-service.ts +++ b/booklore-ui/src/app/book/service/book-progress-service.ts @@ -6,24 +6,21 @@ import {BookUpdateEvent} from '../model/book.model'; providedIn: 'root', }) export class BookProgressService { + private eventSource: EventSource | null = null; connect(libraryId: number): Observable { const url = `http://localhost:8080/v1/library/${libraryId}/parse`; - return new Observable((observer) => { this.eventSource = new EventSource(url); - this.eventSource.onmessage = (event) => { const data: BookUpdateEvent = JSON.parse(event.data); observer.next(data); }; - this.eventSource.onerror = (error) => { console.error('SSE connection error:', error); observer.error(error); }; - return () => { this.closeConnection(); }; diff --git a/booklore-ui/src/app/book/service/book.service.ts b/booklore-ui/src/app/book/service/book.service.ts index 9ba1d84e4..5b6b5f41b 100644 --- a/booklore-ui/src/app/book/service/book.service.ts +++ b/booklore-ui/src/app/book/service/book.service.ts @@ -1,7 +1,9 @@ -import {Observable} from 'rxjs'; +import {Observable, of} from 'rxjs'; import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO, PaginatedBooksResponse} from '../model/book.model'; -import {Injectable} from '@angular/core'; +import {computed, Injectable, signal} from '@angular/core'; import {HttpClient} from '@angular/common/http'; +import {catchError, map} from 'rxjs/operators'; +import {LibraryApiResponse} from '../model/library.model'; @Injectable({ providedIn: 'root', @@ -11,6 +13,25 @@ export class BookService { private readonly libraryUrl = 'http://localhost:8080/v1/library'; private readonly bookUrl = 'http://localhost:8080/v1/book'; + #lastReadBooks = signal([]); + lastReadBooks = computed(this.#lastReadBooks); + + #latestAddedBooks = signal([]); + latestAddedBooks = computed(this.#latestAddedBooks); + + getBooksByLibraryId(libraryId: number, page: number) { + this.http.get(`${this.libraryUrl}/${libraryId}/book?page=${page}&size=${this.pageSize}`) + .pipe( + map(response => { + catchError(error => { + console.error('Error loading libraries:', error); + return of([]); + }) + }) + ).subscribe() + } + + constructor(private http: HttpClient) { } @@ -28,15 +49,33 @@ export class BookService { ); } - loadLatestBooks(page: number): Observable { - return this.http.get( - `${this.bookUrl}?page=${page}&size=10&sortBy=lastReadTime&sortDir=desc` + getLastReadBooks(page: number) { + this.http.get(`${this.bookUrl}?page=${page}&size=25&sortBy=lastReadTime&sortDir=desc`).pipe( + map(response => response.content), + catchError(error => { + console.error('Error loading last read books:', error); + return of([]); + }) + ).subscribe( + (books) => { + this.#lastReadBooks.set([...this.#lastReadBooks(), ...books]); + console.log("Loaded last read books") + } ); } - loadLatestAddedBooks(page: number): Observable { - return this.http.get( - `${this.bookUrl}?page=${page}&size=10&sortBy=addedOn&sortDir=desc` + getLatestAddedBooks(page: number) { + this.http.get(`${this.bookUrl}?page=${page}&size=25&sortBy=addedOn&sortDir=desc`).pipe( + map(response => response.content), + catchError(error => { + console.error('Error loading latest added books:', error); + return of([]); + }) + ).subscribe( + (books) => { + this.#latestAddedBooks.set([...this.#latestAddedBooks(), ...books]); + console.log("Loaded latest added books") + } ); } diff --git a/booklore-ui/src/app/book/service/library.service.ts b/booklore-ui/src/app/book/service/library.service.ts index 027b28dc9..492f26a44 100644 --- a/booklore-ui/src/app/book/service/library.service.ts +++ b/booklore-ui/src/app/book/service/library.service.ts @@ -43,24 +43,4 @@ export class LibraryService { }) ); } - - getLibraryById(libraryId: number): Library | undefined { - return this.#libraries().find(library => library.id === libraryId); - } - - /*updateLibrary(id: number, updatedLibrary: Library): Observable { - const url = `${this.libraryUrl}/${id}`; - return this.http.put(url, updatedLibrary).pipe( - tap((updatedLibraryFromBackend) => { - const updatedLibraries = this._libraries().map((library) => - library.id === id ? { ...library, ...updatedLibraryFromBackend } : library - ); - this._libraries.set(updatedLibraries); - }), - catchError((error) => { - console.error('Error updating library:', error); - throw error; - }) - ); - }*/ }