Revamp state management
This commit is contained in:
@@ -30,6 +30,11 @@ public class ShelfController {
|
|||||||
return ResponseEntity.ok(shelfService.getShelf(shelfId));
|
return ResponseEntity.ok(shelfService.getShelf(shelfId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{shelfId}/books")
|
||||||
|
public ResponseEntity<List<BookDTO>> getShelfBooks(@PathVariable Long shelfId) {
|
||||||
|
return ResponseEntity.ok(shelfService.getShelfBooks(shelfId));
|
||||||
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
public ResponseEntity<ShelfDTO> createShelf(@Valid @RequestBody ShelfCreateRequest request) {
|
public ResponseEntity<ShelfDTO> createShelf(@Valid @RequestBody ShelfCreateRequest request) {
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(shelfService.createShelf(request));
|
return ResponseEntity.status(HttpStatus.CREATED).body(shelfService.createShelf(request));
|
||||||
|
|||||||
@@ -33,5 +33,8 @@ public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificat
|
|||||||
Optional<Book> findFirstByLibraryIdAndIdLessThanOrderByIdDesc(Long libraryId, Long currentBookId);
|
Optional<Book> findFirstByLibraryIdAndIdLessThanOrderByIdDesc(Long libraryId, Long currentBookId);
|
||||||
|
|
||||||
Optional<Book> findFirstByLibraryIdAndIdGreaterThanOrderByIdAsc(Long libraryId, Long currentBookId);
|
Optional<Book> findFirstByLibraryIdAndIdGreaterThanOrderByIdAsc(Long libraryId, Long currentBookId);
|
||||||
|
|
||||||
|
@Query("SELECT b FROM Book b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||||
|
List<Book> findByShelfId(@Param("shelfId") Long shelfId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -75,4 +75,10 @@ public class ShelfService {
|
|||||||
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||||
shelfRepository.deleteById(shelfId);
|
shelfRepository.deleteById(shelfId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<BookDTO> getShelfBooks(Long shelfId) {
|
||||||
|
shelfRepository.findById(shelfId).orElseThrow(() -> ApiError.SHELF_NOT_FOUND.createException(shelfId));
|
||||||
|
List<Book> books = bookRepository.findByShelfId(shelfId);
|
||||||
|
return books.stream().map(BookTransformer::convertToBookDTO).toList();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
<div class="book-card">
|
<div class="book-card">
|
||||||
<div class="cover-container">
|
<div class="cover-container">
|
||||||
<img [src]="coverImageSrc(book)" class="book-cover placeholder" alt="Cover of {{ book.metadata.title }}" loading="lazy" />
|
<img [src]="coverImageSrc(book)" class="book-cover placeholder" alt="Cover of {{ book.metadata?.title }}" loading="lazy" />
|
||||||
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book)"></p-button>
|
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book)"></p-button>
|
||||||
<p-button [rounded]="true" icon="pi pi-book" class="info-btn" (click)="readBook(book)"></p-button>
|
<p-button [rounded]="true" icon="pi pi-book" class="info-btn" (click)="readBook(book)"></p-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="book-info">
|
<div class="book-info">
|
||||||
<div class="book-title-container">
|
<div class="book-title-container">
|
||||||
<h4 class="book-title">{{ book.metadata.title }}</h4>
|
<h4 class="book-title">{{ book.metadata?.title }}</h4>
|
||||||
<p-menu #menu [model]="items" [popup]="true" appendTo="body" />
|
<p-menu #menu [model]="items" [popup]="true" appendTo="body" />
|
||||||
<p-button [text]="true" (click)="menu.toggle($event)" icon="pi pi-ellipsis-v" />
|
<p-button [text]="true" (click)="menu.toggle($event)" icon="pi pi-ellipsis-v" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export class BookCardComponent implements OnInit {
|
|||||||
|
|
||||||
private openShelfDialog(book: Book) {
|
private openShelfDialog(book: Book) {
|
||||||
this.dialogService.open(ShelfAssignerComponent, {
|
this.dialogService.open(ShelfAssignerComponent, {
|
||||||
header: 'Update Shelves: ' + book.metadata.title,
|
header: 'Update Shelves: ' + book.metadata?.title,
|
||||||
modal: true,
|
modal: true,
|
||||||
width: '30%',
|
width: '30%',
|
||||||
height: '70%',
|
height: '70%',
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ export class BookMetadataComponent implements OnInit, OnDestroy {
|
|||||||
data: {
|
data: {
|
||||||
bookId: bookId,
|
bookId: bookId,
|
||||||
libraryId: libraryId,
|
libraryId: libraryId,
|
||||||
bookTitle: this.book?.metadata.title,
|
bookTitle: this.book?.metadata?.title,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div class="library-header">
|
<div class="library-header">
|
||||||
<div class="library-header-dial">
|
<div class="library-header-dial">
|
||||||
<h3 class="library-name">{{ currentEntityName() }}</h3>
|
<h3 class="library-name">{{ title() }}</h3>
|
||||||
<p-speedDial
|
<p-speedDial
|
||||||
[model]="items!"
|
[model]="items!"
|
||||||
direction="right"
|
direction="right"
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
<div class="content-container">
|
<div class="content-container">
|
||||||
<div class="card-container">
|
<div class="card-container">
|
||||||
<virtual-scroller class="virtual-scroller" #scroll [items]="currentEntityBooks()">
|
<virtual-scroller class="virtual-scroller" #scroll [items]="books()">
|
||||||
<div class="grid" #container>
|
<div class="grid" #container>
|
||||||
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
|
<div class="virtual-scroller-item" *ngFor="let book of scroll.viewPortItems">
|
||||||
<app-book-card [book]="book"></app-book-card>
|
<app-book-card [book]="book"></app-book-card>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Component, OnInit, computed, signal } from '@angular/core';
|
import {Component, OnInit, computed, signal, Signal} from '@angular/core';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import { LibraryAndBookService } from '../../service/library-and-book.service';
|
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
||||||
import { ConfirmationService, MenuItem, MessageService } from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
|
import {Book} from "../../model/book.model";
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-books-browser',
|
selector: 'app-books-browser',
|
||||||
@@ -10,27 +11,27 @@ import { ConfirmationService, MenuItem, MessageService } from 'primeng/api';
|
|||||||
styleUrls: ['./books-browser.component.scss']
|
styleUrls: ['./books-browser.component.scss']
|
||||||
})
|
})
|
||||||
export class BooksBrowserComponent implements OnInit {
|
export class BooksBrowserComponent implements OnInit {
|
||||||
|
|
||||||
private currentEntityId = signal<number | null>(null);
|
private currentEntityId = signal<number | null>(null);
|
||||||
private entityType = signal<'library' | 'shelf'>('library'); // Default to library
|
private entityType = signal<'library' | 'shelf'>('library');
|
||||||
|
|
||||||
|
books!: Signal<Book[]>;
|
||||||
|
title = computed(() => {
|
||||||
|
const entityId = this.currentEntityId();
|
||||||
|
const type = this.entityType();
|
||||||
|
if (type === 'library') {
|
||||||
|
const library = this.libraryBookService.getLibraries()().find(library => library.id === entityId);
|
||||||
|
return library ? `Library: ${library.name}` : 'Library not found';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === 'shelf') {
|
||||||
|
const shelf = this.libraryBookService.getShelves()().find(shelf => shelf.id === entityId);
|
||||||
|
return shelf ? `Shelf: ${shelf.name}` : 'Shelf not found';
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
|
||||||
items: MenuItem[] | undefined;
|
items: MenuItem[] | undefined;
|
||||||
|
|
||||||
protected currentEntityBooks = computed(() => {
|
|
||||||
if (this.currentEntityId() != null) {
|
|
||||||
return this.entityType() === 'library'
|
|
||||||
? this.libraryBookService.getLibraryBooks(this.currentEntityId()!)()
|
|
||||||
: this.libraryBookService.getShelfBooks(this.currentEntityId()!)();
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
});
|
|
||||||
|
|
||||||
protected currentEntityName = computed(() => {
|
|
||||||
if (this.entityType() === 'library') {
|
|
||||||
return 'Library: ' + (this.libraryBookService.libraries().find(library => library.id === this.currentEntityId())?.name || 'Library not found');
|
|
||||||
}
|
|
||||||
return 'Shelf: ' + (this.libraryBookService.shelves().find(shelf => shelf.id === this.currentEntityId())?.name || 'Shelf not found');
|
|
||||||
});
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private activatedRoute: ActivatedRoute,
|
private activatedRoute: ActivatedRoute,
|
||||||
@@ -38,70 +39,35 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
private libraryBookService: LibraryAndBookService,
|
private libraryBookService: LibraryAndBookService,
|
||||||
private confirmationService: ConfirmationService,
|
private confirmationService: ConfirmationService,
|
||||||
private messageService: MessageService
|
private messageService: MessageService
|
||||||
) {}
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.activatedRoute.paramMap.subscribe((params) => {
|
this.activatedRoute.paramMap.subscribe((params) => {
|
||||||
const libraryId = Number(params.get('libraryId'));
|
const libraryId = Number(params.get('libraryId'));
|
||||||
const shelfId = Number(params.get('shelfId'));
|
const shelfId = Number(params.get('shelfId'));
|
||||||
|
|
||||||
if (libraryId) {
|
if (libraryId) {
|
||||||
this.entityType.set('library');
|
this.entityType.set('library');
|
||||||
this.currentEntityId.set(libraryId);
|
this.currentEntityId.set(libraryId);
|
||||||
this.libraryBookService.loadLibraryBooks(libraryId);
|
this.books = this.libraryBookService.getLibraryBooks(libraryId);
|
||||||
|
this.libraryBookService.getLibraries();
|
||||||
} else if (shelfId) {
|
} else if (shelfId) {
|
||||||
this.entityType.set('shelf');
|
this.entityType.set('shelf');
|
||||||
this.currentEntityId.set(shelfId);
|
this.currentEntityId.set(shelfId);
|
||||||
this.libraryBookService.loadLibraryBooks(shelfId);
|
this.books = this.libraryBookService.getShelfBooks(shelfId);
|
||||||
|
this.libraryBookService.getShelves();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (this.entityType() === 'library') {
|
if (this.entityType() === 'library') {
|
||||||
this.initializeLibraryMenuItems();
|
this.initializeLibraryMenuItems();
|
||||||
} else if (this.entityType() === 'shelf') {
|
} else if (this.entityType() === 'shelf') {
|
||||||
//this.initializeShelfMenuItems();
|
this.initializeShelfMenuItems();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private initializeLibraryMenuItems(): void {
|
private initializeLibraryMenuItems(): void {
|
||||||
this.items = [
|
this.items = [
|
||||||
{
|
|
||||||
icon: 'pi pi-pencil',
|
|
||||||
tooltipOptions: {
|
|
||||||
tooltipLabel: 'Rename',
|
|
||||||
tooltipPosition: 'top'
|
|
||||||
},
|
|
||||||
command: () => {
|
|
||||||
this.confirmationService.confirm({
|
|
||||||
message: 'Sure you want to delete: ' + this.currentEntityName() + "?",
|
|
||||||
header: 'Confirmation',
|
|
||||||
icon: 'pi pi-exclamation-triangle',
|
|
||||||
acceptIcon: 'none',
|
|
||||||
rejectIcon: 'none',
|
|
||||||
rejectButtonStyleClass: 'p-button-text',
|
|
||||||
accept: () => {
|
|
||||||
this.libraryBookService.deleteLibrary(this.currentEntityId()).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',
|
icon: 'pi pi-trash',
|
||||||
tooltipOptions: {
|
tooltipOptions: {
|
||||||
@@ -110,7 +76,7 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
},
|
},
|
||||||
command: () => {
|
command: () => {
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: 'Sure you want to delete: ' + this.currentEntityName() + "?",
|
message: 'Sure you want to delete ' + this.title() + "?",
|
||||||
header: 'Confirmation',
|
header: 'Confirmation',
|
||||||
icon: 'pi pi-exclamation-triangle',
|
icon: 'pi pi-exclamation-triangle',
|
||||||
acceptIcon: 'none',
|
acceptIcon: 'none',
|
||||||
@@ -142,45 +108,8 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/*private initializeShelfMenuItems(): void {
|
private initializeShelfMenuItems(): void {
|
||||||
this.items = [
|
this.items = [
|
||||||
{
|
|
||||||
icon: 'pi pi-pencil',
|
|
||||||
tooltipOptions: {
|
|
||||||
tooltipLabel: 'Rename',
|
|
||||||
tooltipPosition: 'top'
|
|
||||||
},
|
|
||||||
command: () => {
|
|
||||||
this.confirmationService.confirm({
|
|
||||||
message: 'Sure you want to delete: ' + this.currentEntityName() + "?",
|
|
||||||
header: 'Confirmation',
|
|
||||||
icon: 'pi pi-exclamation-triangle',
|
|
||||||
acceptIcon: 'none',
|
|
||||||
rejectIcon: 'none',
|
|
||||||
rejectButtonStyleClass: 'p-button-text',
|
|
||||||
accept: () => {
|
|
||||||
this.libraryBookService.deleteShelf(this.currentEntityId()).subscribe({
|
|
||||||
complete: () => {
|
|
||||||
this.router.navigate(['/']);
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'info',
|
|
||||||
summary: 'Success',
|
|
||||||
detail: 'Shelf was deleted'
|
|
||||||
});
|
|
||||||
},
|
|
||||||
error: () => {
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'error',
|
|
||||||
summary: 'Failed',
|
|
||||||
detail: 'Failed to delete shelf',
|
|
||||||
life: 3000
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
icon: 'pi pi-trash',
|
icon: 'pi pi-trash',
|
||||||
tooltipOptions: {
|
tooltipOptions: {
|
||||||
@@ -189,14 +118,14 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
},
|
},
|
||||||
command: () => {
|
command: () => {
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: 'Sure you want to delete: ' + this.currentEntityName() + "?",
|
message: 'Sure you want to delete ' + this.title() + "?",
|
||||||
header: 'Confirmation',
|
header: 'Confirmation',
|
||||||
icon: 'pi pi-exclamation-triangle',
|
icon: 'pi pi-exclamation-triangle',
|
||||||
acceptIcon: 'none',
|
acceptIcon: 'none',
|
||||||
rejectIcon: 'none',
|
rejectIcon: 'none',
|
||||||
rejectButtonStyleClass: 'p-button-text',
|
rejectButtonStyleClass: 'p-button-text',
|
||||||
accept: () => {
|
accept: () => {
|
||||||
this.libraryBookService.deleteShelf(this.currentEntityId()).subscribe({
|
this.libraryBookService.deleteShelf(this.currentEntityId()!).subscribe({
|
||||||
complete: () => {
|
complete: () => {
|
||||||
this.router.navigate(['/']);
|
this.router.navigate(['/']);
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
@@ -219,5 +148,5 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
}*/
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -2,7 +2,7 @@
|
|||||||
<div class="book-list-container">
|
<div class="book-list-container">
|
||||||
<div class="last-read-title-container">
|
<div class="last-read-title-container">
|
||||||
<h2 class="last-read-title">{{ title }}</h2>
|
<h2 class="last-read-title">{{ title }}</h2>
|
||||||
<div *ngIf="booksSignal().length === 0">
|
<div *ngIf="booksSignal!().length === 0">
|
||||||
<h4>No books available.</h4>
|
<h4>No books available.</h4>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -12,10 +12,10 @@
|
|||||||
[infiniteScrollThrottle]="50"
|
[infiniteScrollThrottle]="50"
|
||||||
#scrollContainer
|
#scrollContainer
|
||||||
[horizontal]="true">
|
[horizontal]="true">
|
||||||
<div class="book-item" *ngFor="let book of booksSignal()">
|
<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"/>
|
<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>
|
||||||
<p>{{ getAuthorNames(book) }}</p>
|
<p>{{ getAuthorNames(book) }}</p>
|
||||||
<p-button [rounded]="true" icon="pi pi-eye" class="view-btn" (click)="openBook(book)"></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>
|
<p-button [rounded]="true" icon="pi pi-info" class="read-btn" (click)="openBookInfo(book.id, book.libraryId)"></p-button>
|
||||||
|
|||||||
+6
-7
@@ -1,4 +1,4 @@
|
|||||||
import {Component, OnInit, ViewChild, ElementRef, Input, computed, signal} from '@angular/core';
|
import {Component, OnInit, ViewChild, ElementRef, Input, computed, signal, Signal} from '@angular/core';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
@@ -23,21 +23,20 @@ export class DashboardScrollerComponent implements OnInit {
|
|||||||
@Input() title: string = 'Last Read Books';
|
@Input() title: string = 'Last Read Books';
|
||||||
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
|
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
|
||||||
|
|
||||||
booksSignal = computed(() => {
|
booksSignal: Signal<Book[]> | undefined;
|
||||||
return this.bookListType === 'lastRead' ? this.bookService.lastReadBooks() : this.bookService.latestAddedBooks();
|
|
||||||
});
|
|
||||||
|
|
||||||
constructor(private bookService: LibraryAndBookService, private router: Router) {
|
constructor(private bookService: LibraryAndBookService, private router: Router) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.booksSignal = this.bookListType === 'lastRead' ? this.bookService.getLastReadBooks() : this.bookService.getLatestAddedBooks();;
|
||||||
this.loadBooks();
|
this.loadBooks();
|
||||||
}
|
}
|
||||||
|
|
||||||
loadBooks(): void {
|
loadBooks(): void {
|
||||||
if (this.bookListType === 'lastRead' && !this.bookService.lastReadBooksLoaded) {
|
if (this.bookListType === 'lastRead' && !this.bookService.getLastReadBooks()) {
|
||||||
this.bookService.getLastReadBooks();
|
this.bookService.getLastReadBooks();
|
||||||
} else if (this.bookListType === 'latestAdded' && !this.bookService.latestAddedBooksLoaded) {
|
} else if (this.bookListType === 'latestAdded' && !this.bookService.getLatestAddedBooks()) {
|
||||||
this.bookService.getLatestAddedBooks();
|
this.bookService.getLatestAddedBooks();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -47,7 +46,7 @@ export class DashboardScrollerComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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';
|
||||||
}
|
}
|
||||||
|
|
||||||
openBook(book: Book): void {
|
openBook(book: Book): void {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ export class DashboardComponent {
|
|||||||
ref: DynamicDialogRef | undefined;
|
ref: DynamicDialogRef | undefined;
|
||||||
|
|
||||||
constructor(private libraryBookService: LibraryAndBookService, public dialogService: DialogService) {
|
constructor(private libraryBookService: LibraryAndBookService, public dialogService: DialogService) {
|
||||||
this.libraries = this.libraryBookService.libraries;
|
this.libraries = this.libraryBookService.getLibraries();
|
||||||
}
|
}
|
||||||
|
|
||||||
get isLibrariesEmpty(): boolean {
|
get isLibrariesEmpty(): boolean {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export class FileUploadComponent {
|
|||||||
private fileUploadService: FileUploadService,
|
private fileUploadService: FileUploadService,
|
||||||
private toastService: ToastService,
|
private toastService: ToastService,
|
||||||
private dynamicDialogRef: DynamicDialogRef) {
|
private dynamicDialogRef: DynamicDialogRef) {
|
||||||
this.libraries = this.libraryBookService.libraries;
|
this.libraries = this.libraryBookService.getLibraries();
|
||||||
}
|
}
|
||||||
|
|
||||||
triggerFileInput(fileInput: HTMLInputElement): void {
|
triggerFileInput(fileInput: HTMLInputElement): void {
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ export class AppMenuComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
libraryMenu = computed(() => {
|
libraryMenu = computed(() => {
|
||||||
const libraries = this.libraryBookService.libraries();
|
const libraries = this.libraryBookService.getLibraries()();
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
label: 'Library',
|
label: 'Library',
|
||||||
@@ -46,7 +46,7 @@ export class AppMenuComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
|
|
||||||
shelfMenu = computed(() => {
|
shelfMenu = computed(() => {
|
||||||
const shelves = this.libraryBookService.shelves();
|
const shelves = this.libraryBookService.getShelves()();
|
||||||
return [
|
return [
|
||||||
{
|
{
|
||||||
label: 'Shelves',
|
label: 'Shelves',
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
<ng-container *ngIf="books.length > 0; else noResults">
|
<ng-container *ngIf="books.length > 0; else noResults">
|
||||||
<div class="search-dropdown-item" *ngFor="let book of books" (click)="onBookClick(book)">
|
<div class="search-dropdown-item" *ngFor="let book of books" (click)="onBookClick(book)">
|
||||||
<img [src]="getBookCoverUrl(book.id)" alt="Book Cover" class="search-book-cover" />
|
<img [src]="getBookCoverUrl(book.id)" alt="Book Cover" class="search-book-cover" />
|
||||||
<span class="search-book-name">{{ book.metadata.title }}</span>
|
<span class="search-book-name">{{ book.metadata?.title }}</span>
|
||||||
</div>
|
</div>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
|
|
||||||
|
|||||||
@@ -13,9 +13,7 @@ import {MessageService} from 'primeng/api';
|
|||||||
})
|
})
|
||||||
export class ShelfAssignerComponent implements OnInit {
|
export class ShelfAssignerComponent implements OnInit {
|
||||||
|
|
||||||
shelves = computed(() => {
|
shelves;
|
||||||
return this.libraryBookService.shelves();
|
|
||||||
});
|
|
||||||
|
|
||||||
book: Book;
|
book: Book;
|
||||||
selectedShelves: any[] = [];
|
selectedShelves: any[] = [];
|
||||||
@@ -25,6 +23,7 @@ export class ShelfAssignerComponent implements OnInit {
|
|||||||
constructor(
|
constructor(
|
||||||
private libraryBookService: LibraryAndBookService, private dynamicDialogConfig: DynamicDialogConfig,
|
private libraryBookService: LibraryAndBookService, private dynamicDialogConfig: DynamicDialogConfig,
|
||||||
private dynamicDialogRef: DynamicDialogRef, private messageService: MessageService) {
|
private dynamicDialogRef: DynamicDialogRef, private messageService: MessageService) {
|
||||||
|
this.shelves = this.libraryBookService.getShelves();
|
||||||
this.book = this.dynamicDialogConfig.data.book;
|
this.book = this.dynamicDialogConfig.data.book;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
export interface Book {
|
export interface Book {
|
||||||
id: number;
|
id: number;
|
||||||
libraryId: number;
|
libraryId: number;
|
||||||
metadata: BookMetadata;
|
metadata?: BookMetadata;
|
||||||
shelves?: Shelf[];
|
shelves?: Shelf[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,313 +1,577 @@
|
|||||||
import {Observable, of} from 'rxjs';
|
|
||||||
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO, Shelf} from '../model/book.model';
|
|
||||||
import {computed, Injectable, signal} from '@angular/core';
|
import {computed, Injectable, signal} from '@angular/core';
|
||||||
import {HttpClient} from '@angular/common/http';
|
|
||||||
import {catchError, map, tap} from 'rxjs/operators';
|
|
||||||
import {Library, LibraryApiResponse} from '../model/library.model';
|
import {Library, LibraryApiResponse} from '../model/library.model';
|
||||||
|
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO, Shelf} from '../model/book.model';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {Observable, of, tap} from 'rxjs';
|
||||||
|
import {catchError, map} from 'rxjs/operators';
|
||||||
|
|
||||||
@Injectable({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class LibraryAndBookService {
|
export class LibraryAndBookService {
|
||||||
private readonly libraryUrl = 'http://localhost:8080/v1/library';
|
|
||||||
private readonly bookUrl = 'http://localhost:8080/v1/book';
|
|
||||||
private readonly shelfUrl = 'http://localhost:8080/v1/shelf';
|
|
||||||
|
|
||||||
#libraries = signal<Library[]>([]);
|
private readonly libraryUrl = 'http://localhost:8080/v1/library';
|
||||||
libraries = computed(this.#libraries);
|
private readonly bookUrl = 'http://localhost:8080/v1/book';
|
||||||
|
private readonly shelfUrl = 'http://localhost:8080/v1/shelf';
|
||||||
|
|
||||||
#shelves = signal<Shelf[]>([]);
|
#appState = signal<{
|
||||||
shelves = computed(this.#shelves);
|
libraries: Library[];
|
||||||
|
shelves: Shelf[];
|
||||||
|
books: Book[];
|
||||||
|
lastReadBooks: Set<number> | null;
|
||||||
|
latestAddedBooks: Set<number> | null;
|
||||||
|
libraryBooksMap: Map<number, Set<number>>;
|
||||||
|
shelfBooksMap: Map<number, Set<number>>;
|
||||||
|
}>({
|
||||||
|
libraries: [],
|
||||||
|
shelves: [],
|
||||||
|
books: [],
|
||||||
|
lastReadBooks: new Set(),
|
||||||
|
latestAddedBooks: new Set(),
|
||||||
|
libraryBooksMap: new Map(),
|
||||||
|
shelfBooksMap: new Map(),
|
||||||
|
});
|
||||||
|
|
||||||
#lastReadBooks = signal<Book[]>([]);
|
constructor(private http: HttpClient) {
|
||||||
lastReadBooks = computed(this.#lastReadBooks);
|
}
|
||||||
lastReadBooksLoaded: boolean = false;
|
|
||||||
|
|
||||||
#latestAddedBooks = signal<Book[]>([]);
|
|
||||||
latestAddedBooks = computed(this.#latestAddedBooks);
|
|
||||||
latestAddedBooksLoaded: boolean = false;
|
|
||||||
|
|
||||||
private libraryBooksMap = signal<Map<number, Book[]>>(new Map());
|
|
||||||
private loadedLibraries = new Set<number>();
|
|
||||||
|
|
||||||
|
|
||||||
constructor(private http: HttpClient) {
|
/*---------- Shelf Methods go below ----------*/
|
||||||
}
|
|
||||||
|
|
||||||
|
initializeShelves(): void {
|
||||||
/*---------- Shelf Methods go below ----------*/
|
this.http.get<Shelf[]>(this.shelfUrl).pipe(
|
||||||
|
map(response => response),
|
||||||
initializeShelves(): void {
|
catchError(error => {
|
||||||
this.http.get<Shelf[]>(this.shelfUrl).pipe(
|
console.error('Error loading shelves:', error);
|
||||||
map(response => response),
|
return of([]);
|
||||||
catchError(error => {
|
})
|
||||||
console.error('Error loading shelves:', error);
|
).subscribe(
|
||||||
return of([]);
|
(shelves) => {
|
||||||
})
|
this.#appState.set({
|
||||||
).subscribe(
|
...this.#appState(),
|
||||||
(shelves) => {
|
shelves: shelves,
|
||||||
this.#shelves.set(shelves);
|
});
|
||||||
console.log("Shelves Initialized")
|
console.log("Shelves Initialized");
|
||||||
}
|
}
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
createShelf(name: string): Observable<Shelf> {
|
|
||||||
const newShelf: Shelf = {name};
|
|
||||||
return this.http.post<Shelf>(this.shelfUrl, newShelf).pipe(
|
|
||||||
tap((createdShelf) => {
|
|
||||||
this.#shelves.set([...this.#shelves(), createdShelf]);
|
|
||||||
console.log("New Shelf Created", createdShelf);
|
|
||||||
}),
|
|
||||||
catchError((error) => {
|
|
||||||
console.error('Error creating shelf:', error);
|
|
||||||
throw error;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
assignShelvesToBook(book: Book, shelfIds: number[]): Observable<Book> {
|
|
||||||
const requestPayload = {
|
|
||||||
bookId: book.id,
|
|
||||||
shelfIds: shelfIds
|
|
||||||
};
|
|
||||||
return this.http.post<Book>(`${this.shelfUrl}/assign-shelves`, requestPayload).pipe(
|
|
||||||
tap((updatedBook) => {
|
|
||||||
const bookLibraryId = book.libraryId;
|
|
||||||
const updatedMap = new Map(this.libraryBooksMap());
|
|
||||||
const libraryBooks = updatedMap.get(bookLibraryId) || [];
|
|
||||||
const updatedLibraryBooks = libraryBooks.map(b =>
|
|
||||||
b.id === book.id ? { ...b, shelves: updatedBook.shelves } : b
|
|
||||||
);
|
);
|
||||||
updatedMap.set(bookLibraryId, updatedLibraryBooks);
|
|
||||||
this.libraryBooksMap.set(updatedMap);
|
|
||||||
}),
|
|
||||||
catchError((error) => {
|
|
||||||
console.error('Error assigning shelves to book:', error);
|
|
||||||
throw error;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*---------- 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;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
loadLibraryBooks(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}`);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
deleteLibrary(libraryId: number | null): Observable<void> {
|
getShelves() {
|
||||||
return this.http.delete<void>(`${this.libraryUrl}/${libraryId}`).pipe(
|
return computed(() => this.#appState().shelves);
|
||||||
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 {
|
|
||||||
const url = `/pdf-viewer/book/${book.id}`;
|
|
||||||
window.open(url, '_blank');
|
|
||||||
this.addToLastReadBooks(book);
|
|
||||||
this.updateLastReadTime(book.id).subscribe({
|
|
||||||
complete: () => {
|
|
||||||
},
|
|
||||||
error: (err) => console.error('Failed to update last read time', err),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
addToLastReadBooks(book: Book): void {
|
|
||||||
this.#lastReadBooks.set([book, ...this.#lastReadBooks()
|
|
||||||
.filter(b => b.id !== book.id)]
|
|
||||||
.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) || []);
|
|
||||||
}
|
|
||||||
|
|
||||||
getShelfBooks(shelfId: number) {
|
|
||||||
return computed(() => {
|
|
||||||
const allBooks = Array.from(this.libraryBooksMap().values()).flat();
|
|
||||||
return allBooks.filter(book => book.shelves?.some(shelf => shelf.id === shelfId));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
handleNewBook(book: Book) {
|
|
||||||
const newBook: Book = this.convertBookDTOToBook(book);
|
|
||||||
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 {
|
|
||||||
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}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
getBookWithNeighbours(libraryId: number, bookId: number): Observable<BookWithNeighborsDTO> {
|
|
||||||
return this.http.get<BookWithNeighborsDTO>(`${this.libraryUrl}/${libraryId}/book/${bookId}/withNeighbors`);
|
|
||||||
}
|
|
||||||
|
|
||||||
getLastReadBooks() {
|
|
||||||
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([]);
|
|
||||||
})
|
|
||||||
).subscribe(
|
|
||||||
(books) => {
|
|
||||||
this.#lastReadBooks.set([...this.#lastReadBooks(), ...books]);
|
|
||||||
this.lastReadBooksLoaded = true;
|
|
||||||
console.log("Loaded last read books")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
getLatestAddedBooks() {
|
|
||||||
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([]);
|
|
||||||
})
|
|
||||||
).subscribe(
|
|
||||||
(books) => {
|
|
||||||
this.#latestAddedBooks.set([...this.#latestAddedBooks(), ...books]);
|
|
||||||
this.latestAddedBooksLoaded = true;
|
|
||||||
console.log("Loaded latest added books")
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
searchBooks(query: string): Observable<Book[]> {
|
|
||||||
if (query.length < 2) {
|
|
||||||
return of([]);
|
|
||||||
}
|
}
|
||||||
return this.http.get<Book[]>(`${this.bookUrl}/search?title=${encodeURIComponent(query)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> {
|
createShelf(name: string): Observable<Shelf> {
|
||||||
const url = `${this.bookUrl}/${bookId}/viewer-setting`;
|
return this.http.post<Shelf>(this.shelfUrl, {name}).pipe(
|
||||||
return this.http.put<void>(url, viewerSetting);
|
map(newShelf => {
|
||||||
}
|
const updatedShelfBooksMap = new Map(this.#appState().shelfBooksMap);
|
||||||
|
updatedShelfBooksMap.set(newShelf.id!, new Set());
|
||||||
|
const updatedState = {
|
||||||
|
...this.#appState(),
|
||||||
|
shelves: [...this.#appState().shelves, newShelf],
|
||||||
|
shelfBooksMap: updatedShelfBooksMap
|
||||||
|
};
|
||||||
|
this.#appState.set(updatedState);
|
||||||
|
return newShelf;
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error creating shelf:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
getBookSetting(bookId: number): Observable<BookSetting> {
|
getShelfBooks(shelfId: number) {
|
||||||
return this.http.get<BookSetting>(`${this.bookUrl}/${bookId}/viewer-setting`);
|
// Check if shelfBooksMap does not contain the shelfId (books not loaded yet)
|
||||||
}
|
if (!this.#appState().shelfBooksMap.has(shelfId)) {
|
||||||
|
// Fetch the books for the shelf from the backend
|
||||||
|
this.http.get<Book[]>(`${this.shelfUrl}/${shelfId}/books`).pipe(
|
||||||
|
map((fetchedBooks) => {
|
||||||
|
// Filter out books that are already in the books state to avoid duplicates
|
||||||
|
const newBooks = fetchedBooks.filter(fetchedBook =>
|
||||||
|
!this.#appState().books.some(existingBook => existingBook.id === fetchedBook.id)
|
||||||
|
);
|
||||||
|
|
||||||
getBookDataUrl(bookId: number): string {
|
// If there are any new books, add them to the books state
|
||||||
return `${this.bookUrl}/${bookId}/data`;
|
if (newBooks.length > 0) {
|
||||||
}
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
books: [...this.#appState().books, ...newBooks],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
getBookCoverUrl(bookId: number): string {
|
// Update shelfBooksMap with the shelfId and the new books as a Set (not an array)
|
||||||
return `${this.bookUrl}/${bookId}/cover`;
|
const updatedShelfBooksMap = new Map(this.#appState().shelfBooksMap);
|
||||||
}
|
updatedShelfBooksMap.set(shelfId, new Set(fetchedBooks.map(book => book.id)));
|
||||||
|
|
||||||
updateLastReadTime(bookId: number): Observable<void> {
|
// Update the app state with the new shelfBooksMap
|
||||||
return this.http.put<void>(`${this.bookUrl}/${bookId}/update-last-read`, {});
|
this.#appState.set({
|
||||||
}
|
...this.#appState(),
|
||||||
|
shelfBooksMap: updatedShelfBooksMap,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error loading books for shelf:', error);
|
||||||
|
return of([]); // Return an empty array in case of error
|
||||||
|
})
|
||||||
|
).subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
fetchBookMetadataByBookId(bookId: number): Observable<BookMetadata[]> {
|
// Return a computed signal of books for the specified shelf
|
||||||
return this.http.get<BookMetadata[]>(`${this.bookUrl}/${bookId}/fetch-metadata`);
|
return computed(() => {
|
||||||
}
|
const bookIdsForShelf = this.#appState().shelfBooksMap.get(shelfId) || new Set<number>();
|
||||||
|
return this.#appState().books.filter(book => bookIdsForShelf.has(book.id));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fetchBookMetadataByTerm(term: string): Observable<BookMetadata[]> {
|
deleteShelf(shelfId: number): Observable<void> {
|
||||||
return this.http.get<BookMetadata[]>(`${this.bookUrl}/fetch-metadata?term=${term}`);
|
return this.http.delete<void>(`${this.shelfUrl}/${shelfId}`).pipe(
|
||||||
}
|
tap(() => {
|
||||||
|
const state = this.#appState();
|
||||||
|
|
||||||
|
// Update books by removing any references to the deleted shelf
|
||||||
|
const updatedBooks = state.books.map(book => ({
|
||||||
|
...book,
|
||||||
|
shelves: book.shelves?.filter(shelf => shelf.id !== shelfId),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Remove the shelf from shelfBooksMap
|
||||||
|
const updatedShelfBooksMap = new Map(state.shelfBooksMap);
|
||||||
|
updatedShelfBooksMap.delete(shelfId);
|
||||||
|
|
||||||
|
// Remove the shelf from shelves
|
||||||
|
const updatedShelves = state.shelves.filter(shelf => shelf.id !== shelfId);
|
||||||
|
|
||||||
|
this.#appState.update((state) => ({
|
||||||
|
...state,
|
||||||
|
books: updatedBooks,
|
||||||
|
shelfBooksMap: updatedShelfBooksMap,
|
||||||
|
shelves: updatedShelves,
|
||||||
|
}));
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error deleting shelf:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
assignShelvesToBook(book: Book, shelfIds: number[]): Observable<Book> {
|
||||||
|
const requestPayload = {
|
||||||
|
bookId: book.id,
|
||||||
|
shelfIds: shelfIds,
|
||||||
|
};
|
||||||
|
|
||||||
|
return this.http.post<Book>(`${this.shelfUrl}/assign-shelves`, requestPayload).pipe(
|
||||||
|
tap((updatedBook) => {
|
||||||
|
const state = this.#appState();
|
||||||
|
|
||||||
|
const books = [...state.books]; // Create a new books array to trigger reactivity
|
||||||
|
|
||||||
|
// Replace book's shelves with updated data
|
||||||
|
const matchedBookIndex = books.findIndex(b => b.id === updatedBook.id);
|
||||||
|
if (matchedBookIndex !== -1) {
|
||||||
|
books[matchedBookIndex] = {
|
||||||
|
...books[matchedBookIndex],
|
||||||
|
shelves: updatedBook.shelves || [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const shelfBooksMap = new Map(state.shelfBooksMap);
|
||||||
|
|
||||||
|
// Remove the book from all existing/previous shelves in the map
|
||||||
|
shelfBooksMap.forEach((bookSet, shelfId) => {
|
||||||
|
bookSet.delete(updatedBook.id);
|
||||||
|
if (bookSet.size === 0) {
|
||||||
|
shelfBooksMap.delete(shelfId); // Delete empty shelves
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add the book to the updated shelves in the map
|
||||||
|
updatedBook.shelves?.forEach((shelf) => {
|
||||||
|
if (shelf.id !== undefined) {
|
||||||
|
if (!shelfBooksMap.has(shelf.id)) {
|
||||||
|
shelfBooksMap.set(shelf.id, new Set());
|
||||||
|
}
|
||||||
|
shelfBooksMap.get(shelf.id)!.add(updatedBook.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.#appState.update((state) => ({
|
||||||
|
...state,
|
||||||
|
books,
|
||||||
|
shelfBooksMap,
|
||||||
|
}));
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error assigning shelves to book:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*---------- 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.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
libraries: libraries,
|
||||||
|
});
|
||||||
|
console.log("Library Initialized");
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getLibraries() {
|
||||||
|
return computed(() => this.#appState().libraries);
|
||||||
|
}
|
||||||
|
|
||||||
|
getLibraryBooks(libraryId: number) {
|
||||||
|
if (!this.#appState().libraryBooksMap.has(libraryId)) {
|
||||||
|
this.http.get<Book[]>(`${this.libraryUrl}/${libraryId}/book`).subscribe({
|
||||||
|
next: (books) => {
|
||||||
|
const updatedLibraryBooksMap = new Map(this.#appState().libraryBooksMap);
|
||||||
|
updatedLibraryBooksMap.set(libraryId, new Set(books.map(book => book.id)));
|
||||||
|
const existingBookIds = new Set(this.#appState().books.map(book => book.id));
|
||||||
|
const newBooks = books.filter(book => !existingBookIds.has(book.id));
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
libraryBooksMap: updatedLibraryBooksMap,
|
||||||
|
books: [...this.#appState().books, ...newBooks],
|
||||||
|
});
|
||||||
|
console.log(`Loaded books for library ${libraryId}`);
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
console.error(`Failed to load books for library ${libraryId}`, err);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return computed(() => {
|
||||||
|
const bookIds = this.#appState().libraryBooksMap.get(libraryId) || new Set();
|
||||||
|
return this.#appState().books.filter(book => bookIds.has(book.id));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
createLibrary(newLibrary: Library): Observable<Library> {
|
||||||
|
return this.http.post<Library>(this.libraryUrl, newLibrary).pipe(
|
||||||
|
map((createdLibrary) => {
|
||||||
|
const updatedLibraries = [...this.#appState().libraries, createdLibrary];
|
||||||
|
const updatedLibraryBooksMap = new Map(this.#appState().libraryBooksMap);
|
||||||
|
if (createdLibrary.id != null) {
|
||||||
|
updatedLibraryBooksMap.set(createdLibrary.id, new Set());
|
||||||
|
}
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
libraries: updatedLibraries,
|
||||||
|
libraryBooksMap: updatedLibraryBooksMap,
|
||||||
|
});
|
||||||
|
return createdLibrary;
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error creating library:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteLibrary(libraryId: number | null): Observable<void> {
|
||||||
|
if (libraryId === null) {
|
||||||
|
console.error('Library ID is null. Deletion aborted.');
|
||||||
|
return of(); // Return an empty observable
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.http.delete<void>(`${this.libraryUrl}/${libraryId}`).pipe(
|
||||||
|
map(() => {
|
||||||
|
// Filter out the library from the list of libraries
|
||||||
|
const updatedLibraries = this.#appState().libraries.filter(library => library.id !== libraryId);
|
||||||
|
|
||||||
|
// Update the libraryBooksMap by deleting the library's books
|
||||||
|
const updatedLibraryBooksMap = new Map(this.#appState().libraryBooksMap);
|
||||||
|
updatedLibraryBooksMap.delete(libraryId);
|
||||||
|
|
||||||
|
// Get books associated with this library and remove them from the books list
|
||||||
|
const booksToDelete = this.#appState().libraryBooksMap.get(libraryId) || new Set<number>;
|
||||||
|
const updatedBooks = this.#appState().books.filter(book => !booksToDelete.has(book.id));
|
||||||
|
|
||||||
|
// Remove books from lastReadBooks and latestAddedBooks sets
|
||||||
|
const updatedLastReadBooks = new Set([...this.#appState().lastReadBooks!].filter(bookId => !booksToDelete.has(bookId)));
|
||||||
|
const updatedLatestAddedBooks = new Set([...this.#appState().latestAddedBooks!].filter(bookId => !booksToDelete.has(bookId)));
|
||||||
|
|
||||||
|
// Remove books from shelfBooksMap
|
||||||
|
const updatedShelfBooksMap = new Map(this.#appState().shelfBooksMap);
|
||||||
|
booksToDelete.forEach(bookId => {
|
||||||
|
updatedShelfBooksMap.forEach((shelfBooks, shelfId) => {
|
||||||
|
shelfBooks.delete(bookId); // Use Set's delete method
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update the app state with the modified collections
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
libraries: updatedLibraries,
|
||||||
|
libraryBooksMap: updatedLibraryBooksMap,
|
||||||
|
books: updatedBooks,
|
||||||
|
lastReadBooks: updatedLastReadBooks,
|
||||||
|
latestAddedBooks: updatedLatestAddedBooks,
|
||||||
|
shelfBooksMap: updatedShelfBooksMap,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Library with ID ${libraryId} deleted successfully.`);
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error deleting library:', error);
|
||||||
|
return of(); // Return an empty observable in case of error
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*---------- Book Methods go below ----------*/
|
||||||
|
|
||||||
|
addToLastReadBooks(book: Book): void {
|
||||||
|
const currentLastReadBooks = new Set(this.#appState().lastReadBooks!);
|
||||||
|
|
||||||
|
// Step 1: Remove the book if it already exists
|
||||||
|
currentLastReadBooks.delete(book.id);
|
||||||
|
|
||||||
|
// Step 2: Add the book to the beginning of the set (Sets don't have a defined order, but we can simulate this by using delete and add)
|
||||||
|
currentLastReadBooks.add(book.id);
|
||||||
|
|
||||||
|
// Step 3: Ensure the set only contains the latest 25 books
|
||||||
|
// Remove the oldest book if the set exceeds 25 books (note: this simulates the "latest" behavior)
|
||||||
|
if (currentLastReadBooks.size > 25) {
|
||||||
|
const firstAdded = [...currentLastReadBooks][0]; // Get the first added item (oldest)
|
||||||
|
currentLastReadBooks.delete(firstAdded); // Remove the oldest book
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the app state with the new set of last read books
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
lastReadBooks: currentLastReadBooks,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Book added to lastReadBooks: ${book.metadata?.title}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
addToLatestAddedBooks(book: Book): void {
|
||||||
|
const currentLatestAddedBooks = new Set(this.#appState().latestAddedBooks!);
|
||||||
|
|
||||||
|
// Step 1: Remove the book if it already exists
|
||||||
|
currentLatestAddedBooks.delete(book.id);
|
||||||
|
|
||||||
|
// Step 2: Add the book to the set
|
||||||
|
currentLatestAddedBooks.add(book.id);
|
||||||
|
|
||||||
|
// Step 3: Ensure the set only contains the latest 25 books
|
||||||
|
// Remove the oldest book if the set exceeds 25 books
|
||||||
|
if (currentLatestAddedBooks.size > 25) {
|
||||||
|
const firstAdded = [...currentLatestAddedBooks][0]; // Get the first added item (oldest)
|
||||||
|
currentLatestAddedBooks.delete(firstAdded); // Remove the oldest book
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the app state with the new set of latest added books
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
latestAddedBooks: currentLatestAddedBooks,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Book added to latestAddedBooks: ${book.metadata?.title}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
readBook(book: Book): void {
|
||||||
|
const url = `/pdf-viewer/book/${book.id}`;
|
||||||
|
window.open(url, '_blank');
|
||||||
|
this.addToLastReadBooks(book);
|
||||||
|
this.updateLastReadTime(book.id).subscribe({
|
||||||
|
complete: () => {
|
||||||
|
},
|
||||||
|
error: (err) => console.error('Failed to update last read time', err),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
getBook(bookId: number): Observable<Book> {
|
||||||
|
return this.http.get<Book>(`${this.bookUrl}/${bookId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookWithNeighbours(libraryId: number, bookId: number): Observable<BookWithNeighborsDTO> {
|
||||||
|
return this.http.get<BookWithNeighborsDTO>(`${this.libraryUrl}/${libraryId}/book/${bookId}/withNeighbors`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getLastReadBooks() {
|
||||||
|
// If lastReadBooks is null or empty, it means the books have never been loaded
|
||||||
|
if (!this.#appState().lastReadBooks || this.#appState().lastReadBooks!.size === 0) {
|
||||||
|
this.http.get<Book[]>(`${this.bookUrl}?sortBy=lastReadTime&sortDir=desc`).pipe(
|
||||||
|
map((lastReadBooks) => {
|
||||||
|
// Update lastReadBooks signal with the fetched books' IDs (as a Set)
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
lastReadBooks: new Set(lastReadBooks.map(book => book.id)), // Store as Set<number>
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure no duplicate books in the 'books' signal
|
||||||
|
const existingBooks = new Set(this.#appState().books.map(book => book.id));
|
||||||
|
const newBooks = lastReadBooks.filter(book => !existingBooks.has(book.id));
|
||||||
|
|
||||||
|
// Add the new books to the 'books' signal
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
books: [...this.#appState().books, ...newBooks],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update latestAddedBooks signal (initialize with the fetched books' IDs if it was never loaded)
|
||||||
|
if (this.#appState().latestAddedBooks!.size === 0) {
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
latestAddedBooks: new Set(lastReadBooks.map(book => book.id)), // Initialize as Set<number>
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return books as a signal
|
||||||
|
return lastReadBooks;
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error loading last read books:', error);
|
||||||
|
return of([]); // Return an empty array in case of error
|
||||||
|
})
|
||||||
|
).subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return books as a signal from state if already loaded
|
||||||
|
return computed(() => {
|
||||||
|
const lastReadBooksFromState = this.#appState().lastReadBooks;
|
||||||
|
if (lastReadBooksFromState) {
|
||||||
|
return this.#appState().books.filter(book => lastReadBooksFromState.has(book.id));
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getLatestAddedBooks() {
|
||||||
|
// If latestAddedBooks is null or empty, it means they haven't been loaded yet
|
||||||
|
if (!this.#appState().latestAddedBooks || this.#appState().latestAddedBooks!.size === 0) {
|
||||||
|
this.http.get<Book[]>(`${this.bookUrl}?sortBy=addedOn&sortDir=desc`).pipe(
|
||||||
|
map((latestAddedBooks) => {
|
||||||
|
// Update latestAddedBooks signal with the fetched books' IDs (as a Set)
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
latestAddedBooks: new Set(latestAddedBooks.map(book => book.id)), // Store as Set<number>
|
||||||
|
});
|
||||||
|
|
||||||
|
// Ensure no duplicate books in the 'books' signal
|
||||||
|
const existingBooks = new Set(this.#appState().books.map(book => book.id));
|
||||||
|
const newBooks = latestAddedBooks.filter(book => !existingBooks.has(book.id));
|
||||||
|
|
||||||
|
// Add the new books to the 'books' signal
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
books: [...this.#appState().books, ...newBooks],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the latest added books as a signal
|
||||||
|
return latestAddedBooks;
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error loading latest added books:', error);
|
||||||
|
return of([]); // Return an empty array in case of error
|
||||||
|
})
|
||||||
|
).subscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return books as a signal from state if already loaded
|
||||||
|
return computed(() => {
|
||||||
|
const latestAddedBooksFromState = this.#appState().latestAddedBooks;
|
||||||
|
if (latestAddedBooksFromState) {
|
||||||
|
return this.#appState().books.filter(book => latestAddedBooksFromState.has(book.id));
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
searchBooks(query: string): Observable<Book[]> {
|
||||||
|
if (query.length < 2) {
|
||||||
|
return of([]);
|
||||||
|
}
|
||||||
|
return this.http.get<Book[]>(`${this.bookUrl}/search?title=${encodeURIComponent(query)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> {
|
||||||
|
const url = `${this.bookUrl}/${bookId}/viewer-setting`;
|
||||||
|
return this.http.put<void>(url, viewerSetting);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookSetting(bookId: number): Observable<BookSetting> {
|
||||||
|
return this.http.get<BookSetting>(`${this.bookUrl}/${bookId}/viewer-setting`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookDataUrl(bookId: number): string {
|
||||||
|
return `${this.bookUrl}/${bookId}/data`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookCoverUrl(bookId: number): string {
|
||||||
|
return `${this.bookUrl}/${bookId}/cover`;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLastReadTime(bookId: number): Observable<void> {
|
||||||
|
return this.http.put<void>(`${this.bookUrl}/${bookId}/update-last-read`, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBookMetadataByBookId(bookId: number): Observable<BookMetadata[]> {
|
||||||
|
return this.http.get<BookMetadata[]>(`${this.bookUrl}/${bookId}/fetch-metadata`);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBookMetadataByTerm(term: string): Observable<BookMetadata[]> {
|
||||||
|
return this.http.get<BookMetadata[]>(`${this.bookUrl}/fetch-metadata?term=${term}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
setBookMetadata(googleBookId: string, bookId: number): Observable<void> {
|
||||||
|
const requestBody = {googleBookId: googleBookId};
|
||||||
|
return this.http.put<void>(`${this.bookUrl}/${bookId}/set-metadata`, requestBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleNewBook(book: Book): void {
|
||||||
|
// Check if the book already exists in the 'books' state
|
||||||
|
const existingBooks = new Set(this.#appState().books.map(b => b.id));
|
||||||
|
|
||||||
|
if (!existingBooks.has(book.id)) {
|
||||||
|
// If the book is new, add it to the 'books' state
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
books: [...this.#appState().books, book],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update the 'libraryBooksMap' to include this new book
|
||||||
|
const libraryId = book.libraryId;
|
||||||
|
|
||||||
|
// Retrieve the existing book IDs for the library or create a new Set if it doesn't exist
|
||||||
|
const existingLibraryBooks = this.#appState().libraryBooksMap.get(libraryId) || new Set<number>();
|
||||||
|
|
||||||
|
// Add the new book's ID to the library's Set
|
||||||
|
existingLibraryBooks.add(book.id);
|
||||||
|
|
||||||
|
// Update the 'libraryBooksMap' in the state
|
||||||
|
const updatedLibraryBooksMap = new Map(this.#appState().libraryBooksMap);
|
||||||
|
updatedLibraryBooksMap.set(libraryId, existingLibraryBooks);
|
||||||
|
|
||||||
|
this.#appState.set({
|
||||||
|
...this.#appState(),
|
||||||
|
libraryBooksMap: updatedLibraryBooksMap,
|
||||||
|
});
|
||||||
|
|
||||||
|
this.addToLatestAddedBooks(book);
|
||||||
|
} else {
|
||||||
|
console.log(`Book with ID ${book.id} already exists in the state.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setBookMetadata(googleBookId: string, bookId: number): Observable<void> {
|
|
||||||
const requestBody = {googleBookId: googleBookId};
|
|
||||||
return this.http.put<void>(`${this.bookUrl}/${bookId}/set-metadata`, requestBody);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user