Skip to content

Commit

Permalink
feat: 채팅 기능 수정 - #52
Browse files Browse the repository at this point in the history
Feature/#52 채팅 기능 수정
  • Loading branch information
aaahyunseo authored Aug 17, 2024
2 parents 3fc8ff9 + c3401f9 commit 467d98f
Show file tree
Hide file tree
Showing 11 changed files with 124 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ public class StompWebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws/chat") // 클라이언트에서 서버로 WebSocket 연결하기 위해 /ws/chat 으로 요청을 보내도록 엔트포인트 설정
.setAllowedOriginPatterns("*") // 클라이언트에서 웹 소켓 서버에 요청하는 모든 요청을 수락, CORS 방지
.setAllowedOriginPatterns("*"); // 클라이언트에서 웹 소켓 서버에 요청하는 모든 요청을 수락, CORS 방지
registry.addEndpoint("/ws/chat")
.setAllowedOriginPatterns("*")
.withSockJS();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.example.swcompetitionproject.authentication.AuthenticatedUser;
import com.example.swcompetitionproject.dto.request.chatting.ChatMessageDto;
import com.example.swcompetitionproject.entity.Message;
import com.example.swcompetitionproject.entity.User;
import com.example.swcompetitionproject.service.ChattingService;
import lombok.RequiredArgsConstructor;
Expand All @@ -11,6 +12,7 @@
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.UUID;

/**
Expand All @@ -22,38 +24,57 @@
@RequiredArgsConstructor
@Controller
public class ChatMessageController {
private final SimpMessagingTemplate template;
private final SimpMessagingTemplate template; // 기본브로커
private final ChattingService chattingService;

//채팅방 입장하기
/**
* 채팅방 입장하기
**/
@MessageMapping("/ws/chat/{roomId}/enter")
public void enter(@DestinationVariable UUID roomId, @AuthenticatedUser User user, ChatMessageDto message) {
// 사용자를 채팅방에 추가
chattingService.addUserToRoom(user, roomId);
public void enter(@DestinationVariable UUID roomId, @AuthenticatedUser User user) {
// 새로운 유저 판단
boolean isNewUser = chattingService.isNewUserInRoom(user, roomId);

// 입장 메시지 생성 및 전송
message.setContent(user.getStudentNumber() + "님이 입장하셨습니다.");
template.convertAndSend("/sub/ws/chat/room/" + roomId, message);
}
// 사용자가 처음 입장하는 경우에만 입장 메시지 전송
if (isNewUser) {
// 사용자를 채팅방에 추가
chattingService.addUserToRoom(user, roomId);
// 입장 메시지 생성 및 전송
ChatMessageDto enterMessageDto = new ChatMessageDto(roomId, user.getName() + "님이 입장하셨습니다.", user.getStudentNumber());
template.convertAndSend("/sub/ws/chat/room/" + roomId, enterMessageDto);
}

//채팅방 메세지 보내기
@MessageMapping("/ws/chat/{roomId}/send")
public void message(@DestinationVariable UUID roomId, @AuthenticatedUser User user, ChatMessageDto message) {
// 메시지 저장
chattingService.saveMessage(user, roomId, message);
// 기존 메시지들 전송 (처음 입장하는 유저가 아닌 경우에만)
if (!isNewUser) {
List<Message> previousMessages = chattingService.getMessagesByRoomId(roomId);
for (Message message : previousMessages) {
ChatMessageDto messageDto = new ChatMessageDto(roomId, message.getContent(), message.getSender());
template.convertAndSend("/sub/ws/chat/room/" + roomId, messageDto);
}
}
}

/**
* 채팅방에 메시지 보내기
**/
@MessageMapping("/ws/chat/send")
public void message(ChatMessageDto message) {
// MessageRepository 에 메시지 저장
chattingService.saveMessage(message);
// 메시지 전송
template.convertAndSend("/sub/ws/chat/room/" + roomId, message);
template.convertAndSend("/sub/ws/chat/room/" + message.getRoomId(), message);
}

// 채팅방 퇴장하기
/**
* 채팅방 퇴장하기
**/
@MessageMapping("/ws/chat/{roomId}/quit")
public void quit(@DestinationVariable UUID roomId, @AuthenticatedUser User user, ChatMessageDto message) {
public void quit(@DestinationVariable UUID roomId, @AuthenticatedUser User user) {
// 사용자를 채팅방에서 제거
chattingService.removeUserFromRoom(user, roomId);

// 퇴장 메시지 생성 및 전송
message.setContent(user.getStudentNumber() + "님이 퇴장하셨습니다.");
template.convertAndSend("/sub/ws/chat/room/" + roomId, message);
ChatMessageDto quitMessage = new ChatMessageDto(roomId, user.getName() + "님이 퇴장하셨습니다.", user.getStudentNumber());
template.convertAndSend("/sub/ws/chat/room/" + roomId, quitMessage);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@
import lombok.Getter;
import lombok.Setter;

import java.util.UUID;

@Getter
@Setter
@AllArgsConstructor
public class ChatMessageDto {
@NotBlank(message = "roomId를 입력해주세요.")
private UUID roomId;
@NotBlank(message = "메세지 내용을 입력해주세요.")
private String content;
@NotBlank(message = "메세지 발신자를 입력해주세요.")
private String sender;
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,6 @@ public class ChattingRoom extends BaseEntity {
@JoinColumn(name = "board_id")
private Board board;

@OneToMany(mappedBy = "chattingRoom", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RoomMember> roomMembers;

@OneToMany(mappedBy = "chattingRoom", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Message> messages;

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ public enum ErrorCode {

//UnauthorizedException
INVALID_TOKEN("4010", "유효하지 않은 토큰입니다."),
INVALID_DORMITORY("4042", "유효하지 않은 기숙사입니다."),
INVALID_DORMITORY("4012", "유효하지 않은 기숙사입니다."),
ROOM_FULL("4013","채팅방 인원이 가득찼습니다."),

//ForbiddenException
NO_ACCESS("4030", "접근 권한이 없습니다."),

//NotFoundException
COOKIE_NOT_FOUND("4040", "쿠키를 찾을 수 없습니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package com.example.swcompetitionproject.repository;

import com.example.swcompetitionproject.entity.ChattingRoom;
import com.example.swcompetitionproject.entity.Message;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.UUID;

public interface MessageRepository extends JpaRepository<Message, UUID> {
List<Message> findByChattingRoomOrderByCreatedAtAsc(ChattingRoom room);
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package com.example.swcompetitionproject.repository;

import com.example.swcompetitionproject.entity.ChattingRoom;
import com.example.swcompetitionproject.entity.User;
import com.example.swcompetitionproject.entity.UserRoom;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

public interface UserRoomRepository extends JpaRepository<UserRoom, UUID> {
List<UserRoom> findByUser(User user);

Optional<UserRoom> findByUserAndChattingRoom(User user, ChattingRoom chattingRoom);

Boolean existsByUserAndChattingRoom(User user, ChattingRoom chattingRoom);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
import com.example.swcompetitionproject.entity.DormitoryType;
import com.example.swcompetitionproject.entity.User;
import com.example.swcompetitionproject.exception.ErrorCode;
import com.example.swcompetitionproject.exception.ForbiddenException;
import com.example.swcompetitionproject.exception.NotFoundException;
import com.example.swcompetitionproject.exception.UnauthorizedException;
import com.example.swcompetitionproject.repository.BoardRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
Expand All @@ -28,6 +30,7 @@ public class BoardService {
/**
* 게시글 전체 조회
**/
@Transactional
public BoardListData getBoardList(String dormitory) {
DormitoryType dormitoryType = dormitoryNameValidate(dormitory);
List<Board> boards = boardRepository.findAllByDormitoryOrderByCreatedAtDesc(dormitoryType);
Expand All @@ -37,6 +40,7 @@ public BoardListData getBoardList(String dormitory) {
/**
* 게시글 상세 조회
**/
@Transactional
public BoardData getBoardById(String dormitory, UUID boardId) {
DormitoryType dormitoryType = dormitoryNameValidate(dormitory);
Board board = boardRepository.findBoardByDormitoryAndId(dormitoryType, boardId)
Expand All @@ -47,6 +51,7 @@ public BoardData getBoardById(String dormitory, UUID boardId) {
/**
* 게시글 작성
**/
@Transactional
public void createBoard(String dormitory, CreateBoardDto createBoardDto, User user) {
DormitoryType dormitoryType = dormitoryNameValidate(dormitory);

Expand Down Expand Up @@ -90,6 +95,7 @@ public void createBoard(String dormitory, CreateBoardDto createBoardDto, User us
/**
* 게시글 수정
**/
@Transactional
public void updateBoard(String dormitory, UUID boardId, UpdateBoardDto updateBoardDto, User user) {
DormitoryType dormitoryType = dormitoryNameValidate(dormitory);
Board updateBoard = boardValidate(dormitoryType, boardId, user);
Expand All @@ -100,6 +106,7 @@ public void updateBoard(String dormitory, UUID boardId, UpdateBoardDto updateBoa
/**
* 게시글 삭제
**/
@Transactional
public void deleteBoard(String dormitory, UUID boardId, User user) {
DormitoryType dormitoryType = dormitoryNameValidate(dormitory);
Board board = boardValidate(dormitoryType, boardId, user);
Expand All @@ -108,11 +115,11 @@ public void deleteBoard(String dormitory, UUID boardId, User user) {
}

/**
* 게시글 존재 여부 확인 로직
* 접근 유저의 게시글 권한 확인
**/
public Board boardValidate(DormitoryType dormitoryType, UUID boardId, User user) {
return boardRepository.findBoardByDormitoryAndIdAndUser(dormitoryType, boardId, user)
.orElseThrow(() -> new NotFoundException(ErrorCode.BOARD_NOT_FOUND));
.orElseThrow(() -> new ForbiddenException(ErrorCode.NO_ACCESS));
}

/**
Expand Down
Loading

0 comments on commit 467d98f

Please sign in to comment.