refactor(cover): add async cover notifications, for real time updates (#716)
This commit is contained in:
@@ -30,7 +30,6 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
@@ -72,19 +71,13 @@ public class SendEmailV2Service {
|
||||
|
||||
private void sendEmailInVirtualThread(EmailProviderV2Entity emailProvider, String recipientEmail, BookEntity book, BookFileEntity bookFile) {
|
||||
String bookTitle = book.getMetadata().getTitle();
|
||||
Path bookPath = FileUtils.getBookFullPath(book, bookFile);
|
||||
if (bookPath == null) {
|
||||
throw ApiError.FILE_NOT_FOUND.createException(bookTitle);
|
||||
}
|
||||
File bookFileOnDisk = bookPath.toFile();
|
||||
long bookId = book.getId();
|
||||
String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage));
|
||||
log.info(logMessage);
|
||||
taskExecutor.execute(() -> {
|
||||
try {
|
||||
sendEmail(emailProvider, recipientEmail, bookTitle, bookFileOnDisk);
|
||||
auditService.log(AuditAction.BOOK_SENT, "Book", bookId, "Sent book: " + bookTitle + " to " + recipientEmail);
|
||||
sendEmail(emailProvider, recipientEmail, book, bookFile);
|
||||
auditService.log(AuditAction.BOOK_SENT, "Book", book.getId(), "Sent book: " + bookTitle + " to " + recipientEmail);
|
||||
String successMessage = "The book: " + bookTitle + " has been successfully sent to " + recipientEmail;
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(successMessage));
|
||||
log.info(successMessage);
|
||||
@@ -96,14 +89,19 @@ public class SendEmailV2Service {
|
||||
});
|
||||
}
|
||||
|
||||
private void sendEmail(EmailProviderV2Entity emailProvider, String recipientEmail, String bookTitle, File bookFile) throws MessagingException {
|
||||
private void sendEmail(EmailProviderV2Entity emailProvider, String recipientEmail, BookEntity book, BookFileEntity bookFileEntity) throws MessagingException {
|
||||
JavaMailSenderImpl dynamicMailSender = setupMailSender(emailProvider);
|
||||
MimeMessage message = dynamicMailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
helper.setFrom(StringUtils.firstNonEmpty(emailProvider.getFromAddress(), emailProvider.getUsername()));
|
||||
helper.setTo(recipientEmail);
|
||||
helper.setSubject("Your Book from Grimmory: " + bookTitle);
|
||||
helper.setText(generateEmailBody(bookTitle));
|
||||
helper.setSubject("Your Book from Grimmory: " + book.getMetadata().getTitle());
|
||||
helper.setText(generateEmailBody(book.getMetadata().getTitle()));
|
||||
var bookPath = FileUtils.getBookFullPath(book, bookFileEntity);
|
||||
if (bookPath == null) {
|
||||
throw ApiError.FILE_NOT_FOUND.createException(book.getId());
|
||||
}
|
||||
File bookFile = bookPath.toFile();
|
||||
helper.addAttachment(bookFile.getName(), bookFile);
|
||||
dynamicMailSender.send(message);
|
||||
log.info("Book sent successfully to {}", recipientEmail);
|
||||
|
||||
@@ -24,6 +24,8 @@ import org.booklore.util.BookCoverUtils;
|
||||
import org.booklore.util.FileService;
|
||||
import org.booklore.util.MimeDetector;
|
||||
import org.booklore.config.AppProperties;
|
||||
import org.booklore.config.security.service.AuthenticationService;
|
||||
import org.booklore.model.enums.PermissionType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
@@ -57,6 +59,20 @@ public class BookCoverService {
|
||||
private final MetadataWriterFactory metadataWriterFactory;
|
||||
private final Executor taskExecutor;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
private void sendNotification(String username, Topic topic, Object message) {
|
||||
if (username != null) {
|
||||
notificationService.sendMessageToUser(username, topic, message);
|
||||
} else {
|
||||
notificationService.sendMessageToPermissions(topic, message, Set.of(PermissionType.ADMIN, PermissionType.MANAGE_LIBRARY));
|
||||
}
|
||||
}
|
||||
|
||||
private String getCurrentUsername() {
|
||||
var user = authenticationService.getAuthenticatedUser();
|
||||
return user != null ? user.getUsername() : null;
|
||||
}
|
||||
|
||||
private record BookCoverInfo(Long id, String title) {
|
||||
}
|
||||
@@ -219,7 +235,8 @@ public class BookCoverService {
|
||||
validateCoverFile(file);
|
||||
byte[] coverImageBytes = extractBytesFromMultipartFile(file);
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||
taskExecutor.execute(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes));
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes, username));
|
||||
}
|
||||
|
||||
// =========================
|
||||
@@ -287,7 +304,8 @@ public class BookCoverService {
|
||||
*/
|
||||
public void regenerateCoversForBooks(Set<Long> bookIds) {
|
||||
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(bookIds);
|
||||
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks));
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCoverRegeneration(unlockedBooks, username));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -295,13 +313,15 @@ public class BookCoverService {
|
||||
*/
|
||||
public void generateCustomCoversForBooks(Set<Long> bookIds) {
|
||||
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds);
|
||||
taskExecutor.execute(() -> processBulkCustomCoverGeneration(unlockedBooks));
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> processBulkCustomCoverGeneration(unlockedBooks, username));
|
||||
}
|
||||
|
||||
/**
|
||||
* Regenerate covers for all books, optionally only for books with missing covers.
|
||||
*/
|
||||
public void regenerateCovers(boolean missingOnly) {
|
||||
String username = getCurrentUsername();
|
||||
taskExecutor.execute(() -> {
|
||||
try {
|
||||
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
|
||||
@@ -312,15 +332,14 @@ public class BookCoverService {
|
||||
.toList();
|
||||
int total = books.size();
|
||||
String label = missingOnly ? "missing" : "all";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books (" + label + ")"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books (" + label + ")"));
|
||||
|
||||
int current = 1;
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookRegenerationInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
@@ -335,7 +354,7 @@ public class BookCoverService {
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
} else {
|
||||
log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
|
||||
@@ -349,11 +368,10 @@ public class BookCoverService {
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover regeneration: {}", e.getMessage(), e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -362,18 +380,17 @@ public class BookCoverService {
|
||||
// SECTION: BULK OPERATIONS
|
||||
// =========================
|
||||
|
||||
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes) {
|
||||
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes, String username) {
|
||||
try {
|
||||
int total = books.size();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
@@ -381,7 +398,7 @@ public class BookCoverService {
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
});
|
||||
return null;
|
||||
});
|
||||
@@ -393,26 +410,24 @@ public class BookCoverService {
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover update: {}", e.getMessage(), e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover update"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover update"));
|
||||
}
|
||||
}
|
||||
|
||||
private void processBulkCoverRegeneration(List<BookRegenerationInfo> books) {
|
||||
private void processBulkCoverRegeneration(List<BookRegenerationInfo> books, String username) {
|
||||
try {
|
||||
int total = books.size();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookRegenerationInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
@@ -422,7 +437,7 @@ public class BookCoverService {
|
||||
if (success) {
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
}
|
||||
});
|
||||
return null;
|
||||
@@ -435,26 +450,24 @@ public class BookCoverService {
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during cover regeneration: {}", e.getMessage(), e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during cover regeneration"));
|
||||
}
|
||||
}
|
||||
|
||||
private void processBulkCustomCoverGeneration(List<BookCoverInfo> books) {
|
||||
private void processBulkCustomCoverGeneration(List<BookCoverInfo> books, String username) {
|
||||
try {
|
||||
int total = books.size();
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Started generating custom covers for " + total + " selected book(s)"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Started generating custom covers for " + total + " selected book(s)"));
|
||||
|
||||
int current = 1;
|
||||
List<Long> refreshedIds = new ArrayList<>();
|
||||
|
||||
for (BookCoverInfo bookInfo : books) {
|
||||
try {
|
||||
String progress = "(" + current + "/" + total + ") ";
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Generating custom cover for: " + bookInfo.title()));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info(progress + "Generating custom cover for: " + bookInfo.title()));
|
||||
|
||||
transactionTemplate.execute(status -> {
|
||||
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
|
||||
@@ -466,7 +479,7 @@ public class BookCoverService {
|
||||
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
|
||||
updateBookCoverMetadata(book);
|
||||
bookRepository.save(book);
|
||||
refreshedIds.add(book.getId());
|
||||
notifyBulkCoverUpdate(List.of(book.getId()), username);
|
||||
});
|
||||
return null;
|
||||
});
|
||||
@@ -478,11 +491,10 @@ public class BookCoverService {
|
||||
current++;
|
||||
}
|
||||
|
||||
notifyBulkCoverUpdate(refreshedIds);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
|
||||
} catch (Exception e) {
|
||||
log.error("Error during custom cover generation: {}", e.getMessage(), e);
|
||||
notificationService.sendMessage(Topic.LOG, LogNotification.error("Error occurred during custom cover generation"));
|
||||
sendNotification(username, Topic.LOG, LogNotification.error("Error occurred during custom cover generation"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -616,13 +628,13 @@ public class BookCoverService {
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyBulkCoverUpdate(List<Long> refreshedIds) {
|
||||
private void notifyBulkCoverUpdate(List<Long> refreshedIds, String username) {
|
||||
if (refreshedIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds);
|
||||
if (!updates.isEmpty()) {
|
||||
notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates);
|
||||
sendNotification(username, Topic.BOOKS_COVER_UPDATE, updates);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,11 +298,11 @@ class SendEmailV2ServiceTest {
|
||||
|
||||
try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
|
||||
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile))
|
||||
.thenReturn(Path.of("/library/books/test-book.epub"));
|
||||
.thenThrow(new IllegalStateException("Book file not found"));
|
||||
|
||||
sendEmailV2Service.emailBookQuick(10L);
|
||||
|
||||
// Error is caught inside async thread and logged, not rethrown
|
||||
// Error is caught and logged, not rethrown
|
||||
verify(notificationService, atLeastOnce()).sendMessage(any(), any());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user