Add delete library functionality

More reactivity
This commit is contained in:
aditya.chandel
2024-12-20 18:32:41 -07:00
parent e175a7e255
commit 36c85bfb06
24 changed files with 284 additions and 248 deletions
+1
View File
@@ -1,2 +1,3 @@
<p-confirmDialog />
<p-toast></p-toast>
<router-outlet></router-outlet>
+5 -9
View File
@@ -1,8 +1,7 @@
import {Component, OnInit} from '@angular/core';
import {LibraryService} from './book/service/library.service';
import {RxStompService} from './rx-stomp.service';
import {Message} from '@stomp/stompjs';
import {BookService} from './book/service/book.service';
import {LibraryAndBookService} from './book/service/library-and-book.service';
import {Book} from './book/model/book.model';
@Component({
@@ -13,17 +12,14 @@ import {Book} from './book/model/book.model';
})
export class AppComponent implements OnInit {
constructor(private libraryService: LibraryService, private bookService: BookService, private rxStompService: RxStompService) {
constructor(private libraryBookService: LibraryAndBookService, private rxStompService: RxStompService) {
}
ngOnInit(): void {
this.libraryService.initializeLibraries();
this.bookService.loadBooksSignal(1);
this.libraryBookService.initializeLibraries();
this.rxStompService.watch('/topic/books').subscribe((message: Message) => {
const book: Book = JSON.parse(message.body); // Parse the incoming message to book DTO
this.bookService.appendBookToLibrary(book); // Call method to append to libraryBooks
const book: Book = JSON.parse(message.body);
this.libraryBookService.handleNewBook(book);
});
}
+5 -3
View File
@@ -19,13 +19,13 @@ import {PasswordModule} from 'primeng/password';
import {ToastModule} from 'primeng/toast';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {SearchComponent} from './book/component/search/search.component';
import {MessageService} from 'primeng/api';
import {FileUploadComponent} from './book/component/file-upload/file-upload.component';
import {ConfirmationService, MessageService} from 'primeng/api';
import {DropdownModule} from 'primeng/dropdown';
import {rxStompServiceFactory} from './rx-stomp-service-factory';
import {RxStompService} from './rx-stomp.service';
import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
import {LazyLoadImageModule} from 'ng-lazyload-image';
import {ConfirmDialogModule} from 'primeng/confirmdialog';
@NgModule({
declarations: [
@@ -51,11 +51,13 @@ import {LazyLoadImageModule} from 'ng-lazyload-image';
SearchComponent,
DropdownModule,
VirtualScrollerModule,
LazyLoadImageModule
LazyLoadImageModule,
ConfirmDialogModule,
],
providers: [
DialogService,
MessageService,
ConfirmationService,
{
provide: RxStompService,
useFactory: rxStompServiceFactory,
@@ -4,7 +4,7 @@
<div class="cover-container">
<div class="cover-wrapper">
<img [src]="coverImageSrc(book?.id)" class="book-cover placeholder" alt="Cover of {{ book?.metadata?.title }}" loading="lazy"/>
<div class="overlay" (click)="readBook(book?.id)">
<div class="overlay" (click)="readBook(book!)">
<p-button icon="pi pi-book" [rounded]="true"></p-button>
</div>
</div>
@@ -38,7 +38,7 @@
</h1>
<div class="button-group">
<p-button [rounded]="true" [raised]="true" [outlined]="true" (onClick)="openEditDialog(book?.id, book?.libraryId)" icon="pi pi-pencil"></p-button>
<p-button [rounded]="true" [raised]="true" [outlined]="true" (onClick)="readBook(book?.id)" icon="pi pi-eye"></p-button>
<p-button [rounded]="true" [raised]="true" [outlined]="true" (onClick)="readBook(book!)" icon="pi pi-eye"></p-button>
<p-button [rounded]="true" [raised]="true" [outlined]="true" icon="pi pi-download"></p-button>
</div>
</div>
@@ -1,6 +1,6 @@
import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {BookService} from '../../service/book.service';
import {LibraryAndBookService} from '../../service/library-and-book.service';
import {Book} from '../../model/book.model';
import {Button} from 'primeng/button';
import {NgForOf, NgIf} from '@angular/common';
@@ -30,7 +30,7 @@ export class BookMetadataComponent implements OnInit, OnDestroy {
private dialogSubscription?: Subscription;
constructor(
private bookService: BookService, private activatedRoute: ActivatedRoute,
private bookService: LibraryAndBookService, private activatedRoute: ActivatedRoute,
private dialogService: DialogService, private router: Router) {
}
@@ -106,11 +106,7 @@ export class BookMetadataComponent implements OnInit, OnDestroy {
}
}
readBook(id: number | undefined) {
const url = `/pdf-viewer/book/${id}`;
window.open(url, '_blank');
this.routeSubscription?.unsubscribe();
this.dialogSubscription?.unsubscribe();
this.dialogRef?.close();
readBook(book: Book) {
this.bookService.readBook(book);
}
}
@@ -1,6 +1,6 @@
import {Component, OnInit} from '@angular/core';
import {BookMetadata} from '../../model/book.model';
import {BookService} from '../../service/book.service';
import {LibraryAndBookService} from '../../service/library-and-book.service';
import {NgForOf, NgIf} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
@@ -27,7 +27,7 @@ export class BooksMetadataDialogComponent implements OnInit {
bookId: number = 0;
libraryId: number = 0;
constructor(private bookService: BookService, public dynamicDialogConfig: DynamicDialogConfig, private dynamicDialogRef: DynamicDialogRef, private router: Router) {
constructor(private bookService: LibraryAndBookService, public dynamicDialogConfig: DynamicDialogConfig, private dynamicDialogRef: DynamicDialogRef, private router: Router) {
this.searchText = dynamicDialogConfig.data.bookTitle;
this.bookId = this.dynamicDialogConfig.data.bookId;
this.libraryId = this.dynamicDialogConfig.data.libraryId;
@@ -17,7 +17,7 @@
<div class="book-info">
<h4>{{ book.metadata.title }}</h4>
<p>{{ getAuthorNames(book) }}</p>
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="openBook(book.id)"></p-button>
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="openBook(book)"></p-button>
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id, book.libraryId)"></p-button>
</div>
</div>
@@ -1,6 +1,6 @@
import {Component, OnInit, ViewChild, ElementRef, Input, computed, signal} from '@angular/core';
import {Book} from '../../model/book.model';
import {BookService} from '../../service/book.service';
import {LibraryAndBookService} from '../../service/library-and-book.service';
import {Button} from 'primeng/button';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {NgForOf, NgIf} from '@angular/common';
@@ -27,7 +27,7 @@ export class DashboardScrollerComponent implements OnInit {
return this.bookListType === 'lastRead' ? this.bookService.lastReadBooks() : this.bookService.latestAddedBooks();
});
constructor(private bookService: BookService, private router: Router) {
constructor(private bookService: LibraryAndBookService, private router: Router) {
}
ngOnInit(): void {
@@ -50,9 +50,8 @@ export class DashboardScrollerComponent implements OnInit {
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available';
}
openBook(bookId: number): void {
const url = `/pdf-viewer/book/${bookId}`;
window.open(url, '_blank');
openBook(book: Book): void {
this.bookService.readBook(book);
}
openBookInfo(bookId: number, libraryId: number) {
@@ -1,11 +1,11 @@
import {Component, Signal, WritableSignal} from '@angular/core';
import { LibraryService } from '../../service/library.service';
import { Library } from '../../model/library.model';
import { Button } from 'primeng/button';
import { NgIf } from '@angular/common';
import { LibraryCreatorComponent } from '../library-creator/library-creator.component';
import { DialogService, DynamicDialogRef } from 'primeng/dynamicdialog';
import {Component, Signal} from '@angular/core';
import {Library} from '../../model/library.model';
import {Button} from 'primeng/button';
import {NgIf} from '@angular/common';
import {LibraryCreatorComponent} from '../library-creator/library-creator.component';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
import {LibraryAndBookService} from '../../service/library-and-book.service';
@Component({
selector: 'app-home-page',
@@ -22,8 +22,8 @@ export class DashboardComponent {
private libraries: Signal<Library[]>;
ref: DynamicDialogRef | undefined;
constructor(private libraryService: LibraryService, public dialogService: DialogService) {
this.libraries = this.libraryService.libraries;
constructor(private libraryBookService: LibraryAndBookService, public dialogService: DialogService) {
this.libraries = this.libraryBookService.libraries;
}
get isLibrariesEmpty(): boolean {
@@ -1,6 +1,5 @@
import {Component, OnInit, Signal, WritableSignal} from '@angular/core';
import {Component, Signal} from '@angular/core';
import {Library} from '../../model/library.model';
import {LibraryService} from '../../service/library.service';
import {FileUploadService} from '../../../file-upload.service';
import {Button} from 'primeng/button';
import {NgIf} from '@angular/common';
@@ -8,6 +7,7 @@ import {DropdownModule} from 'primeng/dropdown';
import {FormsModule} from '@angular/forms';
import {ToastService} from '../../../toast.service';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {LibraryAndBookService} from '../../service/library-and-book.service';
@Component({
selector: 'app-file-upload-v2',
@@ -29,11 +29,11 @@ export class FileUploadComponent {
errorMessage: string | null = null;
constructor(
private libraryService: LibraryService,
private libraryBookService: LibraryAndBookService,
private fileUploadService: FileUploadService,
private toastService: ToastService,
private dynamicDialogRef: DynamicDialogRef) {
this.libraries = this.libraryService.libraries;
this.libraries = this.libraryBookService.libraries;
}
triggerFileInput(fileInput: HTMLInputElement): void {
@@ -1,9 +1,8 @@
import {Component, computed, OnInit, Signal, WritableSignal} from '@angular/core';
import {Component, computed, OnInit} from '@angular/core';
import {AppMenuitemComponent} from './app.menuitem.component';
import {NgForOf, NgIf} from '@angular/common';
import {MenuModule} from 'primeng/menu';
import {LibraryService} from '../../service/library.service';
import {Library} from '../../model/library.model';
import {LibraryAndBookService} from '../../service/library-and-book.service';
@Component({
selector: 'app-menu',
@@ -14,7 +13,7 @@ export class AppMenuComponent implements OnInit {
home: any[] = [];
libraryMenu = computed(() => {
const libraries = this.libraryService.libraries();
const libraries = this.libraryBookService.libraries();
return [
{
label: 'Library',
@@ -28,7 +27,7 @@ export class AppMenuComponent implements OnInit {
];
});
constructor(private libraryService: LibraryService) {
constructor(private libraryBookService: LibraryAndBookService) {
}
@@ -1,31 +1,40 @@
<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>
<div class="library-header">
<div class="library-header-dial">
<h3 class="library-name">{{ currentLibraryName() }}</h3>
<p-speedDial
[model]="items!"
direction="right"
transitionDelay="80"
showIcon="pi pi-bars"
buttonClassName="p-button-text"
hideIcon="pi pi-times"/>
</div>
<div class="library-header-right">
<p-dropdown
optionLabel="name"
placeholder="Select Sorting"/>
<div class="zoom-controls">
<p-button icon="pi pi-minus" [rounded]="true" [outlined]="true" severity="info"></p-button>
<p-button icon="pi pi-plus" [rounded]="true" [outlined]="true" severity="info"></p-button>
</div>
</div>
</div>
<div class="content-container">
<div class="card-container">
<virtual-scroller class="virtual-scroller" #scroll [items]="booksSignal()">
<virtual-scroller class="virtual-scroller" #scroll [items]="currentLibraryBooks()">
<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"/>
<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>
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="readBook(book)"></p-button>
<p-button [rounded]="true" icon="pi pi-info" class="read-btn"
(click)="openBookInfo(book.id, book.libraryId)"></p-button>
</div>
</div>
@@ -7,6 +7,11 @@
margin-bottom: 15px;
}
.library-header-dial {
display: flex;
margin-right: 5px;
}
.library-header-right {
display: flex;
gap: 2rem;
@@ -25,7 +30,7 @@
.virtual-scroller {
width: 100%;
height: calc(100vh - 200px);
height: calc(100vh - 210px);
padding: 1rem;
box-sizing: border-box;
overflow-y: auto;
@@ -1,15 +1,16 @@
import {Component, computed, OnInit, signal} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {BookService} from '../../service/book.service';
import {LibraryAndBookService} from '../../service/library-and-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';
import {SpeedDialModule} from 'primeng/speeddial';
import {ConfirmationService, MenuItem, MenuItemCommandEvent, MessageService} from 'primeng/api';
import {ConfirmDialogModule} from 'primeng/confirmdialog';
@Component({
selector: 'app-library-browser-v2',
@@ -21,83 +22,111 @@ import {VirtualScrollerModule} from '@iharbeck/ngx-virtual-scroller';
FormsModule,
DropdownModule,
LazyLoadImageModule,
VirtualScrollerModule
VirtualScrollerModule,
SpeedDialModule,
ConfirmDialogModule
]
})
export class LibraryBrowserComponent implements OnInit {
coverSizeClass = 'medium';
coverSizeClasses = ['small', 'medium', 'large', 'extra-large'];
private currentLibraryId = signal<number | null>(null);
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;
protected currentLibraryBooks = computed(() =>
this.currentLibraryId() != null ? this.libraryBookService.getLibraryBooks(this.currentLibraryId()!)() : []);
booksSignal = computed(() => {
return this.bookService.libraryBooks();
});
protected currentLibraryName = computed(() =>
this.libraryBookService.libraries().find(library => library.id === this.currentLibraryId())?.name || 'Library not found');
items: MenuItem[] | undefined;
constructor(
private bookService: BookService,
private activatedRoute: ActivatedRoute,
private router: Router,
private libraryService: LibraryService) {
private router: Router, private libraryBookService: LibraryAndBookService,
private confirmationService: ConfirmationService, private messageService: MessageService) {
}
ngOnInit(): void {
combineLatest([this.activatedRoute.paramMap, this.activatedRoute.queryParamMap])
.subscribe(([params, queryParams]) => {
const libraryId = params.get('libraryId');
const watch = queryParams.get('watch');
});
this.items = [
{
icon: 'pi pi-pencil',
tooltipOptions: {
tooltipLabel: 'Rename',
tooltipPosition: "top"
},
command: () => {
this.confirmationService.confirm({
message: 'Sure you want to delete: ' + this.currentLibraryName() + "?",
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
acceptIcon:"none",
rejectIcon:"none",
rejectButtonStyleClass:"p-button-text",
accept: () => {
this.libraryBookService.deleteLibrary(this.currentLibraryId()).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({ severity: 'info', summary: 'Success', detail: 'Library was deleted' });
},
error: () => {
this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Failed to delete library', life: 3000 });
}
});
}
});
}
},
{
icon: 'pi pi-trash',
tooltipOptions: {
tooltipLabel: 'Delete',
tooltipPosition: "top"
},
command: () => {
this.confirmationService.confirm({
message: 'Sure you want to delete: ' + this.currentLibraryName() + "?",
header: 'Confirmation',
icon: 'pi pi-exclamation-triangle',
acceptIcon:"none",
rejectIcon:"none",
rejectButtonStyleClass:"p-button-text",
accept: () => {
this.libraryBookService.deleteLibrary(this.currentLibraryId()).subscribe({
complete: () => {
this.router.navigate(['/']);
this.messageService.add({ severity: 'info', summary: 'Success', detail: 'Library was deleted' });
},
error: () => {
this.messageService.add({ severity: 'error', summary: 'Failed', detail: 'Failed to delete library', life: 3000 });
}
});
}
});
}
}
];
this.activatedRoute.paramMap.subscribe((params) => {
const libraryId = Number(params.get('libraryId'));
if (libraryId) {
this.currentLibraryId.set(libraryId);
this.libraryBookService.loadBooksSignal(libraryId);
}
});
}
coverImageSrc(bookId: number): string {
return this.bookService.getBookCoverUrl(bookId);
return this.libraryBookService.getBookCoverUrl(bookId);
}
getAuthorNames(book: Book): string {
return book.metadata.authors?.map((author) => author.name).join(', ') || 'No authors available';
}
readBook(bookId: number): void {
const url = `/pdf-viewer/book/${bookId}`;
window.open(url, '_blank');
readBook(book: Book): void {
this.libraryBookService.readBook(book);
}
openBookInfo(bookId: number, libraryId: number) {
this.router.navigate(['/library', libraryId, 'book', bookId, 'info']);
}
getCurrentSizeIndex(): number {
return this.coverSizeClasses.indexOf(this.coverSizeClass);
}
increaseSize() {
const currentIndex = this.getCurrentSizeIndex();
if (currentIndex < this.coverSizeClasses.length - 1) {
this.coverSizeClass = this.coverSizeClasses[currentIndex + 1];
}
}
decreaseSize() {
const currentIndex = this.getCurrentSizeIndex();
if (currentIndex > 0) {
this.coverSizeClass = this.coverSizeClasses[currentIndex - 1];
}
}
isIncreaseDisabled(): boolean {
return this.coverSizeClass === this.coverSizeClasses[this.coverSizeClasses.length - 1];
}
isDecreaseDisabled(): boolean {
return this.coverSizeClass === this.coverSizeClasses[0];
}
}
@@ -2,8 +2,8 @@ import {Component} from '@angular/core';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {DirectoryPickerComponent} from '../directory-picker/directory-picker.component';
import {MessageService} from 'primeng/api';
import {LibraryService} from '../../service/library.service';
import {Router} from '@angular/router';
import {LibraryAndBookService} from '../../service/library-and-book.service';
@Component({
selector: 'app-library-creator',
@@ -20,8 +20,7 @@ export class LibraryCreatorComponent {
constructor(
public dialogService: DialogService,
private dynamicDialogRef: DynamicDialogRef,
private messageService: MessageService,
private libraryService: LibraryService,
private libraryAndBookService: LibraryAndBookService,
private router: Router,
) {
}
@@ -56,11 +55,10 @@ export class LibraryCreatorComponent {
name: this.value,
paths: this.folders,
};
this.libraryService.createLibrary(newLibrary).subscribe({
this.libraryAndBookService.createLibrary(newLibrary).subscribe({
next: (createdLibrary) => {
this.router.navigate(
['/library', createdLibrary.id, 'books'],
{queryParams: {watch: true}}
['/library', createdLibrary.id, 'books']
);
},
error: (err) => {
@@ -1,5 +1,4 @@
import {Component, OnInit, OnDestroy} from '@angular/core';
import {BookProgressService} from '../../service/book-progress-service';
import {Subscription} from 'rxjs';
import {NgClass} from '@angular/common';
import {BookUpdateEvent} from '../../model/book.model';
@@ -16,8 +15,6 @@ export class NotificationComponent implements OnInit, OnDestroy {
glowing: boolean = false;
private eventSubscription!: Subscription;
constructor(private bookProgressService: BookProgressService) {}
ngOnInit(): void {
/*this.eventSubscription = this.bookProgressService.connect(1).subscribe({
next: (event: BookUpdateEvent) => {
@@ -1,7 +1,7 @@
import { ChangeDetectorRef, Component, NgZone, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgxExtendedPdfViewerModule, ScrollModeType } from 'ngx-extended-pdf-viewer';
import { BookService } from '../../service/book.service';
import { LibraryAndBookService } from '../../service/library-and-book.service';
@Component({
selector: 'app-pdf-viewer',
@@ -22,7 +22,7 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
private isInitialLoad = true;
constructor(
private bookService: BookService,
private bookService: LibraryAndBookService,
private zone: NgZone,
private route: ActivatedRoute
) {}
@@ -2,7 +2,7 @@ import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap, catchError } from 'rxjs/operators';
import { Book } from '../../model/book.model';
import { BookService } from '../../service/book.service';
import { LibraryAndBookService } from '../../service/library-and-book.service';
import { FormsModule } from '@angular/forms';
import { InputTextModule } from 'primeng/inputtext';
import { NgForOf, NgIf } from '@angular/common';
@@ -27,7 +27,7 @@ export class SearchComponent implements OnInit, OnDestroy {
#searchSubject = new Subject<string>();
#subscription!: Subscription;
constructor(private bookService: BookService, private router: Router) {}
constructor(private bookService: LibraryAndBookService, private router: Router) {}
ngOnInit(): void {
this.initializeSearch();
@@ -59,8 +59,6 @@ export class SearchComponent implements OnInit, OnDestroy {
}
openBook(bookId: number, libraryId: number): void {
/*const url = `/pdf-viewer/book/${bookId}`;
window.open(url, '_blank');*/
this.router.navigate(['/library', libraryId, 'book', bookId, 'info']);
}
@@ -1,37 +0,0 @@
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {BookUpdateEvent} from '../model/book.model';
@Injectable({
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();
};
});
}
closeConnection(): void {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
console.log('SSE connection closed');
}
}
}
@@ -2,15 +2,19 @@ import {Observable, of} from 'rxjs';
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 {catchError, map, tap} from 'rxjs/operators';
import {Library, LibraryApiResponse} from '../model/library.model';
@Injectable({
providedIn: 'root',
})
export class BookService {
export class LibraryAndBookService {
private readonly libraryUrl = 'http://localhost:8080/v1/library';
private readonly bookUrl = 'http://localhost:8080/v1/book';
#libraries = signal<Library[]>([]);
libraries = computed(this.#libraries);
#lastReadBooks = signal<Book[]>([]);
lastReadBooks = computed(this.#lastReadBooks);
lastReadBooksLoaded: boolean = false;
@@ -19,17 +23,123 @@ export class BookService {
latestAddedBooks = computed(this.#latestAddedBooks);
latestAddedBooksLoaded: boolean = false;
#libraryBooks = signal<Book[]>([]);
libraryBooks = computed(this.#libraryBooks);
lastLibraryBooksLoaded: boolean = false;
private libraryBooksMap = signal<Map<number, Book[]>>(new Map());
private loadedLibraries = new Set<number>();
constructor(private http: HttpClient) {
}
appendBookToLibrary(book: Book) {
/*---------- Library Methods go below ----------*/
initializeLibraries(): void {
this.http.get<LibraryApiResponse>(this.libraryUrl).pipe(
map(response => response.content),
catchError(error => {
console.error('Error loading libraries:', error);
return of([]);
})
).subscribe(
(libraries) => {
this.#libraries.set(libraries);
console.log("Library Initialized")
}
);
}
createLibrary(newLibrary: Library): Observable<Library> {
return this.http.post<Library>(this.libraryUrl, newLibrary).pipe(
tap((createdLibrary) => {
const currentLibraries = this.#libraries();
this.#libraries.set([...currentLibraries, createdLibrary]);
console.log("New Library Created");
}),
catchError((error) => {
console.error('Error creating library:', error);
throw error;
})
);
}
deleteLibrary(libraryId: number | null): Observable<void> {
return this.http.delete<void>(`${this.libraryUrl}/${libraryId}`).pipe(
tap(() => {
const currentLibraries = this.#libraries();
this.#libraries.set(currentLibraries.filter(library => library.id !== libraryId));
const updatedLastReadBooks = this.#lastReadBooks().filter(book => book.libraryId !== libraryId);
this.#lastReadBooks.set(updatedLastReadBooks);
const updatedLatestAddedBooks = this.#latestAddedBooks().filter(book => book.libraryId !== libraryId);
this.#latestAddedBooks.set(updatedLatestAddedBooks);
const updatedMap = new Map(this.libraryBooksMap());
updatedMap.delete(libraryId as number);
this.libraryBooksMap.set(updatedMap);
console.log(`Library ${libraryId} and associated books removed successfully.`);
}),
catchError((error) => {
console.error('Error deleting library:', error);
throw error;
})
);
}
/*---------- Book Methods go below ----------*/
readBook(book: Book): void {
this.addToLastReadBooks(book);
const url = `/pdf-viewer/book/${book.id}`;
window.open(url, '_blank');
this.updateLastReadTime(book.id).subscribe({
complete: () => {
},
error: (err) => console.error('Failed to update last read time', err),
});
}
addToLastReadBooks(book: Book): void {
const updatedBooks = [book, ...this.#lastReadBooks()];
this.#lastReadBooks.set(updatedBooks.slice(0, 25));
}
addToLatestAddedBooks(book: Book): void {
const updatedBooks = [book, ...this.#latestAddedBooks()];
this.#latestAddedBooks.set(updatedBooks.slice(0, 25));
}
getLibraryBooks(libraryId: number) {
return computed(() => this.libraryBooksMap().get(libraryId) || []);
}
loadBooksSignal(libraryId: number) {
if (!this.loadedLibraries.has(libraryId)) {
this.http.get<Book[]>(`${this.libraryUrl}/${libraryId}/book`).pipe(
map(response => response),
catchError(error => {
console.error(`Error loading books for library ${libraryId}:`, error);
return of([]);
})
).subscribe((books) => {
const updatedMap = new Map(this.libraryBooksMap());
updatedMap.set(libraryId, books);
this.libraryBooksMap.set(updatedMap);
this.loadedLibraries.add(libraryId);
console.log(`Loaded books for library ${libraryId}`);
});
}
}
handleNewBook(book: Book) {
const newBook: Book = this.convertBookDTOToBook(book);
this.#libraryBooks.set([newBook, ...this.#libraryBooks()]);
const updatedMap = new Map(this.libraryBooksMap());
const currentBooks = updatedMap.get(newBook.libraryId) || [];
updatedMap.set(newBook.libraryId, [newBook, ...currentBooks]);
this.libraryBooksMap.set(updatedMap);
this.addToLatestAddedBooks(book);
}
private convertBookDTOToBook(book: Book): Book {
@@ -61,28 +171,6 @@ export class BookService {
return this.http.get<BookWithNeighborsDTO>(`${this.libraryUrl}/${libraryId}/book/${bookId}/withNeighbors`);
}
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<Book[]>(`${this.bookUrl}?sortBy=lastReadTime&sortDir=desc`).pipe(
map(response => response),
@@ -1,46 +0,0 @@
import {computed, Injectable, signal} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { Library, LibraryApiResponse } from '../model/library.model';
@Injectable({
providedIn: 'root'
})
export class LibraryService {
private libraryUrl: string = 'http://localhost:8080/v1/library';
#libraries = signal<Library[]>([]);
libraries = computed(this.#libraries);
constructor(private http: HttpClient) {}
initializeLibraries(): void {
this.http.get<LibraryApiResponse>(this.libraryUrl).pipe(
map(response => response.content),
catchError(error => {
console.error('Error loading libraries:', error);
return of([]);
})
).subscribe(
(libraries) => {
this.#libraries.set(libraries);
console.log("Library Initialized")
}
);
}
createLibrary(newLibrary: Library): Observable<Library> {
return this.http.post<Library>(this.libraryUrl, newLibrary).pipe(
tap((createdLibrary) => {
const currentLibraries = this.#libraries();
currentLibraries.push(createdLibrary);
this.#libraries.set(currentLibraries);
}),
catchError(error => {
console.error('Error creating library:', error);
throw error;
})
);
}
}
+2
View File
@@ -5,7 +5,9 @@ import { RxStomp } from '@stomp/rx-stomp';
providedIn: 'root',
})
export class RxStompService extends RxStomp {
constructor() {
super();
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB