Show a persistent loader while a large library is being created (#2200)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-07 18:10:53 -07:00
committed by GitHub
co-authored by acx10
parent 251fe65ec0
commit c17fe58f4c
17 changed files with 567 additions and 111 deletions
@@ -41,8 +41,7 @@ public class LibraryController {
})
@GetMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<Library> getLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
public ResponseEntity<Library> getLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
return ResponseEntity.ok(libraryService.getLibrary(libraryId));
}
@@ -50,8 +49,7 @@ public class LibraryController {
@ApiResponse(responseCode = "200", description = "Library created successfully")
@PostMapping
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Library> createLibrary(
@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
public ResponseEntity<Library> createLibrary(@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) {
return ResponseEntity.ok(libraryService.createLibrary(request));
}
@@ -71,8 +69,7 @@ public class LibraryController {
@DeleteMapping("/{libraryId}")
@CheckLibraryAccess(libraryIdParam = "libraryId")
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<?> deleteLibrary(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
public ResponseEntity<?> deleteLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
libraryService.deleteLibrary(libraryId);
return ResponseEntity.noContent().build();
}
@@ -91,8 +88,7 @@ public class LibraryController {
@ApiResponse(responseCode = "200", description = "Books returned successfully")
@GetMapping("/{libraryId}/book")
@CheckLibraryAccess(libraryIdParam = "libraryId")
public ResponseEntity<List<Book>> getBooks(
@Parameter(description = "ID of the library") @PathVariable long libraryId) {
public ResponseEntity<List<Book>> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) {
List<Book> books = libraryService.getBooks(libraryId);
return ResponseEntity.ok(books);
}
@@ -119,4 +115,15 @@ public class LibraryController {
Library updated = libraryService.setFileNamingPattern(libraryId, pattern);
return ResponseEntity.ok(updated);
}
@Operation(summary = "Scan library paths", description = "Scan the provided library paths and return a count of processable files. Requires admin or manipulation permission.")
@ApiResponse(responseCode = "200", description = "Processable files count returned successfully")
@PostMapping("/scan")
@PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()")
public ResponseEntity<Integer> scanLibraryPaths(
@Parameter(description = "Library creation request with paths to scan")
@Validated @RequestBody CreateLibraryRequest request) {
int processableFilesCount = libraryService.scanLibraryPaths(request);
return ResponseEntity.ok(processableFilesCount);
}
}
@@ -1,5 +1,33 @@
package com.adityachandel.booklore.model.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
@Getter
public enum BookFileType {
PDF, EPUB, CBX, FB2
PDF(Set.of("pdf")),
EPUB(Set.of("epub")),
CBX(Set.of("cbz", "cbr", "cb7")),
FB2(Set.of("fb2"));
private final Set<String> extensions;
BookFileType(Set<String> extensions) {
this.extensions = extensions;
}
public boolean supports(String extension) {
return extensions.contains(extension.toLowerCase());
}
public static Optional<BookFileType> fromExtension(String extension) {
String ext = extension.toLowerCase();
return Arrays.stream(values())
.filter(type -> type.supports(ext))
.findFirst();
}
}
@@ -42,7 +42,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]");
private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(".*\\.(jpg|jpeg|png|webp)");
private static final Pattern IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|webp)");
private static final Pattern CBX_FILE_EXTENSION_PATTERN = Pattern.compile("(?i)\\.cb[rz7]$");
private final CbxMetadataExtractor cbxMetadataExtractor;
public CbxProcessor(BookRepository bookRepository,
@@ -99,17 +98,20 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
}
private Optional<BufferedImage> extractImagesFromArchive(File file) {
String name = file.getName().toLowerCase();
if (name.endsWith(".cbz")) {
return extractFirstImageFromZip(file);
} else if (name.endsWith(".cb7")) {
return extractFirstImageFrom7z(file);
} else if (name.endsWith(".cbr")) {
return extractFirstImageFromRar(file);
} else {
String name = file.getName();
String extension = FileUtils.getExtension(name).toLowerCase();
if (!BookFileType.CBX.supports(extension)) {
log.warn("Unsupported CBX format: {}", name);
return Optional.empty();
}
return switch (extension) {
case "cbz" -> extractFirstImageFromZip(file);
case "cb7" -> extractFirstImageFrom7z(file);
case "cbr" -> extractFirstImageFromRar(file);
default -> Optional.empty();
};
}
private Optional<BufferedImage> extractFirstImageFromZip(File file) {
@@ -242,8 +244,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce
private void setMetadata(BookEntity bookEntity) {
String baseName = new File(bookEntity.getFileName()).getName();
String title = UNDERSCORE_HYPHEN_PATTERN.matcher(CBX_FILE_EXTENSION_PATTERN.matcher(baseName).replaceAll("")).replaceAll(" ")
.trim();
String extension = FileUtils.getExtension(baseName);
if (BookFileType.CBX.supports(extension)) {
baseName = baseName.substring(0, baseName.length() - extension.length() - 1);
}
String title = UNDERSCORE_HYPHEN_PATTERN.matcher(baseName).replaceAll(" ").trim();
bookEntity.getMetadata().setTitle(truncate(title, 1000));
}
}
}
@@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
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.enums.LibraryScanMode;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
@@ -33,9 +34,14 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@@ -250,4 +256,51 @@ public class LibraryService {
library.setFileNamingPattern(pattern);
return libraryMapper.toLibrary(libraryRepository.save(library));
}
}
public int scanLibraryPaths(CreateLibraryRequest request) {
int count = 0;
if (request.getPaths() == null || request.getPaths().isEmpty()) {
return count;
}
for (LibraryPath libraryPath : request.getPaths()) {
Path path = Paths.get(libraryPath.getPath());
if (!Files.exists(path)) {
log.warn("Path does not exist: {}", path);
continue;
}
if (Files.isDirectory(path)) {
count += scanDirectory(path);
} else if (Files.isRegularFile(path) && isProcessableFile(path)) {
count++;
}
}
return count;
}
private int scanDirectory(Path directory) {
int count = 0;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
count += scanDirectory(entry);
} else if (Files.isRegularFile(entry) && isProcessableFile(entry)) {
count++;
}
}
} catch (IOException e) {
log.error("Error scanning directory: {}", directory, e);
}
return count;
}
private boolean isProcessableFile(Path file) {
String fileName = file.getFileName().toString().toLowerCase();
for (BookFileType fileType : BookFileType.values()) {
if (fileName.endsWith("." + fileType.name().toLowerCase())) {
return true;
}
}
return false;
}
}
@@ -63,6 +63,17 @@ public class FileUtils {
}
}
public String getExtension(String fileName) {
if (fileName == null) {
return "";
}
int i = fileName.lastIndexOf('.');
if (i >= 0 && i < fileName.length() - 1) {
return fileName.substring(i + 1);
}
return "";
}
private List<String> systemDirs = Arrays.asList(
// synology
"#recycle",