Implement refresh library
This commit is contained in:
+8
@@ -11,6 +11,7 @@ import lombok.AllArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@@ -63,4 +64,11 @@ public class LibraryController {
|
||||
public ResponseEntity<LibraryDTO> updateLibrary(@PathVariable long libraryId, @RequestBody Sort sort) {
|
||||
return ResponseEntity.ok(libraryService.updateSort(libraryId, sort));
|
||||
}
|
||||
|
||||
@PutMapping("/{libraryId}/refresh")
|
||||
public ResponseEntity<?> refreshLibrary(@PathVariable long libraryId) {
|
||||
libraryService.refreshLibrary(libraryId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.model;
|
||||
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -11,5 +12,5 @@ import lombok.Data;
|
||||
public class LibraryFile {
|
||||
private Library library;
|
||||
private String filePath;
|
||||
private String fileType;
|
||||
private BookFileType bookFileType;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.adityachandel.booklore.model.enums;
|
||||
|
||||
public enum BookFileType {
|
||||
PDF, EPUB
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.adityachandel.booklore.model.stomp;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class BookNotification {
|
||||
|
||||
private Action action;
|
||||
private BookDTO addedBook;
|
||||
private Set<Long> removedBookIds;
|
||||
|
||||
public enum Action {
|
||||
BOOK_ADDED, BOOKS_REMOVED
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,15 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Repository
|
||||
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
|
||||
@@ -36,5 +39,9 @@ public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificat
|
||||
|
||||
@Query("SELECT b FROM Book b JOIN b.shelves s WHERE s.id = :shelfId")
|
||||
List<Book> findByShelfId(@Param("shelfId") Long shelfId);
|
||||
|
||||
@Modifying
|
||||
@Query("DELETE FROM Book b WHERE b.id IN (:ids)")
|
||||
void deleteByIdIn(Collection<Long> ids);
|
||||
}
|
||||
|
||||
|
||||
+5
-4
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -43,7 +44,7 @@ public class FileUploadService {
|
||||
file.transferTo(storageFile);
|
||||
LibraryFile libraryFile = LibraryFile.builder()
|
||||
.library(library)
|
||||
.fileType(getFileType(fileType))
|
||||
.bookFileType(getFileType(fileType))
|
||||
.filePath(storageFile.getAbsolutePath())
|
||||
.build();
|
||||
fileProcessor.processFile(libraryFile, false);
|
||||
@@ -54,11 +55,11 @@ public class FileUploadService {
|
||||
}
|
||||
}
|
||||
|
||||
private String getFileType(String f) {
|
||||
private BookFileType getFileType(String f) {
|
||||
if (f.equalsIgnoreCase("application/pdf")) {
|
||||
return "pdf";
|
||||
return BookFileType.PDF;
|
||||
} else if (f.equalsIgnoreCase("application/epub+zip")) {
|
||||
return "epub";
|
||||
return BookFileType.EPUB;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
+64
-6
@@ -3,12 +3,15 @@ package com.adityachandel.booklore.service;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.LibraryFile;
|
||||
import com.adityachandel.booklore.model.dto.BookDTO;
|
||||
import com.adityachandel.booklore.model.entity.Book;
|
||||
import com.adityachandel.booklore.model.entity.Library;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.stomp.BookNotification;
|
||||
import com.adityachandel.booklore.repository.BookRepository;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -16,6 +19,11 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.adityachandel.booklore.model.stomp.BookNotification.Action.BOOKS_REMOVED;
|
||||
import static com.adityachandel.booklore.model.stomp.BookNotification.Action.BOOK_ADDED;
|
||||
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
@@ -25,29 +33,79 @@ public class LibraryProcessingService {
|
||||
private final LibraryRepository libraryRepository;
|
||||
private final NotificationService notificationService;
|
||||
private final PdfFileProcessor pdfFileProcessor;
|
||||
private final BookRepository bookRepository;
|
||||
|
||||
|
||||
@Transactional
|
||||
public void parseLibraryBooks(long libraryId) throws IOException {
|
||||
public void processLibrary(long libraryId) throws IOException {
|
||||
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(library);
|
||||
processLibraryFiles(libraryFiles);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void refreshLibrary(long libraryId) throws IOException {
|
||||
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
processLibraryFiles(getUnProcessedFiles(library));
|
||||
deleteRemovedBooks(getRemovedBooks(library));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void deleteRemovedBooks(List<Book> removedBooks) {
|
||||
if (!removedBooks.isEmpty()) {
|
||||
Set<Long> bookIds = removedBooks.stream().map(Book::getId).collect(Collectors.toSet());
|
||||
bookRepository.deleteByIdIn(bookIds);
|
||||
BookNotification notification = BookNotification.builder().action(BOOKS_REMOVED).removedBookIds(bookIds).build();
|
||||
notificationService.sendMessage("/topic/books", notification);
|
||||
log.info("Books removed: {}", bookIds);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void processLibraryFiles(List<LibraryFile> libraryFiles) {
|
||||
for (LibraryFile libraryFile : libraryFiles) {
|
||||
log.info("Processing file: {}", libraryFile.getFilePath());
|
||||
BookDTO bookDTO = processLibraryFile(libraryFile);
|
||||
if(bookDTO != null) {
|
||||
notificationService.sendMessage("/topic/books", bookDTO);
|
||||
if (bookDTO != null) {
|
||||
BookNotification notification = BookNotification.builder().action(BOOK_ADDED).addedBook(bookDTO).build();
|
||||
notificationService.sendMessage("/topic/books", notification);
|
||||
log.info("Processed file: {}", libraryFile.getFilePath());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected BookDTO processLibraryFile(LibraryFile libraryFile) {
|
||||
if (libraryFile.getFileType().equalsIgnoreCase("pdf")) {
|
||||
if (libraryFile.getBookFileType() == BookFileType.PDF) {
|
||||
return pdfFileProcessor.processFile(libraryFile, false);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<Book> getRemovedBooks(Library library) throws IOException {
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(library);
|
||||
List<Book> books = library.getBooks();
|
||||
Set<String> libraryFilePaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFilePath)
|
||||
.collect(Collectors.toSet());
|
||||
return books.stream()
|
||||
.filter(book -> !libraryFilePaths.contains(book.getPath()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected List<LibraryFile> getUnProcessedFiles(Library library) throws IOException {
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(library);
|
||||
List<Book> books = library.getBooks();
|
||||
Set<String> processedPaths = books.stream()
|
||||
.map(Book::getPath)
|
||||
.collect(Collectors.toSet());
|
||||
return libraryFiles.stream()
|
||||
.filter(libraryFile -> !processedPaths.contains(libraryFile.getFilePath()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private List<LibraryFile> getLibraryFiles(Library library) throws IOException {
|
||||
List<LibraryFile> libraryFiles = new ArrayList<>();
|
||||
for (String libraryPath : library.getPaths()) {
|
||||
@@ -65,7 +123,7 @@ public class LibraryProcessingService {
|
||||
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
|
||||
})
|
||||
.forEach(file -> {
|
||||
String fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? "PDF" : "EPUB";
|
||||
BookFileType fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? BookFileType.PDF : BookFileType.EPUB;
|
||||
libraryFiles.add(new LibraryFile(library, file.toAbsolutePath().toString(), fileType));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -29,17 +29,12 @@ public class LibraryService {
|
||||
private final LibraryProcessingService libraryProcessingService;
|
||||
|
||||
public LibraryDTO createLibrary(CreateLibraryRequest request) {
|
||||
Library library = Library.builder()
|
||||
.name(request.getName())
|
||||
.paths(request.getPaths())
|
||||
.build();
|
||||
Library library = Library.builder().name(request.getName()).paths(request.getPaths()).build();
|
||||
library = libraryRepository.save(library);
|
||||
Long libraryId = library.getId();
|
||||
|
||||
Thread.startVirtualThread(() -> {
|
||||
log.info("Running in a virtual thread: {}", Thread.currentThread());
|
||||
try {
|
||||
libraryProcessingService.parseLibraryBooks(libraryId);
|
||||
libraryProcessingService.processLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
@@ -47,10 +42,23 @@ public class LibraryService {
|
||||
}
|
||||
log.info("Parsing task completed!");
|
||||
});
|
||||
|
||||
return LibraryTransformer.convertToLibraryDTO(library);
|
||||
}
|
||||
|
||||
public void refreshLibrary(long libraryId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
libraryProcessingService.refreshLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.warn("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
}
|
||||
log.info("Parsing task completed!");
|
||||
});
|
||||
}
|
||||
|
||||
public LibraryDTO getLibrary(long libraryId) {
|
||||
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
return LibraryTransformer.convertToLibraryDTO(library);
|
||||
@@ -83,4 +91,4 @@ public class LibraryService {
|
||||
library.setSort(sort);
|
||||
return LibraryTransformer.convertToLibraryDTO(libraryRepository.save(library));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ spring:
|
||||
hibernate:
|
||||
naming:
|
||||
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
|
||||
show-sql: false
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
jdbc:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {Component, OnInit} from '@angular/core';
|
||||
import {RxStompService} from './book/service/rx-stomp.service';
|
||||
import {Message} from '@stomp/stompjs';
|
||||
import {Book} from './book/model/book.model';
|
||||
import {BookService} from './book/service/book.service';
|
||||
import {Action, parseBookNotification} from './book/model/book-notification.model';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
@@ -17,8 +17,12 @@ export class AppComponent implements OnInit {
|
||||
|
||||
ngOnInit(): void {
|
||||
this.rxStompService.watch('/topic/books').subscribe((message: Message) => {
|
||||
const book: Book = JSON.parse(message.body);
|
||||
this.bookService.handleNewlyCreatedBook(book);
|
||||
const notification = parseBookNotification(message.body);
|
||||
if (notification.action === Action.BOOK_ADDED) {
|
||||
this.bookService.handleNewlyCreatedBook(notification.addedBook!);
|
||||
} else if (notification.action === Action.BOOKS_REMOVED) {
|
||||
this.bookService.handleRemovedBookIds(notification.removedBookIds!);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -37,13 +37,13 @@
|
||||
}
|
||||
|
||||
.virtual-scroller-item {
|
||||
height: 243px;
|
||||
width: 150px;
|
||||
height: 210px;
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
|
||||
gap: 1.3rem;
|
||||
padding: 1rem;
|
||||
width: 100%;
|
||||
|
||||
@@ -225,7 +225,7 @@ export class BooksBrowserComponent implements OnInit {
|
||||
},
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: 'Sure you want to delete ' + this.entity?.name + "?",
|
||||
message: 'Sure you want to delete library: ' + this.entity?.name + "?",
|
||||
header: 'Confirmation',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'none',
|
||||
@@ -249,6 +249,38 @@ export class BooksBrowserComponent implements OnInit {
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
icon: 'pi pi-refresh',
|
||||
tooltipOptions: {
|
||||
tooltipLabel: 'Refresh',
|
||||
tooltipPosition: 'top'
|
||||
},
|
||||
command: () => {
|
||||
this.confirmationService.confirm({
|
||||
message: 'Sure you want to refresh library: ' + this.entity?.name + "?",
|
||||
header: 'Confirmation',
|
||||
icon: 'pi pi-exclamation-triangle',
|
||||
acceptIcon: 'none',
|
||||
rejectIcon: 'none',
|
||||
rejectButtonStyleClass: 'p-button-text',
|
||||
accept: () => {
|
||||
this.libraryService.refreshLibrary(this.entity?.id!).subscribe({
|
||||
complete: () => {
|
||||
this.messageService.add({severity: 'info', summary: 'Success', detail: 'Library refresh scheduled'});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Failed',
|
||||
detail: 'Failed to refresh library',
|
||||
life: 3000
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Book } from './book.model';
|
||||
|
||||
export interface BookNotification {
|
||||
action: Action;
|
||||
addedBook?: Book;
|
||||
removedBookIds?: Set<number>;
|
||||
}
|
||||
|
||||
export enum Action {
|
||||
BOOK_ADDED = 'BOOK_ADDED',
|
||||
BOOKS_REMOVED = 'BOOKS_REMOVED',
|
||||
}
|
||||
|
||||
export function parseBookNotification(messageBody: string): BookNotification {
|
||||
const raw = JSON.parse(messageBody);
|
||||
return {
|
||||
action: raw.action,
|
||||
addedBook: raw.addedBook,
|
||||
removedBookIds: raw.removedBookIds ? new Set<number>(raw.removedBookIds) : undefined,
|
||||
};
|
||||
}
|
||||
@@ -158,4 +158,17 @@ export class BookService {
|
||||
this.books.next(updatedBooks);
|
||||
}
|
||||
|
||||
handleRemovedBookIds(removedBookIds: Set<number>) {
|
||||
console.log(removedBookIds);
|
||||
|
||||
if (!(removedBookIds instanceof Set)) {
|
||||
console.error("removedBookIds should be a Set");
|
||||
return; // Or throw an error if preferred
|
||||
}
|
||||
|
||||
const currentBooks = this.books.getValue();
|
||||
let filteredBooks = currentBooks.filter(currentBook => !removedBookIds.has(currentBook.id));
|
||||
this.books.next(filteredBooks);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -52,6 +52,10 @@ export class LibraryService {
|
||||
);
|
||||
}
|
||||
|
||||
refreshLibrary(libraryId: number): Observable<void> {
|
||||
return this.http.put<void>(`${this.url}/${libraryId}/refresh`, {});
|
||||
}
|
||||
|
||||
updateSort(libraryId: number, sort: SortOption): Observable<Library> {
|
||||
return this.http.put<Library>(`${this.url}/${libraryId}/sort`, sort).pipe(
|
||||
map(updatedLibrary => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
flex-direction: column;
|
||||
min-height: 100vh;
|
||||
justify-content: space-between;
|
||||
padding: 6rem 2rem 2rem 4rem;
|
||||
padding: 5.5rem 2rem 2rem 4rem;
|
||||
transition: margin-left $transitionDuration;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
.layout-sidebar {
|
||||
position: fixed;
|
||||
width: 250px;
|
||||
width: 225px;
|
||||
height: calc(100vh - 9rem);
|
||||
z-index: 999;
|
||||
overflow-y: auto;
|
||||
user-select: none;
|
||||
top: 6rem;
|
||||
top: 5.5rem;
|
||||
left: 1.5rem;
|
||||
transition: transform $transitionDuration, left $transitionDuration;
|
||||
background-color: var(--surface-overlay);
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
|
||||
&.layout-static {
|
||||
.layout-main-container {
|
||||
margin-left: 240px;
|
||||
margin-left: 208px;
|
||||
}
|
||||
|
||||
&.layout-static-inactive {
|
||||
|
||||
Reference in New Issue
Block a user