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

Ping 통신을 위한 데이터 타입 변경 #774

Open
wants to merge 24 commits into
base: develop-be
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
58bd98b
refactor: 메시지 전송 로직 분리
swonny Apr 9, 2024
1d2ba16
refactor: PING response 추가
swonny Apr 9, 2024
c03ddef
refactor: 메서드 분리
swonny Apr 9, 2024
81f6c2d
test: 실패하는 테스트 수정
swonny Apr 9, 2024
76b9b21
refactor: 채팅 타입 enum 설정
swonny Apr 9, 2024
0d108cb
refactor: 채팅 타입 상수로 분리
swonny Apr 9, 2024
7c2aa4f
test: 채팅 데이터타입 테스트 추가
swonny Apr 9, 2024
fc0259e
test: warning 제거
swonny Apr 9, 2024
9aa8fab
style: 개행 추가 및 메서드 순서 정렬
swonny Apr 15, 2024
90fea14
refactor: Ping과 Chat 타입 별 provider 생성
swonny Apr 15, 2024
909d028
refactor: provider명 변경
swonny Apr 15, 2024
2c5a43e
fix: 요구사항에 맞춰 반환하는 변수명 변경
swonny Apr 15, 2024
193c332
refactor: ping handler 메서드 분리
swonny Apr 15, 2024
514e0ac
refactor: ping과 message 전송시 사용되는 data를 Dto로 변환하여 사용하도록 수정
swonny Apr 15, 2024
0e56a7d
test: 사용자 아이디에 해당하는 웹소켓세션 반환 메서드 테스트 추가
swonny Apr 15, 2024
b8f6d51
fix: MockitoJunitRunner 활성화
swonny Apr 16, 2024
4247351
refactor: 메시지와 채팅 타입이 대소문자 구분없이 매핑되도록 수정
JJ503 Apr 11, 2024
c4bc7ef
test: 웹소켓 메시지 전송시 알림 전송, 메시지 로그 업데이트 이벤트 호출 테스트 추가
swonny Apr 17, 2024
6a0a63f
test: 실패하는 테스트 수정
swonny Apr 17, 2024
f20d6b8
test: 불필요한 필드 제거
swonny Apr 18, 2024
84a6a7f
chore: 로그 확인을 위한 알림 전송 임시 로그 추가
swonny Apr 18, 2024
c6e8e91
chore: 로그 확인을 위한 메시지 로그 업데이트 임시 로그 추가
swonny Apr 18, 2024
ceef7d0
chore: 로그 확인을 위한 알림 전송 임시 로그 수정
swonny Apr 18, 2024
5400886
chore: 로그 확인을 위한 임시 로그 수정
swonny Apr 18, 2024
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 @@ -5,7 +5,6 @@
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.ddang.ddang.chat.domain.WebSocketSessions.CHAT_ROOM_ID_KEY;
Expand All @@ -22,10 +21,8 @@ public void add(final WebSocketSession session, final Long chatRoomId) {
webSocketSessions.putIfAbsent(session, chatRoomId);
}

public Set<WebSocketSession> getSessionsByChatRoomId(final Long chatRoomId) {
final WebSocketSessions webSocketSessions = chatRoomSessions.get(chatRoomId);

return webSocketSessions.getSessions();
public WebSocketSessions findSessionsByChatRoomId(final Long chatRoomId) {
return chatRoomSessions.get(chatRoomId);
}
Comment on lines -25 to 26
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

질문

인메모리기에 db와 동일하게 get대신 find로 변경해 주신 게 맞을까요??


public boolean containsByUserId(final Long chatRoomId, final Long userId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.web.socket.WebSocketSession;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

Expand All @@ -27,6 +28,12 @@ public boolean contains(final Long userId) {
.anyMatch(session -> session.getAttributes().get(USER_ID_KEY) == userId);
}

public Optional<WebSocketSession> findByUserId(final long userId) {
return sessions.stream()
.filter(session -> session.getAttributes().get(USER_ID_KEY).equals(userId))
.findFirst();
}

public void remove(final WebSocketSession session) {
sessions.remove(session);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.ddang.ddang.chat.handler;

import com.ddang.ddang.websocket.handler.dto.ChatMessageType;
import com.ddang.ddang.websocket.handler.dto.SendMessageDto;
import com.ddang.ddang.websocket.handler.dto.SessionAttributeDto;
import com.fasterxml.jackson.core.JsonProcessingException;

import java.util.List;
import java.util.Map;

public interface ChatHandleProvider {

List<SendMessageDto> createResponse(
final SessionAttributeDto sessionAttributeDto,
final Map<String, String> data
) throws JsonProcessingException;

ChatMessageType supportsChatType();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.ddang.ddang.chat.handler;

import com.ddang.ddang.websocket.handler.dto.ChatMessageType;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ChatHandleTypeProviderComposite {

private final Map<ChatMessageType, ChatHandleProvider> mappings;

public ChatHandleTypeProviderComposite(final Set<ChatHandleProvider> providers) {
this.mappings = providers.stream()
.collect(Collectors.toMap(ChatHandleProvider::supportsChatType, provider -> provider));
}

public ChatHandleProvider findProvider(final ChatMessageType chatMessageType) {
return mappings.get(chatMessageType);
}
}
Original file line number Diff line number Diff line change
@@ -1,40 +1,30 @@
package com.ddang.ddang.chat.handler;

import com.ddang.ddang.chat.application.MessageService;
import com.ddang.ddang.chat.application.dto.CreateMessageDto;
import com.ddang.ddang.chat.application.event.MessageNotificationEvent;
import com.ddang.ddang.chat.application.event.UpdateReadMessageLogEvent;
import com.ddang.ddang.chat.domain.Message;
import com.ddang.ddang.chat.domain.WebSocketChatSessions;
import com.ddang.ddang.chat.handler.dto.ChatMessageDataDto;
import com.ddang.ddang.chat.handler.dto.MessageDto;
import com.ddang.ddang.chat.presentation.dto.request.CreateMessageRequest;
import com.ddang.ddang.websocket.handler.WebSocketHandleTextMessageProvider;
import com.ddang.ddang.websocket.handler.dto.ChatMessageType;
import com.ddang.ddang.websocket.handler.dto.SendMessageDto;
import com.ddang.ddang.websocket.handler.dto.SessionAttributeDto;
import com.ddang.ddang.websocket.handler.dto.TextMessageType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class ChatWebSocketHandleTextMessageProvider implements WebSocketHandleTextMessageProvider {

private final WebSocketChatSessions sessions;
private static final String CHATROOM_ID_KEY = "chatRoomId";
private static final String TYPE_KEY = "type";

private final ObjectMapper objectMapper;
private final MessageService messageService;
private final ApplicationEventPublisher messageNotificationEventPublisher;
private final ApplicationEventPublisher messageLogEventPublisher;
private final WebSocketChatSessions sessions;
private final ChatHandleTypeProviderComposite chatHandleTypeProviderComposite;

@Override
public TextMessageType supportTextMessageType() {
Expand All @@ -44,94 +34,25 @@ public TextMessageType supportTextMessageType() {
@Override
public List<SendMessageDto> handleCreateSendMessage(
final WebSocketSession session,
final Map<String, String> data
final Map<String, String> chatMessageData
) throws JsonProcessingException {
final SessionAttributeDto sessionAttribute = getSessionAttributes(session);
final ChatMessageDataDto messageData = objectMapper.convertValue(data, ChatMessageDataDto.class);
sessions.add(session, messageData.chatRoomId());
final long chatRoomId = getChatRoomId(chatMessageData);
sessions.add(session, chatRoomId);

final Long writerId = sessionAttribute.userId();
final CreateMessageDto createMessageDto = createMessageDto(messageData, writerId);
final Message message = messageService.create(createMessageDto);
sendNotificationIfReceiverNotInSession(message, sessionAttribute);
final ChatMessageType type = ChatMessageType.findMessageType(chatMessageData.get(TYPE_KEY));
final ChatHandleProvider provider = chatHandleTypeProviderComposite.findProvider(type);

return createSendMessages(message, writerId, createMessageDto.chatRoomId());
return provider.createResponse(convertToSessionAttributeDto(session), chatMessageData);
}

private SessionAttributeDto getSessionAttributes(final WebSocketSession session) {
private SessionAttributeDto convertToSessionAttributeDto(final WebSocketSession session) {
final Map<String, Object> attributes = session.getAttributes();

return objectMapper.convertValue(attributes, SessionAttributeDto.class);
}

private CreateMessageDto createMessageDto(final ChatMessageDataDto messageData, final Long userId) {
final CreateMessageRequest request = new CreateMessageRequest(
messageData.receiverId(),
messageData.contents()
);

return CreateMessageDto.of(userId, messageData.chatRoomId(), request);
}

private void sendNotificationIfReceiverNotInSession(
final Message message,
final SessionAttributeDto sessionAttribute
) {
if (!sessions.containsByUserId(message.getChatRoom().getId(), message.getReceiver().getId())) {
final String profileImageAbsoluteUrl = String.valueOf(sessionAttribute.baseUrl());
messageNotificationEventPublisher.publishEvent(new MessageNotificationEvent(
message,
profileImageAbsoluteUrl
));
}
}

private List<SendMessageDto> createSendMessages(
final Message message,
final Long writerId,
final Long chatRoomId
) throws JsonProcessingException {
final Set<WebSocketSession> groupSessions = sessions.getSessionsByChatRoomId(message.getChatRoom().getId());

final List<SendMessageDto> sendMessageDtos = new ArrayList<>();
for (final WebSocketSession currentSession : groupSessions) {
final TextMessage textMessage = createTextMessage(message, writerId, currentSession);
sendMessageDtos.add(new SendMessageDto(currentSession, textMessage));
updateReadMessageLog(currentSession, chatRoomId, message);
}

return sendMessageDtos;
}

private TextMessage createTextMessage(
final Message message,
final Long writerId,
final WebSocketSession session
) throws JsonProcessingException {
final boolean isMyMessage = isMyMessage(session, writerId);
final MessageDto messageDto = MessageDto.of(message, isMyMessage);

return new TextMessage(objectMapper.writeValueAsString(messageDto));
}

private boolean isMyMessage(final WebSocketSession session, final Long writerId) {
final long userId = Long.parseLong(String.valueOf(session.getAttributes().get("userId")));

return writerId.equals(userId);
}

private void updateReadMessageLog(
final WebSocketSession currentSession,
final Long chatRoomId,
final Message message
) {
final SessionAttributeDto sessionAttributes = getSessionAttributes(currentSession);
final UpdateReadMessageLogEvent updateReadMessageLogEvent = new UpdateReadMessageLogEvent(
sessionAttributes.userId(),
chatRoomId,
message.getId()
);
messageLogEventPublisher.publishEvent(updateReadMessageLogEvent);
private long getChatRoomId(final Map<String, String> data) {
return Long.parseLong(data.get(CHATROOM_ID_KEY));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
package com.ddang.ddang.chat.handler;

import com.ddang.ddang.chat.application.MessageService;
import com.ddang.ddang.chat.application.dto.CreateMessageDto;
import com.ddang.ddang.chat.application.event.MessageNotificationEvent;
import com.ddang.ddang.chat.application.event.UpdateReadMessageLogEvent;
import com.ddang.ddang.chat.domain.Message;
import com.ddang.ddang.chat.domain.WebSocketChatSessions;
import com.ddang.ddang.chat.domain.WebSocketSessions;
import com.ddang.ddang.chat.handler.dto.ChatMessageDataDto;
import com.ddang.ddang.chat.handler.dto.MessageDataDto;
import com.ddang.ddang.chat.handler.dto.MessageDto;
import com.ddang.ddang.chat.handler.dto.SendChatResponse;
import com.ddang.ddang.chat.handler.dto.SendMessageStatus;
import com.ddang.ddang.chat.presentation.dto.request.CreateMessageRequest;
import com.ddang.ddang.websocket.handler.dto.ChatMessageType;
import com.ddang.ddang.websocket.handler.dto.SendMessageDto;
import com.ddang.ddang.websocket.handler.dto.SessionAttributeDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class MessageTypeHandler implements ChatHandleProvider {

private final WebSocketChatSessions sessions;
private final ObjectMapper objectMapper;
private final MessageService messageService;
private final ApplicationEventPublisher messageLogEventPublisher;
private final ApplicationEventPublisher messageNotificationEventPublisher;

@Override
public ChatMessageType supportsChatType() {
return ChatMessageType.MESSAGE;
}

@Override
public List<SendMessageDto> createResponse(
final SessionAttributeDto sessionAttributeDto,
final Map<String, String> data
) throws JsonProcessingException {
final Long writerId = sessionAttributeDto.userId();
final MessageDataDto messageDataDto = MessageDataDto.from(data);

final Message message = createMessage(data, writerId);

sendNotificationIfReceiverNotInSession(message, sessionAttributeDto);

return createSendMessages(message, writerId, messageDataDto.chatRoomId());
}

private Message createMessage(final Map<String, String> data, final long writerId) {
final ChatMessageDataDto messageData = objectMapper.convertValue(data, ChatMessageDataDto.class);
final CreateMessageDto createMessageDto = createMessageDto(messageData, writerId);

return messageService.create(createMessageDto);
}

private void sendNotificationIfReceiverNotInSession(
final Message message,
final SessionAttributeDto sessionAttribute
) {
if (!sessions.containsByUserId(message.getChatRoom().getId(), message.getReceiver().getId())) {
final String profileImageAbsoluteUrl = String.valueOf(sessionAttribute.baseUrl());
messageNotificationEventPublisher.publishEvent(new MessageNotificationEvent(
message,
profileImageAbsoluteUrl
));
}
}

private List<SendMessageDto> createSendMessages(
final Message message,
final Long writerId,
final Long chatRoomId
) throws JsonProcessingException {
final WebSocketSessions groupSessions = sessions.findSessionsByChatRoomId(message.getChatRoom().getId());

final List<SendMessageDto> sendMessageDtos = new ArrayList<>();
for (final WebSocketSession currentSession : groupSessions.getSessions()) {
final MessageDto messageDto = MessageDto.of(message, isMyMessage(currentSession, writerId));
final TextMessage textMessage = createTextMessage(messageDto);
sendMessageDtos.add(new SendMessageDto(currentSession, textMessage));
updateReadMessageLog(currentSession, chatRoomId, message);
}

return sendMessageDtos;
}

private void updateReadMessageLog(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

필수

해당 메서드가 createTextMessage 아래로 내려가야겠네요!

final WebSocketSession currentSession,
final Long chatRoomId,
final Message message
) {
final SessionAttributeDto sessionAttributes = convertToSessionAttributeDto(currentSession);
final UpdateReadMessageLogEvent updateReadMessageLogEvent = new UpdateReadMessageLogEvent(
sessionAttributes.userId(),
chatRoomId,
message.getId()
);
messageLogEventPublisher.publishEvent(updateReadMessageLogEvent);
}

private SessionAttributeDto convertToSessionAttributeDto(final WebSocketSession session) {
final Map<String, Object> attributes = session.getAttributes();

return objectMapper.convertValue(attributes, SessionAttributeDto.class);
}

private CreateMessageDto createMessageDto(final ChatMessageDataDto messageData, final Long userId) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

필수

createMessage 아래로 위치해야겠네요!

final CreateMessageRequest request = new CreateMessageRequest(messageData.receiverId(), messageData.contents());

return CreateMessageDto.of(userId, messageData.chatRoomId(), request);
}

private boolean isMyMessage(
final WebSocketSession session,
final Long writerId
) {
final long userId = Long.parseLong(String.valueOf(session.getAttributes().get("userId")));

return writerId.equals(userId);
}

private TextMessage createTextMessage(final MessageDto messageDto) throws JsonProcessingException {
final SendChatResponse sendChatResponse = new SendChatResponse(SendMessageStatus.SUCCESS, List.of(messageDto));

return new TextMessage(objectMapper.writeValueAsString(sendChatResponse));
}
}
Loading
Loading