Allow book upload GUI to upload into Bookdrop
This commit is contained in:
committed by
Aditya Chandel
parent
1b58b38cbe
commit
fb5a70c7e7
+9
@@ -28,4 +28,13 @@ public class FileUploadController {
|
||||
}
|
||||
return ResponseEntity.ok(fileUploadService.uploadFile(file, libraryId, pathId));
|
||||
}
|
||||
|
||||
@PreAuthorize("@securityUtil.isAdmin() or @securityUtil.canUpload()")
|
||||
@PostMapping(value = "/upload/bookdrop", consumes = "multipart/form-data")
|
||||
public ResponseEntity<Book> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
|
||||
if (file.isEmpty()) {
|
||||
throw new IllegalArgumentException("Uploaded file is missing.");
|
||||
}
|
||||
return ResponseEntity.ok(fileUploadService.uploadFileBookDrop(file));
|
||||
}
|
||||
}
|
||||
|
||||
+31
-17
@@ -39,28 +39,42 @@ public abstract class AbstractFileProcessor implements BookFileProcessor {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
@Override
|
||||
public Book processFile(LibraryFile libraryFile) {
|
||||
Path filePath = libraryFile.getFullPath();
|
||||
String fileName = filePath.getFileName().toString();
|
||||
String hash = FileFingerprint.generateHash(filePath);
|
||||
Path path = libraryFile.getFullPath();
|
||||
String fileName = path.getFileName().toString();
|
||||
String hash = FileFingerprint.generateHash(path);
|
||||
|
||||
Optional<Book> existing = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookMapper);
|
||||
if (existing.isPresent()) {
|
||||
return existing.get();
|
||||
}
|
||||
Optional<BookEntity> byName = bookRepository.findBookByFileNameAndLibraryId(fileName, libraryFile.getLibraryEntity().getId());
|
||||
if (byName.isPresent()) {
|
||||
return bookMapper.toBook(byName.get());
|
||||
Optional<Book> duplicate = fileProcessingUtils.checkForDuplicateAndUpdateMetadataIfNeeded(libraryFile, hash, bookRepository, bookMapper);
|
||||
if (duplicate.isPresent()) {
|
||||
return handleDuplicate(duplicate.get(), libraryFile);
|
||||
}
|
||||
|
||||
BookEntity book = processNewFile(libraryFile);
|
||||
book.setCurrentHash(hash);
|
||||
Long libraryId = libraryFile.getLibraryEntity().getId();
|
||||
return bookRepository.findBookByFileNameAndLibraryId(fileName, libraryId)
|
||||
.map(bookMapper::toBook)
|
||||
.orElseGet(() -> createAndMapBook(libraryFile, hash));
|
||||
}
|
||||
|
||||
Float score = metadataMatchService.calculateMatchScore(book);
|
||||
book.setMetadataMatchScore(score);
|
||||
private Book handleDuplicate(Book bookDto, LibraryFile libraryFile) {
|
||||
bookRepository.findById(bookDto.getId())
|
||||
.ifPresent(entity -> {
|
||||
entity.setFileSubPath(libraryFile.getFileSubPath());
|
||||
entity.setFileName(libraryFile.getFileName());
|
||||
entity.setLibraryPath(libraryFile.getLibraryPathEntity());
|
||||
log.info("Duplicate file handled: bookId={} fileName='{}' libraryId={} subPath='{}'",
|
||||
entity.getId(),
|
||||
libraryFile.getFileName(),
|
||||
libraryFile.getLibraryEntity().getId(),
|
||||
libraryFile.getFileSubPath());
|
||||
});
|
||||
return bookDto;
|
||||
}
|
||||
|
||||
bookCreatorService.saveConnections(book);
|
||||
|
||||
return bookMapper.toBook(book);
|
||||
private Book createAndMapBook(LibraryFile libraryFile, String hash) {
|
||||
BookEntity entity = processNewFile(libraryFile);
|
||||
entity.setCurrentHash(hash);
|
||||
entity.setMetadataMatchScore(metadataMatchService.calculateMatchScore(entity));
|
||||
bookCreatorService.saveConnections(entity);
|
||||
return bookMapper.toBook(entity);
|
||||
}
|
||||
|
||||
protected abstract BookEntity processNewFile(LibraryFile libraryFile);
|
||||
|
||||
+40
-2
@@ -1,6 +1,7 @@
|
||||
package com.adityachandel.booklore.service.library;
|
||||
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.mapper.BookMapper;
|
||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
@@ -21,6 +22,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
@@ -36,6 +38,7 @@ public class LibraryProcessingService {
|
||||
private final NotificationService notificationService;
|
||||
private final BookRepository bookRepository;
|
||||
private final FileService fileService;
|
||||
private final BookMapper bookMapper;
|
||||
private final LibraryFileProcessorRegistry fileProcessorRegistry;
|
||||
|
||||
@Transactional
|
||||
@@ -53,12 +56,47 @@ public class LibraryProcessingService {
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + libraryEntity.getName()));
|
||||
List<LibraryFile> libraryFiles = getLibraryFiles(libraryEntity);
|
||||
deleteRemovedBooks(detectDeletedBookIds(libraryFiles, libraryEntity));
|
||||
List<Long> bookIds = detectDeletedBookIds(libraryFiles, libraryEntity);
|
||||
if (!bookIds.isEmpty()) {
|
||||
log.info("Detected {} removed books in library: {}", bookIds.size(), libraryEntity.getName());
|
||||
deleteRemovedBooks(bookIds);
|
||||
}
|
||||
restoreDeletedBooks(libraryFiles);
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
processor.processLibraryFiles(detectNewBookPaths(libraryFiles, libraryEntity), libraryEntity);
|
||||
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + libraryEntity.getName()));
|
||||
}
|
||||
|
||||
private void restoreDeletedBooks(List<LibraryFile> libraryFiles) {
|
||||
if (libraryFiles.isEmpty()) return;
|
||||
|
||||
LibraryEntity libraryEntity = libraryFiles.get(0).getLibraryEntity();
|
||||
Set<Path> currentPaths = libraryFiles.stream()
|
||||
.map(LibraryFile::getFullPath)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<BookEntity> toRestore = libraryEntity.getBookEntities().stream()
|
||||
.filter(book -> Boolean.TRUE.equals(book.getDeleted()))
|
||||
.filter(book -> currentPaths.contains(book.getFullFilePath()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (toRestore.isEmpty()) return;
|
||||
|
||||
toRestore.forEach(book -> {
|
||||
book.setDeleted(false);
|
||||
book.setDeletedAt(null);
|
||||
book.setAddedOn(Instant.now());
|
||||
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
|
||||
});
|
||||
bookRepository.saveAll(toRestore);
|
||||
|
||||
List<Long> restoredIds = toRestore.stream()
|
||||
.map(BookEntity::getId)
|
||||
.toList();
|
||||
|
||||
log.info("Restored {} books in library: {}", restoredIds.size(), libraryEntity.getName());
|
||||
}
|
||||
|
||||
public void processLibraryFiles(List<LibraryFile> libraryFiles, LibraryEntity libraryEntity) {
|
||||
LibraryFileProcessor processor = fileProcessorRegistry.getProcessor(libraryEntity);
|
||||
processor.processLibraryFiles(libraryFiles, libraryEntity);
|
||||
@@ -150,4 +188,4 @@ public class LibraryProcessingService {
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+31
-9
@@ -1,5 +1,6 @@
|
||||
package com.adityachandel.booklore.service.upload;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||
@@ -48,6 +49,7 @@ public class FileUploadService {
|
||||
private final BookFileProcessorRegistry processorRegistry;
|
||||
private final NotificationService notificationService;
|
||||
private final AppSettingService appSettingService;
|
||||
private final AppProperties appProperties;
|
||||
private final PdfMetadataExtractor pdfMetadataExtractor;
|
||||
private final EpubMetadataExtractor epubMetadataExtractor;
|
||||
private final MonitoringService monitoringService;
|
||||
@@ -61,8 +63,7 @@ public class FileUploadService {
|
||||
public Book uploadFile(MultipartFile file, long libraryId, long pathId) throws IOException {
|
||||
validateFile(file);
|
||||
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId)
|
||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
LibraryEntity libraryEntity = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
|
||||
LibraryPathEntity libraryPathEntity = libraryEntity.getLibraryPaths()
|
||||
.stream()
|
||||
@@ -81,20 +82,15 @@ public class FileUploadService {
|
||||
|
||||
try {
|
||||
file.transferTo(tempPath);
|
||||
|
||||
setTemporaryFileOwnership(tempPath);
|
||||
|
||||
BookFileExtension fileExt = BookFileExtension.fromFileName(file.getOriginalFilename()).orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"));
|
||||
|
||||
BookMetadata metadata = extractMetadata(fileExt, tempPath.toFile());
|
||||
|
||||
String uploadPattern = appSettingService.getAppSettings().getUploadPattern();
|
||||
if (uploadPattern.endsWith("/") || uploadPattern.endsWith("\\")) {
|
||||
uploadPattern += "{currentFilename}";
|
||||
}
|
||||
|
||||
String relativePath = PathPatternResolver.resolvePattern(metadata, uploadPattern, file.getOriginalFilename());
|
||||
|
||||
Path finalPath = Paths.get(libraryPathEntity.getPath(), relativePath);
|
||||
File finalFile = finalPath.toFile();
|
||||
|
||||
@@ -132,6 +128,33 @@ public class FileUploadService {
|
||||
}
|
||||
}
|
||||
|
||||
public Book uploadFileBookDrop(MultipartFile file) throws IOException {
|
||||
validateFile(file);
|
||||
|
||||
Path dropFolder = Paths.get(appProperties.getBookdropFolder());
|
||||
Files.createDirectories(dropFolder);
|
||||
|
||||
String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
|
||||
Path tempPath = Files.createTempFile("bookdrop-", originalFilename);
|
||||
|
||||
try {
|
||||
file.transferTo(tempPath);
|
||||
setTemporaryFileOwnership(tempPath);
|
||||
|
||||
Path finalPath = dropFolder.resolve(originalFilename);
|
||||
|
||||
if (Files.exists(finalPath)) {
|
||||
throw ApiError.FILE_ALREADY_EXISTS.createException();
|
||||
}
|
||||
Files.move(tempPath, finalPath);
|
||||
|
||||
log.info("File moved to book-drop folder: {}", finalPath);
|
||||
return null;
|
||||
} finally {
|
||||
Files.deleteIfExists(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
private BookMetadata extractMetadata(BookFileExtension fileExt, File file) throws IOException {
|
||||
return switch (fileExt) {
|
||||
case PDF -> pdfMetadataExtractor.extractMetadata(file);
|
||||
@@ -153,7 +176,7 @@ public class FileUploadService {
|
||||
|
||||
private void setTemporaryFileOwnership(Path tempPath) throws IOException {
|
||||
UserPrincipalLookupService lookupService = FileSystems.getDefault()
|
||||
.getUserPrincipalLookupService();
|
||||
.getUserPrincipalLookupService();
|
||||
if (!userId.equals("0")) {
|
||||
UserPrincipal user = lookupService.lookupPrincipalByName(userId);
|
||||
Files.getFileAttributeView(tempPath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS).setOwner(user);
|
||||
@@ -178,5 +201,4 @@ public class FileUploadService {
|
||||
BookFileProcessor processor = processorRegistry.getProcessorOrThrow(type);
|
||||
return processor.processFile(libraryFile);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user