Improve notifications

This commit is contained in:
aditya.chandel
2024-12-27 11:14:31 -07:00
parent ea716bfb69
commit 3f13917191
13 changed files with 93 additions and 30 deletions
@@ -1,9 +1,9 @@
package com.adityachandel.booklore.controller;
import com.adityachandel.booklore.model.stomp.Topic;
import com.adityachandel.booklore.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
@@ -28,7 +28,7 @@ public class NotificationController {
System.out.println("Received message: " + message);
}
public void sendMessageToTopic(String topic, Object message) {
public void sendMessageToTopic(Topic topic, Object message) {
notificationService.sendMessage(topic, message);
}
}
@@ -0,0 +1,21 @@
package com.adityachandel.booklore.model.stomp;
import lombok.Getter;
import java.time.Instant;
@Getter
public class LogNotification {
private final Instant timestamp = Instant.now();
private final String message;
private LogNotification(String message) {
this.message = message;
}
public static LogNotification createLogNotification(String message) {
return new LogNotification(message);
}
}
@@ -0,0 +1,16 @@
package com.adityachandel.booklore.model.stomp;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public enum Topic {
BOOK("/topic/book"),
LOG("/topic/log");
private final String path;
@Override
public String toString() {
return path;
}
}
@@ -7,6 +7,8 @@ import com.adityachandel.booklore.model.entity.Book;
import com.adityachandel.booklore.model.entity.Library;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.stomp.BookNotification;
import com.adityachandel.booklore.model.stomp.LogNotification;
import com.adityachandel.booklore.model.stomp.Topic;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.LibraryRepository;
import lombok.AllArgsConstructor;
@@ -24,6 +26,7 @@ import java.util.stream.Collectors;
import static com.adityachandel.booklore.model.stomp.BookNotification.Action.BOOKS_REMOVED;
import static com.adityachandel.booklore.model.stomp.BookNotification.Action.BOOK_ADDED;
import static com.adityachandel.booklore.model.stomp.LogNotification.createLogNotification;
@Service
@AllArgsConstructor
@@ -39,15 +42,19 @@ public class LibraryProcessingService {
@Transactional
public void processLibrary(long libraryId) throws IOException {
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started processing library: " + library.getName()));
List<LibraryFile> libraryFiles = getLibraryFiles(library);
processLibraryFiles(libraryFiles);
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished processing library: " + library.getName()));
}
@Transactional
public void refreshLibrary(long libraryId) throws IOException {
Library library = libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
notificationService.sendMessage(Topic.LOG, createLogNotification("Started refreshing library: " + library.getName()));
processLibraryFiles(getUnProcessedFiles(library));
deleteRemovedBooks(getRemovedBooks(library));
notificationService.sendMessage(Topic.LOG, createLogNotification("Finished refreshing library: " + library.getName()));
}
@Transactional
@@ -56,7 +63,7 @@ public class LibraryProcessingService {
Set<Long> bookIds = removedBooks.stream().map(Book::getId).collect(Collectors.toSet());
bookRepository.deleteByIdIn(bookIds);
BookNotification notification = BookNotification.builder().action(BOOKS_REMOVED).removedBookIds(bookIds).build();
notificationService.sendMessage("/topic/books", notification);
notificationService.sendMessage(Topic.BOOK, notification);
log.info("Books removed: {}", bookIds);
}
}
@@ -68,8 +75,8 @@ public class LibraryProcessingService {
BookDTO bookDTO = processLibraryFile(libraryFile);
if (bookDTO != null) {
BookNotification notification = BookNotification.builder().action(BOOK_ADDED).addedBook(bookDTO).build();
notificationService.sendMessage("/topic/books", notification);
notificationService.sendMessage("/topic/logs", "Book added: " + bookDTO.getFileName());
notificationService.sendMessage(Topic.BOOK, notification);
notificationService.sendMessage(Topic.LOG, createLogNotification("Book added: " + bookDTO.getFileName()));
log.info("Processed file: {}", libraryFile.getFilePath());
}
}
@@ -130,7 +137,4 @@ public class LibraryProcessingService {
}
return libraryFiles;
}
}
}
@@ -1,5 +1,6 @@
package com.adityachandel.booklore.service;
import com.adityachandel.booklore.model.stomp.Topic;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
@@ -12,7 +13,7 @@ public class NotificationService {
this.messagingTemplate = messagingTemplate;
}
public void sendMessage(String topic, Object message) {
messagingTemplate.convertAndSend(topic, message);
public void sendMessage(Topic topic, Object message) {
messagingTemplate.convertAndSend(String.valueOf(topic), message);
}
}
+5 -3
View File
@@ -4,6 +4,7 @@ import {Message} from '@stomp/stompjs';
import {BookService} from './book/service/book.service';
import {Action, parseBookNotification} from './book/model/book-notification.model';
import {EventService} from './book/service/event.service';
import {parseLogNotification} from './book/model/log-notification.model';
@Component({
selector: 'app-root',
@@ -17,7 +18,7 @@ export class AppComponent implements OnInit {
}
ngOnInit(): void {
this.rxStompService.watch('/topic/books').subscribe((message: Message) => {
this.rxStompService.watch('/topic/book').subscribe((message: Message) => {
const notification = parseBookNotification(message.body);
if (notification.action === Action.BOOK_ADDED) {
this.bookService.handleNewlyCreatedBook(notification.addedBook!);
@@ -26,8 +27,9 @@ export class AppComponent implements OnInit {
}
});
this.rxStompService.watch('/topic/logs').subscribe((message: Message) => {
this.eventService.handleIncomingEvent(message.body);
this.rxStompService.watch('/topic/log').subscribe((message: Message) => {
let logNotification = parseLogNotification(message.body);
this.eventService.handleIncomingLog(logNotification);
});
}
@@ -1,6 +1,6 @@
<div class="library-header">
<div class="library-header-dial">
<h3 class="library-name">{{ (entityType$ | async) }}: {{ (entity$ | async)?.name }}</h3>
<h4 class="library-name">{{ (entityType$ | async) }}: {{ (entity$ | async)?.name }}</h4>
<p-speedDial
[model]="speedDialItems!"
direction="right"
@@ -1,10 +1,11 @@
.library-header {
display: flex;
justify-content: space-between;
padding: 15px 15px 10px 17px;
padding: 8px 16px 8px 16px;
background-color: var(--surface-card);
border-radius: 12px 12px 0 0;
margin-bottom: 15px;
align-items: center;
}
.library-header-dial {
@@ -21,13 +21,14 @@
(click)="toggleEventDisplay()"
(mouseenter)="onMouseEnter()"
(mouseleave)="onMouseLeave()"
[class.pi-spin]="eventHighlight"
[class.pulsating]="eventHighlight"
[class.highlight]="eventHighlight">
<i class="pi pi-sync"></i>
<i class="pi pi-wave-pulse"></i>
</button>
<div *ngIf="showEvents" class="live-event-container" (mouseleave)="onMouseLeave()">
{{ latestEvent }}
<p *ngIf="latestEvent.timestamp">{{ latestEvent.timestamp }}</p>
<p>{{ latestEvent.message }}</p>
</div>
<button class="p-link layout-menu-button layout-topbar-button" (click)="openLibraryCreatorDialog()" pTooltip="Create New Library" tooltipPosition="top">
<i class="pi pi-plus-circle"></i>
@@ -16,7 +16,7 @@
}
.highlight {
color: var(--yellow-400) !important;
color: red !important;
}
@keyframes pulsate {
@@ -12,6 +12,7 @@ import {SearchComponent} from '../search/search.component';
import {FileUploadComponent} from '../file-upload/file-upload.component';
import {NgClass, NgIf} from '@angular/common';
import {EventService} from '../../service/event.service';
import {LogNotification} from '../../model/log-notification.model';
@Component({
selector: 'app-topbar',
@@ -31,7 +32,7 @@ export class AppTopBarComponent implements OnDestroy {
items!: MenuItem[];
ref: DynamicDialogRef | undefined;
latestEvent: string = 'No recent events...';
latestEvent: LogNotification = { message: 'No recent notifications...' };
eventHighlight: boolean = false;
showEvents: boolean = false;
eventTimeout: any;
@@ -0,0 +1,14 @@
export interface LogNotification {
timestamp?: string;
message: string;
}
export function parseLogNotification(messageBody: string): LogNotification {
const raw = JSON.parse(messageBody);
const localTime = new Date(raw.timestamp).toLocaleTimeString();
return {
timestamp: localTime,
message: raw.message,
};
}
@@ -1,11 +1,12 @@
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {LogNotification} from '../model/log-notification.model';
@Injectable({
providedIn: 'root',
})
export class EventService {
private latestEventSubject = new BehaviorSubject<string>('No recent events...');
private latestEventSubject = new BehaviorSubject<LogNotification>({message: 'No recent notifications...'});
latestEvent$ = this.latestEventSubject.asObservable();
private eventHighlightSubject = new BehaviorSubject<boolean>(false);
@@ -13,10 +14,11 @@ export class EventService {
private eventTimeout: any;
constructor() {}
constructor() {
}
handleIncomingEvent(event: string): void {
this.latestEventSubject.next(event);
handleIncomingLog(logNotification: LogNotification): void {
this.latestEventSubject.next(logNotification);
this.eventHighlightSubject.next(true);
if (this.eventTimeout) {
@@ -25,12 +27,12 @@ export class EventService {
this.eventTimeout = setTimeout(() => {
this.eventHighlightSubject.next(false);
}, 1000);
}, 2500);
setTimeout(() => {
if (!this.eventHighlightSubject.value) {
this.latestEventSubject.next('No recent events...');
this.latestEventSubject.next({message: 'No recent notifications...'});
}
}, 2500);
}, 7500);
}
}