Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #74

Merged
merged 5 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.chat.yourway.dto.request.TopicRequestDto;
import com.chat.yourway.dto.response.ApiErrorResponseDto;
import com.chat.yourway.dto.response.ContactResponseDto;
import com.chat.yourway.dto.response.TopicInfoResponseDto;
import com.chat.yourway.dto.response.TopicResponseDto;
import com.chat.yourway.service.interfaces.TopicService;
import com.chat.yourway.service.interfaces.TopicSubscriberService;
Expand Down Expand Up @@ -149,7 +150,7 @@ public TopicResponseDto findById(@PathVariable Integer id) {
content = @Content(schema = @Schema(implementation = ApiErrorResponseDto.class)))
})
@GetMapping(path = "/all", produces = APPLICATION_JSON_VALUE)
public List<TopicResponseDto> findAllPublic() {
public List<TopicInfoResponseDto> findAllPublic() {
return topicService.findAllPublic();
}

Expand Down Expand Up @@ -322,7 +323,7 @@ public void removeToFavouriteTopic(
content = @Content(schema = @Schema(implementation = ApiErrorResponseDto.class)))
})
@GetMapping(path = "/favourite", produces = APPLICATION_JSON_VALUE)
public List<TopicResponseDto> findAllFavouriteTopics(
public List<TopicInfoResponseDto> findAllFavouriteTopics(
@AuthenticationPrincipal UserDetails userDetails) {
return topicService.findAllFavouriteTopics(userDetails);
}
Expand All @@ -333,7 +334,7 @@ public List<TopicResponseDto> findAllFavouriteTopics(
@ApiResponse(responseCode = "200", description = SUCCESSFULLY_FOUND_TOPIC)
})
@GetMapping(path = "/popular/public", produces = APPLICATION_JSON_VALUE)
public List<TopicResponseDto> findAllPopularPublicTopics() {
public List<TopicInfoResponseDto> findAllPopularPublicTopics() {
return topicService.findPopularPublicTopics();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.chat.yourway.dto.response;

import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDateTime;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@ToString
public class TopicInfoResponseDto {
@Schema(description = "ID", example = "1")
private Integer id;
@Schema(description = "New Topic name", example = "My programming topic")
private String topicName;
@Schema(description = "Email of Topic creator", example = "[email protected]")
private String createdBy;
@Schema(description = "Created time")
private LocalDateTime createdAt;

}
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);

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

import com.chat.yourway.dto.response.TopicInfoResponseDto;
import com.chat.yourway.dto.response.TopicResponseDto;
import com.chat.yourway.model.Topic;
import java.util.List;
Expand All @@ -12,6 +13,8 @@ public interface TopicMapper {
TopicResponseDto toResponseDto(Topic topic);
List<TopicResponseDto> toListResponseDto(List<Topic> topics);

List<TopicInfoResponseDto> toListInfoResponseDto(List<Topic> topics);

@Mapping(target = "messages", ignore = true)
Topic toEntity(TopicResponseDto topicResponseDto);

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/chat/yourway/model/Topic.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ public class Topic {
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;

@ManyToMany(fetch = FetchType.EAGER)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
schema = "chat",
name = "topic_tag",
joinColumns = @JoinColumn(name = "topic_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))
private Set<Tag> tags;

@OneToMany(mappedBy = "topic", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OneToMany(mappedBy = "topic", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<TopicSubscriber> topicSubscribers;

@OneToMany(mappedBy = "topic", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
Expand Down
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
26 changes: 12 additions & 14 deletions src/main/java/com/chat/yourway/repository/TopicRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public interface TopicRepository extends JpaRepository<Topic, Integer> {
@Query(
value =
"""
SELECT *
FROM chat.topic t
WHERE to_tsvector('english', t.topic_name) @@ to_tsquery('english', :query)
""",
SELECT *
FROM chat.topic t
WHERE to_tsvector('english', t.topic_name) @@ to_tsquery('english', :query)
""",
nativeQuery = true)
List<Topic> findAllByTopicName(String query);

Expand All @@ -31,18 +31,16 @@ WHERE to_tsvector('english', t.topic_name) @@ to_tsquery('english', :query)

@Query(
"select t from Topic t join fetch t.topicSubscribers ts "
+ "where ts.contact.email = :contactEmail and ts.isFavouriteTopic = true")
+ "where ts.contact.email = :contactEmail and ts.isFavouriteTopic = true")
List<Topic> findAllFavouriteTopicsByContactEmail(String contactEmail);

boolean existsByIdAndIsPublic(int topicId, boolean isPublic);

@Query(nativeQuery = true, value =
"SELECT t.*, COUNT(ts.id) AS ts_count, COUNT(m.id) AS m_count " +
"FROM chat.topic t " +
"JOIN chat.topic_subscriber ts ON t.id = ts.topic_id " +
"JOIN chat.message m ON t.id = m.topic_id " +
"WHERE t.is_public = true " +
"GROUP BY t.id " +
"ORDER BY ts_count DESC, m_count DESC")
"SELECT t.*, COUNT(ts.id) AS ts_count, COUNT(m.id) AS m_count " +
"FROM chat.topic t " +
"JOIN chat.topic_subscriber ts ON t.id = ts.topic_id " +
"JOIN chat.message m ON t.id = m.topic_id " +
"WHERE t.is_public = true " +
"GROUP BY t.id " +
"ORDER BY ts_count DESC, m_count DESC")
List<Topic> findPopularPublicTopics();
}
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
Loading
Loading