Skip to content

Commit

Permalink
fix: refactored and optimized notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
Troha7 committed Mar 24, 2024
1 parent 2e4b462 commit 7f88ea8
Show file tree
Hide file tree
Showing 16 changed files with 154 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@ToString
public class TopicNotificationResponseDto {

private TopicResponseDto topic;
private Integer topicId;

private Integer unreadMessages;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
if (isTopicDestination(destination)) {
lastMessageDto = contactEventService.getByTopicIdAndEmail(getTopicId(event), email)
.getLastMessage();
int unreadMessages = contactEventService.getByTopicIdAndEmail(getTopicId(event), email)
.getUnreadMessages();

var contactEvent = new ContactEvent(email, getTopicId(event), SUBSCRIBED,
getTimestamp(event), lastMessageDto);
getTimestamp(event), unreadMessages, lastMessageDto);
contactEventService.updateEventTypeByEmail(ONLINE, email);
contactEventService.save(contactEvent);
}
Expand All @@ -58,7 +61,7 @@ public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
}

if (destination.equals(USER_DESTINATION + properties.getNotifyPrefix() + TOPICS_DESTINATION)) {
chatNotificationService.notifyAllPublicTopics(getEmail(event));
chatNotificationService.notifyAllTopics(getEmail(event));
}

log.info("Contact [{}] subscribe to [{}]", email, destination);
Expand All @@ -72,7 +75,7 @@ public void handleWebSocketUnsubscribeListener(SessionUnsubscribeEvent event) {
try {
if (isTopicDestination(destination)) {
var contactEvent = new ContactEvent(email, getTopicId(event), ONLINE,
getTimestamp(event), lastMessageDto);
getTimestamp(event), 0, lastMessageDto);
contactEventService.save(contactEvent);
}

Expand Down

This file was deleted.

22 changes: 22 additions & 0 deletions src/main/java/com/chat/yourway/mapper/NotificationMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.chat.yourway.mapper;

import com.chat.yourway.dto.response.MessageNotificationResponseDto;
import com.chat.yourway.dto.response.TopicNotificationResponseDto;
import com.chat.yourway.model.event.ContactEvent;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(componentModel = "spring")
public interface NotificationMapper {

@Mapping(target = "status", source = "eventType")
@Mapping(target = "lastRead", source = "timestamp")
@Mapping(target = "email", source = "email")
MessageNotificationResponseDto toMessageNotificationResponseDto(ContactEvent event);

@Mapping(target = "topicId", source = "topicId")
@Mapping(target = "unreadMessages", source = "unreadMessages")
@Mapping(target = "lastMessage", source = "lastMessage")
TopicNotificationResponseDto toTopicNotificationResponseDto(ContactEvent event);

}
4 changes: 3 additions & 1 deletion src/main/java/com/chat/yourway/model/event/ContactEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,18 @@ public class ContactEvent {
private Integer topicId;
private EventType eventType;
private LocalDateTime timestamp;
private int unreadMessages;
private LastMessageResponseDto lastMessage;


public ContactEvent(String email, Integer topicId, EventType eventType, LocalDateTime timestamp,
LastMessageResponseDto lastMessage) {
int unreadMessages, LastMessageResponseDto lastMessage) {
this.id = email + "_" + topicId;
this.email = email;
this.topicId = topicId;
this.eventType = eventType;
this.timestamp = timestamp;
this.unreadMessages = unreadMessages;
this.lastMessage = lastMessage;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,16 +69,16 @@ public List<MessageResponseDto> sendMessageHistoryByTopicId(Integer topicId,

private void sendToTopic(Integer topicId, MessageResponseDto messageDto) {
var lastMessageDto = new LastMessageResponseDto();
lastMessageDto.setTimestamp(messageDto.getTimestamp());
lastMessageDto.setSentFrom(messageDto.getSentFrom());
lastMessageDto.setLastMessage(messageDto.getContent());
lastMessageDto.setTimestamp(messageDto.getTimestamp());
lastMessageDto.setSentFrom(messageDto.getSentFrom());
lastMessageDto.setLastMessage(messageDto.getContent());

contactEventService.setLastMessageToAllTopicSubscribers(topicId, lastMessageDto);
contactEventService.updateMessageInfoForAllTopicSubscribers(topicId, lastMessageDto);

simpMessagingTemplate.convertAndSend(toTopicDestination(topicId), messageDto);

chatNotificationService.notifyTopicSubscribers(topicId);
chatNotificationService.notifyAllWhoSubscribedToTopic(topicId);
chatNotificationService.updateNotificationForAllWhoSubscribedToTopic(topicId);
}

private String toTopicDestination(Integer topicId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,57 @@ public void notifyTopicSubscribers(Integer topicId) {
.forEach(n -> simpMessagingTemplate.convertAndSendToUser(
n.getEmail(), toNotifyMessageDest(topicId), notifications));

log.trace("All subscribers was notified by topic id = [{}]", topicId);
log.info("All subscribers was notified by topic id = [{}]", topicId);
}

@Override
public void notifyAllWhoSubscribedToSameUserTopic(String userEmail) {
log.trace("Started notifyAllWhoSubscribedToSameUserTopic, user email = [{}]", userEmail);

contactEventService.getAllByEmail(userEmail)
.forEach(e -> notifyTopicSubscribers(e.getTopicId()));

log.info("All subscribers who subscribed to same topic was notified, email = [{}]", userEmail);
}

@Override
public void notifyAllPublicTopics(String email){
var notifiedTopics = notificationService.notifyAllPublicTopicsByEmail(email);
public void notifyAllTopics(String email) {
log.trace("Started notifyAllTopics, email = [{}]", email);

var notifiedTopics = notificationService.notifyAllTopicsByEmail(email);
simpMessagingTemplate.convertAndSendToUser(email, toNotifyTopicsDest(), notifiedTopics);

log.info("All topics was notified for user email = [{}]", email);
}

@Override
public void notifyAllWhoSubscribedToTopic(Integer topicId) {
log.trace("Started notifyAllWhoSubscribedToTopic, topicId = [{}]", topicId);

contactEventService.getAllByTopicId(topicId)
.forEach(e -> notifyAllTopics(e.getEmail()));

log.info("All subscribed users was notified, topicId = [{}]", topicId);
}

@Override
public void updateNotificationForAllTopics(String email) {
log.trace("Started updateNotificationForAllTopics, email = [{}]", email);

var notifiedTopics = notificationService.updateTopicNotification(email);
simpMessagingTemplate.convertAndSendToUser(email, toNotifyTopicsDest(), notifiedTopics);

log.info("All topics for user was notified, email = [{}]", email);
}

@Override
public void updateNotificationForAllWhoSubscribedToTopic(Integer topicId) {
log.trace("Started updateNotificationForAllWhoSubscribedToTopic, topicId = [{}]", topicId);

contactEventService.getAllByTopicId(topicId)
.forEach(e -> notifyAllPublicTopics(e.getEmail()));
.forEach(e -> updateNotificationForAllTopics(e.getEmail()));

log.info("Topic notifications was updated for all subscribed users, topicId = [{}]", topicId);
}

private String toNotifyMessageDest(Integer topicId) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.chat.yourway.service;

import static com.chat.yourway.model.event.EventType.ONLINE;
import static com.chat.yourway.model.event.EventType.SUBSCRIBED;

import com.chat.yourway.dto.response.LastMessageResponseDto;
import com.chat.yourway.model.event.ContactEvent;
Expand Down Expand Up @@ -31,7 +32,7 @@ public ContactEvent getByTopicIdAndEmail(Integer topicId, String email) {
log.trace("Started getByTopicIdAndEmail, topicId [{}], email [{}]", topicId, email);

return contactEventRedisRepository.findById(email + "_" + topicId)
.orElse(new ContactEvent(email, topicId, ONLINE, LocalDateTime.now(), null));
.orElse(new ContactEvent(email, topicId, ONLINE, LocalDateTime.now(), 0, null));
}

@Override
Expand Down Expand Up @@ -62,15 +63,21 @@ public List<ContactEvent> getAllByTopicId(Integer topicId) {
}

@Override
public void setLastMessageToAllTopicSubscribers(Integer topicId, LastMessageResponseDto message) {
log.trace("Started setLastMessageToAllTopicSubscribers, topic id [{}], last message [{}]",
public void updateMessageInfoForAllTopicSubscribers(Integer topicId,
LastMessageResponseDto message) {
log.trace("Started updateMessageInfoForAllTopicSubscribers, topic id [{}], last message [{}]",
topicId, message);

List<ContactEvent> events = getAllByTopicId(topicId).stream()
.peek(e -> e.setLastMessage(message))
.peek(e -> {
if (!e.getEventType().equals(SUBSCRIBED)) {
e.setUnreadMessages(e.getUnreadMessages() + 1);
}
e.setLastMessage(message);
})
.toList();

log.trace("Last message [{}] was set to all topic id [{}] subscribers", message, topicId);
log.trace("Message info [{}] was updated for all topic id [{}] subscribers", message, topicId);
contactEventRedisRepository.saveAll(events);
}

Expand Down
38 changes: 19 additions & 19 deletions src/main/java/com/chat/yourway/service/NotificationServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import com.chat.yourway.dto.response.MessageNotificationResponseDto;
import com.chat.yourway.dto.response.TopicNotificationResponseDto;
import com.chat.yourway.mapper.MessageNotificationMapper;
import com.chat.yourway.mapper.NotificationMapper;
import com.chat.yourway.model.event.ContactEvent;
import com.chat.yourway.service.interfaces.ContactEventService;
import com.chat.yourway.service.interfaces.MessageService;
import com.chat.yourway.service.interfaces.NotificationService;
import com.chat.yourway.service.interfaces.TopicService;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -19,39 +18,40 @@
public class NotificationServiceImpl implements NotificationService {

private final ContactEventService contactEventService;
private final TopicService topicService;
private final MessageService messageService;
private final MessageNotificationMapper notificationMapper;
private final NotificationMapper notificationMapper;

@Override
public List<MessageNotificationResponseDto> notifyTopicSubscribers(Integer topicId) {
log.trace("Started notifyTopicSubscribers by topic id [{}]", topicId);

return contactEventService.getAllByTopicId(topicId).stream()
.map(notificationMapper::toNotificationResponseDto)
.map(notificationMapper::toMessageNotificationResponseDto)
.toList();
}

@Override
public List<TopicNotificationResponseDto> notifyAllPublicTopicsByEmail(String email) {

return topicService.findAllPublic().stream()
.map(topic -> {
var event = contactEventService.getByTopicIdAndEmail(topic.getId(), email);
var topicNotificationDto = new TopicNotificationResponseDto();
topicNotificationDto.setTopic(topic);
topicNotificationDto.setUnreadMessages(countUnreadMessages(event));
topicNotificationDto.setLastMessage(event.getLastMessage());
return topicNotificationDto;
})
public List<TopicNotificationResponseDto> notifyAllTopicsByEmail(String email) {

return contactEventService.getAllByEmail(email).stream()
.peek(this::countUnreadMessages)
.map(notificationMapper::toTopicNotificationResponseDto)
.toList();
}

@Override
public List<TopicNotificationResponseDto> updateTopicNotification(String email) {
return contactEventService.getAllByEmail(email).stream()
.map(notificationMapper::toTopicNotificationResponseDto)
.toList();
}

private int countUnreadMessages(ContactEvent event) {
return messageService.countMessagesBetweenTimestampByTopicId(
private void countUnreadMessages(ContactEvent event) {
event.setUnreadMessages(messageService.countMessagesBetweenTimestampByTopicId(
event.getTopicId(),
event.getEmail(),
event.getTimestamp());
event.getTimestamp()));
contactEventService.save(event);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public interface ChatNotificationService {
*
* @param userEmail user email.
*/
void notifyAllPublicTopics(String userEmail);
void notifyAllTopics(String userEmail);

/**
* Notify everyone who is subscribed to the same topic.
Expand All @@ -30,4 +30,18 @@ public interface ChatNotificationService {
*/
void notifyAllWhoSubscribedToTopic(Integer topicId);

/**
* Update topic notification for user who subscribed to the same topic.
*
* @param topicId The id of the topic.
*/
void updateNotificationForAllWhoSubscribedToTopic(Integer topicId);

/**
* Update notification for all topics.
*
* @param email user email.
*/
void updateNotificationForAllTopics(String email);

}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@ public interface ContactEventService {
* @param topicId topic id.
* @param lastMessageDto last message Dto.
*/
void setLastMessageToAllTopicSubscribers(Integer topicId, LastMessageResponseDto lastMessageDto);
void updateMessageInfoForAllTopicSubscribers(Integer topicId, LastMessageResponseDto lastMessageDto);

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,19 @@ public interface NotificationService {
List<MessageNotificationResponseDto> notifyTopicSubscribers(Integer topicId);

/**
* Retrieves a list of notifying all public topics.
* Retrieves a list of notifying all topics.
*
* @param email user email.
* @return A list of public topic's information.
* @return A list of topic's information.
*/
List<TopicNotificationResponseDto> notifyAllPublicTopicsByEmail(String email);
List<TopicNotificationResponseDto> notifyAllTopicsByEmail(String email);

/**
* Update info and return a list of notifying all topics.
*
* @param email user email.
* @return A list of topic's information.
*/
List<TopicNotificationResponseDto> updateTopicNotification(String email);

}
4 changes: 2 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ spring.data.redis.password=${REDIS_PASSWORD:admin}

#Hibernate
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
#spring.jpa.show-sql=true
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=validate

Expand Down Expand Up @@ -59,5 +59,5 @@ spring.mail.properties.mail.smtp.starttls.required=true
message.max.amount.reports=2

#Logging:
logging.level.com.chat.yourway=${LOGGING_LEVEL:trace}
logging.level.com.chat.yourway=${LOGGING_LEVEL:info}

Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ void notifyTopicSubscribers_shouldNotifyTopicSubscribersIfSubscribeEvent() {
lastMessageDto.setSentFrom("[email protected]");
lastMessageDto.setLastMessage("Hi");

var event = new ContactEvent("[email protected]", topicId, ONLINE, LocalDateTime.now(),
var event = new ContactEvent("[email protected]", topicId, ONLINE, LocalDateTime.now(), 0,
lastMessageDto);
saveContactEvent(event);
//Stored subscription results for testing
Expand Down Expand Up @@ -233,7 +233,7 @@ void notifyTopicSubscribers_shouldNotifyTopicSubscribersIfAnyContactSubscribedTo
lastMessageDto.setSentFrom("[email protected]");
lastMessageDto.setLastMessage("Hi");

var event = new ContactEvent("[email protected]", topicId, ONLINE, LocalDateTime.now(),
var event = new ContactEvent("[email protected]", topicId, ONLINE, LocalDateTime.now(), 0,
lastMessageDto);
saveContactEvent(event);
//Stored subscription results for testing
Expand Down
Loading

0 comments on commit 7f88ea8

Please sign in to comment.