Refine bookdrop results and related websocket events

This commit is contained in:
aditya.chandel
2025-08-16 10:18:33 -06:00
committed by Aditya Chandel
parent c75c4dce5b
commit a092d629c9
26 changed files with 288 additions and 120 deletions
@@ -45,6 +45,12 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
private static final ConcurrentMap<String, Object> userLocks = new ConcurrentHashMap<>();
private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor;
private static final List<String> WHITELISTED_PATHS = List.of(
"/api/v1/opds/",
"/api/v1/auth/refresh",
"/api/v1/setup/"
);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
@@ -52,7 +58,9 @@ public class DualJwtAuthenticationFilter extends OncePerRequestFilter {
String path = request.getRequestURI();
if (path.startsWith("/api/v1/opds/") || path.equals("/api/v1/auth/refresh") || path.equals("/api/v1/setup/status")) {
boolean isWhitelisted = WHITELISTED_PATHS.stream().anyMatch(path::startsWith);
if (isWhitelisted) {
chain.doFilter(request, response);
return;
}
@@ -48,7 +48,7 @@ public class SecurityConfig {
"/ws/**",
"/api/v1/auth/**",
"/api/v1/public-settings",
"/api/v1/setup/status",
"/api/v1/setup/**",
"/api/v1/books/*/cover",
"/api/v1/books/*/backup-cover",
"/api/v1/opds/*/cover.jpg",
@@ -1,34 +0,0 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.stereotype.Controller;
@Controller
public class NotificationController {
/*@MessageMapping("/send")
@SendTo("/topic/messages")
public String sendMessage(String message) {
System.out.println("Received message: " + message);
return "Hello";
}*/
private final NotificationService notificationService;
@Autowired
public NotificationController(NotificationService notificationService) {
this.notificationService = notificationService;
}
@MessageMapping("/send")
public void handleIncomingMessage(Object message) {
System.out.println("Received message: " + message);
}
public void sendMessageToTopic(Topic topic, Object message) {
notificationService.sendMessage(topic, message);
}
}
@@ -0,0 +1,17 @@
package com.adityachandel.booklore.model.dto.response;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
import java.util.List;
@Data
@Builder
public class BookdropBatchResult {
private int totalFiles;
private int successfullyImported;
private int failed;
private Instant processedAt;
private List<BookdropFileResult> fileResults;
}
@@ -3,12 +3,17 @@ package com.adityachandel.booklore.model.dto.response;
import lombok.Builder;
import lombok.Data;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Data
@Builder
public class BookdropFinalizeResult {
private int totalFiles;
private int successfullyImported;
private int failed;
private Instant processedAt;
@Builder.Default
private List<BookdropFileResult> results = new ArrayList<>();
}
@@ -0,0 +1,12 @@
package com.adityachandel.booklore.model.enums;
public enum PermissionType {
UPLOAD,
DOWNLOAD,
EDIT_METADATA,
MANIPULATE_LIBRARY,
EMAIL_BOOK,
DELETE_BOOK,
SYNC_KOREADER,
ADMIN
}
@@ -1,12 +1,22 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.config.security.AuthenticationService;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.UserRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import static com.adityachandel.booklore.util.UserPermissionUtils.hasPermission;
@Slf4j
@Service
@AllArgsConstructor
@@ -14,6 +24,7 @@ public class NotificationService {
private final SimpMessagingTemplate messagingTemplate;
private final AuthenticationService authenticationService;
private final UserRepository userRepository;
public void sendMessage(Topic topic, Object message) {
try {
@@ -28,4 +39,28 @@ public class NotificationService {
log.error("Error sending message to topic {}: {}", topic, e.getMessage(), e);
}
}
public void sendMessageToPermissions(Topic topic, Object message, Set<PermissionType> permissionTypes) {
if (permissionTypes == null || permissionTypes.isEmpty()) return;
Set<PermissionType> permissionSet = EnumSet.noneOf(PermissionType.class);
permissionSet.addAll(permissionTypes);
try {
List<BookLoreUserEntity> users = userRepository.findAll();
for (BookLoreUserEntity user : users) {
UserPermissionsEntity perms = user.getPermissions();
if (perms != null) {
for (PermissionType p : permissionSet) {
if (hasPermission(perms, p)) {
messagingTemplate.convertAndSendToUser(user.getUsername(), topic.getPath(), message);
break;
}
}
}
}
} catch (Exception e) {
log.error("Error sending message to users with permissions {}: {}", permissionSet, e.getMessage(), e);
}
}
}
@@ -92,7 +92,9 @@ public class BookDropService {
if (monitoringWasActive) monitoringService.pauseMonitoring();
bookdropMonitoringService.pauseMonitoring();
BookdropFinalizeResult results = BookdropFinalizeResult.builder().build();
BookdropFinalizeResult results = BookdropFinalizeResult.builder()
.processedAt(Instant.now())
.build();
Long defaultLibraryId = request.getDefaultLibraryId();
Long defaultPathId = request.getDefaultPathId();
@@ -103,6 +105,7 @@ public class BookDropService {
final int CHUNK_SIZE = 100;
AtomicInteger failedCount = new AtomicInteger();
AtomicInteger totalFilesProcessed = new AtomicInteger();
log.info("Starting finalizeImport: selectAll={}, provided file count={}, defaultLibraryId={}, defaultPathId={}",
request.getSelectAll(), metadataById.size(), defaultLibraryId, defaultPathId);
@@ -110,7 +113,7 @@ public class BookDropService {
if (Boolean.TRUE.equals(request.getSelectAll())) {
List<Long> excludedIds = Optional.ofNullable(request.getExcludedIds()).orElse(List.of());
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds); // You need to write this
List<Long> allIds = bookdropFileRepository.findAllExcludingIdsFlat(excludedIds);
log.info("SelectAll: Total files to finalize (after exclusions): {}, Excluded IDs: {}", allIds.size(), excludedIds);
for (int i = 0; i < allIds.size(); i += CHUNK_SIZE) {
@@ -127,9 +130,11 @@ public class BookDropService {
if (file == null) {
log.warn("File ID {} missing in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
} else {
@@ -156,17 +161,23 @@ public class BookDropService {
if (file == null) {
log.error("File ID {} not found in DB during finalizeImport chunk processing", id);
failedCount.incrementAndGet();
totalFilesProcessed.incrementAndGet();
continue;
}
processFile(file, metadataById.get(id), defaultLibraryId, defaultPathId, results, failedCount);
totalFilesProcessed.incrementAndGet();
}
}
}
results.setTotalFiles(totalFilesProcessed.get());
results.setFailed(failedCount.get());
results.setSuccessfullyImported(totalFilesProcessed.get() - failedCount.get());
log.info("Finalization complete. Success: {}, Failed: {}, Total processed: {}",
results.getResults().stream().filter(BookdropFileResult::isSuccess).count(),
failedCount.get(),
results.getResults().size());
results.getSuccessfullyImported(),
results.getFailed(),
results.getTotalFiles());
if (monitoringWasActive) {
Thread.startVirtualThread(() -> {
@@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.model.BookDropFileEvent;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.LogNotification;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookdropFileRepository;
@@ -19,6 +20,8 @@ import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
@@ -72,6 +75,7 @@ public class BookdropEventHandlerService {
public void processFile(BookDropFileEvent event) {
Path file = event.getFile();
WatchEvent.Kind<?> kind = event.getKind();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
try {
if (!Files.exists(file)) {
@@ -100,7 +104,11 @@ public class BookdropEventHandlerService {
log.info("Handling new bookdrop file: {}", file);
int queueSize = fileQueue.size();
notificationService.sendMessage(Topic.LOG, new LogNotification("Processing bookdrop file: " + fileName + " (" + queueSize + " books remaining)"));
notificationService.sendMessageToPermissions(
Topic.LOG,
new LogNotification("Processing bookdrop file: " + fileName + " (" + queueSize + " files remaining)"),
Set.of(PermissionType.ADMIN, PermissionType.MANIPULATE_LIBRARY)
);
BookdropFileEntity bookdropFileEntity = BookdropFileEntity.builder()
.filePath(filePath)
@@ -118,20 +126,36 @@ public class BookdropEventHandlerService {
bookdropMetadataService.attachFetchedMetadata(bookdropFileEntity.getId());
} else {
bookdropMetadataService.attachInitialMetadata(bookdropFileEntity.getId());
log.info("Metadata download is disabled in settings. Only initial metadata extracted for file: {}", bookdropFileEntity.getFileName());
log.info("Metadata download is disabled. Only initial metadata extracted for file: {}", bookdropFileEntity.getFileName());
}
bookdropNotificationService.sendBookdropFileSummaryNotification();
notificationService.sendMessage(Topic.LOG, new LogNotification("Finished processing bookdrop file: " + fileName + " (" + queueSize + " books remaining)"));
if (fileQueue.isEmpty()) {
notificationService.sendMessageToPermissions(
Topic.LOG,
new LogNotification("All bookdrop files have finished processing"),
Set.of(PermissionType.ADMIN, PermissionType.MANIPULATE_LIBRARY)
);
} else {
notificationService.sendMessageToPermissions(
Topic.LOG,
new LogNotification("Finished processing bookdrop file: " + fileName + " (" + fileQueue.size() + " files remaining)"),
Set.of(PermissionType.ADMIN, PermissionType.MANIPULATE_LIBRARY)
);
}
} catch (Exception e) {
log.error("Error handling bookdrop file: {}", file, e);
}
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
String deletedPath = event.getFile().toAbsolutePath().toString();
String deletedPath = file.toAbsolutePath().toString();
log.info("Detected deletion event: {}", deletedPath);
int deletedCount = bookdropFileRepository.deleteAllByFilePathStartingWith(deletedPath);
log.info("Deleted {} BookdropFile record(s) from database matching path: {}", deletedCount, deletedPath);
bookdropNotificationService.sendBookdropFileSummaryNotification();
}
}
@@ -2,12 +2,16 @@ package com.adityachandel.booklore.service.bookdrop;
import com.adityachandel.booklore.model.dto.BookdropFileNotification;
import com.adityachandel.booklore.model.entity.BookdropFileEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookdropFileRepository;
import com.adityachandel.booklore.service.NotificationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
import java.util.Set;
@Service
@AllArgsConstructor
@@ -26,6 +30,6 @@ public class BookdropNotificationService {
Instant.now().toString()
);
notificationService.sendMessage(Topic.BOOKDROP_FILE, summaryNotification);
notificationService.sendMessageToPermissions(Topic.BOOKDROP_FILE, summaryNotification, Set.of(PermissionType.ADMIN, PermissionType.MANIPULATE_LIBRARY));
}
}
@@ -10,6 +10,7 @@ import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.EmailProviderRepository;
import com.adityachandel.booklore.repository.EmailRecipientRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import com.adityachandel.booklore.util.FileUtils;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
@@ -54,8 +55,7 @@ public class EmailService {
String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
notificationService.sendMessage(Topic.LOG, createLogNotification(logMessage));
log.info(logMessage);
Thread.startVirtualThread(() -> {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
sendEmail(emailProvider, recipientEmail, book);
String successMessage = "The book: " + bookTitle + " has been successfully sent to " + recipientEmail;
@@ -19,6 +19,7 @@ import com.adityachandel.booklore.repository.LibraryPathRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.repository.UserRepository;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import com.adityachandel.booklore.service.fileprocessor.FileProcessingUtils;
import com.adityachandel.booklore.service.monitoring.MonitoringService;
import jakarta.annotation.PostConstruct;
@@ -27,7 +28,6 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@@ -121,7 +121,7 @@ public class LibraryService {
}
if (!newPaths.isEmpty()) {
Thread.startVirtualThread(() -> {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
libraryProcessingService.processLibrary(libraryId);
} catch (InvalidDataAccessApiUsageException e) {
@@ -160,7 +160,7 @@ public class LibraryService {
}
}
Thread.startVirtualThread(() -> {
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
libraryProcessingService.processLibrary(libraryId);
} catch (InvalidDataAccessApiUsageException e) {
@@ -175,20 +175,16 @@ public class LibraryService {
}
public void rescanLibrary(long libraryId) {
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
Thread.startVirtualThread(() -> {
libraryRepository.findById(libraryId)
.orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(currentAuth);
SecurityContextHolder.setContext(context);
libraryProcessingService.rescanLibrary(libraryId);
} catch (InvalidDataAccessApiUsageException e) {
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
} catch (IOException e) {
log.error("Error while parsing library books", e);
} finally {
SecurityContextHolder.clearContext();
}
log.info("Parsing task completed!");
});
@@ -13,7 +13,6 @@ import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest;
import com.adityachandel.booklore.model.dto.request.ToggleAllLockRequest;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.Lock;
import com.adityachandel.booklore.model.enums.MetadataProvider;
import com.adityachandel.booklore.model.websocket.Topic;
@@ -21,6 +20,7 @@ import com.adityachandel.booklore.repository.BookMetadataRepository;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.BookQueryService;
import com.adityachandel.booklore.service.NotificationService;
import com.adityachandel.booklore.util.SecurityContextVirtualThread;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessor;
import com.adityachandel.booklore.service.fileprocessor.BookFileProcessorRegistry;
@@ -170,23 +170,30 @@ public class BookMetadataService {
}
public void regenerateCovers() {
Thread.startVirtualThread(() -> {
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
.filter(book -> book.getMetadata().getCoverLocked() == null || !book.getMetadata().getCoverLocked())
.toList();
int total = books.size();
notificationService.sendMessage(Topic.LOG, createLogNotification("Started regenerating covers for " + total + " books"));
int[] current = {1};
for (BookEntity book : books) {
try {
String progress = "(" + current[0] + "/" + total + ") ";
regenerateCoverForBook(book, progress);
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage());
SecurityContextVirtualThread.runWithSecurityContext(() -> {
try {
List<BookEntity> books = bookQueryService.getAllFullBookEntities().stream()
.filter(book -> book.getMetadata().getCoverLocked() == null || !book.getMetadata().getCoverLocked())
.toList();
int total = books.size();
notificationService.sendMessage(Topic.LOG, createLogNotification("Started regenerating covers for " + total + " books"));
int[] current = {1};
for (BookEntity book : books) {
try {
String progress = "(" + current[0] + "/" + total + ") ";
regenerateCoverForBook(book, progress);
} catch (Exception e) {
log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage());
}
current[0]++;
}
current[0]++;
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished regenerating covers"));
} catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), e);
notificationService.sendMessage(Topic.LOG, createLogNotification("Error during cover regeneration: " + e.getMessage()));
}
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished regenerating covers"));
});
}
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.mapper.BookMapper;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.service.NotificationService;
@@ -20,6 +21,9 @@ import java.nio.file.Paths;
import java.time.Instant;
import java.util.*;
import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN;
import static com.adityachandel.booklore.model.enums.PermissionType.MANIPULATE_LIBRARY;
@Slf4j
@Service
@AllArgsConstructor
@@ -48,7 +52,7 @@ public class BookFilePersistenceService {
} else {
log.info("[FILE_CREATE] Book with hash '{}' already exists at same path. Skipping update.", currentHash);
}
notificationService.sendMessage(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false));
notificationService.sendMessageToPermissions(Topic.BOOK_ADD, bookMapper.toBookWithDescription(book, false), Set.of(ADMIN, MANIPULATE_LIBRARY));
}
@Transactional(readOnly = true)
@@ -7,6 +7,7 @@ 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.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.NotificationService;
@@ -20,7 +21,10 @@ import org.springframework.stereotype.Service;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static com.adityachandel.booklore.model.enums.PermissionType.ADMIN;
import static com.adityachandel.booklore.model.enums.PermissionType.MANIPULATE_LIBRARY;
import static com.adityachandel.booklore.model.websocket.LogNotification.createLogNotification;
@Slf4j
@@ -48,7 +52,7 @@ public class BookFileTransactionalHandler {
String fileName = path.getFileName().toString();
String libraryPath = bookFilePersistenceService.findMatchingLibraryPath(libraryEntity, path);
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing file: " + filePath));
notificationService.sendMessageToPermissions(Topic.LOG, createLogNotification("Started processing file: " + filePath), Set.of(ADMIN, MANIPULATE_LIBRARY));
LibraryPathEntity libraryPathEntity = bookFilePersistenceService.getLibraryPathEntityForFile(libraryEntity, libraryPath);
@@ -64,7 +68,7 @@ public class BookFileTransactionalHandler {
libraryProcessingService.processLibraryFiles(List.of(libraryFile), libraryEntity);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing file: " + filePath));
notificationService.sendMessageToPermissions(Topic.LOG, createLogNotification("Finished processing file: " + filePath), Set.of(ADMIN, MANIPULATE_LIBRARY));
log.info("[CREATE] Completed processing for file '{}'", filePath);
}
}
@@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.LibraryEntity;
import com.adityachandel.booklore.model.entity.LibraryPathEntity;
import com.adityachandel.booklore.model.enums.BookFileExtension;
import com.adityachandel.booklore.model.enums.PermissionType;
import com.adityachandel.booklore.model.websocket.Topic;
import com.adityachandel.booklore.repository.LibraryRepository;
import com.adityachandel.booklore.service.FileFingerprint;
@@ -18,6 +19,7 @@ import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.*;
@@ -108,7 +110,7 @@ public class LibraryFileEventProcessor {
.ifPresentOrElse(book -> {
book.setDeleted(true);
bookFilePersistenceService.save(book);
notificationService.sendMessage(Topic.BOOKS_REMOVE, Set.of(book.getId()));
notificationService.sendMessageToPermissions(Topic.BOOKS_REMOVE, Set.of(book.getId()), Set.of(PermissionType.ADMIN, PermissionType.MANIPULATE_LIBRARY));
log.info("[MARKED_DELETED] Book '{}' marked as deleted", fileName);
}, () -> log.warn("[NOT_FOUND] Book for deleted path '{}' not found", path));
@@ -0,0 +1,23 @@
package com.adityachandel.booklore.util;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityContextVirtualThread {
public static void runWithSecurityContext(Runnable task) {
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
Thread.startVirtualThread(() -> {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(currentAuth);
SecurityContextHolder.setContext(context);
try {
task.run();
} finally {
SecurityContextHolder.clearContext();
}
});
}
}
@@ -0,0 +1,20 @@
package com.adityachandel.booklore.util;
import com.adityachandel.booklore.model.entity.UserPermissionsEntity;
import com.adityachandel.booklore.model.enums.PermissionType;
public class UserPermissionUtils {
public static boolean hasPermission(UserPermissionsEntity perms, PermissionType type) {
return switch (type) {
case UPLOAD -> perms.isPermissionUpload();
case DOWNLOAD -> perms.isPermissionDownload();
case EDIT_METADATA -> perms.isPermissionEditMetadata();
case MANIPULATE_LIBRARY -> perms.isPermissionManipulateLibrary();
case EMAIL_BOOK -> perms.isPermissionEmailBook();
case DELETE_BOOK -> perms.isPermissionDeleteBook();
case SYNC_KOREADER -> perms.isPermissionSyncKoreader();
case ADMIN -> perms.isPermissionAdmin();
};
}
}
@@ -40,7 +40,7 @@ class BookdropNotificationServiceTest {
bookdropNotificationService.sendBookdropFileSummaryNotification();
ArgumentCaptor<BookdropFileNotification> captor = ArgumentCaptor.forClass(BookdropFileNotification.class);
verify(notificationService).sendMessage(eq(Topic.BOOKDROP_FILE), captor.capture());
verify(notificationService).sendMessageToPermissions(eq(Topic.BOOKDROP_FILE), captor.capture(), anySet());
BookdropFileNotification sentNotification = captor.getValue();
@@ -56,6 +56,6 @@ class BookdropNotificationServiceTest {
bookdropNotificationService.sendBookdropFileSummaryNotification();
verify(notificationService).sendMessage(eq(Topic.BOOKDROP_FILE), any(BookdropFileNotification.class));
verify(notificationService).sendMessageToPermissions(eq(Topic.BOOKDROP_FILE), any(BookdropFileNotification.class), anySet());
}
}
@@ -13,7 +13,7 @@
<div class="absolute inset-0 flex items-center justify-center z-50 rounded-xl">
<div class="flex flex-col items-center space-y-3">
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
<p-progressSpinner class="w-8 h-8" strokeWidth="4"/>
<span class="text-gray-300">Loading Bookdrop files. Please wait...</span>
</div>
</div>
@@ -23,7 +23,7 @@
<div class="px-6 pb-2">
@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">
<p-progressSpinner styleClass="w-8 h-8" strokeWidth="4"/>
<p-progressSpinner class="w-8 h-8" strokeWidth="4"/>
<div class="bg-gray-900/90 px-4 py-2 rounded-md">
<span class="text-sm text-gray-200 text-center">
Organizing and moving files to their designated libraries. Please wait...
@@ -246,7 +246,6 @@
}
</div>
<!-- Center container: paginator, flex-grow and centered -->
<div class="flex-grow flex justify-center">
<p-paginator
[rows]="pageSize"
@@ -258,7 +257,6 @@
</p-paginator>
</div>
<!-- Right container: fixed width, right aligned -->
<div class="flex gap-4 items-center min-w-[200px] justify-end">
<p-button
[label]="'Delete ' + selectedCount + ' File' + (selectedCount !== 1 ? 's' : '')"
@@ -116,7 +116,7 @@ export class BookdropFileReviewComponent implements OnInit {
const selected = this.libraries.find((lib) => lib?.id && String(lib.id) === value)
if (selected && selected.paths.length ===1) {
if (selected && selected.paths.length === 1) {
this.defaultPathId = String(selected.paths[0].id)
}
}
@@ -458,7 +458,7 @@ export class BookdropFileReviewComponent implements OnInit {
modal: true,
closable: true,
closeOnEscape: true,
data: {results: result.results},
data: {result: result},
});
const finalizedIds = new Set(files.map(f => f.fileId));
@@ -42,6 +42,10 @@ export interface BookdropFileResult {
}
export interface BookdropFinalizeResult {
totalFiles: number;
successfullyImported: number;
failed: number;
processedAt: string;
results: BookdropFileResult[];
}
@@ -1,26 +1,53 @@
<ul class="space-y-3">
@for (result of results; track result) {
<li
class="flex items-start gap-3 p-3 rounded-xl border shadow-sm transition-colors"
[ngClass]="{
'bg-green-800/10 border-green-500/40 text-green-100': result.success,
'bg-red-800/10 border-red-500/40 text-red-100': !result.success
}"
>
<i
class="pi text-xl mt-1"
[ngClass]="{
'pi-check-circle text-green-500': result.success,
'pi-times-circle text-red-500': !result.success
}"
></i>
<div class="flex flex-col">
<span class="font-medium text-sm text-white">
{{ result.fileName }}
</span>
<span class="text-sm text-gray-400">{{ result.message }}</span>
<div class="max-w-3xl mx-auto">
<div class="mb-8">
<div class="p-6 bg-zinc-800/50 rounded-xl border border-zinc-500">
<div class="grid grid-cols-3 gap-6 mb-6">
<div class="text-center p-4 bg-zinc-700/30 rounded-lg">
<div class="text-3xl font-bold text-blue-400 mb-1">{{ result.totalFiles }}</div>
<div class="text-sm text-gray-400 font-medium">Total Files</div>
</div>
<div class="text-center p-4 bg-zinc-700/30 rounded-lg">
<div class="text-3xl font-bold text-green-400 mb-1">{{ result.successfullyImported }}</div>
<div class="text-sm text-gray-400 font-medium">Successfully Imported</div>
</div>
<div class="text-center p-4 bg-zinc-700/30 rounded-lg">
<div class="text-3xl font-bold text-red-400 mb-1">{{ result.failed }}</div>
<div class="text-sm text-gray-400 font-medium">Failed</div>
</div>
</div>
</li>
}
</ul>
<div class="text-center pt-4 border-t border-zinc-600">
<div class="text-sm text-gray-300 mb-1">Processed at</div>
<div class="text-base text-white font-mono">{{ result.processedAt | date:'medium' }}</div>
</div>
</div>
</div>
<div class="max-h-[35rem] overflow-y-scroll">
<ul class="space-y-3 px-4">
@for (r of result.results; track r) {
<li
class="flex items-start gap-3 p-3 rounded-xl border shadow-sm transition-colors"
[ngClass]="{
'bg-green-800/10 border-green-500/40 text-green-100': r.success,
'bg-red-800/10 border-red-500/40 text-red-100': !r.success
}"
>
<i
class="pi text-xl mt-1"
[ngClass]="{
'pi-check-circle text-green-500': r.success,
'pi-times-circle text-red-500': !r.success
}"
></i>
<div class="flex flex-col">
<span class="font-medium text-sm text-white">
{{ r.fileName }}
</span>
<span class="text-sm text-gray-400">{{ r.message }}</span>
</div>
</li>
}
</ul>
</div>
</div>
@@ -1,22 +1,23 @@
import {Component, OnDestroy} from '@angular/core';
import {NgClass} from '@angular/common';
import {BookdropFileResult} from '../bookdrop-file-task.service';
import {DatePipe, NgClass} from '@angular/common';
import {BookdropFinalizeResult} from '../bookdrop-file-task.service';
import {DynamicDialogConfig, DynamicDialogRef} from "primeng/dynamicdialog";
@Component({
selector: 'app-bookdrop-finalize-result-dialog-component',
imports: [
NgClass
NgClass,
DatePipe
],
templateUrl: './bookdrop-finalize-result-dialog-component.html',
styleUrl: './bookdrop-finalize-result-dialog-component.scss'
})
export class BookdropFinalizeResultDialogComponent implements OnDestroy {
results: BookdropFileResult[] = [];
result: BookdropFinalizeResult;
constructor(public ref: DynamicDialogRef, public config: DynamicDialogConfig) {
this.results = config.data.results;
this.result = config.data.result;
}
ngOnDestroy(): void {
@@ -20,10 +20,10 @@
@if (permissions.admin || permissions.canManipulateLibrary) {
<div>
<h1 class="no-library-header">
Welcome to BookLore! 📚<br>
Welcome to BookLore!<br>
Let's create your first library
</h1>
<p class="text-gray-300 text-lg mb-8 max-w-md mx-auto leading-relaxed">
<p class="text-gray-300 mb-8 mx-auto leading-relaxed">
A library is where all your books live. Start building your digital collection today!
</p>
<p-button
@@ -47,7 +47,7 @@
}
.dashboard .no-library-header {
font-size: 2rem;
font-size: 1.75rem;
font-weight: 700;
margin-bottom: 2rem;
background: linear-gradient(135deg, #ffffff, #e2e8f0, var(--p-primary-500));