Checkpoint/WIP: Completely refactor state management
This commit is contained in:
+12
-9
@@ -3,9 +3,11 @@ package com.adityachandel.booklore.controller;
|
|||||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||||
import com.adityachandel.booklore.model.dto.BookViewerSettingDTO;
|
import com.adityachandel.booklore.model.dto.BookViewerSettingDTO;
|
||||||
import com.adityachandel.booklore.model.dto.BookWithNeighborsDTO;
|
import com.adityachandel.booklore.model.dto.BookWithNeighborsDTO;
|
||||||
|
import com.adityachandel.booklore.model.dto.request.AssignShelvesRequest;
|
||||||
import com.adityachandel.booklore.model.dto.response.GoogleBooksMetadata;
|
import com.adityachandel.booklore.model.dto.response.GoogleBooksMetadata;
|
||||||
import com.adityachandel.booklore.model.dto.request.SetMetadataRequest;
|
import com.adityachandel.booklore.model.dto.request.SetMetadataRequest;
|
||||||
import com.adityachandel.booklore.service.BooksService;
|
import com.adityachandel.booklore.service.BooksService;
|
||||||
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.Max;
|
import jakarta.validation.constraints.Max;
|
||||||
import jakarta.validation.constraints.Min;
|
import jakarta.validation.constraints.Min;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -15,6 +17,7 @@ import org.springframework.http.ResponseEntity;
|
|||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@RequestMapping("/v1/book")
|
@RequestMapping("/v1/book")
|
||||||
@@ -30,12 +33,8 @@ public class BookController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public ResponseEntity<List<BookDTO>> getBooks(@RequestParam(defaultValue = "lastReadTime") String sortBy, @RequestParam(defaultValue = "desc") String sortDir) {
|
public ResponseEntity<List<BookDTO>> getBooks() {
|
||||||
if (!sortBy.equals("lastReadTime") && !sortBy.equals("addedOn")) {
|
return ResponseEntity.ok( booksService.getBooks());
|
||||||
return ResponseEntity.badRequest().body(null);
|
|
||||||
}
|
|
||||||
List<BookDTO> books = booksService.getBooks(sortBy, sortDir);
|
|
||||||
return ResponseEntity.ok(books);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/search")
|
@GetMapping("/search")
|
||||||
@@ -66,9 +65,8 @@ public class BookController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{bookId}/update-last-read")
|
@PutMapping("/{bookId}/update-last-read")
|
||||||
public ResponseEntity<Void> updateBookViewerSettings(@PathVariable long bookId) {
|
public ResponseEntity<BookDTO> updateBookViewerSettings(@PathVariable long bookId) {
|
||||||
booksService.updateLastReadTime(bookId);
|
return ResponseEntity.ok(booksService.updateLastReadTime(bookId));
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{bookId}/fetch-metadata")
|
@GetMapping("/{bookId}/fetch-metadata")
|
||||||
@@ -86,4 +84,9 @@ public class BookController {
|
|||||||
booksService.setMetadata(setMetadataRequest, bookId);
|
booksService.setMetadata(setMetadataRequest, bookId);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/assign-shelves")
|
||||||
|
public ResponseEntity<BookDTO> addBookToShelf(@RequestBody @Valid AssignShelvesRequest request) {
|
||||||
|
return ResponseEntity.ok(booksService.addBookToShelf(request.getBookId(), request.getShelfIds()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -32,8 +32,8 @@ public class LibraryController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
public ResponseEntity<Page<LibraryDTO>> getLibraries(@RequestParam(defaultValue = "0") @Min(0) int page, @RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
|
public ResponseEntity<List<LibraryDTO>> getLibraries() {
|
||||||
return ResponseEntity.ok(libraryService.getLibraries(page, size));
|
return ResponseEntity.ok(libraryService.getLibraries());
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
|
|||||||
@@ -45,11 +45,6 @@ public class ShelfController {
|
|||||||
return ResponseEntity.ok(shelfService.updateShelf(id, request));
|
return ResponseEntity.ok(shelfService.updateShelf(id, request));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/assign-shelves")
|
|
||||||
public ResponseEntity<BookDTO> addBookToShelf(@RequestBody @Valid AssignShelvesRequest request) {
|
|
||||||
return ResponseEntity.ok(shelfService.addBookToShelf(request.getBookId(), request.getShelfIds()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@DeleteMapping("/{shelfId}")
|
@DeleteMapping("/{shelfId}")
|
||||||
public ResponseEntity<Void> deleteShelf(@PathVariable Long shelfId) {
|
public ResponseEntity<Void> deleteShelf(@PathVariable Long shelfId) {
|
||||||
shelfService.deleteShelf(shelfId);
|
shelfService.deleteShelf(shelfId);
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import org.springframework.data.domain.Sort;
|
|||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
@@ -50,8 +51,7 @@ public class BooksService {
|
|||||||
private final CategoryRepository categoryRepository;
|
private final CategoryRepository categoryRepository;
|
||||||
private final LibraryRepository libraryRepository;
|
private final LibraryRepository libraryRepository;
|
||||||
private final NotificationService notificationService;
|
private final NotificationService notificationService;
|
||||||
|
private final ShelfRepository shelfRepository;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public BookDTO getBook(long bookId) {
|
public BookDTO getBook(long bookId) {
|
||||||
@@ -59,19 +59,8 @@ public class BooksService {
|
|||||||
return BookTransformer.convertToBookDTO(book);
|
return BookTransformer.convertToBookDTO(book);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<BookDTO> getBooks(String sortBy, String sortDir) {
|
public List<BookDTO> getBooks() {
|
||||||
int size = 25;
|
return bookRepository.findAll().stream()
|
||||||
PageRequest pageRequest = PageRequest.of(0, size, Sort.by(Sort.Direction.fromString(sortDir), sortBy));
|
|
||||||
Page<Book> bookPage;
|
|
||||||
if (sortBy.equals("addedOn")) {
|
|
||||||
bookPage = bookRepository.findByAddedOnIsNotNull(pageRequest);
|
|
||||||
} else if (sortBy.equals("lastReadTime")) {
|
|
||||||
bookPage = bookRepository.findByLastReadTimeIsNotNull(pageRequest);
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException("Invalid sortBy parameter");
|
|
||||||
}
|
|
||||||
|
|
||||||
return bookPage.getContent().stream()
|
|
||||||
.map(BookTransformer::convertToBookDTO)
|
.map(BookTransformer::convertToBookDTO)
|
||||||
.collect(Collectors.toList());
|
.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
@@ -119,10 +108,10 @@ public class BooksService {
|
|||||||
return BookSettingTransformer.convertToDTO(bookViewerSetting);
|
return BookSettingTransformer.convertToDTO(bookViewerSetting);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateLastReadTime(long bookId) {
|
public BookDTO updateLastReadTime(long bookId) {
|
||||||
Book book = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
Book book = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
book.setLastReadTime(Instant.now());
|
book.setLastReadTime(Instant.now());
|
||||||
bookRepository.save(book);
|
return BookTransformer.convertToBookDTO(bookRepository.save(book));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<GoogleBooksMetadata> fetchProspectiveMetadataListByBookId(long bookId) {
|
public List<GoogleBooksMetadata> fetchProspectiveMetadataListByBookId(long bookId) {
|
||||||
@@ -230,4 +219,26 @@ public class BooksService {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public BookDTO addBookToShelf(Long bookId, List<Long> shelfIds) {
|
||||||
|
Book book = bookRepository.findById(bookId)
|
||||||
|
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
||||||
|
|
||||||
|
List<Shelf> currentShelves = book.getShelves();
|
||||||
|
List<Shelf> shelvesToAdd = shelfRepository.findAllById(shelfIds);
|
||||||
|
|
||||||
|
currentShelves.stream()
|
||||||
|
.filter(shelf -> !shelfIds.contains(shelf.getId()))
|
||||||
|
.forEach(shelf -> shelf.getBooks().remove(book));
|
||||||
|
|
||||||
|
book.getShelves().clear();
|
||||||
|
book.getShelves().addAll(shelvesToAdd);
|
||||||
|
|
||||||
|
shelvesToAdd.forEach(shelf -> shelf.getBooks().add(book));
|
||||||
|
|
||||||
|
bookRepository.save(book);
|
||||||
|
shelfRepository.saveAll(shelvesToAdd);
|
||||||
|
return BookTransformer.convertToBookDTO(book);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,10 +57,9 @@ public class LibraryService {
|
|||||||
return LibraryTransformer.convertToLibraryDTO(library);
|
return LibraryTransformer.convertToLibraryDTO(library);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Page<LibraryDTO> getLibraries(int page, int size) {
|
public List<LibraryDTO> getLibraries() {
|
||||||
PageRequest pageRequest = PageRequest.of(page, size);
|
List<Library> libraries = libraryRepository.findAll();
|
||||||
Page<Library> libraryPage = libraryRepository.findAll(pageRequest);
|
return libraries.stream().map(LibraryTransformer::convertToLibraryDTO).toList();
|
||||||
return libraryPage.map(LibraryTransformer::convertToLibraryDTO);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void deleteLibrary(long id) {
|
public void deleteLibrary(long id) {
|
||||||
|
|||||||
@@ -12,10 +12,8 @@ import com.adityachandel.booklore.transformer.BookTransformer;
|
|||||||
import com.adityachandel.booklore.transformer.ShelfTransformer;
|
import com.adityachandel.booklore.transformer.ShelfTransformer;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@Service
|
@Service
|
||||||
@@ -40,28 +38,6 @@ public class ShelfService {
|
|||||||
return ShelfTransformer.convertToShelfDTO(shelfRepository.save(shelf));
|
return ShelfTransformer.convertToShelfDTO(shelfRepository.save(shelf));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public BookDTO addBookToShelf(Long bookId, List<Long> shelfIds) {
|
|
||||||
Book book = bookRepository.findById(bookId)
|
|
||||||
.orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId));
|
|
||||||
|
|
||||||
List<Shelf> currentShelves = book.getShelves();
|
|
||||||
List<Shelf> shelvesToAdd = shelfRepository.findAllById(shelfIds);
|
|
||||||
|
|
||||||
currentShelves.stream()
|
|
||||||
.filter(shelf -> !shelfIds.contains(shelf.getId()))
|
|
||||||
.forEach(shelf -> shelf.getBooks().remove(book));
|
|
||||||
|
|
||||||
book.getShelves().clear();
|
|
||||||
book.getShelves().addAll(shelvesToAdd);
|
|
||||||
|
|
||||||
shelvesToAdd.forEach(shelf -> shelf.getBooks().add(book));
|
|
||||||
|
|
||||||
bookRepository.save(book);
|
|
||||||
shelfRepository.saveAll(shelvesToAdd);
|
|
||||||
return BookTransformer.convertToBookDTO(book);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<ShelfDTO> getShelves() {
|
public List<ShelfDTO> getShelves() {
|
||||||
return shelfRepository.findAll().stream().map(ShelfTransformer::convertToShelfDTO).toList();
|
return shelfRepository.findAll().stream().map(ShelfTransformer::convertToShelfDTO).toList();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {Component, OnInit} from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {RxStompService} from './rx-stomp.service';
|
import {RxStompService} from './rx-stomp.service';
|
||||||
import {Message} from '@stomp/stompjs';
|
import {Message} from '@stomp/stompjs';
|
||||||
import {LibraryAndBookService} from './book/service/library-and-book.service';
|
|
||||||
import {Book} from './book/model/book.model';
|
import {Book} from './book/model/book.model';
|
||||||
|
import {BookService} from './book/service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
@@ -12,15 +12,13 @@ import {Book} from './book/model/book.model';
|
|||||||
})
|
})
|
||||||
export class AppComponent implements OnInit {
|
export class AppComponent implements OnInit {
|
||||||
|
|
||||||
constructor(private libraryBookService: LibraryAndBookService, private rxStompService: RxStompService) {
|
constructor(private bookService: BookService, private rxStompService: RxStompService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.libraryBookService.initializeLibraries();
|
|
||||||
this.libraryBookService.initializeShelves();
|
|
||||||
this.rxStompService.watch('/topic/books').subscribe((message: Message) => {
|
this.rxStompService.watch('/topic/books').subscribe((message: Message) => {
|
||||||
const book: Book = JSON.parse(message.body);
|
const book: Book = JSON.parse(message.body);
|
||||||
this.libraryBookService.handleNewBook(book);
|
this.bookService.handleNewlyCreatedBook(book);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
import {Component, Input, OnInit} from '@angular/core';
|
import {Component, Input, OnInit} from '@angular/core';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {MenuModule} from 'primeng/menu';
|
import {MenuModule} from 'primeng/menu';
|
||||||
import {MenuItem} from 'primeng/api';
|
import {MenuItem} from 'primeng/api';
|
||||||
import {DialogService} from "primeng/dynamicdialog";
|
import {DialogService} from "primeng/dynamicdialog";
|
||||||
import {ShelfAssignerComponent} from "../shelf-assigner/shelf-assigner.component";
|
import {ShelfAssignerComponent} from "../shelf-assigner/shelf-assigner.component";
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-card',
|
selector: 'app-book-card',
|
||||||
@@ -23,16 +23,16 @@ export class BookCardComponent implements OnInit {
|
|||||||
items: MenuItem[] | undefined;
|
items: MenuItem[] | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private libraryBookService: LibraryAndBookService, private router: Router,
|
private bookService: BookService, private router: Router,
|
||||||
private dialogService: DialogService) {
|
private dialogService: DialogService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
coverImageSrc(book: Book): string {
|
coverImageSrc(book: Book): string {
|
||||||
return this.libraryBookService.getBookCoverUrl(book.id);
|
return this.bookService.getBookCoverUrl(book.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
readBook(book: Book) {
|
readBook(book: Book) {
|
||||||
this.libraryBookService.readBook(book);
|
this.bookService.readBook(book);
|
||||||
}
|
}
|
||||||
|
|
||||||
openBookInfo(book: Book) {
|
openBookInfo(book: Book) {
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import {Component, OnDestroy, OnInit} from '@angular/core';
|
import {Component, OnDestroy, OnInit} from '@angular/core';
|
||||||
import {ActivatedRoute, Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgForOf, NgIf} from '@angular/common';
|
import {NgForOf, NgIf} from '@angular/common';
|
||||||
@@ -8,6 +7,8 @@ import {BooksMetadataDialogComponent} from '../books-metadata-dialog/books-metad
|
|||||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Subscription} from 'rxjs';
|
import {Subscription} from 'rxjs';
|
||||||
import {TagModule} from 'primeng/tag';
|
import {TagModule} from 'primeng/tag';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-book-metadata',
|
selector: 'app-book-metadata',
|
||||||
@@ -30,8 +31,9 @@ export class BookMetadataComponent implements OnInit, OnDestroy {
|
|||||||
private dialogSubscription?: Subscription;
|
private dialogSubscription?: Subscription;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private bookService: LibraryAndBookService, private activatedRoute: ActivatedRoute,
|
private bookService: BookService, private activatedRoute: ActivatedRoute,
|
||||||
private dialogService: DialogService, private router: Router) {
|
private dialogService: DialogService, private router: Router,
|
||||||
|
private libraryService: LibraryService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
@@ -45,7 +47,7 @@ export class BookMetadataComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private loadBookWithNeighbors(libraryId: number, bookId: number): void {
|
private loadBookWithNeighbors(libraryId: number, bookId: number): void {
|
||||||
this.bookService.getBookWithNeighbours(bookId, libraryId).subscribe((response) => {
|
this.libraryService.getBookWithNeighbours(bookId, libraryId).subscribe((response) => {
|
||||||
this.book = response.currentBook;
|
this.book = response.currentBook;
|
||||||
this.nextBookId = response.nextBookId;
|
this.nextBookId = response.nextBookId;
|
||||||
this.previousBookId = response.previousBookId;
|
this.previousBookId = response.previousBookId;
|
||||||
|
|||||||
@@ -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">{{ title() }}</h3>
|
<h3 class="library-name">{{ (library$ | async)?.name }}</h3>
|
||||||
<p-speedDial
|
<p-speedDial
|
||||||
[model]="items!"
|
[model]="items!"
|
||||||
direction="right"
|
direction="right"
|
||||||
@@ -22,15 +22,15 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="content-container">
|
<div class="content-container">
|
||||||
<div class="card-container">
|
<div class="card-container" *ngIf="books$ | async as books">
|
||||||
<virtual-scroller *ngIf="books().length > 0" class="virtual-scroller" #scroll [items]="books()">
|
<virtual-scroller *ngIf="books.length > 0" 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>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</virtual-scroller>
|
</virtual-scroller>
|
||||||
<div *ngIf="books().length === 0" class="empty-message">
|
<div *ngIf="books.length === 0" class="empty-message">
|
||||||
<p>No books available to display.</p>
|
<p>No books available to display.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
import {Component, OnInit, computed, signal, Signal} from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {ActivatedRoute, Router} from '@angular/router';
|
import {ActivatedRoute, Router} from '@angular/router';
|
||||||
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";
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
import {map, switchMap} from 'rxjs/operators';
|
||||||
|
import {Observable, of} from 'rxjs';
|
||||||
|
import {Book} from '../../model/book.model';
|
||||||
|
import {Library} from '../../model/library.model';
|
||||||
|
import {ShelfService} from '../../service/shelf.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-books-browser',
|
selector: 'app-books-browser',
|
||||||
@@ -11,59 +16,52 @@ import {Book} from "../../model/book.model";
|
|||||||
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 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 '';
|
|
||||||
});
|
|
||||||
|
|
||||||
|
books$: Observable<Book[]> | undefined;
|
||||||
|
library$: Observable<Library | null> | undefined;
|
||||||
items: MenuItem[] | undefined;
|
items: MenuItem[] | undefined;
|
||||||
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private activatedRoute: ActivatedRoute,
|
private activatedRoute: ActivatedRoute,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
private libraryBookService: LibraryAndBookService,
|
|
||||||
private confirmationService: ConfirmationService,
|
private confirmationService: ConfirmationService,
|
||||||
private messageService: MessageService
|
private messageService: MessageService,
|
||||||
|
private libraryService: LibraryService,
|
||||||
|
private bookService: BookService,
|
||||||
|
private shelfService: ShelfService
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.activatedRoute.paramMap.subscribe((params) => {
|
const libraryId$ = this.activatedRoute.paramMap.pipe(
|
||||||
const libraryId = Number(params.get('libraryId'));
|
map(params => Number(params.get('libraryId')))
|
||||||
const shelfId = Number(params.get('shelfId'));
|
);
|
||||||
if (libraryId) {
|
|
||||||
this.entityType.set('library');
|
|
||||||
this.currentEntityId.set(libraryId);
|
|
||||||
this.books = this.libraryBookService.getLibraryBooks(libraryId);
|
|
||||||
this.libraryBookService.getLibraries();
|
|
||||||
} else if (shelfId) {
|
|
||||||
this.entityType.set('shelf');
|
|
||||||
this.currentEntityId.set(shelfId);
|
|
||||||
this.books = this.libraryBookService.getShelfBooks(shelfId);
|
|
||||||
this.libraryBookService.getShelves();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this.entityType() === 'library') {
|
this.books$ = libraryId$.pipe(
|
||||||
this.initializeLibraryMenuItems();
|
switchMap(libraryId => {
|
||||||
} else if (this.entityType() === 'shelf') {
|
if (!isNaN(libraryId)) {
|
||||||
this.initializeShelfMenuItems();
|
return this.bookService.books$.pipe(
|
||||||
|
map(books => books.filter(book => book.libraryId === libraryId))
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return of([]);
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
this.library$ = this.activatedRoute.paramMap.pipe(
|
||||||
|
switchMap(params => {
|
||||||
|
const libraryId = Number(params.get('libraryId'));
|
||||||
|
if (!isNaN(libraryId)) {
|
||||||
|
return this.libraryService.libraries$.pipe(
|
||||||
|
map(libraries => libraries.find(lib => lib.id === libraryId) || null)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return of(null);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
this.initializeLibraryMenuItems();
|
||||||
}
|
}
|
||||||
|
|
||||||
private initializeLibraryMenuItems(): void {
|
private initializeLibraryMenuItems(): void {
|
||||||
@@ -75,15 +73,18 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
tooltipPosition: 'top'
|
tooltipPosition: 'top'
|
||||||
},
|
},
|
||||||
command: () => {
|
command: () => {
|
||||||
|
this.library$?.subscribe(library => {
|
||||||
|
if (library) {
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: 'Sure you want to delete ' + this.title() + "?",
|
message: `Are you sure you want to delete ${library.name}?`,
|
||||||
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.deleteLibrary(this.currentEntityId()).subscribe({
|
if (library.id) {
|
||||||
|
this.libraryService.deleteLibrary(library.id).subscribe({
|
||||||
complete: () => {
|
complete: () => {
|
||||||
this.router.navigate(['/']);
|
this.router.navigate(['/']);
|
||||||
this.messageService.add({
|
this.messageService.add({
|
||||||
@@ -102,51 +103,13 @@ export class BooksBrowserComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
private initializeShelfMenuItems(): void {
|
|
||||||
this.items = [
|
|
||||||
{
|
|
||||||
icon: 'pi pi-trash',
|
|
||||||
tooltipOptions: {
|
|
||||||
tooltipLabel: 'Delete',
|
|
||||||
tooltipPosition: 'top'
|
|
||||||
},
|
|
||||||
command: () => {
|
|
||||||
this.confirmationService.confirm({
|
|
||||||
message: 'Sure you want to delete ' + this.title() + "?",
|
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
import {Component, OnInit} from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {BookMetadata} from '../../model/book.model';
|
import {BookMetadata} from '../../model/book.model';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|
||||||
import {NgForOf, NgIf} from '@angular/common';
|
import {NgForOf, NgIf} from '@angular/common';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-books-metadata-dialog',
|
selector: 'app-books-metadata-dialog',
|
||||||
@@ -27,7 +27,7 @@ export class BooksMetadataDialogComponent implements OnInit {
|
|||||||
bookId: number = 0;
|
bookId: number = 0;
|
||||||
libraryId: number = 0;
|
libraryId: number = 0;
|
||||||
|
|
||||||
constructor(private bookService: LibraryAndBookService, public dynamicDialogConfig: DynamicDialogConfig, private dynamicDialogRef: DynamicDialogRef, private router: Router) {
|
constructor(private bookService: BookService, public dynamicDialogConfig: DynamicDialogConfig, private dynamicDialogRef: DynamicDialogRef, private router: Router) {
|
||||||
this.searchText = dynamicDialogConfig.data.bookTitle;
|
this.searchText = dynamicDialogConfig.data.bookTitle;
|
||||||
this.bookId = this.dynamicDialogConfig.data.bookId;
|
this.bookId = this.dynamicDialogConfig.data.bookId;
|
||||||
this.libraryId = this.dynamicDialogConfig.data.libraryId;
|
this.libraryId = this.dynamicDialogConfig.data.libraryId;
|
||||||
|
|||||||
+2
-2
@@ -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="(books$ | async)?.length === 0">
|
||||||
<h4>No books available.</h4>
|
<h4>No books available.</h4>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
[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 books$ | async">
|
||||||
<app-book-card [book]="book"></app-book-card>
|
<app-book-card [book]="book"></app-book-card>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+27
-33
@@ -1,22 +1,22 @@
|
|||||||
import {Component, OnInit, ViewChild, ElementRef, Input, computed, signal, Signal} from '@angular/core';
|
import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|
||||||
import {Button} from 'primeng/button';
|
|
||||||
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
|
||||||
import {NgForOf, NgIf} from '@angular/common';
|
import {AsyncPipe, NgForOf, NgIf} from '@angular/common';
|
||||||
import {Router} from '@angular/router';
|
|
||||||
import {BookCardComponent} from '../book-card/book-card.component';
|
import {BookCardComponent} from '../book-card/book-card.component';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
import {map} from 'rxjs/operators';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-dashboard-scroller',
|
selector: 'app-dashboard-scroller',
|
||||||
templateUrl: './dashboard-scroller.component.html',
|
templateUrl: './dashboard-scroller.component.html',
|
||||||
styleUrls: ['./dashboard-scroller.component.scss'],
|
styleUrls: ['./dashboard-scroller.component.scss'],
|
||||||
imports: [
|
imports: [
|
||||||
Button,
|
|
||||||
InfiniteScrollDirective,
|
InfiniteScrollDirective,
|
||||||
NgForOf,
|
NgForOf,
|
||||||
NgIf,
|
NgIf,
|
||||||
BookCardComponent
|
BookCardComponent,
|
||||||
|
AsyncPipe
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class DashboardScrollerComponent implements OnInit {
|
export class DashboardScrollerComponent implements OnInit {
|
||||||
@@ -25,37 +25,31 @@ 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: Signal<Book[]> | undefined;
|
books$: Observable<Book[]> | undefined;
|
||||||
|
|
||||||
constructor(private bookService: LibraryAndBookService, private router: Router) {
|
constructor(private bookService: BookService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.booksSignal = this.bookListType === 'lastRead' ? this.bookService.getLastReadBooks() : this.bookService.getLatestAddedBooks();;
|
if (this.bookListType === 'lastRead') {
|
||||||
this.loadBooks();
|
this.books$ = this.bookService.books$.pipe((
|
||||||
|
map(books =>
|
||||||
|
books
|
||||||
|
.filter(book => book.lastReadTime)
|
||||||
|
.sort((a, b) => new Date(b.lastReadTime!).getTime() - new Date(a.lastReadTime!).getTime())
|
||||||
|
.slice(0, 25)
|
||||||
|
)
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
if (this.bookListType === 'latestAdded') {
|
||||||
loadBooks(): void {
|
this.books$ = this.bookService.books$.pipe((
|
||||||
if (this.bookListType === 'lastRead' && !this.bookService.getLastReadBooks()) {
|
map(books =>
|
||||||
this.bookService.getLastReadBooks();
|
books
|
||||||
} else if (this.bookListType === 'latestAdded' && !this.bookService.getLatestAddedBooks()) {
|
.filter(book => book.addedOn)
|
||||||
this.bookService.getLatestAddedBooks();
|
.sort((a, b) => new Date(b.addedOn!).getTime() - new Date(a.addedOn!).getTime())
|
||||||
|
.slice(0, 25)
|
||||||
|
)
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
coverImageSrc(bookId: number): string {
|
|
||||||
return this.bookService.getBookCoverUrl(bookId);
|
|
||||||
}
|
|
||||||
|
|
||||||
getAuthorNames(book: Book): string {
|
|
||||||
return book.metadata?.authors?.map((author) => author.name).join(', ') || 'No authors available';
|
|
||||||
}
|
|
||||||
|
|
||||||
openBook(book: Book): void {
|
|
||||||
this.bookService.readBook(book);
|
|
||||||
}
|
|
||||||
|
|
||||||
openBookInfo(bookId: number, libraryId: number) {
|
|
||||||
this.router.navigate(['/library', libraryId, 'book', bookId, 'info']);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div class="dashboard">
|
<div class="dashboard">
|
||||||
|
|
||||||
<div class="dashboard-no-library" *ngIf="isLibrariesEmpty; else dashboardScroller">
|
<div class="dashboard-no-library" *ngIf="isLibrariesEmpty$ | async; else dashboardScroller">
|
||||||
<h1 class="no-library-header">
|
<h1 class="no-library-header">
|
||||||
Looks like you haven't added a library yet. Let's add one!
|
Looks like you haven't added a library yet. Let's add one!
|
||||||
</h1>
|
</h1>
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import {Component, Signal} from '@angular/core';
|
import {Component} from '@angular/core';
|
||||||
import {Library} from '../../model/library.model';
|
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgIf} from '@angular/common';
|
import {AsyncPipe, NgIf} from '@angular/common';
|
||||||
import {LibraryCreatorComponent} from '../library-creator/library-creator.component';
|
import {LibraryCreatorComponent} from '../library-creator/library-creator.component';
|
||||||
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
import {DashboardScrollerComponent} from '../dashboard-scroller/dashboard-scroller.component';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {map} from 'rxjs/operators';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-home-page',
|
selector: 'app-home-page',
|
||||||
@@ -14,20 +15,19 @@ import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|||||||
imports: [
|
imports: [
|
||||||
Button,
|
Button,
|
||||||
NgIf,
|
NgIf,
|
||||||
DashboardScrollerComponent
|
DashboardScrollerComponent,
|
||||||
|
AsyncPipe
|
||||||
],
|
],
|
||||||
providers: [DialogService],
|
providers: [DialogService],
|
||||||
})
|
})
|
||||||
export class DashboardComponent {
|
export class DashboardComponent {
|
||||||
private libraries: Signal<Library[]>;
|
isLibrariesEmpty$: Observable<boolean>;
|
||||||
ref: DynamicDialogRef | undefined;
|
ref: DynamicDialogRef | undefined;
|
||||||
|
|
||||||
constructor(private libraryBookService: LibraryAndBookService, public dialogService: DialogService) {
|
constructor(private libraryService: LibraryService, public dialogService: DialogService) {
|
||||||
this.libraries = this.libraryBookService.getLibraries();
|
this.isLibrariesEmpty$ = this.libraryService.libraries$.pipe(
|
||||||
}
|
map(libraries => libraries.length === 0)
|
||||||
|
);
|
||||||
get isLibrariesEmpty(): boolean {
|
|
||||||
return this.libraries()?.length === 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createNewLibrary(event: MouseEvent) {
|
createNewLibrary(event: MouseEvent) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
<div class="flex">
|
<div class="flex">
|
||||||
<p-dropdown
|
<p-dropdown
|
||||||
[options]="libraries()"
|
[options]="(libraries$ | async) || []"
|
||||||
optionLabel="name"
|
optionLabel="name"
|
||||||
placeholder="Select Library"
|
placeholder="Select Library"
|
||||||
[(ngModel)]="selectedLibrary">
|
[(ngModel)]="selectedLibrary">
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import {Component, Signal} from '@angular/core';
|
import {Component} from '@angular/core';
|
||||||
import {Library} from '../../model/library.model';
|
import {Library} from '../../model/library.model';
|
||||||
import {FileUploadService} from '../../../file-upload.service';
|
import {FileUploadService} from '../../../file-upload.service';
|
||||||
import {Button} from 'primeng/button';
|
import {Button} from 'primeng/button';
|
||||||
import {NgIf} from '@angular/common';
|
import {AsyncPipe, NgIf} from '@angular/common';
|
||||||
import {DropdownModule} from 'primeng/dropdown';
|
import {DropdownModule} from 'primeng/dropdown';
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {ToastService} from '../../../toast.service';
|
import {ToastService} from '../../../toast.service';
|
||||||
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-file-upload-v2',
|
selector: 'app-file-upload-v2',
|
||||||
@@ -17,11 +18,12 @@ import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|||||||
Button,
|
Button,
|
||||||
NgIf,
|
NgIf,
|
||||||
DropdownModule,
|
DropdownModule,
|
||||||
FormsModule
|
FormsModule,
|
||||||
|
AsyncPipe
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class FileUploadComponent {
|
export class FileUploadComponent {
|
||||||
libraries: Signal<Library[]>;
|
libraries$: Observable<Library[]>;
|
||||||
selectedLibrary: Library | null = null;
|
selectedLibrary: Library | null = null;
|
||||||
selectedPath: string = '';
|
selectedPath: string = '';
|
||||||
selectedFileName: string = '';
|
selectedFileName: string = '';
|
||||||
@@ -29,11 +31,11 @@ export class FileUploadComponent {
|
|||||||
errorMessage: string | null = null;
|
errorMessage: string | null = null;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private libraryBookService: LibraryAndBookService,
|
private libraryService: LibraryService,
|
||||||
private fileUploadService: FileUploadService,
|
private fileUploadService: FileUploadService,
|
||||||
private toastService: ToastService,
|
private toastService: ToastService,
|
||||||
private dynamicDialogRef: DynamicDialogRef) {
|
private dynamicDialogRef: DynamicDialogRef) {
|
||||||
this.libraries = this.libraryBookService.getLibraries();
|
this.libraries$ = this.libraryService.libraries$;
|
||||||
}
|
}
|
||||||
|
|
||||||
triggerFileInput(fileInput: HTMLInputElement): void {
|
triggerFileInput(fileInput: HTMLInputElement): void {
|
||||||
|
|||||||
@@ -6,15 +6,19 @@
|
|||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<ul class="layout-menu">
|
<ul class="layout-menu">
|
||||||
<ng-container *ngFor="let item of libraryMenu(); let i = index;">
|
<ng-container *ngIf="libraryMenu$ | async as libraryMenu">
|
||||||
|
<ng-container *ngFor="let item of libraryMenu; let i = index;">
|
||||||
<li app-menuitem *ngIf="!item.separator" [item]="item" [index]="i" [root]="true"></li>
|
<li app-menuitem *ngIf="!item.separator" [item]="item" [index]="i" [root]="true"></li>
|
||||||
<li *ngIf="item.separator" class="menu-separator"></li>
|
<li *ngIf="item.separator" class="menu-separator"></li>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
|
</ng-container>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<ul class="layout-menu">
|
<ul class="layout-menu">
|
||||||
<ng-container *ngFor="let item of shelfMenu(); let i = index;">
|
<ng-container *ngIf="shelfMenu$ | async as shelfMenu">
|
||||||
|
<ng-container *ngFor="let item of shelfMenu; let i = index;">
|
||||||
<li app-menuitem *ngIf="!item.separator" [item]="item" [index]="i" [root]="true"></li>
|
<li app-menuitem *ngIf="!item.separator" [item]="item" [index]="i" [root]="true"></li>
|
||||||
<li *ngIf="item.separator" class="menu-separator"></li>
|
<li *ngIf="item.separator" class="menu-separator"></li>
|
||||||
</ng-container>
|
</ng-container>
|
||||||
|
</ng-container>
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,53 +1,42 @@
|
|||||||
import {Component, computed, OnInit} from '@angular/core';
|
import {Component, computed, OnInit} from '@angular/core';
|
||||||
import {AppMenuitemComponent} from './app.menuitem.component';
|
import {AppMenuitemComponent} from './app.menuitem.component';
|
||||||
import {NgForOf, NgIf} from '@angular/common';
|
import {AsyncPipe, NgForOf, NgIf} from '@angular/common';
|
||||||
import {MenuModule} from 'primeng/menu';
|
import {MenuModule} from 'primeng/menu';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {map} from 'rxjs/operators';
|
||||||
|
import {ShelfService} from '../../service/shelf.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-menu',
|
selector: 'app-menu',
|
||||||
imports: [AppMenuitemComponent, NgIf, NgForOf, MenuModule],
|
imports: [AppMenuitemComponent, NgIf, NgForOf, MenuModule, AsyncPipe],
|
||||||
templateUrl: './app.menu.component.html',
|
templateUrl: './app.menu.component.html',
|
||||||
})
|
})
|
||||||
export class AppMenuComponent implements OnInit {
|
export class AppMenuComponent implements OnInit {
|
||||||
home: any[] = [];
|
home: any[] = [];
|
||||||
|
libraryMenu$: Observable<any> | undefined;
|
||||||
|
shelfMenu$: Observable<any> | undefined;
|
||||||
|
|
||||||
constructor(private libraryBookService: LibraryAndBookService) {
|
constructor(private libraryService: LibraryService, private shelfService: ShelfService) {
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.populateHome();
|
this.libraryMenu$ = this.libraryService.libraries$.pipe(
|
||||||
}
|
map((libraries) => [
|
||||||
|
|
||||||
populateHome() {
|
|
||||||
this.home = [
|
|
||||||
{
|
|
||||||
label: 'Home',
|
|
||||||
items: [
|
|
||||||
{label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/']},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
libraryMenu = computed(() => {
|
|
||||||
const libraries = this.libraryBookService.getLibraries()();
|
|
||||||
return [
|
|
||||||
{
|
{
|
||||||
label: 'Library',
|
label: 'Library',
|
||||||
separator: false,
|
separator: false,
|
||||||
items: libraries.map((lib) => ({
|
items: libraries.map((library) => ({
|
||||||
label: lib.name,
|
label: library.name,
|
||||||
icon: 'pi pi-fw pi-book',
|
icon: 'pi pi-fw pi-book',
|
||||||
routerLink: [`/library/${lib.id}/books`],
|
routerLink: [`/library/${library.id}/books`],
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
];
|
])
|
||||||
});
|
);
|
||||||
|
|
||||||
shelfMenu = computed(() => {
|
this.shelfMenu$ = this.shelfService.shelves$.pipe(
|
||||||
const shelves = this.libraryBookService.getShelves()();
|
map((shelves) => [
|
||||||
return [
|
|
||||||
{
|
{
|
||||||
label: 'Shelves',
|
label: 'Shelves',
|
||||||
separator: false,
|
separator: false,
|
||||||
@@ -57,6 +46,21 @@ export class AppMenuComponent implements OnInit {
|
|||||||
routerLink: [`/shelf/${shelf.id}/books`],
|
routerLink: [`/shelf/${shelf.id}/books`],
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
|
])
|
||||||
|
)
|
||||||
|
|
||||||
|
this.populateHome();
|
||||||
|
}
|
||||||
|
|
||||||
|
populateHome() {
|
||||||
|
this.home = [
|
||||||
|
{
|
||||||
|
label: 'Home',
|
||||||
|
items: [
|
||||||
|
{label: 'Dashboard', icon: 'pi pi-fw pi-home', routerLink: ['/']}
|
||||||
|
],
|
||||||
|
},
|
||||||
];
|
];
|
||||||
});
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
|
|||||||
import {DirectoryPickerComponent} from '../directory-picker/directory-picker.component';
|
import {DirectoryPickerComponent} from '../directory-picker/directory-picker.component';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
import {LibraryService} from '../../service/library.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-library-creator',
|
selector: 'app-library-creator',
|
||||||
@@ -20,7 +20,7 @@ export class LibraryCreatorComponent {
|
|||||||
constructor(
|
constructor(
|
||||||
private dialogService: DialogService,
|
private dialogService: DialogService,
|
||||||
private dynamicDialogRef: DynamicDialogRef,
|
private dynamicDialogRef: DynamicDialogRef,
|
||||||
private libraryAndBookService: LibraryAndBookService,
|
private libraryService: LibraryService,
|
||||||
private router: Router,
|
private router: Router,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
@@ -55,7 +55,7 @@ export class LibraryCreatorComponent {
|
|||||||
name: this.value,
|
name: this.value,
|
||||||
paths: this.folders,
|
paths: this.folders,
|
||||||
};
|
};
|
||||||
this.libraryAndBookService.createLibrary(newLibrary).subscribe({
|
this.libraryService.createLibrary(newLibrary).subscribe({
|
||||||
next: (createdLibrary) => {
|
next: (createdLibrary) => {
|
||||||
this.router.navigate(
|
this.router.navigate(
|
||||||
['/library', createdLibrary.id, 'books']
|
['/library', createdLibrary.id, 'books']
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ChangeDetectorRef, Component, NgZone, OnInit, OnDestroy } from '@angular/core';
|
import {Component, NgZone, OnDestroy, OnInit} from '@angular/core';
|
||||||
import {ActivatedRoute} from '@angular/router';
|
import {ActivatedRoute} from '@angular/router';
|
||||||
import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewer';
|
import {NgxExtendedPdfViewerModule, ScrollModeType} from 'ngx-extended-pdf-viewer';
|
||||||
import { LibraryAndBookService } from '../../service/library-and-book.service';
|
import {BookService} from '../../service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-pdf-viewer',
|
selector: 'app-pdf-viewer',
|
||||||
@@ -22,7 +22,7 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
|
|||||||
private isInitialLoad = true;
|
private isInitialLoad = true;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private bookService: LibraryAndBookService,
|
private bookService: BookService,
|
||||||
private zone: NgZone,
|
private zone: NgZone,
|
||||||
private route: ActivatedRoute
|
private route: ActivatedRoute
|
||||||
) {}
|
) {}
|
||||||
@@ -40,7 +40,7 @@ export class PdfViewerComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private loadBook(bookId: number): void {
|
private loadBook(bookId: number): void {
|
||||||
this.bookService.getBook(bookId).subscribe((book) => {
|
this.bookService.getBookById(bookId).subscribe((book) => {
|
||||||
this.zone.run(() => {
|
this.zone.run(() => {
|
||||||
this.bookService.getBookSetting(bookId).subscribe((bookSetting) => {
|
this.bookService.getBookSetting(bookId).subscribe((bookSetting) => {
|
||||||
const { pageNumber, zoom, sidebar_visible, spread } = bookSetting;
|
const { pageNumber, zoom, sidebar_visible, spread } = bookSetting;
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import {Component, OnDestroy, OnInit} from '@angular/core';
|
import {Component, OnDestroy, OnInit} from '@angular/core';
|
||||||
import {Subject, Subscription} from 'rxjs';
|
import {Subject, Subscription} from 'rxjs';
|
||||||
import { debounceTime, distinctUntilChanged, switchMap, catchError } from 'rxjs/operators';
|
import {catchError, debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book} from '../../model/book.model';
|
||||||
import { LibraryAndBookService } from '../../service/library-and-book.service';
|
|
||||||
import {FormsModule} from '@angular/forms';
|
import {FormsModule} from '@angular/forms';
|
||||||
import {InputTextModule} from 'primeng/inputtext';
|
import {InputTextModule} from 'primeng/inputtext';
|
||||||
import {NgForOf, NgIf} from '@angular/common';
|
import {NgForOf, NgIf} from '@angular/common';
|
||||||
import {ButtonDirective} from 'primeng/button';
|
import {ButtonDirective} from 'primeng/button';
|
||||||
import {Router} from '@angular/router';
|
import {Router} from '@angular/router';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-search',
|
selector: 'app-search',
|
||||||
@@ -27,7 +27,7 @@ export class SearchComponent implements OnInit, OnDestroy {
|
|||||||
#searchSubject = new Subject<string>();
|
#searchSubject = new Subject<string>();
|
||||||
#subscription!: Subscription;
|
#subscription!: Subscription;
|
||||||
|
|
||||||
constructor(private bookService: LibraryAndBookService, private router: Router) {}
|
constructor(private bookService: BookService, private router: Router) {}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.initializeSearch();
|
this.initializeSearch();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div class="dialog-container">
|
<div class="dialog-container">
|
||||||
<div class="checkbox-list">
|
<div class="checkbox-list">
|
||||||
<div *ngFor="let shelf of shelves()" class="flex items-center">
|
<div *ngFor="let shelf of shelves$ | async" class="flex items-center">
|
||||||
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves" />
|
<p-checkbox [inputId]="shelf.name" name="group" [value]="shelf" [(ngModel)]="selectedShelves" />
|
||||||
<label [for]="shelf.id" class="ml-2">{{ shelf.name }}</label>
|
<label [for]="shelf.id" class="ml-2">{{ shelf.name }}</label>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import {Component, computed, OnInit} from '@angular/core';
|
import {Component, OnInit} from '@angular/core';
|
||||||
import {LibraryAndBookService} from '../../service/library-and-book.service';
|
|
||||||
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog';
|
||||||
import {Book} from '../../model/book.model';
|
import {Book, Shelf} from '../../model/book.model';
|
||||||
import {MessageService} from 'primeng/api';
|
import {MessageService} from 'primeng/api';
|
||||||
|
import {ShelfService} from '../../service/shelf.service';
|
||||||
|
import {Observable} from 'rxjs';
|
||||||
|
import {BookService} from '../../service/book.service';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-shelf-assigner',
|
selector: 'app-shelf-assigner',
|
||||||
@@ -13,29 +15,31 @@ import {MessageService} from 'primeng/api';
|
|||||||
})
|
})
|
||||||
export class ShelfAssignerComponent implements OnInit {
|
export class ShelfAssignerComponent implements OnInit {
|
||||||
|
|
||||||
shelves;
|
shelves$: Observable<Shelf[]>;
|
||||||
|
|
||||||
book: Book;
|
book: Book;
|
||||||
selectedShelves: any[] = [];
|
selectedShelves: any[] = [];
|
||||||
displayShelfDialog: boolean = false;
|
displayShelfDialog: boolean = false;
|
||||||
shelfName: string = '';
|
shelfName: string = '';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private libraryBookService: LibraryAndBookService, private dynamicDialogConfig: DynamicDialogConfig,
|
private shelfService: ShelfService, private dynamicDialogConfig: DynamicDialogConfig,
|
||||||
private dynamicDialogRef: DynamicDialogRef, private messageService: MessageService) {
|
private dynamicDialogRef: DynamicDialogRef, private messageService: MessageService,
|
||||||
this.shelves = this.libraryBookService.getShelves();
|
private bookService: BookService) {
|
||||||
|
this.shelves$ = this.shelfService.shelves$;
|
||||||
this.book = this.dynamicDialogConfig.data.book;
|
this.book = this.dynamicDialogConfig.data.book;
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
|
this.shelves$.subscribe(shelves => {
|
||||||
if (this.book.shelves) {
|
if (this.book.shelves) {
|
||||||
const bookShelfIds = this.book.shelves.map(shelf => shelf.id);
|
const bookShelfIds = this.book.shelves.map(shelf => shelf.id);
|
||||||
this.selectedShelves = this.shelves().filter(shelf => bookShelfIds.includes(shelf.id));
|
this.selectedShelves = shelves.filter(shelf => bookShelfIds.includes(shelf.id));
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
saveNewShelf() {
|
saveNewShelf() {
|
||||||
this.libraryBookService.createShelf(this.shelfName).subscribe(
|
this.shelfService.createShelf(this.shelfName).subscribe(
|
||||||
() => {
|
() => {
|
||||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf created: ' + this.shelfName});
|
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Shelf created: ' + this.shelfName});
|
||||||
this.displayShelfDialog = false;
|
this.displayShelfDialog = false;
|
||||||
@@ -49,7 +53,7 @@ export class ShelfAssignerComponent implements OnInit {
|
|||||||
|
|
||||||
updateBooksShelves() {
|
updateBooksShelves() {
|
||||||
const shelfIds = this.selectedShelves.map((shelf) => shelf.id);
|
const shelfIds = this.selectedShelves.map((shelf) => shelf.id);
|
||||||
this.libraryBookService.assignShelvesToBook(this.book, shelfIds).subscribe(
|
this.bookService.assignShelvesToBook(this.book, shelfIds).subscribe(
|
||||||
() => {
|
() => {
|
||||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book\'s shelves updated'});
|
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Book\'s shelves updated'});
|
||||||
this.dynamicDialogRef.close();
|
this.dynamicDialogRef.close();
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ export interface Book {
|
|||||||
libraryId: number;
|
libraryId: number;
|
||||||
metadata?: BookMetadata;
|
metadata?: BookMetadata;
|
||||||
shelves?: Shelf[];
|
shelves?: Shelf[];
|
||||||
|
lastReadTime?: string;
|
||||||
|
addedOn?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BookMetadata {
|
export interface BookMetadata {
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import {Injectable} from '@angular/core';
|
||||||
|
import {BehaviorSubject, filter, Observable, of, tap} from 'rxjs';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {catchError, map, switchMap} from 'rxjs/operators';
|
||||||
|
import {Book, BookMetadata, BookSetting, BookWithNeighborsDTO} from '../model/book.model';
|
||||||
|
import {ShelfService} from './shelf.service';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class BookService {
|
||||||
|
|
||||||
|
private readonly url = 'http://localhost:8080/v1/book';
|
||||||
|
private books = new BehaviorSubject<Book[]>([]);
|
||||||
|
books$ = this.books.asObservable();
|
||||||
|
|
||||||
|
constructor(private http: HttpClient, private shelfService: ShelfService) {
|
||||||
|
this.http.get<Book[]>(this.url).pipe(
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error loading books:', error);
|
||||||
|
return of([]);
|
||||||
|
})
|
||||||
|
).subscribe((libraries) => {
|
||||||
|
console.log('Books loaded:', libraries);
|
||||||
|
this.books.next(libraries);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
assignShelvesToBook(book: Book, shelfIds: number[]): Observable<Book> {
|
||||||
|
const requestPayload = {
|
||||||
|
bookId: book.id,
|
||||||
|
shelfIds: shelfIds,
|
||||||
|
};
|
||||||
|
return this.http.post<Book>(`${this.url}/assign-shelves`, requestPayload).pipe(
|
||||||
|
map((updatedBook) => {
|
||||||
|
const currentBooks = this.books.value;
|
||||||
|
const bookIndex = currentBooks.findIndex(b => b.id === updatedBook.id);
|
||||||
|
if (bookIndex !== -1) {
|
||||||
|
currentBooks[bookIndex] = updatedBook;
|
||||||
|
this.books.next([...currentBooks]);
|
||||||
|
}
|
||||||
|
return updatedBook;
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error assigning shelves to book:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeBooksByLibraryId(libraryId: number): void {
|
||||||
|
const filteredBooks = this.books.value.filter(book => book.libraryId !== libraryId);
|
||||||
|
this.books.next(filteredBooks);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookById(bookId: number): Observable<Book | undefined> {
|
||||||
|
return this.books$.pipe(
|
||||||
|
map(books => books.find(book => book.id === bookId))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookSetting(bookId: number): Observable<BookSetting> {
|
||||||
|
return this.http.get<BookSetting>(`${this.url}/${bookId}/viewer-setting`);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateViewerSetting(viewerSetting: any, bookId: number): Observable<void> {
|
||||||
|
const url = `${this.url}/${bookId}/viewer-setting`;
|
||||||
|
return this.http.put<void>(url, viewerSetting);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLastReadTime(bookId: number): Observable<Book> {
|
||||||
|
return this.http.put<Book>(`${this.url}/${bookId}/update-last-read`, {}).pipe(
|
||||||
|
switchMap(updatedBook => {
|
||||||
|
console.log(updatedBook);
|
||||||
|
const currentBooks = this.books.getValue();
|
||||||
|
const updatedBooks = currentBooks.map(book =>
|
||||||
|
book.id === updatedBook.id ? { ...book, lastReadTime: updatedBook.lastReadTime } : book
|
||||||
|
);
|
||||||
|
this.books.next(updatedBooks);
|
||||||
|
return [updatedBook];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
readBook(book: Book): void {
|
||||||
|
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),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
searchBooks(query: string): Observable<Book[]> {
|
||||||
|
if (query.length < 2) {
|
||||||
|
return of([]);
|
||||||
|
}
|
||||||
|
return this.http.get<Book[]>(`${this.url}/search?title=${encodeURIComponent(query)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookDataUrl(bookId: number): string {
|
||||||
|
return `${this.url}/${bookId}/data`;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookCoverUrl(bookId: number): string {
|
||||||
|
return `${this.url}/${bookId}/cover`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBookMetadataByBookId(bookId: number): Observable<BookMetadata[]> {
|
||||||
|
return this.http.get<BookMetadata[]>(`${this.url}/${bookId}/fetch-metadata`);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchBookMetadataByTerm(term: string): Observable<BookMetadata[]> {
|
||||||
|
return this.http.get<BookMetadata[]>(`${this.url}/fetch-metadata?term=${term}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
setBookMetadata(googleBookId: string, bookId: number): Observable<void> {
|
||||||
|
const requestBody = {googleBookId: googleBookId};
|
||||||
|
return this.http.put<void>(`${this.url}/${bookId}/set-metadata`, requestBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleNewlyCreatedBook(book: Book): void {
|
||||||
|
const currentBooks = this.books.getValue();
|
||||||
|
const bookIndex = currentBooks.findIndex(existingBook => existingBook.id === book.id);
|
||||||
|
const updatedBooks = [...currentBooks];
|
||||||
|
if (bookIndex > -1) {
|
||||||
|
updatedBooks[bookIndex] = book;
|
||||||
|
} else {
|
||||||
|
updatedBooks.push(book);
|
||||||
|
}
|
||||||
|
this.books.next(updatedBooks);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,577 +0,0 @@
|
|||||||
import {computed, Injectable, signal} from '@angular/core';
|
|
||||||
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({
|
|
||||||
providedIn: 'root'
|
|
||||||
})
|
|
||||||
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';
|
|
||||||
|
|
||||||
#appState = signal<{
|
|
||||||
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(),
|
|
||||||
});
|
|
||||||
|
|
||||||
constructor(private http: HttpClient) {
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*---------- Shelf Methods go below ----------*/
|
|
||||||
|
|
||||||
initializeShelves(): void {
|
|
||||||
this.http.get<Shelf[]>(this.shelfUrl).pipe(
|
|
||||||
map(response => response),
|
|
||||||
catchError(error => {
|
|
||||||
console.error('Error loading shelves:', error);
|
|
||||||
return of([]);
|
|
||||||
})
|
|
||||||
).subscribe(
|
|
||||||
(shelves) => {
|
|
||||||
this.#appState.set({
|
|
||||||
...this.#appState(),
|
|
||||||
shelves: shelves,
|
|
||||||
});
|
|
||||||
console.log("Shelves Initialized");
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
getShelves() {
|
|
||||||
return computed(() => this.#appState().shelves);
|
|
||||||
}
|
|
||||||
|
|
||||||
createShelf(name: string): Observable<Shelf> {
|
|
||||||
return this.http.post<Shelf>(this.shelfUrl, {name}).pipe(
|
|
||||||
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;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
getShelfBooks(shelfId: number) {
|
|
||||||
// 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)
|
|
||||||
);
|
|
||||||
|
|
||||||
// If there are any new books, add them to the books state
|
|
||||||
if (newBooks.length > 0) {
|
|
||||||
this.#appState.set({
|
|
||||||
...this.#appState(),
|
|
||||||
books: [...this.#appState().books, ...newBooks],
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update shelfBooksMap with the shelfId and the new books as a Set (not an array)
|
|
||||||
const updatedShelfBooksMap = new Map(this.#appState().shelfBooksMap);
|
|
||||||
updatedShelfBooksMap.set(shelfId, new Set(fetchedBooks.map(book => book.id)));
|
|
||||||
|
|
||||||
// Update the app state with the new shelfBooksMap
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return a computed signal of books for the specified shelf
|
|
||||||
return computed(() => {
|
|
||||||
const bookIdsForShelf = this.#appState().shelfBooksMap.get(shelfId) || new Set<number>();
|
|
||||||
return this.#appState().books.filter(book => bookIdsForShelf.has(book.id));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteShelf(shelfId: number): Observable<void> {
|
|
||||||
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.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import {Injectable, OnInit} from '@angular/core';
|
||||||
|
import {BehaviorSubject, Observable, of, tap} from 'rxjs';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {catchError, map} from 'rxjs/operators';
|
||||||
|
import {Library} from '../model/library.model';
|
||||||
|
import {BookService} from './book.service';
|
||||||
|
import {BookWithNeighborsDTO} from '../model/book.model';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class LibraryService {
|
||||||
|
|
||||||
|
private readonly url = 'http://localhost:8080/v1/library';
|
||||||
|
private libraries = new BehaviorSubject<Library[]>([]);
|
||||||
|
libraries$ = this.libraries.asObservable();
|
||||||
|
|
||||||
|
constructor(private http: HttpClient, private bookService: BookService) {
|
||||||
|
this.http.get<Library[]>(this.url).pipe(
|
||||||
|
catchError(error => {
|
||||||
|
return of([]);
|
||||||
|
})
|
||||||
|
).subscribe((libraries) => {
|
||||||
|
this.libraries.next(libraries);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
createLibrary(newLibrary: Library): Observable<Library> {
|
||||||
|
return this.http.post<Library>(this.url, newLibrary).pipe(
|
||||||
|
map((createdLibrary) => {
|
||||||
|
this.libraries.next([...this.libraries.value, createdLibrary]);
|
||||||
|
return createdLibrary;
|
||||||
|
}),
|
||||||
|
catchError((error) => {
|
||||||
|
console.error('Error creating library:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteLibrary(libraryId: number) {
|
||||||
|
return this.http.delete(`${this.url}/${libraryId}`).pipe(
|
||||||
|
tap(() => {
|
||||||
|
this.bookService.removeBooksByLibraryId(libraryId);
|
||||||
|
const updatedLibraries = this.libraries.value.filter(library => library.id !== libraryId);
|
||||||
|
this.libraries.next(updatedLibraries);
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
return of(null);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getBookWithNeighbours(libraryId: number, bookId: number): Observable<BookWithNeighborsDTO> {
|
||||||
|
return this.http.get<BookWithNeighborsDTO>(`${this.url}/${libraryId}/book/${bookId}/withNeighbors`);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import {Injectable} from '@angular/core';
|
||||||
|
import {BehaviorSubject, Observable, of} from 'rxjs';
|
||||||
|
import {Shelf} from '../model/book.model';
|
||||||
|
import {catchError, map} from 'rxjs/operators';
|
||||||
|
import {HttpClient} from '@angular/common/http';
|
||||||
|
import {Library} from '../model/library.model';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class ShelfService {
|
||||||
|
|
||||||
|
private readonly url = 'http://localhost:8080/v1/shelf';
|
||||||
|
private shelves = new BehaviorSubject<Shelf[]>([]);
|
||||||
|
shelves$ = this.shelves.asObservable();
|
||||||
|
|
||||||
|
constructor(private http: HttpClient) {
|
||||||
|
this.http.get<Shelf[]>(this.url).pipe(
|
||||||
|
catchError(error => {
|
||||||
|
return of([]);
|
||||||
|
})
|
||||||
|
).subscribe((shelves) => {
|
||||||
|
this.shelves.next(shelves);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
createShelf(name: string): Observable<Shelf> {
|
||||||
|
return this.http.post<Shelf>(this.url, {name}).pipe(
|
||||||
|
map(newShelf => {
|
||||||
|
this.shelves.next([...this.shelves.value, newShelf])
|
||||||
|
return newShelf;
|
||||||
|
}),
|
||||||
|
catchError(error => {
|
||||||
|
console.error('Error creating shelf:', error);
|
||||||
|
throw error;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user