Refine bookdrop results and related websocket events
This commit is contained in:
committed by
Aditya Chandel
parent
c75c4dce5b
commit
a092d629c9
+9
-1
@@ -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;
|
||||
}
|
||||
|
||||
+1
-1
@@ -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",
|
||||
|
||||
-34
@@ -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);
|
||||
}
|
||||
}
|
||||
+17
@@ -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;
|
||||
}
|
||||
+5
@@ -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
|
||||
}
|
||||
+35
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-5
@@ -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(() -> {
|
||||
|
||||
+28
-4
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -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;
|
||||
|
||||
+7
-11
@@ -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!");
|
||||
});
|
||||
|
||||
+23
-16
@@ -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
-1
@@ -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)
|
||||
|
||||
+6
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -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));
|
||||
|
||||
|
||||
+23
@@ -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();
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user