diff --git a/booklore-api/src/main/java/org/booklore/service/email/SendEmailV2Service.java b/booklore-api/src/main/java/org/booklore/service/email/SendEmailV2Service.java index 09d4b351b..af809f593 100644 --- a/booklore-api/src/main/java/org/booklore/service/email/SendEmailV2Service.java +++ b/booklore-api/src/main/java/org/booklore/service/email/SendEmailV2Service.java @@ -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); diff --git a/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java b/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java index 9299c5146..72a8e3ec0 100644 --- a/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java +++ b/booklore-api/src/main/java/org/booklore/service/metadata/BookCoverService.java @@ -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 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 bookIds) { List 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 bookIds) { List 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 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 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 books, byte[] coverImageBytes) { + private void processBulkCoverUpdate(List 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 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 books) { + private void processBulkCoverRegeneration(List 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 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 books) { + private void processBulkCustomCoverGeneration(List 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 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 refreshedIds) { + private void notifyBulkCoverUpdate(List refreshedIds, String username) { if (refreshedIds.isEmpty()) { return; } List updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds); if (!updates.isEmpty()) { - notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates); + sendNotification(username, Topic.BOOKS_COVER_UPDATE, updates); } } } diff --git a/booklore-api/src/test/java/org/booklore/service/email/SendEmailV2ServiceTest.java b/booklore-api/src/test/java/org/booklore/service/email/SendEmailV2ServiceTest.java index b6ad32ef5..8971408a9 100644 --- a/booklore-api/src/test/java/org/booklore/service/email/SendEmailV2ServiceTest.java +++ b/booklore-api/src/test/java/org/booklore/service/email/SendEmailV2ServiceTest.java @@ -298,11 +298,11 @@ class SendEmailV2ServiceTest { try (MockedStatic 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()); } } diff --git a/frontend/src/app/features/book/service/app-books-api.service.ts b/frontend/src/app/features/book/service/app-books-api.service.ts index 7d8ea5d79..c022a63e3 100644 --- a/frontend/src/app/features/book/service/app-books-api.service.ts +++ b/frontend/src/app/features/book/service/app-books-api.service.ts @@ -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; } diff --git a/frontend/src/app/features/book/service/book-query-cache.ts b/frontend/src/app/features/book/service/book-query-cache.ts index 69309289c..1dd8b2239 100644 --- a/frontend/src/app/features/book/service/book-query-cache.ts +++ b/frontend/src/app/features/book/service/book-query-cache.ts @@ -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>>( + {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} : {}), + }; + }) + })) + }; + } + ); +} diff --git a/frontend/src/app/features/book/service/book-socket.service.ts b/frontend/src/app/features/book/service/book-socket.service.ts index 8af2031f7..cd4e13a6d 100644 --- a/frontend/src/app/features/book/service/book-socket.service.ts +++ b/frontend/src/app/features/book/service/book-socket.service.ts @@ -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); } } diff --git a/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts index b5b35315c..685f57403 100644 --- a/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts +++ b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.spec.ts @@ -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; let langChanges$: Subject; let component: LiveNotificationBoxComponent; - let fixture: ComponentFixture; beforeEach(() => { notifications$ = new Subject(); @@ -35,7 +34,7 @@ describe('LiveNotificationBoxComponent', () => { ], }); - fixture = TestBed.createComponent(LiveNotificationBoxComponent); + const fixture = TestBed.createComponent(LiveNotificationBoxComponent); component = fixture.componentInstance; fixture.detectChanges(); }); diff --git a/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.ts b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.ts index 113e8f2c0..f7f0da9f3 100644 --- a/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.ts +++ b/frontend/src/app/shared/components/live-notification-box/live-notification-box.component.ts @@ -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(); 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(); }); }