Deleting books now cleans up empty directories left behind

This commit is contained in:
aditya.chandel
2025-06-30 17:31:34 -06:00
committed by Aditya Chandel
parent 46db40247c
commit b155f567a4
4 changed files with 237 additions and 2 deletions
+8
View File
@@ -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()
}
@@ -37,5 +37,4 @@ public class LibraryEntity {
private boolean watch;
private String icon;
}
@@ -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<Book> getBookDTOs(boolean includeDescription) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
@@ -365,16 +365,25 @@ public class BookService {
public ResponseEntity<BookDeletionResponse> deleteBooks(Set<Long> ids) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(ids);
List<Long> failedFileDeletions = new ArrayList<>();
for (BookEntity book : books) {
Path fullFilePath = book.getFullFilePath();
try {
if (Files.exists(fullFilePath)) {
Files.delete(fullFilePath);
Set<Path> 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<Path> libraryRoots) throws IOException {
Set<String> ignoredFilenames = Set.of(".DS_Store", "Thumbs.db");
currentDir = currentDir.toAbsolutePath().normalize();
Set<Path> 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);
@@ -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);
}
}
}