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);
}
@DeleteMapping("/{libraryId}")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
return ResponseEntity.noContent().build();
}
@GetMapping("/{libraryId}/book/{bookId}/withNeighbors")
public ResponseEntity<BookWithNeighborsDTO> getBookWithNeighbours(@PathVariable long libraryId, @PathVariable long 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> findBookByFileNameAndLibraryId(String fileName, long libraryId);
@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);
@@ -40,7 +40,7 @@ public class PdfFileProcessor implements FileProcessor {
File bookFile = new File(libraryFile.getFilePath());
String fileName = bookFile.getName();
if (!forceProcess) {
Optional<Book> bookOptional = bookRepository.findByFileName(fileName);
Optional<Book> bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibrary().getId());
if (bookOptional.isPresent()) {
return FileProcessResult.builder()
.libraryFile(libraryFile)
@@ -1,14 +1,20 @@
<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"
infiniteScroll
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50"
(scrolled)="loadMore()"
#scrollContainer
[horizontal]="true"
(scrolled)="loadMore()"
(scroll)="onScroll($event)">
<div class="book-item" *ngFor="let book of books">
<div class="book-item" *ngFor="let book of booksSignal()">
<img [src]="coverImageSrc(book.id)" class="book-cover" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
<div class="book-info">
<h4>{{ book.metadata.title }}</h4>
@@ -2,6 +2,10 @@
margin-bottom: 20px;
}
.last-read-title-container {
}
.last-read-title {
font-size: 1.5rem;
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 {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) {
@@ -12,22 +12,24 @@ import {Library} from '../../model/library.model';
})
export class AppMenuComponent implements OnInit {
home: any[] = [];
libraries: Signal<Library[]>;
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() {
@@ -18,7 +18,7 @@
[ngClass]="coverSizeClass"
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50"
(scrolled)="loadMore()">
(scrolled)="loadBooks()">
<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"/>
<div class="book-info">
@@ -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();
}
}
@@ -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}}
@@ -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!');
}
@@ -6,24 +6,21 @@ import {BookUpdateEvent} from '../model/book.model';
providedIn: 'root',
})
export class BookProgressService {
private eventSource: EventSource | null = null;
connect(libraryId: number): Observable<BookUpdateEvent> {
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();
};
@@ -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<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) {
}
@@ -28,15 +49,33 @@ export class BookService {
);
}
loadLatestBooks(page: number): Observable<PaginatedBooksResponse> {
return this.http.get<PaginatedBooksResponse>(
`${this.bookUrl}?page=${page}&size=10&sortBy=lastReadTime&sortDir=desc`
getLastReadBooks(page: number) {
this.http.get<PaginatedBooksResponse>(`${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<PaginatedBooksResponse> {
return this.http.get<PaginatedBooksResponse>(
`${this.bookUrl}?page=${page}&size=10&sortBy=addedOn&sortDir=desc`
getLatestAddedBooks(page: number) {
this.http.get<PaginatedBooksResponse>(`${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")
}
);
}
@@ -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;
})
);
}*/
}