diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java index bd58b4cec..7013f3a8b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/FileMoveRequest.java @@ -7,5 +7,4 @@ import java.util.Set; @Data public class FileMoveRequest { private Set bookIds; - private String pattern; } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java index 0fd7d53f8..b4af38ae2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettings.java @@ -17,7 +17,6 @@ public class AppSettings { private boolean similarBookRecommendation; private boolean opdsServerEnabled; private String uploadPattern; - private String movePattern; private Integer cbxCacheSizeInMb; private Integer pdfCacheSizeInMb; private Integer maxFileUploadSizeInMb; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java index c059df9bd..a9ca6d512 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/AppSettingService.java @@ -73,8 +73,7 @@ public class AppSettingService { builder.coverResolution(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.COVER_IMAGE_RESOLUTION, "250x350")); builder.autoBookSearch(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.AUTO_BOOK_SEARCH, "true"))); - builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{currentFilename}")); - builder.movePattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.MOVE_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>")); + builder.uploadPattern(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.UPLOAD_FILE_PATTERN, "{authors}/<{series}/><{seriesIndex}. >{title}< - {authors}>< ({year})>")); builder.similarBookRecommendation(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.SIMILAR_BOOK_RECOMMENDATION, "true"))); builder.opdsServerEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OPDS_SERVER_ENABLED, "false"))); builder.oidcEnabled(Boolean.parseBoolean(settingPersistenceHelper.getOrCreateSetting(AppSettingKey.OIDC_ENABLED, "false"))); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java index e141ecf10..6ea090364 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/FileMoveService.java @@ -4,10 +4,14 @@ import com.adityachandel.booklore.mapper.BookMapper; import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.request.FileMoveRequest; import com.adityachandel.booklore.model.entity.BookEntity; +import com.adityachandel.booklore.model.entity.LibraryEntity; +import com.adityachandel.booklore.model.entity.LibraryPathEntity; +import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.BookQueryService; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.library.LibraryService; import com.adityachandel.booklore.service.monitoring.MonitoringService; import com.adityachandel.booklore.util.PathPatternResolver; @@ -31,116 +35,175 @@ public class FileMoveService { private final NotificationService notificationService; private final LibraryService libraryService; private final MonitoringService monitoringService; + private final AppSettingService appSettingService; public void moveFiles(FileMoveRequest request) { Set bookIds = request.getBookIds(); - String pattern = request.getPattern(); List books = bookQueryService.findAllWithMetadataByIds(bookIds); + String defaultPattern = appSettingService.getAppSettings().getUploadPattern(); - log.info("Starting file move for {} books using pattern: '{}'", books.size(), pattern); + log.info("Starting file move for {} books", books.size()); Set libraryIds = new HashSet<>(); List updatedBooks = new ArrayList<>(); - boolean didPause = false; - - if (!monitoringService.isPaused()) { - monitoringService.pauseMonitoring(); - didPause = true; - } + boolean didPause = pauseMonitoringIfNeeded(); try { for (BookEntity book : books) { - if (book.getMetadata() == null) continue; - - if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null - || book.getFileSubPath() == null || book.getFileName() == null) { - log.error("Missing required path components for book id {}. Skipping.", book.getId()); - continue; - } - - Path oldFilePath = book.getFullFilePath(); - if (!Files.exists(oldFilePath)) { - log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath); - continue; - } - - log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle()); - - String newRelativePathStr = generatePathFromPattern(book, pattern); - if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { - newRelativePathStr = newRelativePathStr.substring(1); - } - - Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); - Path newFilePath = libraryRoot.resolve(newRelativePathStr).normalize(); - - if (oldFilePath.equals(newFilePath)) { - log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId()); - continue; - } - - try { - if (newFilePath.getParent() != null) { - Files.createDirectories(newFilePath.getParent()); - } - - log.info("Moving file from {} to {}", oldFilePath, newFilePath); - Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING); - - String newFileName = newFilePath.getFileName().toString(); - Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent()); - String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/'); - - book.setFileSubPath(newFileSubPath); - book.setFileName(newFileName); - bookRepository.save(book); - - updatedBooks.add(bookMapper.toBook(book)); - log.info("Updated book id {} with new path", book.getId()); - - deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot)); - - if (book.getLibraryPath().getLibrary().getId() != null) { - libraryIds.add(book.getLibraryPath().getLibrary().getId()); - } - } catch (IOException e) { - log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e); - } + processBookMove(book, defaultPattern, updatedBooks, libraryIds); } log.info("Completed file move for {} books.", books.size()); - - if (!updatedBooks.isEmpty()) { - notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks); - } - - for (Long libraryId : libraryIds) { - try { - libraryService.rescanLibrary(libraryId); - log.info("Rescanned library id {} after file move", libraryId); - } catch (Exception e) { - log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e); - } - } + sendUpdateNotifications(updatedBooks); + rescanLibraries(libraryIds); } finally { - if (didPause && !monitoringService.isPaused()) { - log.info("Monitoring already resumed by another thread."); - } else if (didPause) { - Thread.startVirtualThread(() -> { - try { - Thread.sleep(5_000); - monitoringService.resumeMonitoring(); - log.info("Monitoring resumed after 5s delay"); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.warn("Interrupted while delaying resume of monitoring"); - } - }); + resumeMonitoringWithDelay(didPause); + } + } + + private boolean pauseMonitoringIfNeeded() { + if (!monitoringService.isPaused()) { + monitoringService.pauseMonitoring(); + return true; + } + return false; + } + + private void processBookMove(BookEntity book, String defaultPattern, List updatedBooks, Set libraryIds) { + if (book.getMetadata() == null) return; + + String pattern = getFileNamingPattern(book, defaultPattern); + if (pattern == null) return; + + if (!hasRequiredPathComponents(book)) return; + + Path oldFilePath = book.getFullFilePath(); + if (!Files.exists(oldFilePath)) { + log.warn("File does not exist for book id {}: {}", book.getId(), oldFilePath); + return; + } + + log.info("Processing book id {}: '{}'", book.getId(), book.getMetadata().getTitle()); + + Path newFilePath = generateNewFilePath(book, pattern); + if (oldFilePath.equals(newFilePath)) { + log.info("Source and destination paths are identical for book id {}. Skipping.", book.getId()); + return; + } + + try { + moveFileAndUpdateBook(book, oldFilePath, newFilePath, updatedBooks, libraryIds); + } catch (IOException e) { + log.error("Failed to move file for book id {}: {}", book.getId(), e.getMessage(), e); + } + } + + private String getFileNamingPattern(BookEntity book, String defaultPattern) { + if (book.getLibraryPath() == null || book.getLibraryPath().getLibrary() == null) { + log.error("Book id {} has no library associated. Skipping.", book.getId()); + return null; + } + LibraryEntity library = book.getLibraryPath().getLibrary(); + String pattern = library.getFileNamingPattern(); + if (pattern == null || pattern.trim().isEmpty()) { + pattern = defaultPattern; + log.info("Using default pattern for library {} as no custom pattern is set", library.getName()); + } + if (pattern == null || pattern.trim().isEmpty()) { + log.error("No file naming pattern available for book id {}. Skipping.", book.getId()); + return null; + } + + return pattern; + } + + private boolean hasRequiredPathComponents(BookEntity book) { + if (book.getLibraryPath() == null || book.getLibraryPath().getPath() == null || + book.getFileSubPath() == null || book.getFileName() == null) { + log.error("Missing required path components for book id {}. Skipping.", book.getId()); + return false; + } + return true; + } + + private Path generateNewFilePath(BookEntity book, String pattern) { + String newRelativePathStr = generatePathFromPattern(book, pattern); + if (newRelativePathStr.startsWith("/") || newRelativePathStr.startsWith("\\")) { + newRelativePathStr = newRelativePathStr.substring(1); + } + + Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); + return libraryRoot.resolve(newRelativePathStr).normalize(); + } + + private void moveFileAndUpdateBook(BookEntity book, Path oldFilePath, Path newFilePath, + List updatedBooks, Set libraryIds) throws IOException { + if (newFilePath.getParent() != null) { + Files.createDirectories(newFilePath.getParent()); + } + + log.info("Moving file from {} to {}", oldFilePath, newFilePath); + Files.move(oldFilePath, newFilePath, StandardCopyOption.REPLACE_EXISTING); + + updateBookPaths(book, newFilePath); + bookRepository.save(book); + updatedBooks.add(bookMapper.toBook(book)); + + log.info("Updated book id {} with new path", book.getId()); + + Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); + deleteEmptyParentDirsUpToLibraryFolders(oldFilePath.getParent(), Set.of(libraryRoot)); + + if (book.getLibraryPath().getLibrary().getId() != null) { + libraryIds.add(book.getLibraryPath().getLibrary().getId()); + } + } + + private void updateBookPaths(BookEntity book, Path newFilePath) { + String newFileName = newFilePath.getFileName().toString(); + Path libraryRoot = Paths.get(book.getLibraryPath().getPath()).toAbsolutePath().normalize(); + Path newRelativeSubPath = libraryRoot.relativize(newFilePath.getParent()); + String newFileSubPath = newRelativeSubPath.toString().replace('\\', '/'); + + book.setFileSubPath(newFileSubPath); + book.setFileName(newFileName); + } + + private void sendUpdateNotifications(List updatedBooks) { + if (!updatedBooks.isEmpty()) { + notificationService.sendMessage(Topic.BOOK_METADATA_BATCH_UPDATE, updatedBooks); + } + } + + private void rescanLibraries(Set libraryIds) { + for (Long libraryId : libraryIds) { + try { + libraryService.rescanLibrary(libraryId); + log.info("Rescanned library id {} after file move", libraryId); + } catch (Exception e) { + log.error("Failed to rescan library id {}: {}", libraryId, e.getMessage(), e); } } } + private void resumeMonitoringWithDelay(boolean didPause) { + if (didPause && !monitoringService.isPaused()) { + log.info("Monitoring already resumed by another thread."); + } else if (didPause) { + Thread.startVirtualThread(() -> { + try { + Thread.sleep(5_000); + monitoringService.resumeMonitoring(); + log.info("Monitoring resumed after 5s delay"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + log.warn("Interrupted while delaying resume of monitoring"); + } + }); + } + } + public String generatePathFromPattern(BookEntity book, String pattern) { return PathPatternResolver.resolvePattern(book, pattern); } @@ -155,19 +218,7 @@ public class FileMoveService { } while (currentDir != null) { - boolean isLibraryRoot = false; - for (Path root : normalizedRoots) { - try { - if (Files.isSameFile(root, currentDir)) { - isLibraryRoot = true; - break; - } - } catch (IOException e) { - log.warn("Failed to compare paths: {} and {}", root, currentDir); - } - } - - if (isLibraryRoot) { + if (isLibraryRoot(currentDir, normalizedRoots)) { log.debug("Reached library root: {}. Stopping cleanup.", currentDir); break; } @@ -178,30 +229,8 @@ public class FileMoveService { break; } - boolean hasImportantFiles = false; - for (File file : files) { - if (!ignoredFilenames.contains(file.getName())) { - hasImportantFiles = true; - break; - } - } - - if (!hasImportantFiles) { - for (File file : files) { - try { - Files.delete(file.toPath()); - log.info("Deleted ignored file: {}", file.getAbsolutePath()); - } catch (IOException e) { - log.warn("Failed to delete ignored file: {}", file.getAbsolutePath()); - } - } - try { - Files.delete(currentDir); - log.info("Deleted empty directory: {}", currentDir); - } catch (IOException e) { - log.warn("Failed to delete directory: {}", currentDir, e); - break; - } + if (hasOnlyIgnoredFiles(files, ignoredFilenames)) { + deleteIgnoredFilesAndDirectory(files, currentDir); currentDir = currentDir.getParent(); } else { log.debug("Directory {} contains important files. Stopping cleanup.", currentDir); @@ -209,4 +238,44 @@ public class FileMoveService { } } } + + private boolean isLibraryRoot(Path currentDir, Set normalizedRoots) { + for (Path root : normalizedRoots) { + try { + if (Files.isSameFile(root, currentDir)) { + return true; + } + } catch (IOException e) { + log.warn("Failed to compare paths: {} and {}", root, currentDir); + } + } + return false; + } + + private boolean hasOnlyIgnoredFiles(File[] files, Set ignoredFilenames) { + for (File file : files) { + if (!ignoredFilenames.contains(file.getName())) { + return false; + } + } + return true; + } + + private void deleteIgnoredFilesAndDirectory(File[] files, Path currentDir) { + for (File file : files) { + try { + Files.delete(file.toPath()); + log.info("Deleted ignored file: {}", file.getAbsolutePath()); + } catch (IOException e) { + log.warn("Failed to delete ignored file: {}", file.getAbsolutePath()); + } + } + + try { + Files.delete(currentDir); + log.info("Deleted empty directory: {}", currentDir); + } catch (IOException e) { + log.warn("Failed to delete directory: {}", currentDir, e); + } + } } \ No newline at end of file diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java index 0b6073a57..0e60bd2cf 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/FileMoveServiceMoveFilesTest.java @@ -1,14 +1,18 @@ package com.adityachandel.booklore; import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.model.dto.Book; import com.adityachandel.booklore.model.dto.request.FileMoveRequest; +import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.entity.*; +import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.service.BookQueryService; import com.adityachandel.booklore.service.NotificationService; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.file.FileMoveService; +import com.adityachandel.booklore.service.library.LibraryService; import com.adityachandel.booklore.service.monitoring.MonitoringService; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; @@ -26,7 +30,8 @@ import java.util.List; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class FileMoveServiceMoveFilesTest { @@ -46,6 +51,12 @@ class FileMoveServiceMoveFilesTest { @Mock private MonitoringService monitoringService; + @Mock + private AppSettingService appSettingService; + + @Mock + private LibraryService libraryService; + @InjectMocks private FileMoveService fileMoveService; @@ -56,6 +67,7 @@ class FileMoveServiceMoveFilesTest { LibraryEntity library = LibraryEntity.builder() .id(42L) .name("Test Library") + .fileNamingPattern(null) .build(); LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() @@ -65,7 +77,8 @@ class FileMoveServiceMoveFilesTest { BookMetadataEntity metadata = BookMetadataEntity.builder() .title("Test Book") - .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>())))) + .authors(new HashSet<>(List.of(new AuthorEntity(1L, "Author Name", new ArrayList<>()))) + ) .publishedDate(LocalDate.of(2020, 1, 1)) .build(); @@ -84,44 +97,21 @@ class FileMoveServiceMoveFilesTest { return book; } - @Test - void testMoveFiles_successfulMove() throws IOException { - String fileName = "testbook.epub"; - String fileSubPath = "oldfolder"; - - BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(1L)); - request.setPattern("NewFolder/{title}"); - - Path oldFilePath = book.getFullFilePath(); - - fileMoveService.moveFiles(request); - - Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("Expected the file to be moved to %s", expectedNewPath) - .isTrue(); - - assertThat(Files.exists(oldFilePath)) - .withFailMessage("Original file path should no longer exist: %s", oldFilePath) - .isFalse(); - - Files.deleteIfExists(expectedNewPath); - Files.deleteIfExists(expectedNewPath.getParent()); - } - @Test void testMoveFiles_skipsNonexistentFile() { BookMetadataEntity metadata = BookMetadataEntity.builder() .title("NoFile") .build(); + LibraryEntity library = LibraryEntity.builder() + .id(43L) + .name("Test Library") + .fileNamingPattern("Moved/{title}") + .build(); + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() .path(tempLibraryRoot.toString()) + .library(library) .build(); BookEntity book = BookEntity.builder() @@ -133,10 +123,12 @@ class FileMoveServiceMoveFilesTest { .build(); when(bookQueryService.findAllWithMetadataByIds(Set.of(2L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(2L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -165,10 +157,12 @@ class FileMoveServiceMoveFilesTest { Files.createFile(fakeOldFile); when(bookQueryService.findAllWithMetadataByIds(Set.of(3L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(3L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -183,195 +177,21 @@ class FileMoveServiceMoveFilesTest { Files.deleteIfExists(fakeOldFile); } - @Test - void testMoveFiles_handlesEmptyPattern() throws IOException { - String fileName = "emptypattern.epub"; - String fileSubPath = "folder"; - - BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(4L))).thenReturn(List.of(book)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(4L)); - request.setPattern(""); - - Path oldFilePath = book.getFullFilePath(); - - fileMoveService.moveFiles(request); - - Path expectedNewPath = tempLibraryRoot.resolve(fileName); - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("File should be moved to the original filename path when pattern is empty") - .isTrue(); - - assertThat(Files.exists(oldFilePath)) - .withFailMessage("Original file path should no longer exist") - .isFalse(); - - Files.deleteIfExists(expectedNewPath); - } - - @Test - void testMoveFiles_removesIllegalCharactersFromPath() throws IOException { - String fileName = "badchars.epub"; - String fileSubPath = "folder"; - - BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); - book.getMetadata().setTitle("Bad|Title:Test*?"); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(5L))).thenReturn(List.of(book)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(5L)); - request.setPattern("{title}"); - - Path oldFilePath = book.getFullFilePath(); - - fileMoveService.moveFiles(request); - - Path expectedNewPath = tempLibraryRoot.resolve("BadTitleTest.epub"); - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("Illegal characters should be removed from generated path") - .isTrue(); - - assertThat(Files.exists(oldFilePath)) - .withFailMessage("Original file path should no longer exist") - .isFalse(); - - Files.deleteIfExists(expectedNewPath); - } - - @Test - void testMoveFiles_deletesEmptyOldDirectories() throws IOException { - String fileName = "deleteold.epub"; - String fileSubPath = "folder/emptydir"; - - BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(6L))).thenReturn(List.of(book)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(6L)); - request.setPattern("NewFolder/{title}"); - - Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize(); - assertThat(Files.exists(oldDir)) - .withFailMessage("Precondition failed: old directory must exist before move") - .isTrue(); - - fileMoveService.moveFiles(request); - - Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("Expected file to be moved to new location") - .isTrue(); - - assertThat(Files.exists(oldDir)) - .withFailMessage("Expected old empty directory to be deleted after move") - .isFalse(); - - assertThat(Files.exists(oldDir.getParent())) - .withFailMessage("Expected parent directory of old directory to be deleted if empty") - .isFalse(); - - Files.deleteIfExists(expectedNewPath); - Files.deleteIfExists(expectedNewPath.getParent()); - } - - @Test - void testMoveFiles_keepsOldDirectoryIfNotEmpty() throws IOException { - String fileName = "keepold.epub"; - String fileSubPath = "folder/notempty"; - - BookEntity book = createBookWithFile(tempLibraryRoot, fileSubPath, fileName); - - Path oldDir = tempLibraryRoot.resolve(fileSubPath).normalize(); - Files.createDirectories(oldDir); - - Path otherFile = oldDir.resolve("otherfile.txt"); - Files.createFile(otherFile); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(7L))).thenReturn(List.of(book)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(7L)); - request.setPattern("NewFolder/{title}"); - - Path oldFilePath = book.getFullFilePath(); - - fileMoveService.moveFiles(request); - - Path expectedNewPath = tempLibraryRoot.resolve("NewFolder").resolve("Test Book.epub"); - - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("Expected file to be moved to new location") - .isTrue(); - assertThat(Files.exists(oldFilePath)) - .withFailMessage("Original file path should no longer exist") - .isFalse(); - - assertThat(Files.exists(oldDir)) - .withFailMessage("Old directory should remain if it contains other files") - .isTrue(); - assertThat(Files.exists(otherFile)) - .withFailMessage("Other files in old directory should remain intact") - .isTrue(); - - Files.deleteIfExists(otherFile); - Files.deleteIfExists(expectedNewPath); - Files.deleteIfExists(expectedNewPath.getParent()); - } - - @Test - void testMoveFiles_handlesMultipleBooks() throws IOException { - BookEntity book1 = createBookWithFile(tempLibraryRoot, "folder1", "book1.epub"); - book1.getMetadata().setTitle("Book One"); - - BookEntity book2 = createBookWithFile(tempLibraryRoot, "folder2", "book2.epub"); - book2.getMetadata().setTitle("Book Two"); - - when(bookQueryService.findAllWithMetadataByIds(Set.of(8L, 9L))).thenReturn(List.of(book1, book2)); - - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(8L, 9L)); - request.setPattern("Moved/{title}"); - - Path oldPath1 = book1.getFullFilePath(); - Path oldPath2 = book2.getFullFilePath(); - - fileMoveService.moveFiles(request); - - Path expectedPath1 = tempLibraryRoot.resolve("Moved").resolve("Book One.epub"); - Path expectedPath2 = tempLibraryRoot.resolve("Moved").resolve("Book Two.epub"); - - assertThat(Files.exists(expectedPath1)) - .withFailMessage("Expected first book to be moved to new location") - .isTrue(); - assertThat(Files.exists(expectedPath2)) - .withFailMessage("Expected second book to be moved to new location") - .isTrue(); - - assertThat(Files.exists(oldPath1)) - .withFailMessage("Original path for first book should no longer exist") - .isFalse(); - assertThat(Files.exists(oldPath2)) - .withFailMessage("Original path for second book should no longer exist") - .isFalse(); - - Files.deleteIfExists(expectedPath1); - Files.deleteIfExists(expectedPath2); - Files.deleteIfExists(expectedPath1.getParent()); - } - @Test void testMoveFiles_skipsBookWithNullFileName() throws IOException { BookMetadataEntity metadata = BookMetadataEntity.builder() .title("NullFileName") .build(); + LibraryEntity library = LibraryEntity.builder() + .id(46L) + .name("Test Library") + .fileNamingPattern("Moved/{title}") + .build(); + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() .path(tempLibraryRoot.toString()) + .library(library) .build(); BookEntity book = BookEntity.builder() @@ -383,10 +203,12 @@ class FileMoveServiceMoveFilesTest { .build(); when(bookQueryService.findAllWithMetadataByIds(Set.of(10L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(10L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -402,8 +224,15 @@ class FileMoveServiceMoveFilesTest { .title("EmptyFileName") .build(); + LibraryEntity library = LibraryEntity.builder() + .id(47L) + .name("Test Library") + .fileNamingPattern("Moved/{title}") + .build(); + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() .path(tempLibraryRoot.toString()) + .library(library) .build(); BookEntity book = BookEntity.builder() @@ -415,10 +244,12 @@ class FileMoveServiceMoveFilesTest { .build(); when(bookQueryService.findAllWithMetadataByIds(Set.of(11L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(11L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -434,8 +265,15 @@ class FileMoveServiceMoveFilesTest { .title("NullSubPath") .build(); + LibraryEntity library = LibraryEntity.builder() + .id(48L) + .name("Test Library") + .fileNamingPattern("Moved/{title}") + .build(); + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() .path(tempLibraryRoot.toString()) + .library(library) .build(); BookEntity book = BookEntity.builder() @@ -450,10 +288,12 @@ class FileMoveServiceMoveFilesTest { Files.createFile(oldFile); when(bookQueryService.findAllWithMetadataByIds(Set.of(12L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(12L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -467,8 +307,15 @@ class FileMoveServiceMoveFilesTest { @Test void testMoveFiles_skipsBookWithNullMetadata() throws IOException { + LibraryEntity library = LibraryEntity.builder() + .id(49L) + .name("Test Library") + .fileNamingPattern("Moved/{title}") + .build(); + LibraryPathEntity libraryPathEntity = LibraryPathEntity.builder() .path(tempLibraryRoot.toString()) + .library(library) .build(); BookEntity book = BookEntity.builder() @@ -484,10 +331,12 @@ class FileMoveServiceMoveFilesTest { Files.createFile(oldFile); when(bookQueryService.findAllWithMetadataByIds(Set.of(13L))).thenReturn(List.of(book)); + AppSettings appSettings = new AppSettings(); + appSettings.setUploadPattern("Moved/{title}"); + when(appSettingService.getAppSettings()).thenReturn(appSettings); FileMoveRequest request = new FileMoveRequest(); request.setBookIds(Set.of(13L)); - request.setPattern("Moved/{title}"); fileMoveService.moveFiles(request); @@ -499,26 +348,191 @@ class FileMoveServiceMoveFilesTest { Files.deleteIfExists(oldFile); } - @Disabled @Test - void testMoveFiles_patternWithUnknownPlaceholder() throws IOException { - BookEntity book = createBookWithFile(tempLibraryRoot, "folder", "unknown.epub"); - book.getMetadata().setTitle("UnknownPlaceholder"); + void testMoveFiles_successfulMove() throws IOException { + BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub"); + Path oldFilePath = book.getFullFilePath(); - when(bookQueryService.findAllWithMetadataByIds(Set.of(14L))).thenReturn(List.of(book)); + when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))).thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("X/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + Book dto = Book.builder().id(book.getId()).build(); + when(bookMapper.toBook(book)).thenReturn(dto); - FileMoveRequest request = new FileMoveRequest(); - request.setBookIds(Set.of(14L)); - request.setPattern("Moved/{title}/{foo}"); + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(book.getId())); + fileMoveService.moveFiles(req); - fileMoveService.moveFiles(request); + Path newPath = tempLibraryRoot.resolve("X").resolve("Test Book.epub"); + assertThat(Files.exists(newPath)).isTrue(); + assertThat(Files.exists(oldFilePath)).isFalse(); - Path expectedNewPath = tempLibraryRoot.resolve("Moved").resolve("UnknownPlaceholder").resolve("{foo}.epub"); - assertThat(Files.exists(expectedNewPath)) - .withFailMessage("Unknown placeholders should remain in the generated path") - .isTrue(); - - Files.deleteIfExists(expectedNewPath); - Files.deleteIfExists(expectedNewPath.getParent()); + verify(bookRepository).save(book); + verify(notificationService).sendMessage(eq(Topic.BOOK_METADATA_BATCH_UPDATE), anyList()); + verify(libraryService).rescanLibrary(book.getLibraryPath().getLibrary().getId()); } -} \ No newline at end of file + + @Test + void testMoveFiles_usesDefaultPatternWhenLibraryPatternEmpty() throws IOException { + LibraryEntity lib = LibraryEntity.builder() + .id(99L).name("Lib").fileNamingPattern(" ").build(); + LibraryPathEntity lp = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()).library(lib).build(); + + BookMetadataEntity meta = BookMetadataEntity.builder() + .title("DFT").build(); + BookEntity book = BookEntity.builder() + .id(55L).fileSubPath("old").fileName("a.epub") + .libraryPath(lp).metadata(meta).build(); + + Path old = book.getFullFilePath(); + Files.createDirectories(old.getParent()); + Files.createFile(old); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(55L))).thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("DEF/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + Book dto = Book.builder().id(book.getId()).build(); + when(bookMapper.toBook(book)).thenReturn(dto); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(55L)); + fileMoveService.moveFiles(req); + + Path moved = tempLibraryRoot.resolve("DEF").resolve("DFT.epub"); + assertThat(Files.exists(moved)).isTrue(); + verify(bookRepository).save(book); + } + + @Test + void testMoveFiles_deletesEmptyParentDirectories() throws IOException { + LibraryEntity library = LibraryEntity.builder() + .id(100L).name("Lib").fileNamingPattern(null).build(); + LibraryPathEntity lp = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()).library(library).build(); + BookMetadataEntity meta = BookMetadataEntity.builder() + .title("Nested").build(); + BookEntity book = BookEntity.builder() + .id(101L).fileSubPath("a/b/c").fileName("nested.epub") + .libraryPath(lp).metadata(meta).build(); + Path old = book.getFullFilePath(); + Files.createDirectories(old.getParent()); + Files.createFile(old); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(101L))).thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("Z/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build()); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(101L)); + fileMoveService.moveFiles(req); + + Path newPath = tempLibraryRoot.resolve("Z").resolve("Nested.epub"); + assertThat(Files.exists(newPath)).isTrue(); + assertThat(Files.notExists(tempLibraryRoot.resolve("a"))).isTrue(); + } + + @Test + void testMoveFiles_overwritesExistingDestination() throws IOException { + LibraryEntity library = LibraryEntity.builder() + .id(102L).name("Lib").fileNamingPattern(null).build(); + LibraryPathEntity lp = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()).library(library).build(); + BookMetadataEntity meta = BookMetadataEntity.builder() + .title("Overwrite").build(); + BookEntity book = BookEntity.builder() + .id(103L).fileSubPath("sub").fileName("file.epub") + .libraryPath(lp).metadata(meta).build(); + Path old = book.getFullFilePath(); + Files.createDirectories(old.getParent()); + Files.write(old, "SRC".getBytes()); + Path destDir = tempLibraryRoot.resolve("DEST"); + Files.createDirectories(destDir); + Path dest = destDir.resolve("Overwrite.epub"); + Files.write(dest, "OLD".getBytes()); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(103L))).thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("DEST/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build()); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(103L)); + fileMoveService.moveFiles(req); + + assertThat(Files.exists(dest)).isTrue(); + String content = Files.readString(dest); + assertThat(content).isEqualTo("SRC"); + } + + @Test + void testMoveFiles_usesLibraryPatternWhenSet() throws IOException { + LibraryEntity library = LibraryEntity.builder() + .id(104L).name("Lib").fileNamingPattern("LIBY/{title}").build(); + LibraryPathEntity lp = LibraryPathEntity.builder() + .path(tempLibraryRoot.toString()).library(library).build(); + BookMetadataEntity meta = BookMetadataEntity.builder() + .title("LibTest").build(); + BookEntity book = BookEntity.builder() + .id(105L).fileSubPath("x").fileName("file.epub") + .libraryPath(lp).metadata(meta).build(); + Path old = book.getFullFilePath(); + Files.createDirectories(old.getParent()); + Files.createFile(old); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(105L))).thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("DEFAULT/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + when(bookMapper.toBook(book)).thenReturn(Book.builder().id(book.getId()).build()); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(105L)); + fileMoveService.moveFiles(req); + + Path newPath = tempLibraryRoot.resolve("LIBY").resolve("LibTest.epub"); + assertThat(Files.exists(newPath)).isTrue(); + } + + @Test + void testMoveFiles_skipsWhenDestinationSameAsSource() throws IOException { + BookEntity book = createBookWithFile(tempLibraryRoot, "sub", "mybook.epub"); + Path oldFilePath = book.getFullFilePath(); + + when(bookQueryService.findAllWithMetadataByIds(Set.of(book.getId()))) + .thenReturn(List.of(book)); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("sub/mybook.epub"); + when(appSettingService.getAppSettings()).thenReturn(settings); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(book.getId())); + fileMoveService.moveFiles(req); + + assertThat(Files.exists(oldFilePath)).isTrue(); + verify(bookRepository, never()).save(any()); + verify(notificationService, never()).sendMessage(any(), anyList()); + verify(libraryService, never()).rescanLibrary(anyLong()); + } + + @Test + void testMoveFiles_doesNotPauseMonitoringWhenAlreadyPaused() { + when(monitoringService.isPaused()).thenReturn(true); + when(bookQueryService.findAllWithMetadataByIds(anySet())).thenReturn(List.of()); + AppSettings settings = new AppSettings(); + settings.setUploadPattern("X/{title}"); + when(appSettingService.getAppSettings()).thenReturn(settings); + + FileMoveRequest req = new FileMoveRequest(); + req.setBookIds(Set.of(999L)); + fileMoveService.moveFiles(req); + + verify(monitoringService, never()).pauseMonitoring(); + verify(monitoringService, never()).resumeMonitoring(); + } +} diff --git a/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts index 192a4a801..fbc83dfba 100644 --- a/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts +++ b/booklore-ui/src/app/book/components/book-browser/BookDialogHelperService.ts @@ -94,7 +94,7 @@ export class BookDialogHelperService { openFileMoverDialog(selectedBooks: Set) { const count = selectedBooks.size; return this.dialogService.open(FileMoverComponent, { - header: `Relocate Book Files (${count} book${count !== 1 ? 's' : ''})`, + header: `Organize Book Files (${count} book${count !== 1 ? 's' : ''})`, showHeader: true, modal: true, closable: true, diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss index c220734ad..8296a84c3 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.scss @@ -105,8 +105,8 @@ .select-checkbox { position: absolute; - top: 8px; - right: 8px; + top: 4px; + right: 4px; opacity: 0; visibility: hidden; transition: opacity 0.2s ease, visibility 0.2s ease; @@ -147,7 +147,7 @@ .series-number-overlay { position: absolute; - bottom: 8px; + top: 8px; left: 8px; background-color: rgba(0, 0, 0, 0.7); color: white; @@ -159,7 +159,7 @@ .series-count-overlay { position: absolute; - top: 8px; + bottom: 8px; left: 8px; background-color: var(--primary-color); color: var(--primary-text-color-dark); @@ -174,10 +174,6 @@ box-shadow: 0 0 4px rgba(0, 0, 0, 0.15); } -.series-number-overlay + .series-count-overlay { - top: calc(8px + 1.5rem) -} - ::ng-deep .progress-incomplete .p-progressbar-value { background-color: #3b82f6; } diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts index 0e047e24c..4707487f5 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts @@ -21,7 +21,7 @@ import {BookSenderComponent} from '../../book-sender/book-sender.component'; import {Router} from '@angular/router'; import {ProgressBar} from 'primeng/progressbar'; import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center-component/book-metadata-center.component'; -import {takeUntil} from 'rxjs/operators'; +import {take, takeUntil} from 'rxjs/operators'; import {readStatusLabels} from '../book-filter/book-filter.component'; import {ResetProgressTypes} from '../../../../shared/constants/reset-progress-type'; @@ -67,7 +67,8 @@ export class BookCardComponent implements OnInit, OnDestroy { ngOnInit(): void { this.userService.userState$ .pipe( - filter(userState => !!userState), + filter(userState => !!userState?.user && userState.loaded), + take(1), takeUntil(this.destroy$) ) .subscribe(userState => { diff --git a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts index 905dced27..3fcd65a43 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts @@ -14,7 +14,7 @@ import {filter, Subject} from 'rxjs'; import {UserService} from '../../../../settings/user-management/user.service'; import {BookMetadataCenterComponent} from '../../../../metadata/book-metadata-center-component/book-metadata-center.component'; import {DialogService} from 'primeng/dynamicdialog'; -import {takeUntil} from 'rxjs/operators'; +import {take, takeUntil} from 'rxjs/operators'; @Component({ selector: 'app-book-table', @@ -75,7 +75,8 @@ export class BookTableComponent implements OnInit, OnDestroy, OnChanges { ngOnInit(): void { this.userService.userState$ .pipe( - filter(userState => !!userState), + filter(userState => !!userState?.user && userState.loaded), + take(1), takeUntil(this.destroy$) ) .subscribe(userState => { diff --git a/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts index bc3258914..3a21f641d 100644 --- a/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts +++ b/booklore-ui/src/app/book/components/book-browser/filters/SeriesCollapseFilter.ts @@ -1,7 +1,7 @@ import {BookFilter} from './BookFilter'; import {BehaviorSubject, Observable, Subject} from 'rxjs'; import {BookState} from '../../../model/state/book-state.model'; -import {debounceTime, filter, map, takeUntil} from 'rxjs/operators'; +import {debounceTime, filter, map, take, takeUntil} from 'rxjs/operators'; import {Book} from '../../../model/book.model'; import {inject, Injectable, OnDestroy} from '@angular/core'; import {MessageService} from 'primeng/api'; @@ -21,7 +21,8 @@ export class SeriesCollapseFilter implements BookFilter, OnDestroy { constructor() { this.userService.userState$ .pipe( - filter(userState => !!userState), + filter(userState => !!userState?.user && userState.loaded), + take(1), takeUntil(this.destroy$) ) .subscribe(user => { diff --git a/booklore-ui/src/app/core/model/app-settings.model.ts b/booklore-ui/src/app/core/model/app-settings.model.ts index fb21f3227..7533d6854 100644 --- a/booklore-ui/src/app/core/model/app-settings.model.ts +++ b/booklore-ui/src/app/core/model/app-settings.model.ts @@ -83,7 +83,6 @@ export interface AppSettings { metadataRefreshOptions: MetadataRefreshOptions; coverResolution: string; uploadPattern: string; - movePattern: string; opdsServerEnabled: boolean; remoteAuthEnabled: boolean; oidcEnabled: boolean; @@ -112,6 +111,5 @@ export enum AppSettingKey { METADATA_PROVIDER_SETTINGS = 'METADATA_PROVIDER_SETTINGS', METADATA_MATCH_WEIGHTS = 'METADATA_MATCH_WEIGHTS', METADATA_PERSISTENCE_SETTINGS = 'METADATA_PERSISTENCE_SETTINGS', - MOVE_FILE_PATTERN = 'MOVE_FILE_PATTERN', METADATA_DOWNLOAD_ON_BOOKDROP = 'METADATA_DOWNLOAD_ON_BOOKDROP' } diff --git a/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.html b/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.html index 26fab43b1..23267b9fc 100644 --- a/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.html +++ b/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.html @@ -2,81 +2,57 @@

- Customize Your File Organization + File Organization Preview

-

- Define a naming pattern to reorganize selected book files on your system. Use dynamic placeholders like - {{ '{title}' }} - or - {{ '{authors}' }} - to automatically insert metadata.
- A preview below shows how files will be renamed and moved. - Once you're satisfied, click Move Files to proceed. - +

+

+ Your files will be automatically renamed and organized based on your library's naming rules. + Check the preview below to see how your files will look, then click Move Files to organize them. +

+

+ + Want to change how files are named? Go to Settings → File Naming Pattern +

+

- Files will be physically moved on your system when you apply changes. - -

-
- -
- - {{ placeholdersVisible ? 'Hide' : 'Show' }} available placeholders - - - @if (placeholdersVisible) { -
-
    -
  • {{ '{title}' }} - Book title
  • -
  • {{ '{authors}' }} - Author(s)
  • -
  • {{ '{year}' }} - Full year (e.g. 2025)
  • -
  • {{ '{series}' }} - Series name
  • -
  • {{ '{seriesIndex}' }} - Series index (e.g. 01)
  • -
  • {{ '{language}' }} - Language (e.g. en)
  • -
  • {{ '{publisher}' }} - Publisher
  • -
  • {{ '{isbn}' }} - ISBN
  • -
  • {{ '{currentFilename}' }} - Original file name (with extension)
  • -
- - - -
-

Tip: Optional placeholders

-

Wrap parts of your pattern in angle brackets {{ '<...>' }} to make them optional.

-

If any placeholder inside has no value, the whole block is removed.

-

Example:

-

{{ '<{seriesIndex} - >{title}' }}

-

• {{ '01 - Dune' }} (if {{ '{seriesIndex}' }} is present)

-

• {{ 'Dune' }} (if {{ '{seriesIndex}' }} is missing)

-
-
- } + This will actually move and rename files on your computer, make sure you're happy with the preview first! +

+
- +
+
+ + +
- + @if (!patternsCollapsed) { +
+ @for (pattern of libraryPatterns; track pattern.libraryId) { +
+
+
+

Library: {{ pattern.libraryName }}

+ {{ pattern.pattern || 'No pattern available' }} +

Source: {{ pattern.source }}

+
+ {{ pattern.bookCount }} book{{ pattern.bookCount > 1 ? 's' : '' }} +
+
+ } +
+ } +
-
+
- ID + ID Current Path New Path @@ -95,13 +71,13 @@ {{ preview.bookId }}

- {{ preview.libraryPathPrefix }}/{{ preview.relativeOriginalPath }} + {{ preview.libraryPathPrefix }}/{{ preview.relativeOriginalPath }}

→

- {{ preview.libraryPathPrefix }}/{{ preview.relativeNewPath }} + {{ preview.libraryPathPrefix }}/{{ preview.relativeNewPath }}

diff --git a/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.ts b/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.ts index 2142bd65b..e674d7dd2 100644 --- a/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.ts +++ b/booklore-ui/src/app/utilities/component/file-mover-component/file-mover-component.ts @@ -1,28 +1,27 @@ -import {Component, inject} from '@angular/core'; +import {Component, inject, OnDestroy} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {Button} from 'primeng/button'; import {TableModule} from 'primeng/table'; -import {InputText} from 'primeng/inputtext'; import {Divider} from 'primeng/divider'; import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; import {MessageService} from 'primeng/api'; -import {filter, take} from 'rxjs/operators'; +import {filter, take, takeUntil} from 'rxjs/operators'; +import {Subject} from 'rxjs'; import {BookService} from '../../../book/service/book.service'; import {Book} from '../../../book/model/book.model'; import {FileMoveRequest, FileOperationsService} from '../../service/file-operations-service'; import {LibraryService} from "../../../book/service/library.service"; import {AppSettingsService} from '../../../core/service/app-settings.service'; -import {AppSettingKey} from '../../../core/model/app-settings.model'; @Component({ selector: 'app-file-mover-component', standalone: true, - imports: [Button, FormsModule, TableModule, InputText, Divider], + imports: [Button, FormsModule, TableModule, Divider], templateUrl: './file-mover-component.html', styleUrl: './file-mover-component.scss' }) -export class FileMoverComponent { +export class FileMoverComponent implements OnDestroy { private config = inject(DynamicDialogConfig); private ref = inject(DynamicDialogRef); private bookService = inject(BookService); @@ -30,10 +29,18 @@ export class FileMoverComponent { private fileOperationsService = inject(FileOperationsService); private messageService = inject(MessageService); private appSettingsService = inject(AppSettingsService); + private destroy$ = new Subject(); - movePattern = ''; - placeholdersVisible = false; + libraryPatterns: { + libraryId: number | null; + libraryName: string; + pattern: string; + source: string; + bookCount: number; + }[] = []; + defaultMovePattern = ''; loading = false; + patternsCollapsed = false; bookIds: Set = new Set(); books: Book[] = []; @@ -42,12 +49,69 @@ export class FileMoverComponent { constructor() { this.bookIds = new Set(this.config.data?.bookIds ?? []); this.books = this.bookService.getBooksByIdsFromState([...this.bookIds]); + this.loadDefaultPattern(); + } + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private loadDefaultPattern(): void { this.appSettingsService.appSettings$.pipe( filter(settings => settings != null), - take(1) + take(1), + takeUntil(this.destroy$) ).subscribe(settings => { - this.movePattern = settings?.movePattern; + this.defaultMovePattern = settings?.uploadPattern || ''; + this.loadLibraryPatterns(); + }); + } + + private loadLibraryPatterns(): void { + this.libraryService.libraryState$.pipe( + filter(state => state.loaded && state.libraries != null), + take(1), + takeUntil(this.destroy$) + ).subscribe(state => { + const booksByLibrary = new Map(); + this.books.forEach(book => { + const libraryId = + book.libraryId ?? + book.libraryPath?.id ?? + (book as any).library?.id ?? + null; + if (!booksByLibrary.has(libraryId)) { + booksByLibrary.set(libraryId, []); + } + booksByLibrary.get(libraryId)!.push(book); + }); + + this.libraryPatterns = Array.from(booksByLibrary.entries()).map(([libraryId, books]) => { + let libraryName = 'Unknown Library'; + let pattern = this.defaultMovePattern; + let source = 'App Default'; + + if (libraryId) { + const library = state.libraries?.find(lib => lib.id === libraryId); + if (library) { + libraryName = library.name; + if (library.fileNamingPattern) { + pattern = library.fileNamingPattern; + source = 'Library Setting'; + } + } + } + + return { + libraryId, + libraryName, + pattern, + source, + bookCount: books.length + }; + }); + this.applyPattern(); }); } @@ -66,6 +130,14 @@ export class FileMoverComponent { : ''; const originalPath = `${libraryPathPrefix}/${relativeOriginalPath}`.replace(/\/\/+/g, '/'); + const bookLibraryId = + book.libraryId ?? + book.libraryPath?.id ?? + (book as any).library?.id ?? + null; + const libraryPattern = this.libraryPatterns.find(p => p.libraryId === bookLibraryId); + const pattern = libraryPattern?.pattern || this.defaultMovePattern; + const values: Record = { authors: this.sanitize(meta.authors?.join(', ') || 'Unknown Author'), title: this.sanitize(meta.title || 'Untitled'), @@ -80,11 +152,10 @@ export class FileMoverComponent { let newPath: string; - if (!this.movePattern?.trim()) { - // If pattern empty, just use current filename as the new path - newPath = `${fileSubPath}${fileName}`; // preserve subpath + filename + if (!pattern?.trim()) { + newPath = `${fileSubPath}${fileName}`; } else { - newPath = this.movePattern.replace(/<([^<>]+)>/g, (_, block) => { + newPath = pattern.replace(/<([^<>]+)>/g, (_, block) => { const placeholders = [...block.matchAll(/{(.*?)}/g)].map(m => m[1]); const allHaveValues = placeholders.every(key => values[key]?.trim()); return allHaveValues @@ -94,7 +165,6 @@ export class FileMoverComponent { newPath = newPath.replace(/{(.*?)}/g, (_, key) => values[key] ?? ''); - // Append extension if not already present (most patterns won't include extension) if (!newPath.endsWith(extension)) { newPath += extension; } @@ -111,6 +181,7 @@ export class FileMoverComponent { newPath: fullNewPath, relativeNewPath }; + }); } @@ -136,35 +207,23 @@ export class FileMoverComponent { return this.sanitize(seriesNumber.toString()); } - getDefaultPattern(): string { - return 'e.g. {authors}/<{series}/><{seriesIndex}. >{title} - {authors}< ({year})>'; - } - saveChanges(): void { - if (!this.movePattern?.trim()) { - this.messageService.add({ - severity: 'error', - summary: 'Missing Pattern', - detail: 'Move pattern cannot be empty. Please enter a valid pattern.', - life: 3000 - }); - return; - } - this.loading = true; + const request: FileMoveRequest = { - bookIds: [...this.bookIds], - pattern: this.movePattern + bookIds: [...this.bookIds] }; - this.fileOperationsService.moveFiles(request).subscribe({ + this.fileOperationsService.moveFiles(request).pipe( + takeUntil(this.destroy$) + ).subscribe({ next: () => { this.loading = false; this.filePreviews.forEach(p => (p.isMoved = true)); this.messageService.add({ severity: 'success', - summary: 'Files Moved', - detail: `${this.filePreviews.length} file(s) successfully relocated.`, + summary: 'Files Organized!', + detail: `Successfully organized ${this.filePreviews.length} file${this.filePreviews.length === 1 ? '' : 's'}.`, life: 3000 }); }, @@ -172,48 +231,19 @@ export class FileMoverComponent { this.loading = false; this.messageService.add({ severity: 'error', - summary: 'Move Failed', - detail: 'An error occurred while moving the files.', + summary: 'Oops! Something went wrong', + detail: 'We had trouble organizing your files. Please try again.', life: 3000 }); } }); } - setDefaultPattern(): void { - const trimmedPattern = this.movePattern?.trim(); - - if (!trimmedPattern) { - this.messageService.add({ - severity: 'error', - summary: 'Cannot Save', - detail: 'Move pattern cannot be empty.' - }); - return; - } - - const payload = [ - { - key: AppSettingKey.MOVE_FILE_PATTERN, - newValue: trimmedPattern - } - ]; - - this.appSettingsService.saveSettings(payload).subscribe({ - next: () => this.messageService.add({ - severity: 'success', - summary: 'Saved', - detail: 'Move pattern saved as default.' - }), - error: () => this.messageService.add({ - severity: 'error', - summary: 'Error', - detail: 'Failed to save default move pattern.' - }) - }); - } - cancel(): void { this.ref.close(); } + + togglePatternsCollapsed(): void { + this.patternsCollapsed = !this.patternsCollapsed; + } } diff --git a/booklore-ui/src/app/utilities/service/file-operations-service.ts b/booklore-ui/src/app/utilities/service/file-operations-service.ts index a1674f7b7..607e969b8 100644 --- a/booklore-ui/src/app/utilities/service/file-operations-service.ts +++ b/booklore-ui/src/app/utilities/service/file-operations-service.ts @@ -5,7 +5,6 @@ import {API_CONFIG} from '../../config/api-config'; export interface FileMoveRequest { bookIds: number[]; - pattern: string; } @Injectable({