More signals

This commit is contained in:
aditya.chandel
2024-12-18 16:08:22 -07:00
parent 71f5927364
commit ce515649f6
14 changed files with 160 additions and 129 deletions
@@ -43,16 +43,12 @@ public class LibraryController {
return libraryService.parseLibraryBooks(libraryId, force); return libraryService.parseLibraryBooks(libraryId, force);
} }
@DeleteMapping("/{libraryId}") @DeleteMapping("/{libraryId}")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) { public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId); libraryService.deleteLibrary(libraryId);
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@GetMapping("/{libraryId}/book/{bookId}/withNeighbors") @GetMapping("/{libraryId}/book/{bookId}/withNeighbors")
public ResponseEntity<BookWithNeighborsDTO> getBookWithNeighbours(@PathVariable long libraryId, @PathVariable long bookId) { public ResponseEntity<BookWithNeighborsDTO> getBookWithNeighbours(@PathVariable long libraryId, @PathVariable long bookId) {
return ResponseEntity.ok(booksService.getBookWithNeighbours(libraryId, bookId)); return ResponseEntity.ok(booksService.getBookWithNeighbours(libraryId, bookId));
@@ -21,6 +21,8 @@ public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificat
Optional<Book> findBookByIdAndLibraryId(long id, long libraryId); Optional<Book> findBookByIdAndLibraryId(long id, long libraryId);
Optional<Book> findBookByFileNameAndLibraryId(String fileName, long libraryId);
@Query("SELECT b FROM Book b JOIN b.metadata bm WHERE LOWER(bm.title) LIKE LOWER(CONCAT('%', :title, '%'))") @Query("SELECT b FROM Book b JOIN b.metadata bm WHERE LOWER(bm.title) LIKE LOWER(CONCAT('%', :title, '%'))")
List<Book> findByTitleContainingIgnoreCase(@Param("title") String title); List<Book> findByTitleContainingIgnoreCase(@Param("title") String title);
@@ -40,7 +40,7 @@ public class PdfFileProcessor implements FileProcessor {
File bookFile = new File(libraryFile.getFilePath()); File bookFile = new File(libraryFile.getFilePath());
String fileName = bookFile.getName(); String fileName = bookFile.getName();
if (!forceProcess) { if (!forceProcess) {
Optional<Book> bookOptional = bookRepository.findByFileName(fileName); Optional<Book> bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibrary().getId());
if (bookOptional.isPresent()) { if (bookOptional.isPresent()) {
return FileProcessResult.builder() return FileProcessResult.builder()
.libraryFile(libraryFile) .libraryFile(libraryFile)
@@ -1,14 +1,20 @@
<div class="book-list-container"> <div class="book-list-container">
<h2 class="last-read-title">{{ title }}</h2> <div class="last-read-title-container">
<h2 class="last-read-title">{{ title }}</h2>
<div *ngIf="booksSignal().length === 0">
<h4>No books available.</h4>
</div>
</div>
<div class="book-list" <div class="book-list"
infiniteScroll infiniteScroll
[infiniteScrollDistance]="2" [infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50" [infiniteScrollThrottle]="50"
(scrolled)="loadMore()"
#scrollContainer #scrollContainer
[horizontal]="true"
(scrolled)="loadMore()"
(scroll)="onScroll($event)"> (scroll)="onScroll($event)">
<div class="book-item" *ngFor="let book of booksSignal()">
<div class="book-item" *ngFor="let book of books">
<img [src]="coverImageSrc(book.id)" class="book-cover" alt="Cover of {{ book.metadata.title }}" loading="lazy"/> <img [src]="coverImageSrc(book.id)" class="book-cover" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
<div class="book-info"> <div class="book-info">
<h4>{{ book.metadata.title }}</h4> <h4>{{ book.metadata.title }}</h4>
@@ -2,6 +2,10 @@
margin-bottom: 20px; margin-bottom: 20px;
} }
.last-read-title-container {
}
.last-read-title { .last-read-title {
font-size: 1.5rem; font-size: 1.5rem;
color: var(--text-color); color: var(--text-color);
@@ -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 {Book} from '../../model/book.model';
import {BookService} from '../../service/book.service'; import {BookService} from '../../service/book.service';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {NgForOf} from '@angular/common'; import {NgForOf, NgIf} from '@angular/common';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
@Component({ @Component({
selector: 'app-dashboard-scroller', selector: 'app-dashboard-scroller',
templateUrl: './dashboard-scroller.component.html', templateUrl: './dashboard-scroller.component.html',
styleUrls: ['./dashboard-scroller.component.scss'],
imports: [ imports: [
Button, Button,
InfiniteScrollDirective, InfiniteScrollDirective,
NgForOf NgForOf,
NgIf
], ],
styleUrls: ['./dashboard-scroller.component.scss']
}) })
export class DashboardScrollerComponent implements OnInit { export class DashboardScrollerComponent implements OnInit {
@Input() bookListType: 'lastRead' | 'latestAdded' = 'lastRead'; @Input() bookListType: 'lastRead' | 'latestAdded' = 'lastRead';
@Input() title: string = 'Last Read Books'; @Input() title: string = 'Last Read Books';
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
books: Book[] = [];
private currentPage: number = 0; 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) { constructor(private bookService: BookService, private router: Router) {
} }
@@ -36,37 +38,17 @@ export class DashboardScrollerComponent implements OnInit {
loadBooks(): void { loadBooks(): void {
if (this.bookListType === 'lastRead') { if (this.bookListType === 'lastRead') {
this.bookService.loadLatestBooks(this.currentPage).subscribe({ this.bookService.getLastReadBooks(this.currentPage);
next: (response) => {
this.books = [...this.books, ...response.content];
this.currentPage++;
},
error: (err) => {
console.error('Error loading books:', err);
},
});
} else { } else {
this.bookService.loadLatestAddedBooks(this.currentPage).subscribe({ this.bookService.getLatestAddedBooks(this.currentPage);
next: (response) => {
this.books = [...this.books, ...response.content];
this.currentPage++;
},
error: (err) => {
console.error('Error loading books:', err);
},
});
} }
this.currentPage++;
} }
coverImageSrc(bookId: number): string { coverImageSrc(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId); return this.bookService.getBookCoverUrl(bookId);
} }
loadMore(): void {
console.log('Loading more books...');
this.loadBooks();
}
getAuthorNames(book: Book): string { getAuthorNames(book: Book): string {
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available'; 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'); window.open(url, '_blank');
} }
loadMore() {
/*this.loadBooks();
this.currentPage++;*/
}
onScroll(event: any): void { onScroll(event: any): void {
const container = this.scrollContainer.nativeElement; /*const container = this.scrollContainer.nativeElement;
const scrollRight = container.scrollWidth - container.scrollLeft === container.clientWidth; const scrollRight = container.scrollWidth - container.scrollLeft === container.clientWidth;
if (scrollRight) { if (scrollRight) {
this.loadMore(); this.currentPage++;
} this.loadBooks();
}*/
} }
openBookInfo(bookId: number, libraryId: number) { openBookInfo(bookId: number, libraryId: number) {
@@ -12,22 +12,24 @@ import {Library} from '../../model/library.model';
}) })
export class AppMenuComponent implements OnInit { export class AppMenuComponent implements OnInit {
home: any[] = []; home: any[] = [];
libraries: Signal<Library[]>;
libraryMenu = computed(() => [ libraryMenu = computed(() => {
{ const libraries = this.libraryService.libraries();
label: 'Library', return [
separator: false, {
items: this.libraries().map((lib: Library) => ({ label: 'Library',
label: lib.name, separator: false,
icon: 'pi pi-fw pi-home', items: libraries.map((lib) => ({
routerLink: [`/library/${lib.id}/books`] label: lib.name,
})), icon: 'pi pi-fw pi-home',
}, routerLink: [`/library/${lib.id}/books`],
]); })),
},
];
});
constructor(private libraryService: LibraryService) { constructor(private libraryService: LibraryService) {
this.libraries = this.libraryService.libraries;
} }
ngOnInit() { ngOnInit() {
@@ -18,7 +18,7 @@
[ngClass]="coverSizeClass" [ngClass]="coverSizeClass"
[infiniteScrollDistance]="2" [infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50" [infiniteScrollThrottle]="50"
(scrolled)="loadMore()"> (scrolled)="loadBooks()">
<div class="book-item" *ngFor="let book of books"> <div class="book-item" *ngFor="let book of books">
<img [src]="coverImageSrc(book.id)" class="book-cover placeholder" alt="Cover of {{ book.metadata.title }}" loading="lazy"/> <img [src]="coverImageSrc(book.id)" class="book-cover placeholder" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
<div class="book-info"> <div class="book-info">
@@ -1,15 +1,15 @@
import {Component, computed, NgZone, OnChanges, OnInit, signal} from '@angular/core'; import { Component, NgZone, OnDestroy, OnInit, signal, computed } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import {BookProgressService} from '../../service/book-progress-service'; import { BookProgressService } from '../../service/book-progress-service';
import {BookService} from '../../service/book.service'; import { BookService } from '../../service/book.service';
import {Book, BookUpdateEvent} from '../../model/book.model'; import { Book, BookUpdateEvent } from '../../model/book.model';
import {combineLatest} from 'rxjs'; import { combineLatest, Subscription } from 'rxjs';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll'; import { InfiniteScrollDirective } from 'ngx-infinite-scroll';
import {Button} from 'primeng/button'; import { Button } from 'primeng/button';
import {NgClass, NgForOf} from '@angular/common'; import { NgClass, NgForOf } from '@angular/common';
import {FormsModule} from '@angular/forms'; import { FormsModule } from '@angular/forms';
import {DropdownModule} from 'primeng/dropdown'; import { DropdownModule } from 'primeng/dropdown';
import {LibraryService} from '../../service/library.service'; import { LibraryService } from '../../service/library.service';
@Component({ @Component({
selector: 'app-library-browser-v2', selector: 'app-library-browser-v2',
@@ -24,21 +24,22 @@ import {LibraryService} from '../../service/library.service';
NgClass NgClass
] ]
}) })
export class LibraryBrowserComponent implements OnInit { export class LibraryBrowserComponent implements OnInit, OnDestroy {
books: Book[] = []; books: Book[] = [];
private libraryIdSignal = signal(1);
private currentPage: number = 0; private currentPage: number = 0;
cities: any[] | undefined; private progressSubscription?: Subscription;
selectedCity: any;
coverSizeClass = 'medium'; coverSizeClass = 'medium';
coverSizeClasses = ['small', 'medium', 'large', 'extra-large']; coverSizeClasses = ['small', 'medium', 'large', 'extra-large'];
private libraryIdSignal = signal(1);
libraryNameSignal = computed(() => { libraryNameSignal = computed(() => {
const library = this.libraryService const library = this.libraryService
.libraries() .libraries()
.find((library) => library.id === this.libraryIdSignal()); .find((library) => library.id === this.libraryIdSignal());
return library ? library.name : 'Library not found'; return library ? library.name : 'Library not found';
}); });
selectedCity: any;
cities: any[] | undefined;
constructor( constructor(
private bookService: BookService, private bookService: BookService,
@@ -53,27 +54,43 @@ export class LibraryBrowserComponent implements OnInit {
combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap]) combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap])
.subscribe(([params, queryParams]) => { .subscribe(([params, queryParams]) => {
const libraryId = params.get('libraryId'); const libraryId = params.get('libraryId');
if (libraryId) {
this.libraryIdSignal.set(+libraryId);
this.resetState();
this.loadBooks();
}
const watch = queryParams.get('watch'); 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(); this.startListeningForProgress();
} else if (!watch && this.progressSubscription) {
this.stopListeningForProgress();
} }
}); });
} }
startListeningForProgress(): void { startListeningForProgress(): void {
this.bookProgressService.connect(this.libraryIdSignal()).subscribe({ this.progressSubscription = this.bookProgressService
next: (event: BookUpdateEvent) => this.addBookToCollection(event), .connect(this.libraryIdSignal())
error: (error) => console.error('Error receiving progress updates:', error), .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 { addBookToCollection(event: BookUpdateEvent): void {
if(event.parsingStatus === 'PARSED_NEW_BOOK') { if (event.parsingStatus === 'PARSED_NEW_BOOK') {
const newBook: Book = { const newBook: Book = {
id: event.book.id, id: event.book.id,
libraryId: event.book.libraryId, libraryId: event.book.libraryId,
@@ -85,16 +102,12 @@ export class LibraryBrowserComponent implements OnInit {
} }
}); });
} else { } 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 { loadBooks(): void {
console.log('loadBooks()')
this.bookService.loadBooks(this.libraryIdSignal(), this.currentPage).subscribe({ this.bookService.loadBooks(this.libraryIdSignal(), this.currentPage).subscribe({
next: (response) => { next: (response) => {
this.books = [...this.books, ...response.content]; this.books = [...this.books, ...response.content];
@@ -108,10 +121,6 @@ export class LibraryBrowserComponent implements OnInit {
return this.bookService.getBookCoverUrl(bookId); return this.bookService.getBookCoverUrl(bookId);
} }
loadMore(): void {
this.loadBooks();
}
getAuthorNames(book: Book): string { getAuthorNames(book: Book): string {
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available'; return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available';
} }
@@ -150,4 +159,15 @@ export class LibraryBrowserComponent implements OnInit {
isDecreaseDisabled(): boolean { isDecreaseDisabled(): boolean {
return this.coverSizeClass === this.coverSizeClasses[0]; return this.coverSizeClass === this.coverSizeClasses[0];
} }
resetState(): void {
this.books = [];
this.currentPage = 0;
this.stopListeningForProgress();
}
ngOnDestroy(): void {
this.stopListeningForProgress();
}
} }
@@ -21,7 +21,7 @@ export class LibraryCreatorComponent {
public dialogService: DialogService, public dialogService: DialogService,
private dynamicDialogRef: DynamicDialogRef, private dynamicDialogRef: DynamicDialogRef,
private messageService: MessageService, private messageService: MessageService,
private libraryServiceV2: LibraryService, private libraryService: LibraryService,
private router: Router, private router: Router,
) { ) {
} }
@@ -56,9 +56,8 @@ export class LibraryCreatorComponent {
name: this.value, name: this.value,
paths: this.folders, paths: this.folders,
}; };
this.libraryServiceV2.createLibrary(newLibrary).subscribe({ this.libraryService.createLibrary(newLibrary).subscribe({
next: (createdLibrary) => { next: (createdLibrary) => {
console.log('Library successfully created:', createdLibrary);
this.router.navigate( this.router.navigate(
['/library', createdLibrary.id, 'books'], ['/library', createdLibrary.id, 'books'],
{queryParams: {watch: true}} {queryParams: {watch: true}}
@@ -51,7 +51,6 @@ export class ThemeSwitcherComponent implements OnInit {
const themeLink = document.getElementById('theme-link') as HTMLLinkElement; const themeLink = document.getElementById('theme-link') as HTMLLinkElement;
if (themeLink) { if (themeLink) {
themeLink.href = `assets/layout/styles/theme/${theme}/theme.css`; themeLink.href = `assets/layout/styles/theme/${theme}/theme.css`;
console.log(`Theme applied: ${theme}`);
} else { } else {
console.error('Theme link element not found!'); console.error('Theme link element not found!');
} }
@@ -6,24 +6,21 @@ import {BookUpdateEvent} from '../model/book.model';
providedIn: 'root', providedIn: 'root',
}) })
export class BookProgressService { export class BookProgressService {
private eventSource: EventSource | null = null; private eventSource: EventSource | null = null;
connect(libraryId: number): Observable<BookUpdateEvent> { connect(libraryId: number): Observable<BookUpdateEvent> {
const url = `http://localhost:8080/v1/library/${libraryId}/parse`; const url = `http://localhost:8080/v1/library/${libraryId}/parse`;
return new Observable((observer) => { return new Observable((observer) => {
this.eventSource = new EventSource(url); this.eventSource = new EventSource(url);
this.eventSource.onmessage = (event) => { this.eventSource.onmessage = (event) => {
const data: BookUpdateEvent = JSON.parse(event.data); const data: BookUpdateEvent = JSON.parse(event.data);
observer.next(data); observer.next(data);
}; };
this.eventSource.onerror = (error) => { this.eventSource.onerror = (error) => {
console.error('SSE connection error:', error); console.error('SSE connection error:', error);
observer.error(error); observer.error(error);
}; };
return () => { return () => {
this.closeConnection(); this.closeConnection();
}; };
@@ -1,7 +1,9 @@
import {Observable} from 'rxjs'; import {Observable, of} from 'rxjs';
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO, PaginatedBooksResponse} from '../model/book.model'; 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 {HttpClient} from '@angular/common/http';
import {catchError, map} from 'rxjs/operators';
import {LibraryApiResponse} from '../model/library.model';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
@@ -11,6 +13,25 @@ export class BookService {
private readonly libraryUrl = 'http://localhost:8080/v1/library'; private readonly libraryUrl = 'http://localhost:8080/v1/library';
private readonly bookUrl = 'http://localhost:8080/v1/book'; private readonly bookUrl = 'http://localhost:8080/v1/book';
#lastReadBooks = signal<Book[]>([]);
lastReadBooks = computed(this.#lastReadBooks);
#latestAddedBooks = signal<Book[]>([]);
latestAddedBooks = computed(this.#latestAddedBooks);
getBooksByLibraryId(libraryId: number, page: number) {
this.http.get<PaginatedBooksResponse>(`${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) { constructor(private http: HttpClient) {
} }
@@ -28,15 +49,33 @@ export class BookService {
); );
} }
loadLatestBooks(page: number): Observable<PaginatedBooksResponse> { getLastReadBooks(page: number) {
return this.http.get<PaginatedBooksResponse>( this.http.get<PaginatedBooksResponse>(`${this.bookUrl}?page=${page}&size=25&sortBy=lastReadTime&sortDir=desc`).pipe(
`${this.bookUrl}?page=${page}&size=10&sortBy=lastReadTime&sortDir=desc` 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<PaginatedBooksResponse> { getLatestAddedBooks(page: number) {
return this.http.get<PaginatedBooksResponse>( this.http.get<PaginatedBooksResponse>(`${this.bookUrl}?page=${page}&size=25&sortBy=addedOn&sortDir=desc`).pipe(
`${this.bookUrl}?page=${page}&size=10&sortBy=addedOn&sortDir=desc` 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")
}
); );
} }
@@ -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<Library> {
const url = `${this.libraryUrl}/${id}`;
return this.http.put<Library>(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;
})
);
}*/
} }