Websocket and stuffs

This commit is contained in:
aditya.chandel
2024-12-19 16:10:08 -07:00
parent 9e3b45fffc
commit e175a7e255
24 changed files with 569 additions and 496 deletions
@@ -1,32 +1,38 @@
<div>
<div class="library-header">
<h3 class="library-name">{{ libraryNameSignal() }}</h3>
<div class="library-header-right">
<p-dropdown
[options]="cities"
[(ngModel)]="selectedCity"
optionLabel="name"
placeholder="Select Sorting" />
<div class="zoom-controls">
<p-button icon="pi pi-minus" [rounded]="true" [outlined]="true" (click)="decreaseSize()" [disabled]="isDecreaseDisabled()" severity="info"></p-button>
<p-button icon="pi pi-plus" [rounded]="true" [outlined]="true" (click)="increaseSize()" [disabled]="isIncreaseDisabled()" severity="info"></p-button>
<div class="library-header">
<h3 class="library-name">{{ libraryNameSignal() }}</h3>
<div class="library-header-right">
<p-dropdown
[options]="cities"
[(ngModel)]="selectedCity"
optionLabel="name"
placeholder="Select Sorting" />
<div class="zoom-controls">
<p-button icon="pi pi-minus" [rounded]="true" [outlined]="true" (click)="decreaseSize()" [disabled]="isDecreaseDisabled()" severity="info"></p-button>
<p-button icon="pi pi-plus" [rounded]="true" [outlined]="true" (click)="increaseSize()" [disabled]="isIncreaseDisabled()" severity="info"></p-button>
</div>
</div>
</div>
</div>
<div class="book-list"
infiniteScroll
[ngClass]="coverSizeClass"
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="50"
(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">
<h4 class="book-title">{{ book.metadata.title }}</h4>
<p class="book-authors">{{ getAuthorNames(book) }}</p>
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="readBook(book.id)"></p-button>
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id, book.libraryId)"></p-button>
</div>
<div class="content-container">
<div class="card-container">
<virtual-scroller class="virtual-scroller" #scroll [items]="booksSignal()">
<div class="grid" #container>
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
<!--<img [lazyLoad]="coverImageSrc(book.id)" class="book-cover placeholder"/>-->
<img [src]="coverImageSrc(book.id)" class="book-cover placeholder" alt="Cover of {{ book.metadata.title }}" loading="lazy"/>
<div class="book-info">
<h4 class="book-title">{{ book.metadata.title }}</h4>
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="readBook(book.id)"></p-button>
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id, book.libraryId)"></p-button>
</div>
</div>
</div>
</virtual-scroller>
</div>
</div>
</div>
@@ -23,62 +23,49 @@
align-items: center;
}
.book-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(135px, 1fr));
gap: 20px;
transition: all 0.3s ease-in-out;
.virtual-scroller {
width: 100%;
height: calc(100vh - 200px);
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
}
.small {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
}
.medium {
grid-template-columns: repeat(auto-fill, minmax(135px, 1fr));
}
.large {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
.extra-large {
grid-template-columns: repeat(auto-fill, minmax(165px, 1fr));
}
.book-item {
.virtual-scroller-item {
background-color: var(--surface-card);
height: 240px;
width: 150px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
display: flex;
flex-direction: column;
justify-content: space-between;
position: relative;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 1.3rem;
padding: 1rem;
width: 100%;
overflow: hidden;
align-items: start;
}
.book-cover {
width: 100%;
height: auto;
max-height: 100%;
object-fit: cover;
transition: filter 0.3s ease-in-out;
}
.book-item:hover .book-cover {
filter: blur(2px);
}
.book-info {
padding: 7px 7px 5px;
text-align: center;
border-radius: 8px 8px 0 0;
}
.book-title {
font-size: 0.9rem;
font-size: 0.85rem;
color: var(--text-color);
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
padding: 6px 6px 5px;
}
.book-authors {
@@ -89,15 +76,7 @@
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.authors {
font-weight: bold;
}
.no-authors {
color: #888;
font-style: italic;
text-align: center;
}
.view-btn, .read-btn {
@@ -110,15 +89,19 @@
transition: opacity 0.2s ease-in-out;
}
.book-item:hover .view-btn,
.book-item:hover .read-btn {
.virtual-scroller-item:hover .view-btn,
.virtual-scroller-item:hover .read-btn {
display: block;
}
.book-item:hover .read-btn {
.virtual-scroller-item:hover .read-btn {
top: 70%;
}
.infinite-scroll {
margin-top: 20px;
.virtual-scroller-item:hover .book-cover {
filter: blur(2px);
}
@@ -1,33 +1,30 @@
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';
import {Component, computed, OnInit, signal} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {BookService} from '../../service/book.service';
import {Book} from '../../model/book.model';
import {combineLatest} from 'rxjs';
import {Button} from 'primeng/button';
import {NgForOf} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {DropdownModule} from 'primeng/dropdown';
import {LibraryService} from '../../service/library.service';
import {LazyLoadImageModule} from 'ng-lazyload-image';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
@Component({
selector: 'app-library-browser-v2',
templateUrl: './library-browser.component.html',
styleUrls: ['./library-browser.component.scss'],
imports: [
InfiniteScrollDirective,
Button,
NgForOf,
FormsModule,
DropdownModule,
NgClass
LazyLoadImageModule,
VirtualScrollerModule
]
})
export class LibraryBrowserComponent implements OnInit, OnDestroy {
books: Book[] = [];
private currentPage: number = 0;
private progressSubscription?: Subscription;
export class LibraryBrowserComponent implements OnInit {
coverSizeClass = 'medium';
coverSizeClasses = ['small', 'medium', 'large', 'extra-large'];
@@ -41,81 +38,25 @@ export class LibraryBrowserComponent implements OnInit, OnDestroy {
selectedCity: any;
cities: any[] | undefined;
booksSignal = computed(() => {
return this.bookService.libraryBooks();
});
constructor(
private bookService: BookService,
private activatedRoute: ActivatedRoute,
private router: Router,
private bookProgressService: BookProgressService,
private ngZone: NgZone,
private libraryService: LibraryService
) {}
private libraryService: LibraryService) {
}
ngOnInit(): void {
combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap])
.subscribe(([params, queryParams]) => {
const libraryId = params.get('libraryId');
const watch = queryParams.get('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.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') {
const newBook: Book = {
id: event.book.id,
libraryId: event.book.libraryId,
metadata: event.book.metadata,
};
this.ngZone.run(() => {
if (!this.books.find((book) => book.id === newBook.id)) {
this.books = [newBook, ...this.books];
}
});
} else {
console.warn('Status other than: PARSED_NEW_BOOK');
}
}
loadBooks(): void {
this.bookService.loadBooks(this.libraryIdSignal(), this.currentPage).subscribe({
next: (response) => {
this.books = [...this.books, ...response.content];
this.currentPage++;
},
error: (err) => console.error('Error loading books:', err),
});
}
coverImageSrc(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
}
@@ -159,14 +100,4 @@ export class LibraryBrowserComponent implements OnInit, OnDestroy {
return this.coverSizeClass === this.coverSizeClasses[0];
}
resetState(): void {
this.books = [];
this.currentPage = 0;
this.stopListeningForProgress();
}
ngOnDestroy(): void {
this.stopListeningForProgress();
}
}
@@ -4,16 +4,6 @@ export interface Book {
metadata: BookMetadata
}
export interface PaginatedBooksResponse {
content: Book[];
totalElements: number;
totalPages: number;
size: number;
number: number;
first: boolean;
last: boolean;
}
export interface BookMetadata {
thumbnail: string;
title: string;
@@ -1,15 +1,13 @@
import {Observable, of} from 'rxjs';
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO, PaginatedBooksResponse} from '../model/book.model';
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO} from '../model/book.model';
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',
})
export class BookService {
private readonly pageSize = 50;
private readonly libraryUrl = 'http://localhost:8080/v1/library';
private readonly bookUrl = 'http://localhost:8080/v1/book';
@@ -21,10 +19,40 @@ export class BookService {
latestAddedBooks = computed(this.#latestAddedBooks);
latestAddedBooksLoaded: boolean = false;
#libraryBooks = signal<Book[]>([]);
libraryBooks = computed(this.#libraryBooks);
lastLibraryBooksLoaded: boolean = false;
constructor(private http: HttpClient) {
}
appendBookToLibrary(book: Book) {
const newBook: Book = this.convertBookDTOToBook(book);
this.#libraryBooks.set([newBook, ...this.#libraryBooks()]);
}
private convertBookDTOToBook(book: Book): Book {
return {
id: book.id,
libraryId: book.libraryId,
metadata: {
thumbnail: book.metadata.thumbnail,
title: book.metadata.title,
subtitle: book.metadata.subtitle,
authors: book.metadata.authors,
categories: book.metadata.categories,
publisher: book.metadata.publisher,
publishedDate: book.metadata.publishedDate,
isbn10: book.metadata.isbn10,
description: book.metadata.description,
pageCount: book.metadata.pageCount,
language: book.metadata.language,
googleBookId: book.metadata.googleBookId,
}
};
}
getBook(bookId: number): Observable<Book> {
return this.http.get<Book>(`${this.bookUrl}/${bookId}`);
}
@@ -33,15 +61,31 @@ export class BookService {
return this.http.get<BookWithNeighborsDTO>(`${this.libraryUrl}/${libraryId}/book/${bookId}/withNeighbors`);
}
loadBooks(libraryId: number, page: number): Observable<PaginatedBooksResponse> {
return this.http.get<PaginatedBooksResponse>(
`${this.libraryUrl}/${libraryId}/book?page=${page}&size=${this.pageSize}`
loadBooksSignal(libraryId: number) {
this.http.get<Book[]>(`${this.libraryUrl}/${libraryId}/book`).pipe(
map(response => response),
catchError(error => {
console.error('Error loading library books:', error);
return of([]);
})
).subscribe(
(books) => {
this.#libraryBooks.set([...this.#libraryBooks(), ...books]);
this.lastReadBooksLoaded = true;
console.log("Loaded library books")
}
);
}
loadBooks(libraryId: number): Observable<Book[]> {
return this.http.get<Book[]>(
`${this.libraryUrl}/${libraryId}/book`
);
}
getLastReadBooks() {
this.http.get<PaginatedBooksResponse>(`${this.bookUrl}?page=0&size=25&sortBy=lastReadTime&sortDir=desc`).pipe(
map(response => response.content),
this.http.get<Book[]>(`${this.bookUrl}?sortBy=lastReadTime&sortDir=desc`).pipe(
map(response => response),
catchError(error => {
console.error('Error loading last read books:', error);
return of([]);
@@ -56,8 +100,8 @@ export class BookService {
}
getLatestAddedBooks() {
this.http.get<PaginatedBooksResponse>(`${this.bookUrl}?page=0&size=25&sortBy=addedOn&sortDir=desc`).pipe(
map(response => response.content),
this.http.get<Book[]>(`${this.bookUrl}?sortBy=addedOn&sortDir=desc`).pipe(
map(response => response),
catchError(error => {
console.error('Error loading latest added books:', error);
return of([]);