Skip to content

Commit

Permalink
Merge pull request #73 from kookmin-sw/refactor/wsresponse
Browse files Browse the repository at this point in the history
Refactor/wsresponse
  • Loading branch information
imjanghyeok authored May 15, 2024
2 parents ffecaf3 + 0214f84 commit f095f44
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,11 @@ public String leftRoom(Long roomId, Long memberId) {
return "속해있지 않은 채팅방입니다.";
}
chatRoom.setStatus(ChatRoom.Status.close);
simpMessagingTemplate.convertAndSend("/sub/chat/" + sender.getId(), ChatRoomLeftResponse.of(sender, "상대방이 떠났습니다."));
String content = "상대방이 떠났습니다.";
String method = "receiveLeftRoom";
LocalDateTime sendTime = LocalDateTime.now();
ChatRoomLeftResponse chatRoomLeftResponse =ChatRoomLeftResponse.of(method, roomId, leftMember, sendTime, content);
simpMessagingTemplate.convertAndSend("/sub/chat/" + sender.getId(),chatRoomLeftResponse);
chatRoomRepository.save(chatRoom);
chatRoomMemberRepository.save(chatRoomMember);

Expand Down
84 changes: 57 additions & 27 deletions src/main/java/capstone/facefriend/chat/service/MessageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ private ChatRoom findRoomById(String destination, Long roomId) {
ChatRoom chatRoom = chatRoomRepository.findById(roomId)
.orElse(null);
if (chatRoom == null) {
simpMessagingTemplate.convertAndSend(destination, MemberExceptionType.NOT_FOUND.message());
throw new MemberException(MemberExceptionType.NOT_FOUND);
simpMessagingTemplate.convertAndSend(destination, ChatExceptionType.NOT_FOUND.message());
throw new ChatException(ChatExceptionType.NOT_FOUND);
}
return chatRoom;
}
Expand All @@ -70,8 +70,8 @@ private ChatRoomMember findSenderReceiver(String destination, Long senderId, Lon
ChatRoomMember chatRoomMember = chatRoomMemberRepository.findBySenderAndReceiver(senderId, receiveId)
.orElse(null);
if (chatRoomMember == null) {
simpMessagingTemplate.convertAndSend(destination, MemberExceptionType.NOT_FOUND.message());
throw new MemberException(MemberExceptionType.NOT_FOUND);
simpMessagingTemplate.convertAndSend(destination, ChatExceptionType.NOT_FOUND.message());
throw new ChatException(ChatExceptionType.NOT_FOUND);
}
return chatRoomMember;
}
Expand All @@ -80,8 +80,8 @@ private ChatRoomMember findChatRoomMemberByChatRoomId(String destination, Long r
ChatRoomMember chatRoomMember = chatRoomMemberRepository.findByChatRoomId(roomId)
.orElse(null);
if (chatRoomMember == null) {
simpMessagingTemplate.convertAndSend(destination, MemberExceptionType.NOT_FOUND.message());
throw new MemberException(MemberExceptionType.NOT_FOUND);
simpMessagingTemplate.convertAndSend(destination, ChatExceptionType.NOT_FOUND.message());
throw new ChatException(ChatExceptionType.NOT_FOUND);
}
return chatRoomMember;
}
Expand Down Expand Up @@ -133,6 +133,7 @@ public void sendMessage(MessageRequest messageRequest, Long senderId) {
chatMessageRepository.save(chatMessage);

MessageResponse messageResponse = new MessageResponse();
messageResponse.setMethod("receiveChat");
messageResponse.setRoomId(chatMessage.getChatRoom().getId());
messageResponse.setSenderId(senderId);
messageResponse.setReceiveId(receiver.getId());
Expand Down Expand Up @@ -180,12 +181,16 @@ public void sendHeart(Long senderId, Long receiveId) {
chatRoomMemberRepository.save(chatRoomMember);

SendHeartResponse sendHeartResponse = new SendHeartResponse();
sendHeartResponse.setRoomId(chatRoom.getId());
sendHeartResponse.setSenderId(sender.getId());
sendHeartResponse.setReceiveId(receiveId);
sendHeartResponse.setMethod("receiveHeart");
sendHeartResponse.setMemberId(receiveId);
sendHeartResponse.setSenderName(sender.getBasicInfo().getNickname());
sendHeartResponse.setCreatedAt(LocalDateTime.now());
sendHeartResponse.setSenderId(sender.getId());
sendHeartResponse.setType("Heart");
sendHeartResponse.setSenderOriginS3url(sender.getFaceInfo().getOriginS3url());
sendHeartResponse.setSenderGeneratedS3url(sender.getFaceInfo().getGeneratedS3url());
sendHeartResponse.setChatRoom(chatRoom);
sendHeartResponse.setCreatedAt(LocalDateTime.now());
sendHeartResponse.setSender(false);

String topic = channelTopic.getTopic();
simpMessagingTemplate.convertAndSend(exceptionDestination, "대화 요청 성공");
Expand Down Expand Up @@ -222,7 +227,9 @@ public void heartReply(HeartReplyRequest heartReplyRequest, Long receiveId) {
// 동적으로 목적지 설정
String destination = "/sub/chat/" + sender.getId();

HeartReplyResponse heartReplyResponse = HeartReplyResponse.of(receiveId, heartReplyRequest);
String method = "receiveHeartResponse";

HeartReplyResponse heartReplyResponse = HeartReplyResponse.of(receiveId, heartReplyRequest, method);

// 메시지 전송
simpMessagingTemplate.convertAndSend(destination, heartReplyResponse);
Expand Down Expand Up @@ -252,10 +259,14 @@ public void enterApplication(Long memberId) {
socketInfoRedisRepository.save(socketInfo);
if (isExistUnReadMessage(memberId)) {
sendSentMessage(memberId);
} else {
simpMessagingTemplate.convertAndSend(exceptionDestination, "큐잉된 메시지가 없습니다.");
}

if(isExistUnSendHeart(memberId)) {
sendSentHeart(memberId);
sendSentHeart(exceptionDestination, memberId);
} else {
simpMessagingTemplate.convertAndSend(exceptionDestination, "큐잉된 대화요청이 없습니다.");
}

simpMessagingTemplate.convertAndSend(exceptionDestination, "저장 성공");
Expand Down Expand Up @@ -283,33 +294,52 @@ private Boolean isExistUnSendHeart(Long memberId) {
private void sendSentMessage(Long receiveId) {
String topic = channelTopic.getTopic();
String destination = "/sub/chat" + receiveId + "message";
Long messagesListSize = redisTemplate.opsForList().size(destination);
log.info(messagesListSize.toString());
log.info("messageList: {}", redisTemplate.opsForList().range(destination, 0, -1));
List<Object> messages = redisTemplate.opsForList().range(destination, 0, -1);
Long messagesListSize = (messages != null) ? (long) messages.size() : 0;
log.info("Message list size: {}", messagesListSize);

if (messagesListSize > 0) {
for (Long i = messagesListSize; i > 0; i--) {
// 맵으로 받음
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) redisTemplate.opsForList().rightPop(destination);
MessageResponse messageResponse = (MessageResponse) map.get(destination);
log.info("messageResponse: {}", messageResponse.toString());
for (Object messageObj : messages) {
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) messageObj;
MessageResponse messageResponse = new MessageResponse(map);
log.info("UnReadMessageResponse: {}", messageResponse.toString());
redisTemplate.convertAndSend(topic, messageResponse);
}
// 리스트 비우기
redisTemplate.delete(destination);
log.info("Message list cleared.");
} else {
log.warn("Message list is empty.");
}
}

private void sendSentHeart(Long receiveId) {





private void sendSentHeart(String exceptionDestination, Long receiveId) {
String topic = channelTopic.getTopic();
String destination = "/sub/chat" + receiveId + "heart";
Long messagesListSize = redisTemplate.opsForList().size(destination);
log.info("SendHeartListSize: {}", messagesListSize.toString());
List<Object> sendHearts = redisTemplate.opsForList().range(destination, 0, -1);
Long messagesListSize = (sendHearts != null) ? (long) sendHearts.size() : 0;
log.info("Message list size: {}", messagesListSize);

if (messagesListSize > 0) {
for (Long i = messagesListSize; i > 0; i--) {
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) redisTemplate.opsForList().rightPop(destination);
SendHeartResponse sendHeartResponse = (SendHeartResponse) map.get(destination);
log.info("messageResponse: {}", sendHeartResponse.toString());
for (Object sendHeartObj : sendHearts) {
LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) sendHeartObj;
LinkedHashMap<String, Object> chatRoomMap = (LinkedHashMap<String, Object>) map.get("chatRoom");
Long roomId = ((Number) chatRoomMap.get("id")).longValue();
ChatRoom chatRoom = findRoomById(exceptionDestination, roomId);
SendHeartResponse sendHeartResponse = new SendHeartResponse(map, chatRoom);
log.info("UnReadSendHeartResponse: {}", sendHeartResponse.toString());
redisTemplate.convertAndSend(topic, sendHeartResponse);
}
// 리스트 비우기
redisTemplate.delete(destination);
log.info("Sendheart list cleared.");
} else {
log.warn("Sendheart list is empty.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ public void onMessage(Message message, byte[] pattern) {
SendHeartResponse sendHeartResponse = objectMapper.readValue(publishMessage, SendHeartResponse.class);

GetSendHeartResponse chatSendHeartResponse = new GetSendHeartResponse(sendHeartResponse);
if (isExistSubscriber(chatSendHeartResponse.getReceiveId())) {
messagingTemplate.convertAndSend("/sub/chat/" + sendHeartResponse.getReceiveId(), chatSendHeartResponse);
if (isExistSubscriber(chatSendHeartResponse.getMemberId())) {
messagingTemplate.convertAndSend("/sub/chat/" + sendHeartResponse.getMemberId(), chatSendHeartResponse);
} else {
saveUnReadHeart("/sub/chat" + sendHeartResponse.getReceiveId() + "heart", sendHeartResponse);
saveUnReadHeart("/sub/chat" + sendHeartResponse.getMemberId() + "heart", sendHeartResponse);
}

messagingTemplate.convertAndSend("/sub/chat/" + sendHeartResponse.getReceiveId(), chatSendHeartResponse);
messagingTemplate.convertAndSend("/sub/chat/" + sendHeartResponse.getMemberId(), chatSendHeartResponse);
}
} catch (IOException e) {
throw new RuntimeException("Failed to process message", e);
Expand All @@ -79,17 +79,21 @@ private void saveUnReadMessage(String destination, MessageResponse messageRespon
Boolean isUnRead = redisTemplate.hasKey(destination);
log.info(isUnRead.toString());
if (isUnRead) {
messageResponse.setMethod("connectChat");
redisTemplate.opsForList().rightPush(destination, messageResponse);
} else {
messageResponse.setMethod("connectChat");
redisTemplate.opsForList().rightPush(destination, messageResponse);
}
}

private void saveUnReadHeart(String destination, SendHeartResponse sendHeartResponse) {
Boolean isUnRead = redisTemplate.hasKey(destination);
if (isUnRead) {
sendHeartResponse.setMethod("connectHeart");
redisTemplate.opsForList().rightPush(destination, sendHeartResponse);
} else {
sendHeartResponse.setMethod("connectHeart");
redisTemplate.opsForList().rightPush(destination, sendHeartResponse);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
package capstone.facefriend.chat.service.dto.chatroom;

import capstone.facefriend.member.domain.member.Member;
import com.fasterxml.jackson.annotation.JsonFormat;

import java.time.LocalDateTime;

public record ChatRoomLeftResponse (
String method,
Long roomId,
Long senderId,
String senderNickname,
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "Asia/Seoul") LocalDateTime sendTime,
String content
){
public static ChatRoomLeftResponse of (Member sender, String content) {
public static ChatRoomLeftResponse of (String method, Long roomId, Member sender, LocalDateTime sendTime, String content) {
return new ChatRoomLeftResponse(
method,
roomId,
sender.getId(),
sender.getBasicInfo().getNickname(),
sendTime,
content
);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package capstone.facefriend.chat.service.dto.heart;

import capstone.facefriend.chat.domain.ChatRoom;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
Expand All @@ -10,21 +11,29 @@
@Data
@NoArgsConstructor
public class GetSendHeartResponse {
private String method;
private String senderName;
private Long senderId;
private Long receiveId;
private Long memberId;
private String type;
private Long roomId;
private String senderGeneratedS3url;
private String senderOriginS3url;
private ChatRoom chatRoom;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "Asia/Seoul")
private LocalDateTime sendTime;
private Boolean isSender;


public GetSendHeartResponse(SendHeartResponse sendHeartResponse) {
this.method = sendHeartResponse.getMethod();
this.senderName = sendHeartResponse.getSenderName();
this.senderId = sendHeartResponse.getSenderId();
this.receiveId = sendHeartResponse.getReceiveId();
this.memberId = sendHeartResponse.getMemberId();
this.type = sendHeartResponse.getType();
this.roomId = sendHeartResponse.getRoomId();
this.sendTime = sendHeartResponse.getCreatedAt();
this.isSender = sendHeartResponse.isSender();
this.chatRoom = sendHeartResponse.getChatRoom();
this.senderGeneratedS3url = sendHeartResponse.getSenderGeneratedS3url();
this.senderOriginS3url = sendHeartResponse.getSenderOriginS3url();
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package capstone.facefriend.chat.service.dto.heart;

public record HeartReplyResponse(
String method,
Long senderId,
String intention

) {
public static HeartReplyResponse of (Long senderId, HeartReplyRequest heartReplyRequest) {
public static HeartReplyResponse of (Long senderId, HeartReplyRequest heartReplyRequest, String method) {
return new HeartReplyResponse(
method,
senderId,
heartReplyRequest.intention()
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,41 @@
package capstone.facefriend.chat.service.dto.heart;

import capstone.facefriend.chat.domain.ChatRoom;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SendHeartResponse implements Serializable {
private Long roomId;
private Long senderId;
private Long receiveId;
private String method;
private Long memberId;
private String senderName;
private Long senderId;
private String type;
private String senderGeneratedS3url;
private String senderOriginS3url;
private ChatRoom chatRoom;
private String sessionId;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "Asia/Seoul")
private LocalDateTime createdAt;
private boolean isSender;

public SendHeartResponse(LinkedHashMap<String, Object> map, ChatRoom chatRoom) {
this.method = (String) map.get("method");
this.memberId = ((Number) map.get("memberId")).longValue();
this.senderName = (String) map.get("senderName");
this.senderId = ((Number) map.get("senderId")).longValue(); // Fix this line
this.type = (String) map.get("type");
this.senderGeneratedS3url = (String) map.get("senderGeneratedS3url");
this.senderOriginS3url = (String) map.get("senderOriginS3url");
this.sessionId = (String) map.get("sessionId");
this.createdAt = LocalDateTime.parse((String) map.get("createdAt"));
this.isSender = (boolean) map.get("sender");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
@Data
@NoArgsConstructor
public class GetMessageResponse {
private String method;
private Long roomId;
private Long senderId;
private Long receiveId;
Expand All @@ -22,6 +23,7 @@ public class GetMessageResponse {
private Boolean isRead;

public GetMessageResponse(MessageResponse messageResponse) {
this.method = messageResponse.getMethod();
this.roomId = messageResponse.getRoomId();
this.senderId = messageResponse.getSenderId();
this.receiveId = messageResponse.getReceiveId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.LinkedList;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageResponse implements Serializable {
private String method;
private Long roomId;
private Long receiveId;
private Long senderId;
Expand All @@ -23,4 +26,17 @@ public class MessageResponse implements Serializable {
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "Asia/Seoul")
private LocalDateTime createdAt;
private Boolean isRead;

public MessageResponse(LinkedHashMap<String, Object> map) {
this.method = (String) map.get("method");
this.roomId = ((Number) map.get("roomId")).longValue();
this.receiveId = ((Number) map.get("receiveId")).longValue();
this.senderId = ((Number) map.get("senderId")).longValue();
this.content = (String) map.get("content");
this.type = (String) map.get("type");
this.senderNickname = (String) map.get("senderNickname");
this.senderFaceInfoS3Url = (String) map.get("senderFaceInfoS3Url");
this.createdAt = LocalDateTime.parse((String) map.get("createdAt"));
this.isRead = (Boolean) map.get("isRead");
}
}

0 comments on commit f095f44

Please sign in to comment.