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.File;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
@@ -72,19 +71,13 @@ public class SendEmailV2Service {
private void sendEmailInVirtualThread(EmailProviderV2Entity emailProvider, String recipientEmail, BookEntity book, BookFileEntity bookFile) { private void sendEmailInVirtualThread(EmailProviderV2Entity emailProvider, String recipientEmail, BookEntity book, BookFileEntity bookFile) {
String bookTitle = book.getMetadata().getTitle(); 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; String logMessage = "Email dispatch initiated for book: " + bookTitle + " to " + recipientEmail;
notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage)); notificationService.sendMessage(Topic.LOG, LogNotification.info(logMessage));
log.info(logMessage); log.info(logMessage);
taskExecutor.execute(() -> { taskExecutor.execute(() -> {
try { try {
sendEmail(emailProvider, recipientEmail, bookTitle, bookFileOnDisk); sendEmail(emailProvider, recipientEmail, book, bookFile);
auditService.log(AuditAction.BOOK_SENT, "Book", bookId, "Sent book: " + bookTitle + " to " + recipientEmail); auditService.log(AuditAction.BOOK_SENT, "Book", book.getId(), "Sent book: " + bookTitle + " to " + recipientEmail);
String successMessage = "The book: " + bookTitle + " has been successfully sent to " + recipientEmail; String successMessage = "The book: " + bookTitle + " has been successfully sent to " + recipientEmail;
notificationService.sendMessage(Topic.LOG, LogNotification.info(successMessage)); notificationService.sendMessage(Topic.LOG, LogNotification.info(successMessage));
log.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); JavaMailSenderImpl dynamicMailSender = setupMailSender(emailProvider);
MimeMessage message = dynamicMailSender.createMimeMessage(); MimeMessage message = dynamicMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true); MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(StringUtils.firstNonEmpty(emailProvider.getFromAddress(), emailProvider.getUsername())); helper.setFrom(StringUtils.firstNonEmpty(emailProvider.getFromAddress(), emailProvider.getUsername()));
helper.setTo(recipientEmail); helper.setTo(recipientEmail);
helper.setSubject("Your Book from Grimmory: " + bookTitle); helper.setSubject("Your Book from Grimmory: " + book.getMetadata().getTitle());
helper.setText(generateEmailBody(bookTitle)); 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); helper.addAttachment(bookFile.getName(), bookFile);
dynamicMailSender.send(message); dynamicMailSender.send(message);
log.info("Book sent successfully to {}", recipientEmail); 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.FileService;
import org.booklore.util.MimeDetector; import org.booklore.util.MimeDetector;
import org.booklore.config.AppProperties; 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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
@@ -57,6 +59,20 @@ public class BookCoverService {
private final MetadataWriterFactory metadataWriterFactory; private final MetadataWriterFactory metadataWriterFactory;
private final Executor taskExecutor; private final Executor taskExecutor;
private final TransactionTemplate transactionTemplate; 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) { private record BookCoverInfo(Long id, String title) {
} }
@@ -219,7 +235,8 @@ public class BookCoverService {
validateCoverFile(file); validateCoverFile(file);
byte[] coverImageBytes = extractBytesFromMultipartFile(file); byte[] coverImageBytes = extractBytesFromMultipartFile(file);
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(bookIds); 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) { public void regenerateCoversForBooks(Set<Long> bookIds) {
List<BookRegenerationInfo> unlockedBooks = getUnlockedBookRegenerationInfos(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) { public void generateCustomCoversForBooks(Set<Long> bookIds) {
List<BookCoverInfo> unlockedBooks = getUnlockedBookCoverInfos(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. * Regenerate covers for all books, optionally only for books with missing covers.
*/ */
public void regenerateCovers(boolean missingOnly) { public void regenerateCovers(boolean missingOnly) {
String username = getCurrentUsername();
taskExecutor.execute(() -> { taskExecutor.execute(() -> {
try { try {
List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream() List<BookRegenerationInfo> books = bookQueryService.getAllFullBookEntities().stream()
@@ -312,15 +332,14 @@ public class BookCoverService {
.toList(); .toList();
int total = books.size(); int total = books.size();
String label = missingOnly ? "missing" : "all"; 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; int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) { for (BookRegenerationInfo bookInfo : books) {
try { try {
String progress = "(" + current + "/" + total + ") "; 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 -> { transactionTemplate.execute(status -> {
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> { bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
@@ -335,7 +354,7 @@ public class BookCoverService {
if (success) { if (success) {
updateBookCoverMetadata(book); updateBookCoverMetadata(book);
bookRepository.save(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()); log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
} else { } else {
log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title()); log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title());
@@ -349,11 +368,10 @@ public class BookCoverService {
current++; current++;
} }
notifyBulkCoverUpdate(refreshedIds); sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers"));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers"));
} catch (Exception e) { } catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), 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 // SECTION: BULK OPERATIONS
// ========================= // =========================
private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes) { private void processBulkCoverUpdate(List<BookCoverInfo> books, byte[] coverImageBytes, String username) {
try { try {
int total = books.size(); 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; int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookCoverInfo bookInfo : books) { for (BookCoverInfo bookInfo : books) {
try { try {
String progress = "(" + current + "/" + total + ") "; 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 -> { transactionTemplate.execute(status -> {
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> { bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
@@ -381,7 +398,7 @@ public class BookCoverService {
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes)); writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes));
updateBookCoverMetadata(book); updateBookCoverMetadata(book);
bookRepository.save(book); bookRepository.save(book);
refreshedIds.add(book.getId()); notifyBulkCoverUpdate(List.of(book.getId()), username);
}); });
return null; return null;
}); });
@@ -393,26 +410,24 @@ public class BookCoverService {
current++; current++;
} }
notifyBulkCoverUpdate(refreshedIds); sendNotification(username, Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books"));
} catch (Exception e) { } catch (Exception e) {
log.error("Error during cover update: {}", e.getMessage(), 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 { try {
int total = books.size(); 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; int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookRegenerationInfo bookInfo : books) { for (BookRegenerationInfo bookInfo : books) {
try { try {
String progress = "(" + current + "/" + total + ") "; 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 -> { transactionTemplate.execute(status -> {
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> { bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
@@ -422,7 +437,7 @@ public class BookCoverService {
if (success) { if (success) {
updateBookCoverMetadata(book); updateBookCoverMetadata(book);
bookRepository.save(book); bookRepository.save(book);
refreshedIds.add(book.getId()); notifyBulkCoverUpdate(List.of(book.getId()), username);
} }
}); });
return null; return null;
@@ -435,26 +450,24 @@ public class BookCoverService {
current++; current++;
} }
notifyBulkCoverUpdate(refreshedIds); sendNotification(username, Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers for selected books"));
} catch (Exception e) { } catch (Exception e) {
log.error("Error during cover regeneration: {}", e.getMessage(), 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 { try {
int total = books.size(); 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; int current = 1;
List<Long> refreshedIds = new ArrayList<>();
for (BookCoverInfo bookInfo : books) { for (BookCoverInfo bookInfo : books) {
try { try {
String progress = "(" + current + "/" + total + ") "; 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 -> { transactionTemplate.execute(status -> {
bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> { bookRepository.findByIdWithBookFiles(bookInfo.id()).ifPresent(book -> {
@@ -466,7 +479,7 @@ public class BookCoverService {
writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes)); writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverBytes));
updateBookCoverMetadata(book); updateBookCoverMetadata(book);
bookRepository.save(book); bookRepository.save(book);
refreshedIds.add(book.getId()); notifyBulkCoverUpdate(List.of(book.getId()), username);
}); });
return null; return null;
}); });
@@ -478,11 +491,10 @@ public class BookCoverService {
current++; current++;
} }
notifyBulkCoverUpdate(refreshedIds); sendNotification(username, Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished generating custom covers for selected books"));
} catch (Exception e) { } catch (Exception e) {
log.error("Error during custom cover generation: {}", e.getMessage(), 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()) { if (refreshedIds.isEmpty()) {
return; return;
} }
List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds); List<BookCoverUpdateProjection> updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds);
if (!updates.isEmpty()) { 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)) { try (MockedStatic<FileUtils> fileUtilsMock = mockStatic(FileUtils.class)) {
fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile)) fileUtilsMock.when(() -> FileUtils.getBookFullPath(book, bookFile))
.thenReturn(Path.of("/library/books/test-book.epub")); .thenThrow(new IllegalStateException("Book file not found"));
sendEmailV2Service.emailBookQuick(10L); 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()); verify(notificationService, atLeastOnce()).sendMessage(any(), any());
} }
} }
@@ -67,6 +67,8 @@ export class AppBooksApiService {
if (a.length !== b.length) return false; if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) { for (let i = 0; i < a.length; i++) {
if (a[i].id !== b[i].id) return false; 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; 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 {Book, BookMetadata} from '../model/book.model';
import {AppBookSummary, AppPageResponse} from '../model/app-book.model';
import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys'; import {BOOKS_QUERY_KEY, bookDetailQueryPrefix, bookRecommendationsQueryPrefix} from './book-query-keys';
const APP_BOOKS_QUERY_PREFIX = ['app-books'] as const; 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)); invalidateBookDetailQueries(queryClient, updates.map(u => u.bookId));
invalidateAppBooksQueries(queryClient); 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 {BOOKS_QUERY_KEY} from './book-query-keys';
import { import {
addBookToCache, addBookToCache,
invalidateAppBooksQueries,
invalidateBookDetailQueries, invalidateBookDetailQueries,
invalidateBooksQuery, invalidateBooksQuery,
patchAppBooksCoverInCache,
patchBooksInCache, patchBooksInCache,
removeBookQueries, removeBookQueries,
} from './book-query-cache'; } from './book-query-cache';
@@ -50,7 +50,7 @@ export class BookSocketService {
: book; : book;
}) })
); );
patchAppBooksCoverInCache(this.queryClient, patches);
invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id)); invalidateBookDetailQueries(this.queryClient, patches.map(p => p.id));
invalidateAppBooksQueries(this.queryClient);
} }
} }
@@ -1,5 +1,5 @@
import {Subject} from 'rxjs'; 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 {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {TranslocoService} from '@jsverse/transloco'; import {TranslocoService} from '@jsverse/transloco';
@@ -12,7 +12,6 @@ describe('LiveNotificationBoxComponent', () => {
let notifications$: Subject<LogNotification>; let notifications$: Subject<LogNotification>;
let langChanges$: Subject<string>; let langChanges$: Subject<string>;
let component: LiveNotificationBoxComponent; let component: LiveNotificationBoxComponent;
let fixture: ComponentFixture<LiveNotificationBoxComponent>;
beforeEach(() => { beforeEach(() => {
notifications$ = new Subject<LogNotification>(); notifications$ = new Subject<LogNotification>();
@@ -35,7 +34,7 @@ describe('LiveNotificationBoxComponent', () => {
], ],
}); });
fixture = TestBed.createComponent(LiveNotificationBoxComponent); const fixture = TestBed.createComponent(LiveNotificationBoxComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges(); 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 {NotificationEventService} from '../../websocket/notification-event.service';
import {LogNotification} from '../../websocket/model/log-notification.model'; import {LogNotification} from '../../websocket/model/log-notification.model';
import {TranslocoService} from '@jsverse/transloco'; import {TranslocoService} from '@jsverse/transloco';
@@ -21,6 +21,7 @@ import {TagComponent} from '../tag/tag.component';
}) })
export class LiveNotificationBoxComponent implements OnDestroy { export class LiveNotificationBoxComponent implements OnDestroy {
private readonly t = inject(TranslocoService); private readonly t = inject(TranslocoService);
private readonly cdr = inject(ChangeDetectorRef);
private readonly destroy$ = new Subject<void>(); private readonly destroy$ = new Subject<void>();
latestNotification: LogNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')}; latestNotification: LogNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
private hasReceivedNotification = false; private hasReceivedNotification = false;
@@ -31,11 +32,13 @@ export class LiveNotificationBoxComponent implements OnDestroy {
this.notificationService.latestNotification$.pipe(takeUntil(this.destroy$)).subscribe(notification => { this.notificationService.latestNotification$.pipe(takeUntil(this.destroy$)).subscribe(notification => {
this.hasReceivedNotification = true; this.hasReceivedNotification = true;
this.latestNotification = notification; this.latestNotification = notification;
this.cdr.markForCheck();
}); });
this.t.langChanges$.pipe(takeUntil(this.destroy$)).subscribe(() => { this.t.langChanges$.pipe(takeUntil(this.destroy$)).subscribe(() => {
if (!this.hasReceivedNotification) { if (!this.hasReceivedNotification) {
this.latestNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')}; this.latestNotification = {message: this.t.translate('shared.liveNotification.defaultMessage')};
} }
this.cdr.markForCheck();
}); });
} }