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);
|
||||
}
|
||||
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package com.adityachandel.booklore.service.upload;
|
||||
|
||||
import com.adityachandel.booklore.config.AppProperties;
|
||||
import com.adityachandel.booklore.exception.APIException;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.Book;
|
||||
import com.adityachandel.booklore.model.dto.settings.AppSettings;
|
||||
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||
import com.adityachandel.booklore.service.NotificationService;
|
||||
import com.adityachandel.booklore.service.appsettings.AppSettingService;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.EpubMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.metadata.extractor.PdfMetadataExtractor;
|
||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class FileUploadServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
LibraryRepository libraryRepository;
|
||||
@Mock
|
||||
BookFileProcessorRegistry processorRegistry;
|
||||
@Mock
|
||||
NotificationService notificationService;
|
||||
@Mock
|
||||
AppSettingService appSettingService;
|
||||
@Mock
|
||||
PdfMetadataExtractor pdfMetadataExtractor;
|
||||
@Mock
|
||||
EpubMetadataExtractor epubMetadataExtractor;
|
||||
@Mock
|
||||
MonitoringService monitoringService;
|
||||
|
||||
AppProperties appProperties;
|
||||
FileUploadService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
appProperties = new AppProperties();
|
||||
appProperties.setBookdropFolder(tempDir.toString());
|
||||
|
||||
AppSettings settings = new AppSettings();
|
||||
settings.setMaxFileUploadSizeInMb(10);
|
||||
settings.setUploadPattern("{currentFilename}");
|
||||
when(appSettingService.getAppSettings()).thenReturn(settings);
|
||||
|
||||
service = new FileUploadService(
|
||||
libraryRepository, processorRegistry, notificationService,
|
||||
appSettingService, appProperties, pdfMetadataExtractor,
|
||||
epubMetadataExtractor, monitoringService
|
||||
);
|
||||
|
||||
ReflectionTestUtils.setField(service, "userId", "0");
|
||||
ReflectionTestUtils.setField(service, "groupId", "0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFileBookDrop_succeeds_and_copiesFile() throws IOException {
|
||||
byte[] content = "hello".getBytes();
|
||||
MockMultipartFile file = new MockMultipartFile("file", "test.pdf", "application/pdf", content);
|
||||
|
||||
assertThat(service.uploadFileBookDrop(file)).isNull();
|
||||
|
||||
Path dropped = tempDir.resolve("test.pdf");
|
||||
assertThat(Files.exists(dropped)).isTrue();
|
||||
assertThat(Files.readAllBytes(dropped)).isEqualTo(content);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFileBookDrop_throws_when_duplicate() throws IOException {
|
||||
byte[] content = "data".getBytes();
|
||||
MockMultipartFile file = new MockMultipartFile("file", "dup.epub", "application/epub+zip", content);
|
||||
Files.write(tempDir.resolve("dup.epub"), new byte[]{1, 2, 3});
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getStatus());
|
||||
assertThat(ex.getMessage()).isEqualTo(ApiError.FILE_ALREADY_EXISTS.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFileBookDrop_throws_on_invalid_extension() {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "bad.txt", "text/plain", "x".getBytes());
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_FILE_FORMAT.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Invalid file format, only pdf and epub are supported");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFileBookDrop_throws_when_too_large() {
|
||||
byte[] content = new byte[2 * 1024 * 1024];
|
||||
MockMultipartFile file = new MockMultipartFile("file", "big.pdf", "application/pdf", content);
|
||||
AppSettings small = new AppSettings();
|
||||
small.setMaxFileUploadSizeInMb(1);
|
||||
when(appSettingService.getAppSettings()).thenReturn(small);
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFileBookDrop(file))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_TOO_LARGE.getStatus());
|
||||
assertThat(ex.getMessage()).contains("1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFile_throws_when_library_not_found() {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", new byte[]{1});
|
||||
when(libraryRepository.findById(42L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 1L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.LIBRARY_NOT_FOUND.getStatus()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFile_throws_when_invalid_library_path() {
|
||||
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", new byte[]{1});
|
||||
LibraryEntity lib = new LibraryEntity();
|
||||
lib.setId(42L);
|
||||
lib.setLibraryPaths(List.of());
|
||||
when(libraryRepository.findById(42L)).thenReturn(Optional.of(lib));
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 42L, 99L))
|
||||
.satisfies(ex -> assertThat(ex.getStatus()).isEqualTo(ApiError.INVALID_LIBRARY_PATH.getStatus()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFile_throws_on_transfer_io_exception() throws IOException {
|
||||
MultipartFile file = mock(MultipartFile.class);
|
||||
when(file.getOriginalFilename()).thenReturn("book.cbz");
|
||||
when(file.getSize()).thenReturn(100L);
|
||||
when(file.getName()).thenReturn("file");
|
||||
doThrow(new IOException("disk error")).when(file).transferTo(any(Path.class));
|
||||
|
||||
LibraryEntity lib = new LibraryEntity();
|
||||
lib.setId(1L);
|
||||
LibraryPathEntity path = new LibraryPathEntity();
|
||||
path.setId(1L);
|
||||
path.setPath(tempDir.toString());
|
||||
lib.setLibraryPaths(List.of(path));
|
||||
when(libraryRepository.findById(1L)).thenReturn(Optional.of(lib));
|
||||
|
||||
assertThatExceptionOfType(APIException.class)
|
||||
.isThrownBy(() -> service.uploadFile(file, 1L, 1L))
|
||||
.satisfies(ex -> {
|
||||
assertThat(ex.getStatus()).isEqualTo(ApiError.FILE_READ_ERROR.getStatus());
|
||||
assertThat(ex.getMessage()).contains("Error reading files from path");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFile_succeeds_and_processes() throws IOException {
|
||||
byte[] data = "content".getBytes();
|
||||
MockMultipartFile file = new MockMultipartFile("file", "book.cbz", "application/octet-stream", data);
|
||||
|
||||
LibraryEntity lib = new LibraryEntity();
|
||||
lib.setId(7L);
|
||||
LibraryPathEntity path = new LibraryPathEntity();
|
||||
path.setId(2L);
|
||||
path.setPath(tempDir.toString());
|
||||
lib.setLibraryPaths(List.of(path));
|
||||
when(libraryRepository.findById(7L)).thenReturn(Optional.of(lib));
|
||||
|
||||
BookFileProcessor proc = mock(BookFileProcessor.class);
|
||||
Book stubBook = Book.builder().build();
|
||||
stubBook.setTitle("X");
|
||||
when(processorRegistry.getProcessorOrThrow(BookFileType.CBX)).thenReturn(proc);
|
||||
when(proc.processFile(any())).thenReturn(stubBook);
|
||||
|
||||
Book result = service.uploadFile(file, 7L, 2L);
|
||||
|
||||
assertThat(result).isSameAs(stubBook);
|
||||
Path moved = tempDir.resolve("book.cbz");
|
||||
assertThat(Files.exists(moved)).isTrue();
|
||||
verify(notificationService).sendMessage(eq(Topic.BOOK_ADD), same(stubBook));
|
||||
verifyNoInteractions(pdfMetadataExtractor, epubMetadataExtractor);
|
||||
}
|
||||
}
|
||||
Generated
+4
-4
@@ -28,7 +28,7 @@
|
||||
"ngx-extended-pdf-viewer": "^23.3.1",
|
||||
"ngx-infinite-scroll": "^19.0.0",
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "19.1.2",
|
||||
"primeng": "19.1.4",
|
||||
"quill": "^2.0.3",
|
||||
"rxjs": "^7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
@@ -14289,9 +14289,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/primeng": {
|
||||
"version": "19.1.2",
|
||||
"resolved": "https://registry.npmjs.org/primeng/-/primeng-19.1.2.tgz",
|
||||
"integrity": "sha512-iu4lDrStBPCyYn+iSfofp/Hsv/dHVlnlsOhqFZlYTQB1o+MlVXa4PanLgHdoBr1thy3ozRkNDZHsICkUecWu0A==",
|
||||
"version": "19.1.4",
|
||||
"resolved": "https://registry.npmjs.org/primeng/-/primeng-19.1.4.tgz",
|
||||
"integrity": "sha512-l5l8SHTxopxxyyXZx1BvbQ11P7ndLv2Qp8H5k2/+OCi65jTZn4xmtrBDGDs7k2K5UMHSqAnGjBgtpbckyqQETg==",
|
||||
"license": "SEE LICENSE IN LICENSE.md",
|
||||
"dependencies": {
|
||||
"@primeuix/styled": "^0.3.2",
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"ngx-extended-pdf-viewer": "^23.3.1",
|
||||
"ngx-infinite-scroll": "^19.0.0",
|
||||
"primeicons": "^7.0.0",
|
||||
"primeng": "19.1.2",
|
||||
"primeng": "19.1.4",
|
||||
"quill": "^2.0.3",
|
||||
"rxjs": "^7.8.2",
|
||||
"showdown": "^2.1.0",
|
||||
|
||||
+27
-15
@@ -1,26 +1,38 @@
|
||||
@if ((libraryState$ | async)?.libraries; as libraries) {
|
||||
<div
|
||||
class="flex flex-col gap-10 p-4 items-center justify-center w-full max-w-[700px]">
|
||||
<p-select
|
||||
[options]="libraries"
|
||||
optionLabel="name"
|
||||
placeholder="Select Library"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
class="w-full"></p-select>
|
||||
<p-select
|
||||
[options]="selectedLibrary?.paths"
|
||||
optionLabel="path"
|
||||
placeholder="Select Upload Location"
|
||||
[(ngModel)]="selectedPath"
|
||||
[disabled]="!selectedLibrary"
|
||||
class="w-full"></p-select>
|
||||
class="flex flex-col gap-8 p-4 items-center justify-center w-full max-w-[700px]">
|
||||
<div class="flex flex-col items-center gap-2 w-full">
|
||||
<label class="text-sm text-stone-400">Upload Destination</label>
|
||||
<p-selectbutton
|
||||
[options]="stateOptions"
|
||||
[(ngModel)]="value"
|
||||
[allowEmpty]="false"
|
||||
optionLabel="label"
|
||||
optionValue="value">
|
||||
</p-selectbutton>
|
||||
</div>
|
||||
@if (value === 'library') {
|
||||
<p-select
|
||||
[options]="libraries"
|
||||
optionLabel="name"
|
||||
placeholder="Select Library"
|
||||
[(ngModel)]="selectedLibrary"
|
||||
class="w-full"></p-select>
|
||||
<p-select
|
||||
[options]="selectedLibrary?.paths"
|
||||
optionLabel="path"
|
||||
placeholder="Select Subpath"
|
||||
[(ngModel)]="selectedPath"
|
||||
[disabled]="!selectedLibrary"
|
||||
class="w-full"></p-select>
|
||||
}
|
||||
<p-fileupload class="w-full" name="file"
|
||||
[maxFileSize]="maxFileSizeBytes"
|
||||
[customUpload]="true"
|
||||
[multiple]="true" accept=".pdf,.epub,.cbz,.cbr,.cb7"
|
||||
(onSelect)="onFilesSelect($event)"
|
||||
(uploadHandler)="uploadFiles($event)"
|
||||
[disabled]="!selectedLibrary || !selectedPath">
|
||||
[disabled]="value === 'library' ? (!selectedLibrary || !selectedPath) : false">
|
||||
<ng-template #header let-files let-chooseCallback="chooseCallback" let-clearCallback="clearCallback" let-uploadCallback="uploadCallback">
|
||||
<div class="flex flex-col items-center justify-center flex-1 gap-4">
|
||||
<div class="flex gap-4">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {FileSelectEvent, FileUpload, FileUploadHandlerEvent} from 'primeng/fileupload';
|
||||
import {Button} from 'primeng/button';
|
||||
import { AsyncPipe } from '@angular/common';
|
||||
import {AsyncPipe} from '@angular/common';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {MessageService} from 'primeng/api';
|
||||
import {Select} from 'primeng/select';
|
||||
@@ -17,6 +17,7 @@ import {Tooltip} from 'primeng/tooltip';
|
||||
import {AppSettingsService} from '../../../core/service/app-settings.service';
|
||||
import {filter, take} from 'rxjs/operators';
|
||||
import {AppSettings} from '../../../core/model/app-settings.model';
|
||||
import {SelectButton} from 'primeng/selectbutton';
|
||||
|
||||
interface UploadingFile {
|
||||
file: File;
|
||||
@@ -34,8 +35,9 @@ interface UploadingFile {
|
||||
FormsModule,
|
||||
Select,
|
||||
Badge,
|
||||
Tooltip
|
||||
],
|
||||
Tooltip,
|
||||
SelectButton
|
||||
],
|
||||
templateUrl: './book-uploader.component.html',
|
||||
styleUrl: './book-uploader.component.scss'
|
||||
})
|
||||
@@ -53,6 +55,11 @@ export class BookUploaderComponent implements OnInit {
|
||||
readonly libraryState$: Observable<LibraryState> = this.libraryService.libraryState$;
|
||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||
maxFileSizeBytes?: number;
|
||||
stateOptions = [
|
||||
{label: 'Library', value: 'library'},
|
||||
{label: 'Bookdrop', value: 'bookdrop'}
|
||||
];
|
||||
value = 'library';
|
||||
|
||||
ngOnInit(): void {
|
||||
this.appSettings$
|
||||
@@ -101,7 +108,7 @@ export class BookUploaderComponent implements OnInit {
|
||||
}
|
||||
|
||||
uploadFiles(event: FileUploadHandlerEvent): void {
|
||||
if (!this.selectedLibrary || !this.selectedPath) {
|
||||
if (this.value === 'library' && (!this.selectedLibrary || !this.selectedPath)) {
|
||||
this.messageService.add({
|
||||
severity: 'warn',
|
||||
summary: 'Missing Data',
|
||||
@@ -111,34 +118,52 @@ export class BookUploaderComponent implements OnInit {
|
||||
return;
|
||||
}
|
||||
|
||||
const libraryId = this.selectedLibrary.id!.toString();
|
||||
const pathId = this.selectedPath.id!.toString();
|
||||
const filesToUpload = this.files.filter(f => f.status === 'Pending');
|
||||
|
||||
if (filesToUpload.length === 0) return;
|
||||
|
||||
this.isUploading = true;
|
||||
let pending = filesToUpload.length;
|
||||
this.uploadBatch(filesToUpload, 0, 5);
|
||||
}
|
||||
|
||||
for (const uploadFile of filesToUpload) {
|
||||
private uploadBatch(files: UploadingFile[], startIndex: number, batchSize: number): void {
|
||||
const batch = files.slice(startIndex, startIndex + batchSize);
|
||||
if (batch.length === 0) {
|
||||
this.isUploading = false;
|
||||
return;
|
||||
}
|
||||
|
||||
let pending = batch.length;
|
||||
|
||||
for (const uploadFile of batch) {
|
||||
uploadFile.status = 'Uploading';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', uploadFile.file);
|
||||
formData.append('libraryId', libraryId);
|
||||
formData.append('pathId', pathId);
|
||||
|
||||
this.http.post<Book>(`${API_CONFIG.BASE_URL}/api/v1/files/upload`, formData).subscribe({
|
||||
let uploadUrl: string;
|
||||
if (this.value === 'library') {
|
||||
const libraryId = this.selectedLibrary!.id!.toString();
|
||||
const pathId = this.selectedPath!.id!.toString();
|
||||
formData.append('libraryId', libraryId);
|
||||
formData.append('pathId', pathId);
|
||||
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload`;
|
||||
} else {
|
||||
uploadUrl = `${API_CONFIG.BASE_URL}/api/v1/files/upload/bookdrop`;
|
||||
}
|
||||
|
||||
this.http.post<Book>(uploadUrl, formData).subscribe({
|
||||
next: () => {
|
||||
uploadFile.status = 'Uploaded';
|
||||
if (--pending === 0) this.isUploading = false;
|
||||
if (--pending === 0) {
|
||||
this.uploadBatch(files, startIndex + batchSize, batchSize);
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
uploadFile.status = 'Failed';
|
||||
uploadFile.errorMessage = err?.error?.message || 'Upload failed due to unknown error.';
|
||||
console.error('Upload failed for', uploadFile.file.name, err);
|
||||
if (--pending === 0) {
|
||||
this.isUploading = false;
|
||||
this.uploadBatch(files, startIndex + batchSize, batchSize);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -146,11 +171,14 @@ export class BookUploaderComponent implements OnInit {
|
||||
}
|
||||
|
||||
isChooseDisabled(): boolean {
|
||||
if (this.value === 'bookdrop') {
|
||||
return this.isUploading;
|
||||
}
|
||||
return !this.selectedLibrary || !this.selectedPath || this.isUploading;
|
||||
}
|
||||
|
||||
isUploadDisabled(): boolean {
|
||||
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles;
|
||||
return this.isChooseDisabled() || !this.filesPresent() || !this.hasPendingFiles();
|
||||
}
|
||||
|
||||
formatSize(bytes: number): string {
|
||||
|
||||
+3
-3
@@ -11,7 +11,7 @@
|
||||
<code class="bg-gray-800 px-1 py-0.5 rounded text-[var(--primary-color)] font-mono text-xs">{{ '{authors}' }}</code>
|
||||
to automatically insert metadata. <br>
|
||||
A preview below shows how files will be renamed and moved.
|
||||
Once you're satisfied, click <span class="font-semibold text-green-400">Apply</span> to proceed.
|
||||
Once you're satisfied, click <span class="font-semibold text-green-400">Move Files</span> to proceed.
|
||||
<span class="text-yellow-500 font-medium flex items-center gap-2">
|
||||
<i class="pi pi-exclamation-triangle text-yellow-400"></i>
|
||||
Files will be physically moved on your system when you apply changes.
|
||||
@@ -57,7 +57,7 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mb-4 px-2 items-center w-full">
|
||||
<div class="flex gap-4 mb-4 px-2 items-center w-full">
|
||||
<input
|
||||
type="text"
|
||||
pInputText
|
||||
@@ -116,7 +116,7 @@
|
||||
|
||||
<p-divider></p-divider>
|
||||
|
||||
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4">
|
||||
<div class="flex justify-end items-center gap-4 flex-shrink-0 px-4 pt-4">
|
||||
@if (movedFileCount > 0) {
|
||||
<span class="text-green-500 flex items-center font-semibold drop-shadow-sm select-none">
|
||||
{{ movedFileCount }} file{{ movedFileCount > 1 ? 's' : '' }} successfully moved
|
||||
|
||||
Reference in New Issue
Block a user