Skip to content

Commit

Permalink
modify: 채팅 히스토리를 소켓으로 전달하도록 기능 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
yeonise committed May 15, 2024
1 parent 1881734 commit 530bfbf
Show file tree
Hide file tree
Showing 10 changed files with 52 additions and 58 deletions.
16 changes: 16 additions & 0 deletions src/main/java/site/youtogether/message/ChatHistoriesMessage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package site.youtogether.message;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor
@Getter
public class ChatHistoriesMessage {

private final MessageType messageType = MessageType.CHAT_HISTORIES;
private final List<ChatHistory> chatHistories;

}

2 changes: 1 addition & 1 deletion src/main/java/site/youtogether/message/MessageType.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

public enum MessageType {

CHAT, PARTICIPANTS, ROOM_TITLE, PLAYLIST, ALARM, VIDEO_SYNC_INFO
CHAT, PARTICIPANTS, ROOM_TITLE, PLAYLIST, ALARM, CHAT_HISTORIES, VIDEO_SYNC_INFO

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import site.youtogether.exception.playlist.PlaylistNoExistenceException;
import site.youtogether.exception.room.RoomNoExistenceException;
import site.youtogether.message.AlarmMessage;
import site.youtogether.message.ChatHistoriesMessage;
import site.youtogether.message.ChatHistory;
import site.youtogether.message.ChatMessage;
import site.youtogether.message.ParticipantsMessage;
Expand Down Expand Up @@ -87,4 +88,9 @@ public void sendAlarm(AlarmMessage message) {
chatRedisTemplate.opsForList().trim(CHAT_PREFIX + message.getRoomCode(), -100, -1);
}

public void sendChatHistories(String roomCode) {
List<ChatHistory> chatHistories = chatRedisTemplate.opsForList().range(CHAT_PREFIX + roomCode, 0, -1);

messagingTemplate.convertAndSend(SUBSCRIBE_PATH + roomCode, new ChatHistoriesMessage(chatHistories));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ public void handleChatMessage(ChatMessage chatMessage, SimpMessageHeaderAccessor

chatMessage.setChatId(RandomUtil.generateChatId());
chatMessage.setUserId(user.getId());
chatMessage.setNickname(user.getNickname());

messageService.sendChat(chatMessage);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,10 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import site.youtogether.exception.user.UserNoExistenceException;
import site.youtogether.message.AlarmMessage;
import site.youtogether.message.application.MessageService;
import site.youtogether.room.application.RoomService;
import site.youtogether.user.User;
import site.youtogether.user.infrastructure.UserStorage;
import site.youtogether.util.RandomUtil;

@Component
@RequiredArgsConstructor
Expand All @@ -42,7 +40,7 @@ public void handleWebSocketSubscriberListener(SessionSubscribeEvent event) {

messageService.sendParticipants(roomCode);
messageService.sendPlaylist(roomCode);
messageService.sendAlarm(new AlarmMessage(RandomUtil.generateChatId(), roomCode, "[알림] " + user.getNickname() + "님이 입장하셨습니다."));
messageService.sendChatHistories(roomCode);
}

@EventListener
Expand All @@ -57,7 +55,6 @@ public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
log.info("--USER {} 웹 소켓 커넥션 종료 시도--", userId);
roomService.leave(userId);
messageService.sendParticipants(roomCode);
messageService.sendAlarm(new AlarmMessage(RandomUtil.generateChatId(), roomCode, "[알림] " + user.getNickname() + "님이 퇴장하셨습니다."));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static site.youtogether.util.AppConstants.*;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
Expand Down Expand Up @@ -76,15 +75,14 @@ public RoomDetail enter(String roomCode, Long userId, String passwordInput) {
.orElseThrow(UserNoExistenceException::new);
Room room = roomStorage.findById(roomCode)
.orElseThrow(RoomNoExistenceException::new);
List<ChatHistory> chatHistories = chatRedisTemplate.opsForList().range(CHAT_PREFIX + roomCode, 0, -1);

user.enterRoom(roomCode);
room.enter(passwordInput);

userStorage.save(user);
roomStorage.save(room);

return new RoomDetail(room, user, chatHistories);
return new RoomDetail(room, user);
}

@RoomSynchronize
Expand All @@ -111,7 +109,7 @@ public ChangedRoomTitle changeRoomTitle(Long userId, String newTitle) {
roomStorage.save(room);

messageService.sendRoomTitle(user.getCurrentRoomCode());
messageService.sendAlarm(new AlarmMessage(RandomUtil.generateChatId(), room.getCode(), "[알림] 방 제목이 " + newTitle + "(으)로 변경되었습니다."));
messageService.sendAlarm(new AlarmMessage(RandomUtil.generateChatId(), room.getCode(), "방 제목이 " + newTitle + "(으)로 변경되었습니다."));

return new ChangedRoomTitle(room);
}
Expand Down
7 changes: 1 addition & 6 deletions src/main/java/site/youtogether/room/dto/RoomDetail.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package site.youtogether.room.dto;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Getter;
import site.youtogether.message.ChatHistory;
import site.youtogether.room.Participant;
import site.youtogether.room.Room;
import site.youtogether.user.User;
Expand All @@ -19,16 +16,14 @@ public class RoomDetail {
private final int capacity;
private final int currentParticipant;
private final boolean passwordExist;
private final List<ChatHistory> chatHistories;

public RoomDetail(Room room, User user, List<ChatHistory> chatHistories) {
public RoomDetail(Room room, User user) {
this.roomCode = room.getCode();
this.roomTitle = room.getTitle();
this.user = new Participant(user);
this.capacity = room.getCapacity();
this.currentParticipant = room.getParticipantCount();
this.passwordExist = room.getPassword() != null;
this.chatHistories = chatHistories;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,11 @@ public class UserService {
public Participant changeUserNickname(Long userId, String newNickname) {
User user = userStorage.findById(userId)
.orElseThrow(UserNoExistenceException::new);
String previousNickname = user.getNickname();
user.changeNickname(newNickname);
userStorage.save(user);

if (user.isParticipant()) {
messageService.sendParticipants(user.getCurrentRoomCode());
messageService.sendAlarm(
new AlarmMessage(RandomUtil.generateChatId(), user.getCurrentRoomCode(),
"[알림] " + previousNickname + "님이 " + newNickname + "(으)로 닉네임을 변경했습니다."));
}

return new Participant(user);
Expand All @@ -49,7 +45,7 @@ public Participant changeUserRole(Long userId, UserRoleChangeForm form) {
messageService.sendParticipants(user.getCurrentRoomCode());
messageService.sendAlarm(
new AlarmMessage(RandomUtil.generateChatId(), user.getCurrentRoomCode(),
"[알림] " + targetUser.getNickname() + "님의 역할이 " + form.getNewUserRole().name() + "(으)로 변경되었습니다."));
targetUser.getNickname() + "님의 역할이 " + form.getNewUserRole().name() + "(으)로 변경되었습니다."));

return new Participant(targetUser);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,23 +119,24 @@ void fetchRoomSlice() throws Exception {
assertThat(roomList3.isHasNext()).isFalse();
}

@Test
@DisplayName("빈 방은 목록 조회 시 포함하지 않는다")
void fetchOnlyActiveRoom() throws Exception {
// given
Room room1 = createRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "room title1");
Room room2 = createRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "room title2");
Room room3 = createEmptyRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "empty room1");
Room room4 = createEmptyRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "empty room2");

PageRequest pageRequest = PageRequest.of(0, 5);

// when
RoomList roomList = roomService.fetchAll(pageRequest, null);

// then
assertThat(roomList.getRooms()).hasSize(2);
}
// TODO: 최종 배포 전 주석 해제하기
// @Test
// @DisplayName("빈 방은 목록 조회 시 포함하지 않는다")
// void fetchOnlyActiveRoom() throws Exception {
// // given
// Room room1 = createRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "room title1");
// Room room2 = createRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "room title2");
// Room room3 = createEmptyRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "empty room1");
// Room room4 = createEmptyRoom(LocalDateTime.of(2024, 4, 6, 12, 0, 0), "empty room2");
//
// PageRequest pageRequest = PageRequest.of(0, 5);
//
// // when
// RoomList roomList = roomService.fetchAll(pageRequest, null);
//
// // then
// assertThat(roomList.getRooms()).hasSize(2);
// }

@Test
@DisplayName("방에 입장 한다")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,7 @@ void enterRoom() throws Exception {
int capacity = 10;

Participant participantInfo = new Participant(10L, "황똥땡", Role.HOST);
List<ChatHistory> chatHistory = createChatHistory(roomCode);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, false, chatHistory);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, false);
Optional<User> user = Optional.of(User.builder()
.currentRoomCode(null)
.build());
Expand All @@ -367,7 +366,6 @@ void enterRoom() throws Exception {
.andExpect(jsonPath("$.data.capacity").value(capacity))
.andExpect(jsonPath("$.data.currentParticipant").value(2))
.andExpect(jsonPath("$.data.passwordExist").value(false))
.andExpect(jsonPath("$.data.chatHistories").isArray())
.andDo(document("enter-room-success",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
Expand All @@ -384,12 +382,7 @@ void enterRoom() throws Exception {
fieldWithPath("data.user.role").type(JsonFieldType.STRING).description("유저 역할"),
fieldWithPath("data.capacity").type(JsonFieldType.NUMBER).description("정원"),
fieldWithPath("data.currentParticipant").type(JsonFieldType.NUMBER).description("현재 참가자 수"),
fieldWithPath("data.passwordExist").type(JsonFieldType.BOOLEAN).description("비밀번호 존재 여부"),
fieldWithPath("data.chatHistories").type(JsonFieldType.ARRAY).description("채팅 기록"),
fieldWithPath("data.chatHistories[].messageType").type(JsonFieldType.STRING).description("메세지 타입"),
fieldWithPath("data.chatHistories[].userId").type(JsonFieldType.NUMBER).optional().description("유저 아이디"),
fieldWithPath("data.chatHistories[].content").type(JsonFieldType.STRING).description("메시지 내용"),
fieldWithPath("data.chatHistories[].createdAt").type(JsonFieldType.STRING).description("전송 시간")
fieldWithPath("data.passwordExist").type(JsonFieldType.BOOLEAN).description("비밀번호 존재 여부")
)
));
}
Expand All @@ -404,7 +397,7 @@ void enterRoomFail() throws Exception {
int capacity = 10;

Participant participantInfo = new Participant(10L, "황똥땡", Role.HOST);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, false, null);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, false);
Optional<User> user = Optional.of(User.builder()
.currentRoomCode("1e7050f7d7")
.build());
Expand Down Expand Up @@ -451,8 +444,7 @@ void enterPasswordRoom() throws Exception {
int capacity = 10;

Participant participantInfo = new Participant(10L, "황똥땡", Role.HOST);
List<ChatHistory> chatHistory = createChatHistory(roomCode);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, true, chatHistory);
RoomDetail createdRoomDetail = new RoomDetail(roomCode, roomTitle, participantInfo, capacity, 2, true);
Optional<User> user = Optional.of(User.builder()
.currentRoomCode(null)
.build());
Expand Down Expand Up @@ -480,7 +472,6 @@ void enterPasswordRoom() throws Exception {
.andExpect(jsonPath("$.data.capacity").value(capacity))
.andExpect(jsonPath("$.data.currentParticipant").value(2))
.andExpect(jsonPath("$.data.passwordExist").value(true))
.andExpect(jsonPath("$.data.chatHistories").isArray())
.andDo(document("enter-password-room-success",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
Expand All @@ -500,12 +491,7 @@ void enterPasswordRoom() throws Exception {
fieldWithPath("data.user.role").type(JsonFieldType.STRING).description("유저 역할"),
fieldWithPath("data.capacity").type(JsonFieldType.NUMBER).description("정원"),
fieldWithPath("data.currentParticipant").type(JsonFieldType.NUMBER).description("현재 참가자 수"),
fieldWithPath("data.passwordExist").type(JsonFieldType.BOOLEAN).description("비밀번호 존재 여부"),
fieldWithPath("data.chatHistories").type(JsonFieldType.ARRAY).description("채팅 기록"),
fieldWithPath("data.chatHistories[].messageType").type(JsonFieldType.STRING).description("메세지 타입"),
fieldWithPath("data.chatHistories[].userId").type(JsonFieldType.NUMBER).optional().description("유저 아이디"),
fieldWithPath("data.chatHistories[].content").type(JsonFieldType.STRING).description("메시지 내용"),
fieldWithPath("data.chatHistories[].createdAt").type(JsonFieldType.STRING).description("전송 시간")
fieldWithPath("data.passwordExist").type(JsonFieldType.BOOLEAN).description("비밀번호 존재 여부")
)
));
}
Expand Down Expand Up @@ -794,7 +780,7 @@ private List<Room> generateRooms(int count) {
private List<ChatHistory> createChatHistory(String roomCode) {
return List.of(
new ChatHistory(MessageType.CHAT, 1L, "안녕하세요", LocalDateTime.now().toString()),
new ChatHistory(MessageType.ALARM, null, "[알림] yeon님이 입장하셨습니다.", LocalDateTime.now().toString()),
new ChatHistory(MessageType.ALARM, null, "yeon님이 입장하셨습니다.", LocalDateTime.now().toString()),
new ChatHistory(MessageType.CHAT, 2L, "방가방가 햄토리", LocalDateTime.now().toString()),
new ChatHistory(MessageType.CHAT, 1L, "ㄷㄷ", LocalDateTime.now().toString())
);
Expand Down

0 comments on commit 530bfbf

Please sign in to comment.