refactor(cover): add async cover notifications, for real time updates (#716)

This commit is contained in:
brios
2026-04-22 17:27:42 -04:00
committed by Zach Yale
parent 4bac913574
commit 7a88b12430
8 changed files with 102 additions and 57 deletions
@@ -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());
}
}
@@ -67,6 +67,8 @@ export class AppBooksApiService {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i].id !== b[i].id) return false;
if (a[i].metadata?.coverUpdatedOn !== b[i].metadata?.coverUpdatedOn) return false;
if (a[i].metadata?.audiobookCoverUpdatedOn !== b[i].metadata?.audiobookCoverUpdatedOn) return false;
}
return true;
}
@@ -1,6 +1,7 @@
import {QueryClient} from '@tanstack/angular-query-experimental';
import {InfiniteData, QueryClient} from '@tanstack/angular-query-experimental';
import {Book, BookMetadata} from '../model/book.model';
import {AppBookSummary, AppPageResponse} from '../model/app-book.model';
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
const APP_BOOKS_QUERY_PREFIX = ['app-books'] as const;
@@ -98,3 +99,33 @@ export function patchBookFieldsInCache(queryClient: QueryClient, updates: {bookI
invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
invalidateAppBooksQueries(queryClient);
}
export function patchAppBooksCoverInCache(
queryClient: QueryClient,
patches: {id: number; coverUpdatedOn?: string | null; audiobookCoverUpdatedOn?: string | null}[]
): void {
if (patches.length === 0) return;
const patchMap = new Map(patches.map(p => [p.id, p]));
queryClient.setQueriesData<InfiniteData<AppPageResponse<AppBookSummary>>>(
{queryKey: APP_BOOKS_QUERY_PREFIX},
(current) => {
if (!current) return current;
return {
...current,
pages: current.pages.map(page => ({
...page,
content: page.content.map(summary => {
const patch = patchMap.get(summary.id);
if (!patch) return summary;
return {
...summary,
...('coverUpdatedOn' in patch ? {coverUpdatedOn: patch.coverUpdatedOn ?? null} : {}),
...('audiobookCoverUpdatedOn' in patch ? {audiobookCoverUpdatedOn: patch.audiobookCoverUpdatedOn ?? null} : {}),
};
})
}))
};
}
);
}
@@ -4,9 +4,9 @@ import {QueryClient} from '@tanstack/angular-query-experimental';
import {BOOKS_QUERY_KEY} from './book-query-keys';
import {
addBookToCache,
invalidateAppBooksQueries,
invalidateBookDetailQueries,
invalidateBooksQuery,
patchAppBooksCoverInCache,
patchBooksInCache,
removeBookQueries,
} from './book-query-cache';
@@ -50,7 +50,7 @@ export class BookSocketService {
: book;
})
);
patchAppBooksCoverInCache(this.queryClient, patches);
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
invalidateAppBooksQueries(this.queryClient);
}
}
@@ -1,5 +1,5 @@
import {Subject} from 'rxjs';
import {TestBed, ComponentFixture} from '@angular/core/testing';
import {TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {TranslocoService} from '@jsverse/transloco';
@@ -12,7 +12,6 @@ describe('LiveNotificationBoxComponent', () => {
let notifications$: Subject<LogNotification>;
let langChanges$: Subject<string>;
let component: LiveNotificationBoxComponent;
let fixture: ComponentFixture<LiveNotificationBoxComponent>;
beforeEach(() => {
notifications$ = new Subject<LogNotification>();
@@ -35,7 +34,7 @@ describe('LiveNotificationBoxComponent', () => {
],
});
fixture = TestBed.createComponent(LiveNotificationBoxComponent);
const fixture = TestBed.createComponent(LiveNotificationBoxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
@@ -1,4 +1,4 @@
import {Component, inject, OnDestroy} from '@angular/core';
import {ChangeDetectorRef, Component, inject, OnDestroy} from '@angular/core';
import {NotificationEventService} from '../../websocket/notification-event.service';
import {LogNotification} from '../../websocket/model/log-notification.model';
import {TranslocoService} from '@jsverse/transloco';
@@ -21,6 +21,7 @@ import {TagComponent} from '../tag/tag.component';
})
export class LiveNotificationBoxComponent implements OnDestroy {
private readonly t = inject(TranslocoService);
private readonly cdr = inject(ChangeDetectorRef);
private readonly destroy$ = new Subject<void>();
latestNotification: LogNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
private hasReceivedNotification = false;
@@ -31,11 +32,13 @@ export class LiveNotificationBoxComponent implements OnDestroy {
this.notificationService.latestNotification$.pipe(takeUntil(this.destroy$)).subscribe(notification => {
this.hasReceivedNotification = true;
this.latestNotification = notification;
this.cdr.markForCheck();
});
this.t.langChanges$.pipe(takeUntil(this.destroy$)).subscribe(() => {
if (!this.hasReceivedNotification) {
this.latestNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
}
this.cdr.markForCheck();
});
}