From b155f567a4f10c771b5ba3efb525070b3fa29270 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" Date: Mon, 30 Jun 2025 17:27:53 -0600 Subject: [PATCH] Deleting books now cleans up empty directories left behind --- booklore-api/build.gradle | 8 + .../booklore/model/entity/LibraryEntity.java | 1 - .../booklore/service/BookService.java | 76 ++++++++- .../booklore/BookServiceDeleteTests.java | 154 ++++++++++++++++++ 4 files changed, 237 insertions(+), 2 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 7d6347a96..4ed8bfed8 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -73,10 +73,18 @@ dependencies { implementation 'org.apache.commons:commons-compress:1.27.1' implementation 'com.github.junrar:junrar:7.5.5' implementation 'org.apache.commons:commons-text:1.13.1' + + // --- Test Dependencies --- + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.assertj:assertj-core:3.26.3' } hibernate { enhancement { enableAssociationManagement = true } +} + +test { + useJUnitPlatform() } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java index a479ef373..4ec3a2e28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/LibraryEntity.java @@ -37,5 +37,4 @@ public class LibraryEntity { private boolean watch; private String icon; - } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java index fe703c043..0661893c8 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookService.java @@ -28,6 +28,7 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; @@ -55,7 +56,6 @@ public class BookService { private final AuthenticationService authenticationService; private final BookQueryService bookQueryService; private final UserProgressService userProgressService; - private final AppSettingService appSettingService; public List getBookDTOs(boolean includeDescription) { BookLoreUser user = authenticationService.getAuthenticatedUser(); @@ -365,16 +365,25 @@ public class BookService { public ResponseEntity deleteBooks(Set ids) { List books = bookQueryService.findAllWithMetadataByIds(ids); List failedFileDeletions = new ArrayList<>(); + for (BookEntity book : books) { Path fullFilePath = book.getFullFilePath(); try { if (Files.exists(fullFilePath)) { Files.delete(fullFilePath); + Set libraryRoots = book.getLibrary().getLibraryPaths().stream() + .map(LibraryPathEntity::getPath) + .map(Paths::get) + .map(Path::normalize) + .collect(Collectors.toSet()); + + deleteEmptyParentDirsUpToLibraryFolders(fullFilePath.getParent(), libraryRoots); } } catch (IOException e) { failedFileDeletions.add(book.getId()); } } + bookRepository.deleteAll(books); BookDeletionResponse response = new BookDeletionResponse(ids, failedFileDeletions); return failedFileDeletions.isEmpty() @@ -382,6 +391,71 @@ public class BookService { : ResponseEntity.status(HttpStatus.MULTI_STATUS).body(response); } + public void deleteEmptyParentDirsUpToLibraryFolders(Path currentDir, Set libraryRoots) throws IOException { + Set ignoredFilenames = Set.of(".DS_Store", "Thumbs.db"); + currentDir = currentDir.toAbsolutePath().normalize(); + + Set normalizedRoots = new HashSet<>(); + for (Path root : libraryRoots) { + normalizedRoots.add(root.toAbsolutePath().normalize()); + } + + 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) { + log.debug("Reached library root: {}. Stopping cleanup.", currentDir); + break; + } + + File[] files = currentDir.toFile().listFiles(); + if (files == null) { + log.warn("Cannot read directory: {}. Stopping cleanup.", currentDir); + 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; + } + currentDir = currentDir.getParent(); + } else { + log.debug("Directory {} contains important files. Stopping cleanup.", currentDir); + break; + } + } + } + public void updateReadStatus(long bookId, @NotBlank String status) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); ReadStatus readStatus = EnumUtils.getEnumIgnoreCase(ReadStatus.class, status); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java new file mode 100644 index 000000000..cee1ea1a5 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/BookServiceDeleteTests.java @@ -0,0 +1,154 @@ +package com.adityachandel.booklore; + +import com.adityachandel.booklore.config.security.AuthenticationService; +import com.adityachandel.booklore.mapper.BookMapper; +import com.adityachandel.booklore.repository.*; +import com.adityachandel.booklore.service.BookQueryService; +import com.adityachandel.booklore.service.BookService; +import com.adityachandel.booklore.service.UserProgressService; +import com.adityachandel.booklore.util.FileService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +@ExtendWith(MockitoExtension.class) +class BookServiceDeleteTests { + + private BookService bookService; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() { + BookRepository bookRepository = Mockito.mock(BookRepository.class); + PdfViewerPreferencesRepository pdfViewerPreferencesRepository = Mockito.mock(PdfViewerPreferencesRepository.class); + EpubViewerPreferencesRepository epubViewerPreferencesRepository = Mockito.mock(EpubViewerPreferencesRepository.class); + CbxViewerPreferencesRepository cbxViewerPreferencesRepository = Mockito.mock(CbxViewerPreferencesRepository.class); + NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository = Mockito.mock(NewPdfViewerPreferencesRepository.class); + ShelfRepository shelfRepository = Mockito.mock(ShelfRepository.class); + FileService fileService = Mockito.mock(FileService.class); + BookMapper bookMapper = Mockito.mock(BookMapper.class); + UserRepository userRepository = Mockito.mock(UserRepository.class); + UserBookProgressRepository userBookProgressRepository = Mockito.mock(UserBookProgressRepository.class); + AuthenticationService authenticationService = Mockito.mock(AuthenticationService.class); + BookQueryService bookQueryService = Mockito.mock(BookQueryService.class); + UserProgressService userProgressService = Mockito.mock(UserProgressService.class); + + bookService = new BookService( + bookRepository, + pdfViewerPreferencesRepository, + epubViewerPreferencesRepository, + cbxViewerPreferencesRepository, + newPdfViewerPreferencesRepository, + shelfRepository, + fileService, + bookMapper, + userRepository, + userBookProgressRepository, + authenticationService, + bookQueryService, + userProgressService + ); + } + + @Test + void deletesEmptyDirectoriesUpToLibraryRoot() throws IOException { + Path libraryRoot = tempDir.resolve("libraryRoot"); + Files.createDirectories(libraryRoot); + + Path nestedDir1 = libraryRoot.resolve("1"); + Path nestedDir2 = nestedDir1.resolve("2"); + Path nestedDir3 = nestedDir2.resolve("3"); + Files.createDirectories(nestedDir3); + + bookService.deleteEmptyParentDirsUpToLibraryFolders(nestedDir3, Set.of(libraryRoot)); + + assertThat(Files.exists(nestedDir3)).isFalse(); + assertThat(Files.exists(nestedDir2)).isFalse(); + assertThat(Files.exists(nestedDir1)).isFalse(); + assertThat(Files.exists(libraryRoot)).isTrue(); + } + + @Test + void doesNotDeleteDirectoryWithImportantFile() throws IOException { + Path libraryRoot = tempDir.resolve("libraryRoot"); + Files.createDirectories(libraryRoot); + + Path nestedDir = libraryRoot.resolve("nested"); + Files.createDirectories(nestedDir); + + Path importantFile = nestedDir.resolve("important.txt"); + Files.createFile(importantFile); + + bookService.deleteEmptyParentDirsUpToLibraryFolders(nestedDir, Set.of(libraryRoot)); + + assertThat(Files.exists(nestedDir)).isTrue(); + assertThat(Files.exists(importantFile)).isTrue(); + assertThat(Files.exists(libraryRoot)).isTrue(); + } + + @Test + void deletesIgnoredFilesBeforeDeletingDirectory() throws IOException { + Path libraryRoot = tempDir.resolve("libraryRoot"); + Files.createDirectories(libraryRoot); + + Path nestedDir = libraryRoot.resolve("nested"); + Files.createDirectories(nestedDir); + + Path ignoredFile = nestedDir.resolve(".DS_Store"); + Files.createFile(ignoredFile); + + bookService.deleteEmptyParentDirsUpToLibraryFolders(nestedDir, Set.of(libraryRoot)); + + assertThat(Files.exists(ignoredFile)).isFalse(); + assertThat(Files.exists(nestedDir)).isFalse(); + assertThat(Files.exists(libraryRoot)).isTrue(); + } + + @Test + void stopsAtLibraryRoot() throws IOException { + Path libraryRoot = tempDir.resolve("libraryRoot"); + Files.createDirectories(libraryRoot); + + bookService.deleteEmptyParentDirsUpToLibraryFolders(libraryRoot, Set.of(libraryRoot)); + + assertThat(Files.exists(libraryRoot)).isTrue(); + } + + @Test + void handlesUnreadableDirectoryGracefully() throws IOException { + Path libraryRoot = tempDir.resolve("libraryRoot"); + Files.createDirectories(libraryRoot); + + Path nestedDir = libraryRoot.resolve("nested"); + Files.createDirectories(nestedDir); + + File nestedDirFile = nestedDir.toFile(); + + boolean readableBefore = nestedDirFile.canRead(); + + try { + if (nestedDirFile.setReadable(false)) { + assertThatCode(() -> bookService.deleteEmptyParentDirsUpToLibraryFolders(nestedDir, Set.of(libraryRoot))) + .doesNotThrowAnyException(); + } else { + System.out.println("Could not change read permission; skipping unreadable directory test."); + } + } finally { + nestedDirFile.setReadable(readableBefore); + } + } +} \ No newline at end of file