feat(bookdrop): add full pagination support with select-all and metadata caching
- Implemented backend pagination for Bookdrop file review - Updated finalizeImport logic to support select-all with excluded IDs - Handled partial metadata submission from frontend - Refactored chunk processing and logging for clarity - Enhanced frontend Bookdrop UI with paginated selection, metadata sync, and virtual scroll compatibility - Improved UX for bulk finalize and discard actions
This commit is contained in:
committed by
Aditya Chandel
parent
6fb458dc33
commit
f69110c164
+13
-36
@@ -1,62 +1,40 @@
|
|||||||
package com.adityachandel.booklore.controller;
|
package com.adityachandel.booklore.controller;
|
||||||
|
|
||||||
import com.adityachandel.booklore.mapper.BookdropFileMapper;
|
|
||||||
import com.adityachandel.booklore.model.dto.BookdropFile;
|
import com.adityachandel.booklore.model.dto.BookdropFile;
|
||||||
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
|
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
|
||||||
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
|
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
|
||||||
|
import com.adityachandel.booklore.model.dto.request.BookdropSelectionRequest;
|
||||||
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
|
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
|
||||||
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
|
|
||||||
import com.adityachandel.booklore.repository.BookdropFileRepository;
|
|
||||||
import com.adityachandel.booklore.service.bookdrop.BookDropService;
|
import com.adityachandel.booklore.service.bookdrop.BookDropService;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.time.Instant;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/bookdrop")
|
@RequestMapping("/api/bookdrop")
|
||||||
public class BookdropFileController {
|
public class BookdropFileController {
|
||||||
|
|
||||||
private final BookdropFileRepository repository;
|
|
||||||
private final BookdropFileMapper mapper;
|
|
||||||
private final BookDropService bookDropService;
|
private final BookDropService bookDropService;
|
||||||
|
|
||||||
@GetMapping("/notification")
|
@GetMapping("/notification")
|
||||||
public BookdropFileNotification getSummary() {
|
public BookdropFileNotification getSummary() {
|
||||||
long pendingCount = repository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
|
return bookDropService.getFileNotificationSummary();
|
||||||
long totalCount = repository.count();
|
|
||||||
|
|
||||||
return new BookdropFileNotification(
|
|
||||||
(int) pendingCount,
|
|
||||||
(int) totalCount,
|
|
||||||
Instant.now().toString()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/files")
|
@GetMapping("/files")
|
||||||
public List<BookdropFile> getFilesByStatus(@RequestParam(required = false) String status) {
|
public Page<BookdropFile> getFilesByStatus(@RequestParam(required = false) String status, Pageable pageable) {
|
||||||
if ("pending".equalsIgnoreCase(status)) {
|
return bookDropService.getFilesByStatus(status, pageable);
|
||||||
return repository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW)
|
|
||||||
.stream()
|
|
||||||
.map(mapper::toDto)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
return repository.findAll()
|
|
||||||
.stream()
|
|
||||||
.map(mapper::toDto)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@DeleteMapping("/files")
|
@PostMapping("/files/discard")
|
||||||
public ResponseEntity<Void> discardAllFiles() {
|
public ResponseEntity<Void> discardSelectedFiles(@RequestBody BookdropSelectionRequest request) {
|
||||||
bookDropService.discardAllFiles();
|
bookDropService.discardSelectedFiles(request.isSelectAll(), request.getExcludedIds(), request.getSelectedIds());
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,12 +47,11 @@ public class BookdropFileController {
|
|||||||
@GetMapping("/{bookdropId}/cover")
|
@GetMapping("/{bookdropId}/cover")
|
||||||
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
|
public ResponseEntity<Resource> getBookdropCover(@PathVariable long bookdropId) {
|
||||||
Resource file = bookDropService.getBookdropCover(bookdropId);
|
Resource file = bookDropService.getBookdropCover(bookdropId);
|
||||||
if (file == null) {
|
return (file != null)
|
||||||
return ResponseEntity.noContent().build();
|
? ResponseEntity.ok()
|
||||||
}
|
|
||||||
return ResponseEntity.ok()
|
|
||||||
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=cover.jpg")
|
||||||
.contentType(MediaType.IMAGE_JPEG)
|
.contentType(MediaType.IMAGE_JPEG)
|
||||||
.body(file);
|
.body(file)
|
||||||
|
: ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+4
@@ -8,7 +8,11 @@ import java.util.List;
|
|||||||
@Data
|
@Data
|
||||||
public class BookdropFinalizeRequest {
|
public class BookdropFinalizeRequest {
|
||||||
private String uploadPattern;
|
private String uploadPattern;
|
||||||
|
private Boolean selectAll;
|
||||||
|
private List<Long> excludedIds;
|
||||||
private List<BookdropFinalizeFile> files;
|
private List<BookdropFinalizeFile> files;
|
||||||
|
private Long defaultLibraryId;
|
||||||
|
private Long defaultPathId;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class BookdropFinalizeFile {
|
public static class BookdropFinalizeFile {
|
||||||
|
|||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package com.adityachandel.booklore.model.dto.request;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
public class BookdropSelectionRequest {
|
||||||
|
private boolean selectAll;
|
||||||
|
private List<Long> excludedIds;
|
||||||
|
private List<Long> selectedIds;
|
||||||
|
}
|
||||||
+6
-1
@@ -4,6 +4,8 @@ package com.adityachandel.booklore.repository;
|
|||||||
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
|
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
|
||||||
import com.adityachandel.booklore.model.entity.BookdropFileEntity.Status;
|
import com.adityachandel.booklore.model.entity.BookdropFileEntity.Status;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Modifying;
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
@@ -18,7 +20,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
|
|||||||
|
|
||||||
Optional<BookdropFileEntity> findByFilePath(String filePath);
|
Optional<BookdropFileEntity> findByFilePath(String filePath);
|
||||||
|
|
||||||
List<BookdropFileEntity> findAllByStatus(Status status);
|
Page<BookdropFileEntity> findAllByStatus(Status status, Pageable pageable);
|
||||||
|
|
||||||
long countByStatus(Status status);
|
long countByStatus(Status status);
|
||||||
|
|
||||||
@@ -26,4 +28,7 @@ public interface BookdropFileRepository extends JpaRepository<BookdropFileEntity
|
|||||||
@Modifying
|
@Modifying
|
||||||
@Query("DELETE FROM BookdropFileEntity f WHERE f.filePath LIKE CONCAT(:prefix, '%')")
|
@Query("DELETE FROM BookdropFileEntity f WHERE f.filePath LIKE CONCAT(:prefix, '%')")
|
||||||
int deleteAllByFilePathStartingWith(@Param("prefix") String prefix);
|
int deleteAllByFilePathStartingWith(@Param("prefix") String prefix);
|
||||||
|
|
||||||
|
@Query("SELECT f.id FROM BookdropFileEntity f WHERE f.id NOT IN :excludedIds")
|
||||||
|
List<Long> findAllExcludingIdsFlat(@Param("excludedIds") List<Long> excludedIds);
|
||||||
}
|
}
|
||||||
|
|||||||
+230
-62
@@ -2,34 +2,55 @@ package com.adityachandel.booklore.service.bookdrop;
|
|||||||
|
|
||||||
import com.adityachandel.booklore.config.AppProperties;
|
import com.adityachandel.booklore.config.AppProperties;
|
||||||
import com.adityachandel.booklore.exception.ApiError;
|
import com.adityachandel.booklore.exception.ApiError;
|
||||||
|
import com.adityachandel.booklore.mapper.BookdropFileMapper;
|
||||||
import com.adityachandel.booklore.model.dto.Book;
|
import com.adityachandel.booklore.model.dto.Book;
|
||||||
import com.adityachandel.booklore.model.dto.BookMetadata;
|
import com.adityachandel.booklore.model.dto.BookMetadata;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookdropFile;
|
||||||
|
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
|
||||||
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
|
import com.adityachandel.booklore.model.dto.request.BookdropFinalizeRequest;
|
||||||
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
|
|
||||||
import com.adityachandel.booklore.model.dto.response.BookdropFileResult;
|
import com.adityachandel.booklore.model.dto.response.BookdropFileResult;
|
||||||
|
import com.adityachandel.booklore.model.dto.response.BookdropFinalizeResult;
|
||||||
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
import com.adityachandel.booklore.model.dto.settings.LibraryFile;
|
||||||
import com.adityachandel.booklore.model.entity.*;
|
import com.adityachandel.booklore.model.entity.BookEntity;
|
||||||
import com.adityachandel.booklore.model.enums.*;
|
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.LibraryEntity;
|
||||||
|
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
|
||||||
|
import com.adityachandel.booklore.model.enums.BookFileExtension;
|
||||||
|
import com.adityachandel.booklore.model.enums.BookFileType;
|
||||||
import com.adityachandel.booklore.model.websocket.Topic;
|
import com.adityachandel.booklore.model.websocket.Topic;
|
||||||
import com.adityachandel.booklore.repository.*;
|
import com.adityachandel.booklore.repository.BookRepository;
|
||||||
|
import com.adityachandel.booklore.repository.BookdropFileRepository;
|
||||||
|
import com.adityachandel.booklore.repository.LibraryRepository;
|
||||||
import com.adityachandel.booklore.service.NotificationService;
|
import com.adityachandel.booklore.service.NotificationService;
|
||||||
import com.adityachandel.booklore.service.fileprocessor.*;
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
|
||||||
|
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
||||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||||
import com.adityachandel.booklore.service.monitoring.*;
|
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
||||||
import com.adityachandel.booklore.util.FileUtils;
|
import com.adityachandel.booklore.util.FileUtils;
|
||||||
import com.adityachandel.booklore.util.PathPatternResolver;
|
import com.adityachandel.booklore.util.PathPatternResolver;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.io.FilenameUtils;
|
import org.apache.commons.io.FilenameUtils;
|
||||||
import org.springframework.core.io.PathResource;
|
import org.springframework.core.io.PathResource;
|
||||||
import org.springframework.core.io.Resource;
|
import org.springframework.core.io.Resource;
|
||||||
|
import org.springframework.data.domain.Page;
|
||||||
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.*;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -47,6 +68,22 @@ public class BookDropService {
|
|||||||
private final BookdropNotificationService bookdropNotificationService;
|
private final BookdropNotificationService bookdropNotificationService;
|
||||||
private final BookFileProcessorRegistry processorRegistry;
|
private final BookFileProcessorRegistry processorRegistry;
|
||||||
private final AppProperties appProperties;
|
private final AppProperties appProperties;
|
||||||
|
private final BookdropFileMapper mapper;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public BookdropFileNotification getFileNotificationSummary() {
|
||||||
|
long pendingCount = bookdropFileRepository.countByStatus(BookdropFileEntity.Status.PENDING_REVIEW);
|
||||||
|
long totalCount = bookdropFileRepository.count();
|
||||||
|
return new BookdropFileNotification((int) pendingCount, (int) totalCount, Instant.now().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Page<BookdropFile> getFilesByStatus(String status, Pageable pageable) {
|
||||||
|
if ("pending".equalsIgnoreCase(status)) {
|
||||||
|
return bookdropFileRepository.findAllByStatus(BookdropFileEntity.Status.PENDING_REVIEW, pageable).map(mapper::toDto);
|
||||||
|
} else {
|
||||||
|
return bookdropFileRepository.findAll(pageable).map(mapper::toDto);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
|
public BookdropFinalizeResult finalizeImport(BookdropFinalizeRequest request) {
|
||||||
boolean monitoringWasActive = !monitoringService.isPaused();
|
boolean monitoringWasActive = !monitoringService.isPaused();
|
||||||
@@ -54,36 +91,91 @@ public class BookDropService {
|
|||||||
bookdropMonitoringService.pauseMonitoring();
|
bookdropMonitoringService.pauseMonitoring();
|
||||||
|
|
||||||
BookdropFinalizeResult results = BookdropFinalizeResult.builder().build();
|
BookdropFinalizeResult results = BookdropFinalizeResult.builder().build();
|
||||||
|
Long defaultLibraryId = request.getDefaultLibraryId();
|
||||||
|
Long defaultPathId = request.getDefaultPathId();
|
||||||
|
|
||||||
for (BookdropFinalizeRequest.BookdropFinalizeFile fileReq : request.getFiles()) {
|
Map<Long, BookdropFinalizeRequest.BookdropFinalizeFile> metadataById = Optional.ofNullable(request.getFiles())
|
||||||
try {
|
.orElse(List.of())
|
||||||
BookdropFileEntity fileEntity = bookdropFileRepository.findById(fileReq.getFileId()).orElseThrow(() -> ApiError.FILE_NOT_FOUND.createException(fileReq.getFileId()));
|
.stream()
|
||||||
|
.collect(Collectors.toMap(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId, Function.identity()));
|
||||||
|
|
||||||
BookdropFileResult result = moveFile(
|
final int CHUNK_SIZE = 100;
|
||||||
fileReq.getLibraryId(),
|
AtomicInteger failedCount = new AtomicInteger();
|
||||||
fileReq.getPathId(),
|
|
||||||
request.getUploadPattern(),
|
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
|
||||||
fileReq.getMetadata(),
|
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
|
||||||
fileEntity
|
|
||||||
);
|
if (Boolean.TRUE.equals(request.getSelectAll())) {
|
||||||
results.getResults().add(result);
|
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
|
||||||
} catch (Exception e) {
|
|
||||||
String msg = String.format("Failed to finalize file [id=%s]: %s", fileReq.getFileId(), e.getMessage());
|
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds); // You need to write this
|
||||||
log.error(msg, e);
|
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
|
||||||
notificationService.sendMessage(Topic.LOG, msg);
|
|
||||||
|
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
|
||||||
|
int end = Math.min(i + CHUNK_SIZE, allIds.size());
|
||||||
|
List<Long> chunk = allIds.subList(i, end);
|
||||||
|
|
||||||
|
log.info("Processing chunk {}/{} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) allIds.size() / CHUNK_SIZE), chunk.size(), chunk);
|
||||||
|
|
||||||
|
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunk);
|
||||||
|
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream().collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
|
||||||
|
|
||||||
|
for (Long id : chunk) {
|
||||||
|
BookdropFileEntity file = fileMap.get(id);
|
||||||
|
if (file == null) {
|
||||||
|
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
|
||||||
|
failedCount.incrementAndGet();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
List<Long> ids = Optional.ofNullable(request.getFiles())
|
||||||
|
.orElse(List.of())
|
||||||
|
.stream()
|
||||||
|
.map(BookdropFinalizeRequest.BookdropFinalizeFile::getFileId)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
log.info("Processing {} manually selected files in chunks of {}. File IDs: {}", ids.size(), CHUNK_SIZE, ids);
|
||||||
|
|
||||||
|
for (int i = 0; i < ids.size(); i += CHUNK_SIZE) {
|
||||||
|
int end = Math.min(i + CHUNK_SIZE, ids.size());
|
||||||
|
List<Long> chunkIds = ids.subList(i, end);
|
||||||
|
List<BookdropFileEntity> chunkFiles = bookdropFileRepository.findAllById(chunkIds);
|
||||||
|
|
||||||
|
log.info("Processing chunk {} of {} ({} files): IDs={}", (i / CHUNK_SIZE + 1), (int) Math.ceil((double) ids.size() / CHUNK_SIZE), chunkFiles.size(), chunkIds);
|
||||||
|
|
||||||
|
Map<Long, BookdropFileEntity> fileMap = chunkFiles.stream()
|
||||||
|
.collect(Collectors.toMap(BookdropFileEntity::getId, Function.identity()));
|
||||||
|
|
||||||
|
for (Long id : chunkIds) {
|
||||||
|
BookdropFileEntity file = fileMap.get(id);
|
||||||
|
if (file == null) {
|
||||||
|
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
|
||||||
|
failedCount.incrementAndGet();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, request.getUploadPattern(), results, failedCount);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
|
||||||
|
results.getResults().stream().filter(BookdropFileResult::isSuccess).count(),
|
||||||
|
failedCount.get(),
|
||||||
|
results.getResults().size());
|
||||||
|
|
||||||
if (monitoringWasActive) {
|
if (monitoringWasActive) {
|
||||||
Thread.startVirtualThread(() -> {
|
Thread.startVirtualThread(() -> {
|
||||||
try {
|
try {
|
||||||
Thread.sleep(5000);
|
Thread.sleep(5000);
|
||||||
monitoringService.resumeMonitoring();
|
monitoringService.resumeMonitoring();
|
||||||
bookdropMonitoringService.resumeMonitoring();
|
bookdropMonitoringService.resumeMonitoring();
|
||||||
log.info("Monitoring resumed after 5s delay");
|
log.info("Monitoring resumed after 5s delay following finalizeImport");
|
||||||
} catch (InterruptedException e) {
|
} catch (InterruptedException e) {
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
log.warn("Interrupted while delaying resume of monitoring");
|
log.warn("Interrupted while delaying resume of monitoring after finalizeImport");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -91,6 +183,64 @@ public class BookDropService {
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void processFile(
|
||||||
|
BookdropFileEntity fileEntity,
|
||||||
|
BookdropFinalizeRequest.BookdropFinalizeFile fileReq,
|
||||||
|
Long defaultLibraryId,
|
||||||
|
Long defaultPathId,
|
||||||
|
String uploadPattern,
|
||||||
|
BookdropFinalizeResult results,
|
||||||
|
AtomicInteger failedCount
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
Long libraryId;
|
||||||
|
Long pathId;
|
||||||
|
BookMetadata metadata;
|
||||||
|
|
||||||
|
if (fileReq != null) {
|
||||||
|
libraryId = fileReq.getLibraryId() != null ? fileReq.getLibraryId() : defaultLibraryId;
|
||||||
|
pathId = fileReq.getPathId() != null ? fileReq.getPathId() : defaultPathId;
|
||||||
|
metadata = fileReq.getMetadata();
|
||||||
|
log.debug("Processing fileId={}, fileName={} with provided metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
|
||||||
|
} else {
|
||||||
|
if (defaultLibraryId == null || defaultPathId == null) {
|
||||||
|
log.warn("Missing default metadata for fileId={}", fileEntity.getId());
|
||||||
|
throw ApiError.BAD_REQUEST.createException("Missing metadata and defaults for fileId=" + fileEntity.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
metadata = fileEntity.getFetchedMetadata() != null
|
||||||
|
? objectMapper.readValue(fileEntity.getFetchedMetadata(), BookMetadata.class)
|
||||||
|
: objectMapper.readValue(fileEntity.getOriginalMetadata(), BookMetadata.class);
|
||||||
|
|
||||||
|
libraryId = defaultLibraryId;
|
||||||
|
pathId = defaultPathId;
|
||||||
|
log.debug("Processing fileId={}, fileName={} with default metadata, libraryId={}, pathId={}", fileEntity.getId(), fileEntity.getFileName(), libraryId, pathId);
|
||||||
|
}
|
||||||
|
|
||||||
|
BookdropFileResult result = moveFile(
|
||||||
|
libraryId,
|
||||||
|
pathId,
|
||||||
|
uploadPattern,
|
||||||
|
metadata,
|
||||||
|
fileEntity
|
||||||
|
);
|
||||||
|
|
||||||
|
results.getResults().add(result);
|
||||||
|
if (!result.isSuccess()) {
|
||||||
|
log.warn("Finalization failed (non-exception) for file id={}, name={}, message={}", fileEntity.getId(), fileEntity.getFileName(), result.getMessage());
|
||||||
|
failedCount.incrementAndGet();
|
||||||
|
} else {
|
||||||
|
log.info("Successfully finalized file id={}, name={}", fileEntity.getId(), fileEntity.getFileName());
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
failedCount.incrementAndGet();
|
||||||
|
String msg = String.format("Error finalizing file [id=%s, name=%s]: %s", fileEntity.getId(), fileEntity.getFileName(), e.getMessage());
|
||||||
|
log.error(msg, e);
|
||||||
|
notificationService.sendMessage(Topic.LOG, msg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private BookdropFileResult moveFile(long libraryId, long pathId, String filePattern, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
|
private BookdropFileResult moveFile(long libraryId, long pathId, String filePattern, BookMetadata metadata, BookdropFileEntity bookdropFile) throws Exception {
|
||||||
LibraryEntity library = libraryRepository.findById(libraryId)
|
LibraryEntity library = libraryRepository.findById(libraryId)
|
||||||
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||||
@@ -109,20 +259,26 @@ public class BookDropService {
|
|||||||
Path target = Paths.get(path.getPath(), relativePath);
|
Path target = Paths.get(path.getPath(), relativePath);
|
||||||
File targetFile = target.toFile();
|
File targetFile = target.toFile();
|
||||||
|
|
||||||
|
log.debug("Preparing to move file id={}, name={}, source={}, target={}, library={}, path={}",
|
||||||
|
bookdropFile.getId(), bookdropFile.getFileName(), source, target, library.getName(), path.getPath());
|
||||||
|
|
||||||
if (!Files.exists(source)) {
|
if (!Files.exists(source)) {
|
||||||
bookdropFileRepository.deleteById(bookdropFile.getId());
|
bookdropFileRepository.deleteById(bookdropFile.getId());
|
||||||
log.warn("Source file [id={}] not found. Deleting entry.", bookdropFile.getId());
|
log.warn("Source file [id={}] not found at '{}'. Deleting entry from DB.", bookdropFile.getId(), source);
|
||||||
bookdropNotificationService.sendBookdropFileSummaryNotification();
|
bookdropNotificationService.sendBookdropFileSummaryNotification();
|
||||||
return failureResult(targetFile.getName(), "Source file does not exist in bookdrop folder");
|
return failureResult(targetFile.getName(), "Source file does not exist in bookdrop folder");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (targetFile.exists()) {
|
if (targetFile.exists()) {
|
||||||
|
log.warn("Target file already exists: id={}, name={}, target={}", bookdropFile.getId(), bookdropFile.getFileName(), target);
|
||||||
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
|
return failureResult(targetFile.getName(), "File already exists in the library '" + library.getName() + "'");
|
||||||
}
|
}
|
||||||
|
|
||||||
Files.createDirectories(target.getParent());
|
Files.createDirectories(target.getParent());
|
||||||
Files.move(source, target);
|
Files.move(source, target);
|
||||||
|
|
||||||
|
log.info("Moved file id={}, name={} from '{}' to '{}'", bookdropFile.getId(), bookdropFile.getFileName(), source, target);
|
||||||
|
|
||||||
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
|
Book processedBook = processFile(targetFile.getName(), library, path, targetFile,
|
||||||
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
BookFileExtension.fromFileName(bookdropFile.getFileName())
|
||||||
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
.orElseThrow(() -> ApiError.INVALID_FILE_FORMAT.createException("Unsupported file extension"))
|
||||||
@@ -143,6 +299,8 @@ public class BookDropService {
|
|||||||
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
|
log.debug("Deleted cached cover image for bookdropId={}: {}", bookdropFile.getId(), deleted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info("File import completed: id={}, name={}, library={}, path={}", bookdropFile.getId(), targetFile.getName(), library.getName(), path.getPath());
|
||||||
|
|
||||||
return BookdropFileResult.builder()
|
return BookdropFileResult.builder()
|
||||||
.fileName(targetFile.getName())
|
.fileName(targetFile.getName())
|
||||||
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
|
.message("File successfully imported into the '" + library.getName() + "' library from the Bookdrop folder")
|
||||||
@@ -171,7 +329,7 @@ public class BookDropService {
|
|||||||
return processor.processFile(libraryFile);
|
return processor.processFile(libraryFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void discardAllFiles() {
|
public void discardSelectedFiles(boolean selectAll, List<Long> excludedIds, List<Long> selectedIds) {
|
||||||
bookdropMonitoringService.pauseMonitoring();
|
bookdropMonitoringService.pauseMonitoring();
|
||||||
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
|
Path bookdropPath = Path.of(appProperties.getBookdropFolder());
|
||||||
|
|
||||||
@@ -185,52 +343,62 @@ public class BookDropService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try (Stream<Path> paths = Files.walk(bookdropPath)) {
|
List<BookdropFileEntity> filesToDelete;
|
||||||
paths.sorted(Comparator.reverseOrder())
|
if (selectAll) {
|
||||||
.filter(p -> !p.equals(bookdropPath))
|
filesToDelete = bookdropFileRepository.findAll().stream()
|
||||||
.forEach(path -> {
|
.filter(f -> excludedIds == null || !excludedIds.contains(f.getId()))
|
||||||
try {
|
.toList();
|
||||||
if (Files.isRegularFile(path) && Files.deleteIfExists(path)) {
|
log.info("Discarding all files except excluded IDs: {}", excludedIds);
|
||||||
deletedFiles.incrementAndGet();
|
} else {
|
||||||
} else if (Files.isDirectory(path) && Files.deleteIfExists(path)) {
|
filesToDelete = bookdropFileRepository.findAllById(selectedIds == null ? List.of() : selectedIds);
|
||||||
deletedDirs.incrementAndGet();
|
log.info("Discarding selected files: {}", selectedIds);
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("Failed to delete path: {}", path, e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
long removedDbCount = bookdropFileRepository.count();
|
for (BookdropFileEntity entity : filesToDelete) {
|
||||||
bookdropFileRepository.deleteAll();
|
try {
|
||||||
|
Path filePath = Path.of(entity.getFilePath());
|
||||||
Path tempCoverDir = Paths.get(appProperties.getPathConfig(), "bookdrop_temp");
|
if (Files.exists(filePath) && Files.isRegularFile(filePath) && Files.deleteIfExists(filePath)) {
|
||||||
if (Files.exists(tempCoverDir)) {
|
deletedFiles.incrementAndGet();
|
||||||
try (Stream<Path> files = Files.walk(tempCoverDir)) {
|
log.debug("Deleted file from disk: id={}, path={}", entity.getId(), filePath);
|
||||||
files
|
}
|
||||||
.filter(Files::isRegularFile)
|
Path coverPath = Paths.get(appProperties.getPathConfig(), "bookdrop_temp", entity.getId() + ".jpg");
|
||||||
.filter(p -> p.toString().endsWith(".jpg"))
|
if (Files.exists(coverPath) && Files.deleteIfExists(coverPath)) {
|
||||||
.forEach(p -> {
|
deletedCovers.incrementAndGet();
|
||||||
try {
|
log.debug("Deleted cover image: id={}, path={}", entity.getId(), coverPath);
|
||||||
Files.delete(p);
|
}
|
||||||
deletedCovers.incrementAndGet();
|
|
||||||
} catch (IOException e) {
|
|
||||||
log.warn("Failed to delete cached cover: {}", p, e);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
log.warn("Failed to clean bookdrop_temp folder", e);
|
log.warn("Failed to delete file or cover for bookdropId={}: {}", entity.getId(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bookdropFileRepository.deleteAllById(filesToDelete.stream().map(BookdropFileEntity::getId).toList());
|
||||||
|
log.info("Deleted {} bookdrop DB entries", filesToDelete.size());
|
||||||
|
|
||||||
|
try (Stream<Path> paths = Files.walk(bookdropPath)) {
|
||||||
|
paths.sorted(Comparator.reverseOrder())
|
||||||
|
.filter(p -> !p.equals(bookdropPath) && Files.isDirectory(p))
|
||||||
|
.forEach(p -> {
|
||||||
|
try (Stream<Path> subPaths = Files.list(p)) {
|
||||||
|
if (subPaths.findAny().isEmpty()) {
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
deletedDirs.incrementAndGet();
|
||||||
|
log.debug("Deleted empty directory: {}", p);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("Failed to delete folder: {}", p, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (IOException e) {
|
||||||
|
log.warn("Failed to scan bookdrop folder for empty directories", e);
|
||||||
|
}
|
||||||
|
|
||||||
bookdropNotificationService.sendBookdropFileSummaryNotification();
|
bookdropNotificationService.sendBookdropFileSummaryNotification();
|
||||||
|
log.info("Bookdrop cleanup summary: deleted {} files, {} folders, {} DB entries, {} covers",
|
||||||
|
deletedFiles.get(), deletedDirs.get(), filesToDelete.size(), deletedCovers.get());
|
||||||
|
|
||||||
log.info("Discarded all files: deleted {} files, {} folders, {} DB entries, and {} cover images", deletedFiles.get(), deletedDirs.get(), removedDbCount, deletedCovers.get());
|
|
||||||
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException("Failed to clean bookdrop folder", e);
|
|
||||||
} finally {
|
} finally {
|
||||||
bookdropMonitoringService.resumeMonitoring();
|
bookdropMonitoringService.resumeMonitoring();
|
||||||
|
log.info("Bookdrop monitoring resumed after cleanup");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -93,7 +93,7 @@ public class BookdropEventHandlerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (bookdropFileRepository.findByFilePath(filePath).isPresent()) {
|
if (bookdropFileRepository.findByFilePath(filePath).isPresent()) {
|
||||||
log.info("File already processed in bookdrop, ignoring: {}", filePath);
|
log.info("File already exists in Bookdrop and is pending review or acceptance: {}", filePath);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
-121
@@ -1,121 +0,0 @@
|
|||||||
package com.adityachandel.booklore.service;
|
|
||||||
|
|
||||||
import com.adityachandel.booklore.config.AppProperties;
|
|
||||||
import com.adityachandel.booklore.repository.BookRepository;
|
|
||||||
import com.adityachandel.booklore.repository.BookdropFileRepository;
|
|
||||||
import com.adityachandel.booklore.repository.LibraryRepository;
|
|
||||||
import com.adityachandel.booklore.service.bookdrop.BookDropService;
|
|
||||||
import com.adityachandel.booklore.service.bookdrop.BookdropNotificationService;
|
|
||||||
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
|
|
||||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
|
||||||
import com.adityachandel.booklore.service.bookdrop.BookdropMonitoringService;
|
|
||||||
import com.adityachandel.booklore.service.monitoring.MonitoringService;
|
|
||||||
import com.adityachandel.booklore.service.NotificationService;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.springframework.core.io.PathResource;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
|
|
||||||
import java.io.File;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Path;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
|
|
||||||
class BookDropServiceTest {
|
|
||||||
|
|
||||||
private BookdropFileRepository bookdropFileRepository;
|
|
||||||
private LibraryRepository libraryRepository;
|
|
||||||
private BookRepository bookRepository;
|
|
||||||
private MonitoringService monitoringService;
|
|
||||||
private BookdropMonitoringService bookdropMonitoringService;
|
|
||||||
private NotificationService notificationService;
|
|
||||||
private MetadataRefreshService metadataRefreshService;
|
|
||||||
private BookdropNotificationService bookdropNotificationService;
|
|
||||||
private AppProperties appProperties;
|
|
||||||
|
|
||||||
private BookDropService bookDropService;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
void setUp() {
|
|
||||||
bookdropFileRepository = mock(BookdropFileRepository.class);
|
|
||||||
libraryRepository = mock(LibraryRepository.class);
|
|
||||||
bookRepository = mock(BookRepository.class);
|
|
||||||
monitoringService = mock(MonitoringService.class);
|
|
||||||
bookdropMonitoringService = mock(BookdropMonitoringService.class);
|
|
||||||
notificationService = mock(NotificationService.class);
|
|
||||||
metadataRefreshService = mock(MetadataRefreshService.class);
|
|
||||||
bookdropNotificationService = mock(BookdropNotificationService.class);
|
|
||||||
BookFileProcessorRegistry processorRegistry = mock(BookFileProcessorRegistry.class);
|
|
||||||
appProperties = mock(AppProperties.class);
|
|
||||||
|
|
||||||
bookDropService = new BookDropService(
|
|
||||||
bookdropFileRepository, libraryRepository, bookRepository,
|
|
||||||
monitoringService, bookdropMonitoringService,
|
|
||||||
notificationService, metadataRefreshService,
|
|
||||||
bookdropNotificationService,
|
|
||||||
processorRegistry,
|
|
||||||
appProperties
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void discardAllFiles_shouldDeleteFilesDirsAndNotify() throws Exception {
|
|
||||||
Path bookdropPath = Paths.get("/tmp/bookdrop");
|
|
||||||
when(appProperties.getBookdropFolder()).thenReturn(bookdropPath.toString());
|
|
||||||
|
|
||||||
Files.createDirectories(bookdropPath);
|
|
||||||
Path testFile = bookdropPath.resolve("testfile.txt");
|
|
||||||
Files.createFile(testFile);
|
|
||||||
|
|
||||||
when(bookdropFileRepository.count()).thenReturn(1L);
|
|
||||||
|
|
||||||
Path tempCoverDir = Paths.get("/tmp/config/bookdrop_temp");
|
|
||||||
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
|
|
||||||
Files.createDirectories(tempCoverDir);
|
|
||||||
Path tempCover = tempCoverDir.resolve("1.jpg");
|
|
||||||
Files.createFile(tempCover);
|
|
||||||
|
|
||||||
bookDropService.discardAllFiles();
|
|
||||||
|
|
||||||
verify(bookdropFileRepository).deleteAll();
|
|
||||||
verify(bookdropNotificationService).sendBookdropFileSummaryNotification();
|
|
||||||
verify(bookdropMonitoringService).pauseMonitoring();
|
|
||||||
verify(bookdropMonitoringService).resumeMonitoring();
|
|
||||||
|
|
||||||
Files.deleteIfExists(testFile);
|
|
||||||
Files.deleteIfExists(bookdropPath);
|
|
||||||
Files.deleteIfExists(tempCover);
|
|
||||||
Files.deleteIfExists(tempCoverDir);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getBookdropCover_shouldReturnResourceIfExists() throws Exception {
|
|
||||||
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
|
|
||||||
long bookdropId = 123L;
|
|
||||||
Path coverPath = Paths.get("/tmp/config/bookdrop_temp", bookdropId + ".jpg");
|
|
||||||
File coverFile = coverPath.toFile();
|
|
||||||
|
|
||||||
coverFile.getParentFile().mkdirs();
|
|
||||||
coverFile.createNewFile();
|
|
||||||
|
|
||||||
Resource resource = bookDropService.getBookdropCover(bookdropId);
|
|
||||||
|
|
||||||
assertThat(resource).isInstanceOf(PathResource.class);
|
|
||||||
assertThat(resource.getFilename()).isEqualTo(bookdropId + ".jpg");
|
|
||||||
|
|
||||||
coverFile.delete();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void getBookdropCover_shouldReturnNullIfNotExists() {
|
|
||||||
when(appProperties.getPathConfig()).thenReturn("/tmp/config");
|
|
||||||
long bookdropId = 99999L;
|
|
||||||
|
|
||||||
Resource resource = bookDropService.getBookdropCover(bookdropId);
|
|
||||||
|
|
||||||
assertThat(resource).isNull();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
@if (fetchedMetadata) {
|
@if (fetchedMetadata) {
|
||||||
<form [formGroup]="metadataForm" class="flex flex-col h-[30rem] w-full">
|
<form [formGroup]="metadataForm" class="flex flex-col h-[35rem] w-full">
|
||||||
<div class="flex-grow overflow-auto">
|
<div class="flex-grow overflow-auto">
|
||||||
<div class="relative flex items-center justify-between pb-3">
|
<div class="relative flex items-center justify-between pb-3">
|
||||||
<div class="absolute left-1/2 transform -translate-x-1/2 flex items-center pl-24">
|
<div class="absolute left-1/2 transform -translate-x-1/2 flex items-center pl-24">
|
||||||
|
|||||||
+105
-70
@@ -10,28 +10,30 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (loading) {
|
@if (loading) {
|
||||||
|
|
||||||
<div class="absolute inset-0 flex items-center justify-center z-50 rounded-xl">
|
<div class="absolute inset-0 flex items-center justify-center z-50 rounded-xl">
|
||||||
<div class="flex flex-col items-center space-y-3">
|
<div class="flex flex-col items-center space-y-3">
|
||||||
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
|
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
|
||||||
<span class="text-gray-300">
|
<span class="text-gray-300">Loading Bookdrop files. Please wait...</span>
|
||||||
Loading Bookdrop files. Please wait...
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
} @else {
|
} @else {
|
||||||
|
|
||||||
<div class="px-6 pb-2">
|
<div class="px-6 pb-2">
|
||||||
@if (saving) {
|
@if (saving) {
|
||||||
<div class="absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center z-50 rounded-xl space-y-3">
|
<div class="absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center z-50 rounded-xl space-y-3">
|
||||||
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
|
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
|
||||||
<div class="bg-gray-900/90 px-4 py-2 rounded-md">
|
<div class="bg-gray-900/90 px-4 py-2 rounded-md">
|
||||||
<span class="text-sm text-gray-200 text-center">
|
<span class="text-sm text-gray-200 text-center">
|
||||||
Organizing and moving files to their designated libraries. Please wait...
|
Organizing and moving files to their designated libraries. Please wait...
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (bookdropFileUis.length !== 0) {
|
@if (bookdropFileUis.length !== 0) {
|
||||||
|
|
||||||
<div class="flex gap-2 items-center px-1 pb-4 w-full">
|
<div class="flex gap-2 items-center px-1 pb-4 w-full">
|
||||||
<label for="uploadPatternInput" class="text-sm text-gray-300 font-medium">File Naming Pattern:</label>
|
<label for="uploadPatternInput" class="text-sm text-gray-300 font-medium">File Naming Pattern:</label>
|
||||||
<input
|
<input
|
||||||
@@ -42,17 +44,16 @@
|
|||||||
type="text"
|
type="text"
|
||||||
pInputText
|
pInputText
|
||||||
[(ngModel)]="uploadPattern"
|
[(ngModel)]="uploadPattern"
|
||||||
placeholder="e.g., {title} - {authors}"
|
placeholder="e.g., {title} - {authors}"/>
|
||||||
/>
|
|
||||||
<i
|
<i
|
||||||
class="pi pi-info-circle text-blue-500 cursor-help"
|
class="pi pi-info-circle text-blue-500 cursor-help"
|
||||||
pTooltip="Sets the filename pattern used when moving files from bookdrop folder to the library, using metadata placeholders like {title}, {authors}, etc."
|
pTooltip="Sets the filename pattern used when moving files from bookdrop folder to the library, using metadata placeholders like {title}, {authors}, etc."
|
||||||
tooltipPosition="top"
|
tooltipPosition="top"
|
||||||
style="font-size: 1rem; margin-left: 0.25rem;"
|
style="font-size: 1rem; margin-left: 0.25rem;"></i>
|
||||||
></i>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex justify-between items-center gap-4 px-1">
|
<div class="flex justify-between items-center gap-4 px-1">
|
||||||
|
|
||||||
<div class="flex gap-4 items-center">
|
<div class="flex gap-4 items-center">
|
||||||
<span class="text-sm text-gray-300 font-medium">Library for All Files:</span>
|
<span class="text-sm text-gray-300 font-medium">Library for All Files:</span>
|
||||||
<p-select
|
<p-select
|
||||||
@@ -109,6 +110,7 @@
|
|||||||
pTooltip="For all files, replace current metadata with fetched metadata, excluding cover images"
|
pTooltip="For all files, replace current metadata with fetched metadata, excluding cover images"
|
||||||
tooltipPosition="top">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
|
|
||||||
<p-button
|
<p-button
|
||||||
size="small"
|
size="small"
|
||||||
outlined
|
outlined
|
||||||
@@ -123,6 +125,7 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex-1 overflow-y-auto px-6 space-y-2 pb-4">
|
<div class="flex-1 overflow-y-auto px-6 space-y-2 pb-4">
|
||||||
@if (bookdropFileUis.length === 0) {
|
@if (bookdropFileUis.length === 0) {
|
||||||
<div class="h-full w-full flex items-center justify-center text-gray-400 italic py-8">
|
<div class="h-full w-full flex items-center justify-center text-gray-400 italic py-8">
|
||||||
@@ -130,68 +133,60 @@
|
|||||||
</div>
|
</div>
|
||||||
} @else {
|
} @else {
|
||||||
@for (file of bookdropFileUis; track file) {
|
@for (file of bookdropFileUis; track file) {
|
||||||
|
|
||||||
<div class="flex flex-col">
|
<div class="flex flex-col">
|
||||||
<div class="flex items-center gap-4 custom-border rounded-xl px-4 py-2">
|
<div class="flex items-center gap-4 custom-border rounded-xl px-4 py-2">
|
||||||
|
|
||||||
@if (file.file.fetchedMetadata) {
|
<p-checkbox
|
||||||
<i
|
[binary]="true"
|
||||||
class="pi pi-circle-fill"
|
[(ngModel)]="file.selected"
|
||||||
style="color: green; font-size: 0.75rem"
|
(ngModelChange)="toggleFileSelection(file.file.id, $event)">
|
||||||
pTooltip="Fetched metadata is available."
|
</p-checkbox>
|
||||||
tooltipPosition="top">
|
|
||||||
</i>
|
<i
|
||||||
} @else {
|
class="pi pi-circle-fill"
|
||||||
<i
|
[ngStyle]="{'color': file.file.fetchedMetadata ? 'green' : 'darkorange'}"
|
||||||
class="pi pi-circle-fill"
|
style="font-size: 0.75rem"
|
||||||
style="color: darkorange; font-size: 0.75rem"
|
pTooltip="{{file.file.fetchedMetadata ? 'Fetched metadata is available.' : 'No fetched metadata available.'}}"
|
||||||
pTooltip="No fetched metadata available."
|
tooltipPosition="top">
|
||||||
tooltipPosition="top">
|
</i>
|
||||||
</i>
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (file.metadataForm.get('thumbnailUrl')?.value) {
|
@if (file.metadataForm.get('thumbnailUrl')?.value) {
|
||||||
<img
|
<img
|
||||||
[src]="file.metadataForm.get('thumbnailUrl')?.value"
|
[src]="file.metadataForm.get('thumbnailUrl')?.value"
|
||||||
alt="Cover"
|
alt="Cover"
|
||||||
title="Original cover"
|
title="Original cover"
|
||||||
(click)="file.showDetails = !file.showDetails"
|
class="w-6 h-8 rounded-sm object-cover cursor-pointer hover:scale-105 hover:shadow-md transition-transform duration-200"
|
||||||
class="w-6 h-8 flex-shrink-0 rounded-sm object-cover cursor-pointer transition-transform duration-200 hover:scale-105 hover:shadow-md"
|
(click)="file.showDetails = !file.showDetails"/>
|
||||||
/>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@if (file.file.fetchedMetadata?.thumbnailUrl) {
|
@if (file.file.fetchedMetadata?.thumbnailUrl) {
|
||||||
<img
|
<img
|
||||||
[src]="file.file.fetchedMetadata?.thumbnailUrl"
|
[src]="file.file.fetchedMetadata?.thumbnailUrl"
|
||||||
alt="Cover"
|
alt="Fetched Cover"
|
||||||
title="Fetched cover"
|
title="Fetched cover"
|
||||||
(click)="file.showDetails = !file.showDetails"
|
class="w-6 h-8 rounded-sm object-cover cursor-pointer hover:scale-105 hover:shadow-md transition-transform duration-200"
|
||||||
class="w-6 h-8 flex-shrink-0 rounded-sm object-cover cursor-pointer transition-transform duration-200 hover:scale-105 hover:shadow-md"
|
(click)="file.showDetails = !file.showDetails"/>
|
||||||
/>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="flex-1 font-medium text-sm truncate" (click)="file.showDetails = !file.showDetails">
|
<div class="flex-1 font-medium text-sm truncate" (click)="file.showDetails = !file.showDetails">
|
||||||
{{ file.file.fileName }}
|
{{ file.file.fileName }}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@if (copiedFlags[file.file.id]) {
|
<i
|
||||||
<i
|
class="pi"
|
||||||
class="pi pi-check-circle text-green-500"
|
[ngClass]="{
|
||||||
pTooltip="Fetched metadata has been applied."
|
'pi-check-circle text-green-500': copiedFlags[file.file.id],
|
||||||
tooltipPosition="top">
|
'pi-check-circle text-blue-500': !file.file.fetchedMetadata,
|
||||||
</i>
|
'pi-exclamation-triangle text-red-500': file.file.fetchedMetadata && !copiedFlags[file.file.id]
|
||||||
} @else if (!file.file.fetchedMetadata) {
|
}"
|
||||||
<i
|
[pTooltip]="copiedFlags[file.file.id]
|
||||||
class="pi pi-check-circle text-blue-500"
|
? 'Fetched metadata has been applied.'
|
||||||
pTooltip="No fetched metadata available. Original metadata will used."
|
: !file.file.fetchedMetadata
|
||||||
tooltipPosition="top">
|
? 'No fetched metadata available. Original metadata will be used.'
|
||||||
</i>
|
: 'Fetched metadata hasn’t been applied yet. Open metadata picker to review.'"
|
||||||
} @else {
|
tooltipPosition="top">
|
||||||
<i
|
</i>
|
||||||
class="pi pi-exclamation-triangle text-red-500"
|
|
||||||
pTooltip="Fetched metadata hasn’t been applied yet. You can open the metadata picker using the dropdown on the right, or skip and keep the original metadata."
|
|
||||||
tooltipPosition="top">
|
|
||||||
</i>
|
|
||||||
}
|
|
||||||
|
|
||||||
<p-select
|
<p-select
|
||||||
size="small"
|
size="small"
|
||||||
@@ -223,12 +218,9 @@
|
|||||||
</p-button>
|
</p-button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
@if (file.showDetails) {
|
@if (file.showDetails) {
|
||||||
<app-bookdrop-file-metadata-picker-component
|
<app-bookdrop-file-metadata-picker-component
|
||||||
class="px-12 py-8 custom-border1"
|
class="px-12 py-8 custom-border1"
|
||||||
style="transition: opacity 0.3s ease"
|
|
||||||
#metadataPicker
|
|
||||||
[originalMetadata]="file.file.originalMetadata"
|
[originalMetadata]="file.file.originalMetadata"
|
||||||
[fetchedMetadata]="file.file.fetchedMetadata!"
|
[fetchedMetadata]="file.file.fetchedMetadata!"
|
||||||
[metadataForm]="file.metadataForm"
|
[metadataForm]="file.metadataForm"
|
||||||
@@ -242,29 +234,72 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p-divider></p-divider>
|
<p-divider></p-divider>
|
||||||
<div class="pb-4 px-6 gap-4 flex justify-end">
|
|
||||||
@if (bookdropFileUis.length !== 0) {
|
<div class="pb-2 px-4 flex items-center justify-between gap-4">
|
||||||
|
|
||||||
|
<div class="flex gap-4 items-center min-w-[160px] justify-start">
|
||||||
|
@if (bookdropFileUis.length > 0) {
|
||||||
|
<p-button
|
||||||
|
label="Select All"
|
||||||
|
icon="pi pi-check-square"
|
||||||
|
severity="info"
|
||||||
|
(click)="selectAll(true)"
|
||||||
|
outlined
|
||||||
|
pTooltip="Select all files across all pages you have navigated"
|
||||||
|
tooltipPosition="top">
|
||||||
|
</p-button>
|
||||||
|
|
||||||
|
<p-button
|
||||||
|
label="Clear All"
|
||||||
|
icon="pi pi-times-circle"
|
||||||
|
severity="warn"
|
||||||
|
(click)="selectAll(false)"
|
||||||
|
outlined
|
||||||
|
pTooltip="Deselect all files across all pages you have navigated"
|
||||||
|
tooltipPosition="top">
|
||||||
|
</p-button>
|
||||||
|
} @else {
|
||||||
|
<div class="min-w-[160px]"></div>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Center container: paginator, flex-grow and centered -->
|
||||||
|
<div class="flex-grow flex justify-center">
|
||||||
|
<p-paginator
|
||||||
|
[rows]="pageSize"
|
||||||
|
[totalRecords]="totalRecords"
|
||||||
|
[first]="currentPage * pageSize"
|
||||||
|
(onPageChange)="loadPage($event.page ?? 0)"
|
||||||
|
[showCurrentPageReport]="true"
|
||||||
|
currentPageReportTemplate="Showing files {first} - {last} of {totalRecords}">
|
||||||
|
</p-paginator>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Right container: fixed width, right aligned -->
|
||||||
|
<div class="flex gap-4 items-center min-w-[200px] justify-end">
|
||||||
<p-button
|
<p-button
|
||||||
label="Delete Files"
|
[label]="'Delete ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : '')"
|
||||||
icon="pi pi-times"
|
icon="pi pi-times"
|
||||||
severity="danger"
|
severity="danger"
|
||||||
|
[disabled]="!hasSelectedFiles"
|
||||||
outlined
|
outlined
|
||||||
pTooltip="Permanently delete all Bookdrop files and discard any changes"
|
(click)="confirmDelete()"
|
||||||
tooltipPosition="top"
|
pTooltip="Permanently delete selected Bookdrop files and discard any changes"
|
||||||
(click)="confirmDelete()">
|
tooltipPosition="top">
|
||||||
</p-button>
|
</p-button>
|
||||||
}
|
<p-button
|
||||||
|
[label]="saving ? ('Finalizing ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : '') + '...') : ('Finalize ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : ''))"
|
||||||
|
[icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
|
||||||
|
severity="success"
|
||||||
|
outlined
|
||||||
|
[disabled]="!canFinalize || saving"
|
||||||
|
(click)="confirmFinalize()"
|
||||||
|
pTooltip="Move selected files into the chosen library and subpath">
|
||||||
|
</p-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<p-button
|
|
||||||
[label]="saving ? 'Finalize Imports...' : 'Finalize Imports'"
|
|
||||||
[icon]="saving ? 'pi pi-spin pi-spinner' : 'pi pi-save'"
|
|
||||||
severity="success"
|
|
||||||
outlined
|
|
||||||
pTooltip="This will move all staged files into the selected library and subpath."
|
|
||||||
(click)="confirmFinalize()"
|
|
||||||
[disabled]="!canFinalize || saving">
|
|
||||||
</p-button>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+278
-113
@@ -25,6 +25,9 @@ import {BookdropFinalizeResultDialogComponent} from '../bookdrop-finalize-result
|
|||||||
import {DialogService} from 'primeng/dynamicdialog';
|
import {DialogService} from 'primeng/dynamicdialog';
|
||||||
import {BookMetadata} from '../../book/model/book.model';
|
import {BookMetadata} from '../../book/model/book.model';
|
||||||
import {UrlHelperService} from '../../utilities/service/url-helper.service';
|
import {UrlHelperService} from '../../utilities/service/url-helper.service';
|
||||||
|
import {Checkbox} from 'primeng/checkbox';
|
||||||
|
import {NgClass, NgStyle} from '@angular/common';
|
||||||
|
import {Paginator} from 'primeng/paginator';
|
||||||
|
|
||||||
export interface BookdropFileUI {
|
export interface BookdropFileUI {
|
||||||
file: BookdropFile;
|
file: BookdropFile;
|
||||||
@@ -53,7 +56,10 @@ export interface BookdropFileUI {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Divider,
|
Divider,
|
||||||
InputText,
|
InputText,
|
||||||
|
Checkbox,
|
||||||
|
NgStyle,
|
||||||
|
NgClass,
|
||||||
|
Paginator,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class BookdropFileReviewComponent implements OnInit {
|
export class BookdropFileReviewComponent implements OnInit {
|
||||||
@@ -64,28 +70,32 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
private readonly dialogService = inject(DialogService);
|
private readonly dialogService = inject(DialogService);
|
||||||
private readonly appSettingsService = inject(AppSettingsService);
|
private readonly appSettingsService = inject(AppSettingsService);
|
||||||
private readonly messageService = inject(MessageService);
|
private readonly messageService = inject(MessageService);
|
||||||
|
private readonly urlHelper = inject(UrlHelperService);
|
||||||
|
|
||||||
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
|
@ViewChildren('metadataPicker') metadataPickers!: QueryList<BookdropFileMetadataPickerComponent>;
|
||||||
|
|
||||||
|
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
||||||
|
|
||||||
uploadPattern = '';
|
uploadPattern = '';
|
||||||
defaultLibraryId: string | null = null;
|
defaultLibraryId: string | null = null;
|
||||||
defaultPathId: string | null = null;
|
defaultPathId: string | null = null;
|
||||||
bookdropFileUis: BookdropFileUI[] = [];
|
|
||||||
libraries: Library[] = [];
|
libraries: Library[] = [];
|
||||||
|
bookdropFileUis: BookdropFileUI[] = [];
|
||||||
|
fileUiCache: Record<number, BookdropFileUI> = {};
|
||||||
copiedFlags: Record<number, boolean> = {};
|
copiedFlags: Record<number, boolean> = {};
|
||||||
loading = true;
|
loading = true;
|
||||||
saving = false;
|
saving = false;
|
||||||
appSettings$: Observable<AppSettings | null> = this.appSettingsService.appSettings$;
|
|
||||||
|
|
||||||
protected urlHelper = inject(UrlHelperService);
|
pageSize = 50;
|
||||||
|
totalRecords = 0;
|
||||||
|
currentPage = 0;
|
||||||
|
|
||||||
|
selectAllAcrossPages = false;
|
||||||
|
excludedFiles = new Set<number>();
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.bookdropFileService.getPendingFiles()
|
this.loading = true;
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
this.loadPage(0);
|
||||||
.subscribe(files => {
|
|
||||||
this.bookdropFileUis = files.map(file => this.createFileUI(file));
|
|
||||||
this.loading = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
this.libraryService.libraryState$
|
this.libraryService.libraryState$
|
||||||
.pipe(filter(state => !!state?.loaded), take(1))
|
.pipe(filter(state => !!state?.loaded), take(1))
|
||||||
@@ -101,14 +111,82 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get libraryOptions() {
|
get libraryOptions() {
|
||||||
|
if (!this.libraries) return [];
|
||||||
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
|
return this.libraries.map(lib => ({label: lib.name, value: String(lib.id ?? '')}));
|
||||||
}
|
}
|
||||||
|
|
||||||
get selectedLibraryPaths() {
|
get selectedLibraryPaths() {
|
||||||
|
if (!this.libraries) return [];
|
||||||
const selectedLibrary = this.libraries.find(lib => String(lib.id) === this.defaultLibraryId);
|
const selectedLibrary = this.libraries.find(lib => String(lib.id) === this.defaultLibraryId);
|
||||||
return selectedLibrary?.paths.map(path => ({label: path.path, value: String(path.id ?? '')})) ?? [];
|
return selectedLibrary?.paths.map(path => ({label: path.path, value: String(path.id ?? '')})) ?? [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get canApplyDefaults(): boolean {
|
||||||
|
return !!(this.defaultLibraryId && this.defaultPathId);
|
||||||
|
}
|
||||||
|
|
||||||
|
get canFinalize(): boolean {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
return (this.totalRecords - this.excludedFiles.size) > 0 && this.areAllSelectedHaveLibraryAndPath();
|
||||||
|
}
|
||||||
|
const selectedFiles = this.bookdropFileUis.filter(f => f.selected);
|
||||||
|
if (selectedFiles.length === 0) return false;
|
||||||
|
return selectedFiles.every(f => f.selectedLibraryId && f.selectedPathId);
|
||||||
|
}
|
||||||
|
|
||||||
|
get hasSelectedFiles(): boolean {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
return this.totalRecords > this.excludedFiles.size;
|
||||||
|
} else {
|
||||||
|
return Object.values(this.fileUiCache).some(file => file.selected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
get selectedCount(): number {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
return this.totalRecords - this.excludedFiles.size;
|
||||||
|
} else {
|
||||||
|
return Object.values(this.fileUiCache).filter(file => file.selected).length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loadPage(page: number): void {
|
||||||
|
this.bookdropFileService.getPendingFiles(page, this.pageSize)
|
||||||
|
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||||
|
.subscribe({
|
||||||
|
next: response => {
|
||||||
|
this.bookdropFileUis = response.content.map(file => {
|
||||||
|
const cached = this.fileUiCache[file.id];
|
||||||
|
if (cached) {
|
||||||
|
cached.file = file;
|
||||||
|
return cached;
|
||||||
|
} else {
|
||||||
|
const fresh = this.createFileUI(file);
|
||||||
|
|
||||||
|
if (this.defaultLibraryId) {
|
||||||
|
const selectedLib = this.libraries.find(l => String(l.id) === this.defaultLibraryId);
|
||||||
|
const selectedPaths = selectedLib?.paths ?? [];
|
||||||
|
fresh.selectedLibraryId = this.defaultLibraryId;
|
||||||
|
fresh.availablePaths = selectedPaths.map(p => ({id: String(p.id ?? ''), name: p.path}));
|
||||||
|
fresh.selectedPathId = this.defaultPathId ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.fileUiCache[file.id] = fresh;
|
||||||
|
return fresh;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.totalRecords = response.totalElements;
|
||||||
|
this.currentPage = page;
|
||||||
|
this.loading = false;
|
||||||
|
this.syncCurrentPageSelection();
|
||||||
|
},
|
||||||
|
error: err => {
|
||||||
|
console.error('Error loading files:', err);
|
||||||
|
this.loading = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
onLibraryChange(file: BookdropFileUI): void {
|
onLibraryChange(file: BookdropFileUI): void {
|
||||||
const lib = this.libraries.find(l => String(l.id) === file.selectedLibraryId);
|
const lib = this.libraries.find(l => String(l.id) === file.selectedLibraryId);
|
||||||
file.availablePaths = lib?.paths.map(p => ({id: String(p.id ?? ''), name: p.path})) ?? [];
|
file.availablePaths = lib?.paths.map(p => ({id: String(p.id ?? ''), name: p.path})) ?? [];
|
||||||
@@ -120,27 +198,23 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
applyDefaultsToAll(): void {
|
applyDefaultsToAll(): void {
|
||||||
if (!this.defaultLibraryId) return;
|
if (!this.defaultLibraryId || !this.libraries) return;
|
||||||
|
|
||||||
const selectedLib = this.libraries.find(l => String(l.id) === this.defaultLibraryId);
|
const selectedLib = this.libraries.find(l => String(l.id) === this.defaultLibraryId);
|
||||||
const selectedPaths = selectedLib?.paths ?? [];
|
const selectedPaths = selectedLib?.paths ?? [];
|
||||||
|
|
||||||
for (const file of this.bookdropFileUis) {
|
Object.values(this.fileUiCache).forEach(file => {
|
||||||
file.selectedLibraryId = this.defaultLibraryId;
|
file.selectedLibraryId = this.defaultLibraryId;
|
||||||
file.availablePaths = selectedPaths.map(path => ({id: String(path.id), name: path.path}));
|
file.availablePaths = selectedPaths.map(path => ({id: String(path.id), name: path.path}));
|
||||||
file.selectedPathId = this.defaultPathId ?? null;
|
file.selectedPathId = this.defaultPathId ?? null;
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
get canApplyDefaults(): boolean {
|
|
||||||
return !!(this.defaultLibraryId && this.defaultPathId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
copyAll(includeThumbnail: boolean): void {
|
copyAll(includeThumbnail: boolean): void {
|
||||||
for (const fileUi of this.bookdropFileUis) {
|
Object.values(this.fileUiCache).forEach(fileUi => {
|
||||||
const fetched = fileUi.file.fetchedMetadata;
|
const fetched = fileUi.file.fetchedMetadata;
|
||||||
const form = fileUi.metadataForm;
|
const form = fileUi.metadataForm;
|
||||||
if (!fetched) continue;
|
if (!fetched) return;
|
||||||
for (const key of Object.keys(fetched)) {
|
for (const key of Object.keys(fetched)) {
|
||||||
if (!includeThumbnail && key === 'thumbnailUrl') continue;
|
if (!includeThumbnail && key === 'thumbnailUrl') continue;
|
||||||
const value = fetched[key as keyof typeof fetched];
|
const value = fetched[key as keyof typeof fetched];
|
||||||
@@ -150,11 +224,11 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.onMetadataCopied(fileUi.file.id, true);
|
this.onMetadataCopied(fileUi.file.id, true);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
resetAll(): void {
|
resetAll(): void {
|
||||||
for (const fileUi of this.bookdropFileUis) {
|
Object.values(this.fileUiCache).forEach(fileUi => {
|
||||||
const original = fileUi.file.originalMetadata;
|
const original = fileUi.file.originalMetadata;
|
||||||
fileUi.metadataForm.patchValue({
|
fileUi.metadataForm.patchValue({
|
||||||
title: original.title || null,
|
title: original.title || null,
|
||||||
@@ -163,40 +237,75 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
categories: [...(original.categories ?? [])].sort(),
|
categories: [...(original.categories ?? [])].sort(),
|
||||||
publisher: original.publisher || null,
|
publisher: original.publisher || null,
|
||||||
publishedDate: original.publishedDate || null,
|
publishedDate: original.publishedDate || null,
|
||||||
isbn10: original.isbn10 || null,
|
isbn10: original.isbn10 ?? null,
|
||||||
isbn13: original.isbn13 || null,
|
isbn13: original.isbn13 ?? null,
|
||||||
description: original.description || null,
|
description: original.description ?? null,
|
||||||
pageCount: original.pageCount || null,
|
pageCount: original.pageCount ?? null,
|
||||||
language: original.language || null,
|
language: original.language ?? null,
|
||||||
asin: original.asin || null,
|
asin: original.asin ?? null,
|
||||||
amazonRating: original.amazonRating || null,
|
amazonRating: original.amazonRating ?? null,
|
||||||
amazonReviewCount: original.amazonReviewCount || null,
|
amazonReviewCount: original.amazonReviewCount ?? null,
|
||||||
goodreadsId: original.goodreadsId || null,
|
goodreadsId: original.goodreadsId ?? null,
|
||||||
goodreadsRating: original.goodreadsRating || null,
|
goodreadsRating: original.goodreadsRating ?? null,
|
||||||
goodreadsReviewCount: original.goodreadsReviewCount || null,
|
goodreadsReviewCount: original.goodreadsReviewCount ?? null,
|
||||||
hardcoverId: original.hardcoverId || null,
|
hardcoverId: original.hardcoverId ?? null,
|
||||||
hardcoverRating: original.hardcoverRating || null,
|
hardcoverRating: original.hardcoverRating ?? null,
|
||||||
hardcoverReviewCount: original.hardcoverReviewCount || null,
|
hardcoverReviewCount: original.hardcoverReviewCount ?? null,
|
||||||
googleId: original.googleId || null,
|
googleId: original.googleId ?? null,
|
||||||
seriesName: original.seriesName || null,
|
seriesName: original.seriesName ?? null,
|
||||||
seriesNumber: original.seriesNumber || null,
|
seriesNumber: original.seriesNumber ?? null,
|
||||||
seriesTotal: original.seriesTotal || null,
|
seriesTotal: original.seriesTotal ?? null,
|
||||||
thumbnailUrl: this.urlHelper.getBookdropCoverUrl(fileUi.file.id),
|
thumbnailUrl: this.urlHelper.getBookdropCoverUrl(fileUi.file.id),
|
||||||
});
|
});
|
||||||
fileUi.copiedFields = {};
|
fileUi.copiedFields = {};
|
||||||
fileUi.savedFields = {};
|
fileUi.savedFields = {};
|
||||||
}
|
});
|
||||||
this.copiedFlags = {};
|
this.copiedFlags = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
get canFinalize(): boolean {
|
selectAll(selected: boolean): void {
|
||||||
return this.bookdropFileUis.length > 0 &&
|
if (selected) {
|
||||||
this.bookdropFileUis.every(file => file.selectedLibraryId && file.selectedPathId);
|
this.selectAllAcrossPages = true;
|
||||||
|
this.excludedFiles.clear();
|
||||||
|
Object.values(this.fileUiCache).forEach(file => file.selected = true);
|
||||||
|
this.bookdropFileUis.forEach(file => file.selected = true);
|
||||||
|
} else {
|
||||||
|
this.selectAllAcrossPages = false;
|
||||||
|
this.excludedFiles.clear();
|
||||||
|
Object.values(this.fileUiCache).forEach(file => file.selected = false);
|
||||||
|
this.bookdropFileUis.forEach(file => file.selected = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleFileSelection(fileId: number, selected: boolean): void {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
if (!selected) {
|
||||||
|
this.excludedFiles.add(fileId);
|
||||||
|
} else {
|
||||||
|
this.excludedFiles.delete(fileId);
|
||||||
|
}
|
||||||
|
const cachedFile = this.fileUiCache[fileId];
|
||||||
|
if (cachedFile) cachedFile.selected = selected;
|
||||||
|
} else {
|
||||||
|
const cachedFile = this.fileUiCache[fileId];
|
||||||
|
if (cachedFile) cachedFile.selected = selected;
|
||||||
|
}
|
||||||
|
this.syncCurrentPageSelection();
|
||||||
}
|
}
|
||||||
|
|
||||||
confirmFinalize(): void {
|
confirmFinalize(): void {
|
||||||
|
const selectedCount = this.selectedCount;
|
||||||
|
if (selectedCount === 0) {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'warn',
|
||||||
|
summary: 'No files selected',
|
||||||
|
detail: 'Please select files to finalize.',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
this.confirmationService.confirm({
|
this.confirmationService.confirm({
|
||||||
message: 'Are you sure you want to finalize the import?',
|
message: `Are you sure you want to finalize the import of ${selectedCount} file${selectedCount !== 1 ? 's' : ''}?`,
|
||||||
header: 'Confirm Finalize',
|
header: 'Confirm Finalize',
|
||||||
icon: 'pi pi-exclamation-triangle',
|
icon: 'pi pi-exclamation-triangle',
|
||||||
acceptLabel: 'Yes',
|
acceptLabel: 'Yes',
|
||||||
@@ -205,9 +314,123 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
confirmDelete(): void {
|
||||||
|
const selectedCount = this.selectedCount;
|
||||||
|
if (selectedCount === 0) {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'warn',
|
||||||
|
summary: 'No files selected',
|
||||||
|
detail: 'Please select files to delete.',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.confirmationService.confirm({
|
||||||
|
message: `Are you sure you want to delete ${selectedCount} selected Bookdrop file${selectedCount !== 1 ? 's' : ''}? This action cannot be undone.`,
|
||||||
|
header: 'Confirm Delete',
|
||||||
|
icon: 'pi pi-exclamation-triangle',
|
||||||
|
accept: () => {
|
||||||
|
const payload: any = {
|
||||||
|
selectAll: this.selectAllAcrossPages,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
payload.excludedIds = Array.from(this.excludedFiles);
|
||||||
|
} else {
|
||||||
|
payload.selectedIds = Object.values(this.fileUiCache)
|
||||||
|
.filter(file => file.selected)
|
||||||
|
.map(file => file.file.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.bookdropFileService.discardFiles(payload).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'success',
|
||||||
|
summary: 'Files Deleted',
|
||||||
|
detail: 'Selected Bookdrop files were deleted successfully.',
|
||||||
|
});
|
||||||
|
|
||||||
|
const toDelete = Object.values(this.fileUiCache).filter(file => {
|
||||||
|
return this.selectAllAcrossPages
|
||||||
|
? !this.excludedFiles.has(file.file.id)
|
||||||
|
: file.selected;
|
||||||
|
});
|
||||||
|
toDelete.forEach(file => delete this.fileUiCache[file.file.id]);
|
||||||
|
|
||||||
|
this.selectAllAcrossPages = false;
|
||||||
|
this.excludedFiles.clear();
|
||||||
|
this.loadPage(this.currentPage);
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
console.error('Error deleting files:', err);
|
||||||
|
this.messageService.add({
|
||||||
|
severity: 'error',
|
||||||
|
summary: 'Delete Failed',
|
||||||
|
detail: 'An error occurred while deleting Bookdrop files.',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private areAllSelectedHaveLibraryAndPath(): boolean {
|
||||||
|
return Object.values(this.fileUiCache).every(file => {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
if (this.excludedFiles.has(file.file.id)) return true;
|
||||||
|
return file.selectedLibraryId != null && file.selectedPathId != null;
|
||||||
|
} else {
|
||||||
|
if (!file.selected) return true;
|
||||||
|
return file.selectedLibraryId != null && file.selectedPathId != null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private syncCurrentPageSelection(): void {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
this.bookdropFileUis.forEach(fileUi => {
|
||||||
|
fileUi.selected = !this.excludedFiles.has(fileUi.file.id);
|
||||||
|
const cachedFile = this.fileUiCache[fileUi.file.id];
|
||||||
|
if (cachedFile) cachedFile.selected = fileUi.selected;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private finalizeImport(): void {
|
private finalizeImport(): void {
|
||||||
this.saving = true;
|
this.saving = true;
|
||||||
const payload = this.buildFinalizePayload();
|
|
||||||
|
const selectedFiles = Object.values(this.fileUiCache).filter(file => {
|
||||||
|
if (this.selectAllAcrossPages) {
|
||||||
|
return !this.excludedFiles.has(file.file.id);
|
||||||
|
} else {
|
||||||
|
return file.selected;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const files = selectedFiles.map(fileUi => {
|
||||||
|
const rawMetadata = fileUi.metadataForm.value;
|
||||||
|
const metadata = {...rawMetadata};
|
||||||
|
|
||||||
|
if (metadata.thumbnailUrl?.includes('/api/bookdrop/')) {
|
||||||
|
delete metadata.thumbnailUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
fileId: fileUi.file.id,
|
||||||
|
libraryId: Number(fileUi.selectedLibraryId),
|
||||||
|
pathId: Number(fileUi.selectedPathId),
|
||||||
|
metadata,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload: BookdropFinalizePayload = {
|
||||||
|
uploadPattern: this.uploadPattern,
|
||||||
|
selectAll: this.selectAllAcrossPages,
|
||||||
|
excludedIds: this.selectAllAcrossPages ? Array.from(this.excludedFiles) : undefined,
|
||||||
|
defaultLibraryId: this.defaultLibraryId ? Number(this.defaultLibraryId) : undefined,
|
||||||
|
defaultPathId: this.defaultPathId ? Number(this.defaultPathId) : undefined,
|
||||||
|
files,
|
||||||
|
};
|
||||||
|
|
||||||
this.bookdropFileService.finalizeImport(payload).subscribe({
|
this.bookdropFileService.finalizeImport(payload).subscribe({
|
||||||
next: (result: BookdropFinalizeResult) => {
|
next: (result: BookdropFinalizeResult) => {
|
||||||
@@ -224,12 +447,18 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
modal: true,
|
modal: true,
|
||||||
closable: true,
|
closable: true,
|
||||||
closeOnEscape: true,
|
closeOnEscape: true,
|
||||||
data: {
|
data: {results: result.results},
|
||||||
results: result.results
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
this.reloadPendingFiles();
|
const finalizedIds = new Set(files.map(f => f.fileId));
|
||||||
|
Object.keys(this.fileUiCache).forEach(idStr => {
|
||||||
|
const id = Number(idStr);
|
||||||
|
if (finalizedIds.has(id)) delete this.fileUiCache[id];
|
||||||
|
});
|
||||||
|
|
||||||
|
this.selectAllAcrossPages = false;
|
||||||
|
this.excludedFiles.clear();
|
||||||
|
this.loadPage(this.currentPage);
|
||||||
},
|
},
|
||||||
error: (err) => {
|
error: (err) => {
|
||||||
console.error('Error finalizing import:', err);
|
console.error('Error finalizing import:', err);
|
||||||
@@ -243,70 +472,6 @@ export class BookdropFileReviewComponent implements OnInit {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildFinalizePayload(): BookdropFinalizePayload {
|
|
||||||
return {
|
|
||||||
uploadPattern: this.uploadPattern,
|
|
||||||
files: this.bookdropFileUis.map((fileUi, index) => {
|
|
||||||
const rawMetadata = this.bookdropFileUis[index].metadataForm.value;
|
|
||||||
const metadata = {...rawMetadata};
|
|
||||||
if (metadata.thumbnailUrl?.includes('/api/bookdrop/')) {
|
|
||||||
delete metadata.thumbnailUrl;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
fileId: fileUi.file.id,
|
|
||||||
libraryId: Number(fileUi.selectedLibraryId),
|
|
||||||
pathId: Number(fileUi.selectedPathId),
|
|
||||||
metadata,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private reloadPendingFiles(): void {
|
|
||||||
this.loading = true;
|
|
||||||
this.bookdropFileService.getPendingFiles()
|
|
||||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
|
||||||
.subscribe({
|
|
||||||
next: files => {
|
|
||||||
this.bookdropFileUis = files.map(file => this.createFileUI(file));
|
|
||||||
this.loading = false;
|
|
||||||
this.saving = false;
|
|
||||||
},
|
|
||||||
error: err => {
|
|
||||||
console.error('Error loading pending files:', err);
|
|
||||||
this.loading = false;
|
|
||||||
this.saving = false;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
confirmDelete(): void {
|
|
||||||
this.confirmationService.confirm({
|
|
||||||
message: 'Are you sure you want to delete all Bookdrop files? This action cannot be undone.',
|
|
||||||
header: 'Confirm Delete',
|
|
||||||
icon: 'pi pi-exclamation-triangle',
|
|
||||||
accept: () => {
|
|
||||||
this.bookdropFileService.discardAllFile().subscribe({
|
|
||||||
next: () => {
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'success',
|
|
||||||
summary: 'Files Deleted',
|
|
||||||
detail: 'All Bookdrop files were deleted successfully.',
|
|
||||||
});
|
|
||||||
this.reloadPendingFiles();
|
|
||||||
},
|
|
||||||
error: (err) => {
|
|
||||||
this.messageService.add({
|
|
||||||
severity: 'error',
|
|
||||||
summary: 'Delete Failed',
|
|
||||||
detail: 'An error occurred while deleting Bookdrop files.',
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private createMetadataForm(original: BookMetadata, bookdropFileId: number): FormGroup {
|
private createMetadataForm(original: BookMetadata, bookdropFileId: number): FormGroup {
|
||||||
return new FormGroup({
|
return new FormGroup({
|
||||||
title: new FormControl(original.title ?? ''),
|
title: new FormControl(original.title ?? ''),
|
||||||
|
|||||||
@@ -12,7 +12,11 @@ export enum BookdropFileStatus {
|
|||||||
|
|
||||||
export interface BookdropFinalizePayload {
|
export interface BookdropFinalizePayload {
|
||||||
uploadPattern: string;
|
uploadPattern: string;
|
||||||
files: {
|
selectAll?: boolean;
|
||||||
|
excludedIds?: number[];
|
||||||
|
defaultLibraryId?: number;
|
||||||
|
defaultPathId?: number;
|
||||||
|
files?: {
|
||||||
fileId: number;
|
fileId: number;
|
||||||
libraryId: number;
|
libraryId: number;
|
||||||
pathId: number;
|
pathId: number;
|
||||||
@@ -43,22 +47,27 @@ export interface BookdropFinalizeResult {
|
|||||||
results: BookdropFileResult[];
|
results: BookdropFileResult[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@Injectable({
|
export interface Page<T> {
|
||||||
providedIn: 'root',
|
content: T[];
|
||||||
})
|
totalElements: number;
|
||||||
|
totalPages: number;
|
||||||
|
number: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable({providedIn: 'root'})
|
||||||
export class BookdropFileTaskService {
|
export class BookdropFileTaskService {
|
||||||
private readonly url = `${API_CONFIG.BASE_URL}/api/bookdrop`;
|
private readonly url = `${API_CONFIG.BASE_URL}/api/bookdrop`;
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
|
|
||||||
getPendingFiles(): Observable<BookdropFile[]> {
|
getPendingFiles(page: number = 0, size: number = 50): Observable<Page<BookdropFile>> {
|
||||||
return this.http.get<BookdropFile[]>(`${this.url}/files?status=pending`);
|
return this.http.get<Page<BookdropFile>>(`${this.url}/files?status=pending&page=${page}&size=${size}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
finalizeImport(payload: BookdropFinalizePayload): Observable<BookdropFinalizeResult> {
|
finalizeImport(payload: BookdropFinalizePayload): Observable<BookdropFinalizeResult> {
|
||||||
return this.http.post<BookdropFinalizeResult>(`${this.url}/imports/finalize`, payload);
|
return this.http.post<BookdropFinalizeResult>(`${this.url}/imports/finalize`, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
discardAllFile(): Observable<void> {
|
discardFiles(payload: { selectAll: boolean; excludedIds?: number[]; selectedIds?: number[] }): Observable<void> {
|
||||||
return this.http.delete<void>(`${this.url}/files`);
|
return this.http.post<void>(`${this.url}/files/discard`, payload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user