Websocket and stuffs

This commit is contained in:
aditya.chandel
2024-12-19 16:10:08 -07:00
parent 9e3b45fffc
commit e175a7e255
24 changed files with 569 additions and 496 deletions
@@ -0,0 +1,24 @@
package com.adityachandel.booklore.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*");
System.out.println("WebSocket endpoint registered at /ws");
}
}
@@ -30,15 +30,11 @@ public class BookController {
}
@GetMapping
public ResponseEntity<Page<BookDTO>> getBooks(
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int size,
@RequestParam(defaultValue = "lastReadTime") String sortBy,
@RequestParam(defaultValue = "desc") String sortDir) {
public ResponseEntity<List<BookDTO>> getBooks(@RequestParam(defaultValue = "lastReadTime") String sortBy, @RequestParam(defaultValue = "desc") String sortDir) {
if (!sortBy.equals("lastReadTime") && !sortBy.equals("addedOn")) {
return ResponseEntity.badRequest().body(null);
}
Page<BookDTO> books = booksService.getBooks(page, size, sortBy, sortDir);
List<BookDTO> books = booksService.getBooks(sortBy, sortDir);
return ResponseEntity.ok(books);
}
@@ -14,6 +14,9 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/v1/library")
@@ -38,11 +41,6 @@ public class LibraryController {
return ResponseEntity.ok(libraryService.createLibrary(request));
}
@GetMapping(path = "/{libraryId}/parse")
public SseEmitter parseLibrary(@RequestParam(required = false, defaultValue = "false") boolean force, @PathVariable long libraryId) {
return libraryService.parseLibraryBooks(libraryId, force);
}
@DeleteMapping("/{libraryId}")
public ResponseEntity<?> deleteLibrary(@PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
@@ -60,11 +58,8 @@ public class LibraryController {
}
@GetMapping("/{libraryId}/book")
public ResponseEntity<Page<BookDTO>> getBooks(
@PathVariable long libraryId,
@RequestParam(defaultValue = "0") @Min(0) int page,
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int size) {
Page<BookDTO> books = libraryService.getBooks(libraryId, page, size);
public ResponseEntity<List<BookDTO>> getBooks(@PathVariable long libraryId) {
List<BookDTO> books = libraryService.getBooks(libraryId);
return ResponseEntity.ok(books);
}
}
@@ -0,0 +1,34 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class NotificationController {
/*@MessageMapping("/send")
@SendTo("/topic/messages")
public String sendMessage(String message) {
System.out.println("Received message: " + message);
return "Hello";
}*/
private final NotificationService notificationService;
@Autowired
public NotificationController(NotificationService notificationService) {
this.notificationService = notificationService;
}
@MessageMapping("/send")
public void handleIncomingMessage(Object message) {
System.out.println("Received message: " + message);
}
public void sendMessageToTopic(String topic, Object message) {
notificationService.sendMessage(topic, message);
}
}
@@ -17,7 +17,7 @@ public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificat
Optional<Book> findByFileName(String fileName);
Page<Book> findBooksByLibraryId(Long libraryId, Pageable pageable);
List<Book> findBooksByLibraryId(Long libraryId);
Optional<Book> findBookByIdAndLibraryId(long id, long libraryId);
@@ -49,6 +49,9 @@ public class BooksService {
private final AuthorRepository authorRepository;
private final CategoryRepository categoryRepository;
private final LibraryRepository libraryRepository;
private final NotificationService notificationService;
public BookDTO getBook(long bookId) {
@@ -56,19 +59,20 @@ public class BooksService {
return BookTransformer.convertToBookDTO(book);
}
public Page<BookDTO> getBooks(int page, int size, String sortBy, String sortDir) {
Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
PageRequest pageRequest = PageRequest.of(page, size, sort);
Page<Book> bookPage = Page.empty();
public List<BookDTO> getBooks(String sortBy, String sortDir) {
int size = 25;
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");
}
List<BookDTO> bookDTOs = bookPage.getContent().stream()
return bookPage.getContent().stream()
.map(BookTransformer::convertToBookDTO)
.collect(Collectors.toList());
return new PageImpl<>(bookDTOs, pageRequest, bookPage.getTotalElements());
}
public void saveBookViewerSetting(long bookId, BookViewerSettingDTO bookViewerSettingDTO) {
@@ -2,7 +2,8 @@ package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.LibraryFile;
import com.adityachandel.booklore.model.dto.BookDTO;
public interface FileProcessor {
FileProcessResult processFile(LibraryFile libraryFile, boolean forceProcess);
BookDTO processFile(LibraryFile libraryFile, boolean forceProcess);
}
@@ -0,0 +1,77 @@
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.Library;
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;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@Service
@AllArgsConstructor
@Slf4j
public class LibraryProcessingService {
private final LibraryRepository libraryRepository;
private final NotificationService notificationService;
private final PdfFileProcessor pdfFileProcessor;
@Transactional
public void parseLibraryBooks(long libraryId) throws IOException {
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
List<LibraryFile> libraryFiles = getLibraryFiles(library);
for (LibraryFile libraryFile : libraryFiles) {
log.info("Processing file: {}", libraryFile.getFilePath());
BookDTO bookDTO = processLibraryFile(libraryFile);
if(bookDTO != null) {
notificationService.sendMessage("/topic/books", bookDTO);
}
}
}
@Transactional
protected BookDTO processLibraryFile(LibraryFile libraryFile) {
if (libraryFile.getFileType().equalsIgnoreCase("pdf")) {
return pdfFileProcessor.processFile(libraryFile, false);
}
return null;
}
private List<LibraryFile> getLibraryFiles(Library library) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>();
for (String libraryPath : library.getPaths()) {
libraryFiles.addAll(findLibraryFiles(libraryPath, library));
}
return libraryFiles;
}
private List<LibraryFile> findLibraryFiles(String directoryPath, Library library) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>();
try (var stream = Files.walk(Path.of(directoryPath))) {
stream.filter(Files::isRegularFile)
.filter(file -> {
String fileName = file.getFileName().toString().toLowerCase();
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
})
.forEach(file -> {
String fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? "PDF" : "EPUB";
libraryFiles.add(new LibraryFile(library, file.toAbsolutePath().toString(), fileType));
});
}
return libraryFiles;
}
}
@@ -1,37 +1,24 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.FileProcessResult;
import com.adityachandel.booklore.model.LibraryFile;
import com.adityachandel.booklore.model.ParseLibraryEvent;
import com.adityachandel.booklore.model.enums.ParsingStatus;
import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.model.dto.BookDTO;
import com.adityachandel.booklore.model.dto.LibraryDTO;
import com.adityachandel.booklore.model.dto.request.CreateLibraryRequest;
import com.adityachandel.booklore.model.entity.Book;
import com.adityachandel.booklore.model.entity.Library;
import com.adityachandel.booklore.exception.ApiError;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.transformer.BookTransformer;
import com.adityachandel.booklore.transformer.LibraryTransformer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.AsyncRequestNotUsableException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j
@Service
@@ -40,16 +27,29 @@ public class LibraryService {
private LibraryRepository libraryRepository;
private BookRepository bookRepository;
private PdfFileProcessor pdfFileProcessor;
private final Map<Long, ReentrantLock> libraryLocks = new ConcurrentHashMap<>();
private final LibraryProcessingService libraryProcessingService;
public LibraryDTO createLibrary(CreateLibraryRequest request) {
Library library = Library.builder()
.name(request.getName())
.paths(request.getPaths())
.build();
return LibraryTransformer.convertToLibraryDTO(libraryRepository.save(library));
library = libraryRepository.save(library);
Long libraryId = library.getId();
Thread.startVirtualThread(() -> {
log.info("Running in a virtual thread: {}", Thread.currentThread());
try {
libraryProcessingService.parseLibraryBooks(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!");
});
return LibraryTransformer.convertToLibraryDTO(library);
}
public LibraryDTO getLibrary(long libraryId) {
@@ -74,127 +74,9 @@ public class LibraryService {
return BookTransformer.convertToBookDTO(book);
}
public Page<BookDTO> getBooks(long libraryId, int page, int size) {
public List<BookDTO> getBooks(long libraryId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
PageRequest pageRequest = PageRequest.of(page, size);
Page<Book> bookPage = bookRepository.findBooksByLibraryId(libraryId, pageRequest);
return bookPage.map(BookTransformer::convertToBookDTO);
}
public SseEmitter parseLibraryBooks(long libraryId, boolean force) {
ReentrantLock lock = libraryLocks.computeIfAbsent(libraryId, k -> new ReentrantLock());
if (!lock.tryLock()) {
SseEmitter emitter = new SseEmitter();
emitter.completeWithError(new IllegalStateException("Library is already being processed"));
return emitter;
}
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
if(library.isInitialProcessed()) {
SseEmitter emitter = new SseEmitter();
emitter.complete();
return emitter;
}
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
final AtomicBoolean isCompleted = new AtomicBoolean(false);
emitter.onTimeout(() -> {
log.info("Emitter timeout reached. Stopping further processing.");
emitter.complete();
isCompleted.set(true);
});
emitter.onCompletion(() -> {
log.info("Emitter completed. Shutting down executor.");
isCompleted.set(true);
sseMvcExecutor.shutdown();
});
sseMvcExecutor.execute(() -> {
try {
List<LibraryFile> libraryFiles = getLibraryFiles(library);
for (LibraryFile libraryFile : libraryFiles) {
try {
log.info("Processing file: {}", libraryFile.getFilePath());
FileProcessResult fileProcessResult = processLibraryFile(libraryFile);
ParseLibraryEvent event = createParseLibraryEvent(libraryId, fileProcessResult);
if (!isCompleted.get()) {
emitter.send(event);
}
Thread.sleep(500);
} catch (AsyncRequestNotUsableException | IllegalStateException e) {
log.warn("Client disconnected! Continue processing.");
} catch (IOException e) {
log.warn("Client disconnected or failed to send response: {}", libraryFile.getFilePath(), e);
emitter.completeWithError(e);
sseMvcExecutor.shutdown();
return;
} catch (Exception e) {
log.error("Error processing file: {}", libraryFile.getFilePath(), e);
emitter.completeWithError(e);
sseMvcExecutor.shutdown();
return;
}
}
library.setInitialProcessed(true);
libraryRepository.save(library);
emitter.complete();
sseMvcExecutor.shutdown();
} catch (Exception ex) {
log.error("Error during file processing: ", ex);
if (!isCompleted.get()) {
emitter.completeWithError(ex);
sseMvcExecutor.shutdown();
}
} finally {
log.info("File processing complete. Executor shutting down.");
lock.unlock();
emitter.complete();
sseMvcExecutor.shutdown();
}
});
return emitter;
}
private ParseLibraryEvent createParseLibraryEvent(long libraryId, FileProcessResult result) {
return ParseLibraryEvent.builder()
.libraryId(libraryId)
.file(result.getLibraryFile().getFilePath())
.parsingStatus(result.getParsingStatus())
.book(result.getBookDTO())
.build();
}
private FileProcessResult processLibraryFile(LibraryFile libraryFile) {
if (libraryFile.getFileType().equalsIgnoreCase("pdf")) {
return pdfFileProcessor.processFile(libraryFile, false);
} else if (libraryFile.getFileType().equalsIgnoreCase("epub")) {
// TODO:: To implement
return FileProcessResult.builder().parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK).libraryFile(libraryFile).build();
}
// TODO:: To handle
return FileProcessResult.builder().parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK).libraryFile(libraryFile).build();
}
private List<LibraryFile> getLibraryFiles(Library library) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>();
for (String libraryPath : library.getPaths()) {
libraryFiles.addAll(findLibraryFiles(libraryPath, library));
}
return libraryFiles;
}
private List<LibraryFile> findLibraryFiles(String directoryPath, Library library) throws IOException {
List<LibraryFile> libraryFiles = new ArrayList<>();
try (var stream = Files.walk(Path.of(directoryPath))) {
stream.filter(Files::isRegularFile)
.filter(file -> {
String fileName = file.getFileName().toString().toLowerCase();
return fileName.endsWith(".pdf") || fileName.endsWith(".epub");
})
.forEach(file -> {
String fileType = file.getFileName().toString().toLowerCase().endsWith(".pdf") ? "PDF" : "EPUB";
libraryFiles.add(new LibraryFile(library, file.toAbsolutePath().toString(), fileType));
});
}
return libraryFiles;
List<Book> books = bookRepository.findBooksByLibraryId(libraryId);
return books.stream().map(BookTransformer::convertToBookDTO).toList();
}
}
@@ -0,0 +1,18 @@
package com.adityachandel.booklore.service;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
@Service
public class NotificationService {
private final SimpMessagingTemplate messagingTemplate;
public NotificationService(SimpMessagingTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
public void sendMessage(String topic, Object message) {
messagingTemplate.convertAndSend(topic, message);
}
}
@@ -1,13 +1,14 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.AppProperties;
import com.adityachandel.booklore.model.enums.ParsingStatus;
import com.adityachandel.booklore.model.FileProcessResult;
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.BookMetadata;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.transformer.BookTransformer;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.Loader;
@@ -15,6 +16,7 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.imageio.ImageIO;
@@ -22,7 +24,10 @@ import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@@ -34,32 +39,24 @@ public class PdfFileProcessor implements FileProcessor {
private BookCreatorService bookCreatorService;
private AppProperties appProperties;
@Transactional
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Override
public FileProcessResult processFile(LibraryFile libraryFile, boolean forceProcess) {
public BookDTO processFile(LibraryFile libraryFile, boolean forceProcess) {
File bookFile = new File(libraryFile.getFilePath());
String fileName = bookFile.getName();
if (!forceProcess) {
Optional<Book> bookOptional = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibrary().getId());
if (bookOptional.isPresent()) {
return FileProcessResult.builder()
.libraryFile(libraryFile)
.bookDTO(BookTransformer.convertToBookDTO(bookOptional.get()))
.parsingStatus(ParsingStatus.EXISTING_BOOK_NO_FORCED_UPDATE)
.build();
} else {
return processNewFile(libraryFile);
}
return bookOptional.map(BookTransformer::convertToBookDTO).orElseGet(() -> processNewFile(libraryFile));
} else {
return processNewFile(libraryFile);
}
}
private FileProcessResult processNewFile(LibraryFile libraryFile) {
@Transactional(propagation = Propagation.REQUIRES_NEW)
protected BookDTO processNewFile(LibraryFile libraryFile) {
File bookFile = new File(libraryFile.getFilePath());
Book book = bookCreatorService.createShellBook(libraryFile);
BookMetadata bookMetadata = book.getMetadata();
FileProcessResult fileProcessResult;
try (PDDocument document = Loader.loadPDF(bookFile)) {
if (document.getDocumentInformation() == null) {
log.warn("No document information found");
@@ -74,19 +71,12 @@ public class PdfFileProcessor implements FileProcessor {
}
generateCoverImage(bookFile, new File(appProperties.getPathConfig() + "/thumbs"), document);
} catch (Exception e) {
log.error("Error while processing file {}", libraryFile.getFilePath(), e);
return FileProcessResult.builder()
.libraryFile(libraryFile)
.parsingStatus(ParsingStatus.FAILED_TO_PARSE_BOOK)
.build();
log.error("Error while processing file {}, error: {}", libraryFile.getFilePath(), e.getMessage());
}
bookCreatorService.saveConnections(book);
fileProcessResult = FileProcessResult.builder()
.bookDTO(BookTransformer.convertToBookDTO(book))
.parsingStatus(ParsingStatus.PARSED_NEW_BOOK)
.libraryFile(libraryFile)
.build();
return fileProcessResult;
bookRepository.save(book);
bookRepository.flush();
return BookTransformer.convertToBookDTO(book);
}
private Set<String> getAuthors(PDDocument document) {