Skip to content

Commit

Permalink
Merge pull request #19 from kjungw1025/feat/withDankook
Browse files Browse the repository at this point in the history
feat: 단터디, 베어이츠, 단혼밥 게시글 채팅방과 연결
  • Loading branch information
kjungw1025 authored Feb 27, 2024
2 parents fb580f0 + 1b538b8 commit d7d11a7
Show file tree
Hide file tree
Showing 18 changed files with 157 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,6 @@ public class ChatController {
@Value("${spring.kafka.consumer.topic}")
private String topic;

/**
* 아래에서 사용되는 convertAndSend 를 사용하기 위한 선언
* convertAndSend 는 객체를 인자로 넘겨주면 자동으로 Message 객체로 변환 후 도착지로 전송한다.
*/
private final SimpMessageSendingOperations template;

private final UserService userService;
private final ChatService chatService;
private final ChatRoomMessageService chatRoomMessageService;
private final MessageSender sender;
Expand All @@ -64,26 +57,15 @@ public class ChatController {
* 처리가 완료되면 /sub/chatRoom/enter/roomId 로 메시지가 전송된다.
*/
@MessageMapping("/chat/enterUser")
public void enterUser(@Payload RequestChatDto chat,
SimpMessageHeaderAccessor headerAccessor) {

if(chatService.alreadyInRoom(chat.getRoomId(), chat.getUserId())) {
// 반환 결과를 socket session 에 userUUID 로 저장
headerAccessor.getSessionAttributes().put("username", chat.getSender());
headerAccessor.getSessionAttributes().put("userId", chat.getUserId());
headerAccessor.getSessionAttributes().put("roomId", chat.getRoomId());
} else {
public void enterUser(@Payload RequestChatDto chat) {

if(!chatService.alreadyInRoom(chat.getRoomId(), chat.getUserId())) {
// 채팅방 유저+1
chatService.plusUserCnt(chat.getRoomId());

// 채팅방에 유저 추가 및 UserUUID 반환
// 채팅방에 유저 추가
String username = chatService.addUser(chat.getRoomId(), chat.getSender());

// 반환 결과를 socket session 에 userUUID 로 저장
headerAccessor.getSessionAttributes().put("username", username);
headerAccessor.getSessionAttributes().put("userId", chat.getUserId());
headerAccessor.getSessionAttributes().put("roomId", chat.getRoomId());

String enterMessage = chat.getSender() + " 님 입장!!";
LocalDateTime messageTime = LocalDateTime.now();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public String createRoom(@RequestParam("roomName") String name,
AppAuthentication auth,
RedirectAttributes rttr) {

ResponseChatRoomDto room = chatService.createChatRoom(name,
ResponseChatRoomDto room = chatService.createChatRoomForTest(name,
Integer.parseInt(maxUserCount),
auth.getUserId());

Expand Down Expand Up @@ -104,8 +104,9 @@ public boolean confirmPwd(AppAuthentication auth,
* @param roomId 채팅방 id
*/
@DeleteMapping
@ResponseBody
@UserAuth
public String delChatRoom(@RequestParam String roomId, AppAuthentication auth){
public boolean delChatRoom(@RequestParam String roomId, AppAuthentication auth){

// 해당 채팅방에 존재하는 파일들 삭제
chatFileService.deleteAllFilesInChatRoom(roomId);
Expand All @@ -116,7 +117,7 @@ public String delChatRoom(@RequestParam String roomId, AppAuthentication auth){
// roomId(UUID 값) 기준으로 채팅방 삭제
chatService.delChatRoom(auth.getUserId(), roomId, auth.isAdmin());

return "redirect:/chatRoom";
return true;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.dku.council.domain.chat.model.dto.response;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class ResponseChatRoomIdDto {
private final String roomId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.dku.council.domain.chat.model.ChatRoomStatus;
import com.dku.council.domain.user.model.entity.User;
import com.dku.council.domain.with_dankook.model.entity.WithDankook;
import com.dku.council.global.base.BaseEntity;
import lombok.AccessLevel;
import lombok.Builder;
Expand Down Expand Up @@ -42,18 +43,24 @@ public class ChatRoom extends BaseEntity {
@NotNull
private int maxUserCount;

@ManyToOne(fetch = LAZY)
@JoinColumn(name = "with_dankook_id")
private WithDankook withDankook;

@OneToMany(mappedBy = "chatRoom", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ChatRoomUser> users = new ArrayList<>();

@Enumerated(STRING)
private ChatRoomStatus chatRoomStatus;

@Builder
private ChatRoom(@NotNull String roomId,
private ChatRoom(WithDankook withDankook,
@NotNull String roomId,
@NotNull String roomName,
@NotNull int userCount,
@NotNull int maxUserCount,
User roomManager) {
this.withDankook = withDankook;
this.roomId = roomId;
this.roomName = roomName;
this.userCount = userCount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> {
"where c.roomId = :roomId and c.roomManager.id = :userId ")
Optional<ChatRoom> checkChatRoomManagerByUserId(@Param("roomId") String roomId,
@Param("userId") Long userId);

/**
* 게시글과 채팅방이 1 : 1로 생성 되는 단터디, 베어이츠, 단혼밥에서 사용하는 메소드
*/
@Query("select c from ChatRoom c " +
"where c.withDankook.id = :withDankookId and c.chatRoomStatus = 'ACTIVE' ")
Optional<ChatRoom> findChatRoomByWithDankookId(@Param("withDankookId") Long withDankookId);
}
32 changes: 30 additions & 2 deletions src/main/java/com/dku/council/domain/chat/service/ChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,22 @@
import com.dku.council.domain.chat.repository.ChatRoomUserRepository;
import com.dku.council.domain.user.model.entity.User;
import com.dku.council.domain.user.repository.UserRepository;
import com.dku.council.domain.with_dankook.model.entity.WithDankook;
import com.dku.council.global.error.exception.NotGrantedException;
import com.dku.council.global.error.exception.UserNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional(readOnly = true)
public class ChatService {

private final ChatRoomRepository chatRoomRepository;
Expand Down Expand Up @@ -72,7 +74,33 @@ public ResponseChatRoomDto findRoomById(String roomId) {
* @param userId 채팅방을 생성하고자 하는 사용자 id
* @return 채팅방 정보
*/
public ResponseChatRoomDto createChatRoom(String roomName, int maxUserCount, Long userId){
@Transactional
public void createChatRoom(WithDankook withDankook, String roomName, int maxUserCount, Long userId){
// roomName 와 roomPwd 로 chatRoom 빌드 후 return

User user = userRepository.findById(userId).orElseThrow(UserNotFoundException::new);

ChatRoom chatRoom = ChatRoom.builder()
.withDankook(withDankook)
.roomId(UUID.randomUUID().toString())
.roomName(roomName)
.roomManager(user) // 채팅방 방장
.userCount(0) // 채팅방 참여 인원수
.maxUserCount(maxUserCount) // 최대 인원수 제한
.build();
chatRoomRepository.save(chatRoom);
}

/**
* 채팅방 생성 (프론트 화면 확인용. with-Dankook이랑 연결 안되어있음)
*
* @param roomName 생성할 채팅방의 이름
* @param maxUserCount 생성할 채팅방의 최대 인원수 제한
* @param userId 채팅방을 생성하고자 하는 사용자 id
* @return 채팅방 정보
*/
@Transactional
public ResponseChatRoomDto createChatRoomForTest(String roomName, int maxUserCount, Long userId){
// roomName 와 roomPwd 로 chatRoom 빌드 후 return

User user = userRepository.findById(userId).orElseThrow(UserNotFoundException::new);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dku.council.domain.with_dankook.controller;

import com.dku.council.domain.chat.model.dto.response.ResponseChatRoomIdDto;
import com.dku.council.domain.post.model.dto.response.ResponsePage;
import com.dku.council.domain.user.service.UserService;
import com.dku.council.domain.with_dankook.model.dto.list.SummarizedBearEatsDto;
Expand Down Expand Up @@ -89,9 +90,9 @@ public ResponseIdDto create(AppAuthentication auth,
*/
@PostMapping("/{id}/enter")
@UserAuth
public void enter(AppAuthentication auth, @PathVariable @Valid Long id) {
public ResponseChatRoomIdDto enter(AppAuthentication auth, @PathVariable @Valid Long id) {
userService.isDkuChecked(auth.getUserId());
bearEatsService.enter(id, auth.getUserId(), auth.getUserRole());
return bearEatsService.enter(id, auth.getUserId(), auth.getUserRole());
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dku.council.domain.with_dankook.controller;

import com.dku.council.domain.chat.model.dto.response.ResponseChatRoomIdDto;
import com.dku.council.domain.post.model.dto.response.ResponsePage;
import com.dku.council.domain.user.service.UserService;
import com.dku.council.domain.with_dankook.model.dto.list.SummarizedEatingAloneDto;
Expand Down Expand Up @@ -89,10 +90,10 @@ public ResponseIdDto create(AppAuthentication auth,
*/
@PostMapping("/{id}/enter")
@UserAuth
public void enter(AppAuthentication auth,
@PathVariable @Valid Long id) {
public ResponseChatRoomIdDto enter(AppAuthentication auth,
@PathVariable @Valid Long id) {
userService.isDkuChecked(auth.getUserId());
eatingAloneService.enter(id, auth.getUserId(), auth.getUserRole());
return eatingAloneService.enter(id, auth.getUserId(), auth.getUserRole());
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dku.council.domain.with_dankook.controller;

import com.dku.council.domain.chat.model.dto.response.ResponseChatRoomIdDto;
import com.dku.council.domain.post.model.dto.response.ResponsePage;
import com.dku.council.domain.user.service.UserService;
import com.dku.council.domain.with_dankook.model.dto.list.SummarizedStudyDto;
Expand Down Expand Up @@ -100,14 +101,20 @@ public ResponseIdDto create(AppAuthentication auth,

/**
* 단터디 게시글 신청
* <p>
* 프론트에서 성공적으로 roomId를 받는다면, </br>
* 사용자를 게시글에 해당하는 채팅방에 입장시켜야 하므로 </br>
* 바로 /pub/chat/enterUser에 roomId를 포함한 request 양식에 맞춰 요청을 보내줘야합니다. </br>
* </p>
*
* @param id 게시글 id
* @param id 게시글 id
* @return roomId 해당 게시글에 대한 채팅방 roomId
*/
@PostMapping("/{id}/enter")
@UserAuth
public void enter(AppAuthentication auth, @PathVariable @Valid Long id) {
public ResponseChatRoomIdDto enter(AppAuthentication auth, @PathVariable @Valid Long id) {
userService.isDkuChecked(auth.getUserId());
studyService.enter(id, auth.getUserId(), auth.getUserRole());
return studyService.enter(id, auth.getUserId(), auth.getUserRole());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

@Getter
@RequiredArgsConstructor
public class RequestCreateBearEatsDto extends RequestCreateWithDankookDto<BearEats>{

@NotNull
Expand All @@ -22,24 +24,14 @@ public class RequestCreateBearEatsDto extends RequestCreateWithDankookDto<BearEa
private final String deliveryPlace;

@NotNull
@JsonFormat(pattern = "yyyy-MM-dd HH:MM")
@Schema(description = "배달 시간", example = "2023-12-25 17:30")
@Schema(description = "배달 시간", example = "2023-12-25 17:30", type = "string")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private final LocalDateTime deliveryTime;

@NotBlank
@Schema(description = "본문", example = "내용")
private final String content;

public RequestCreateBearEatsDto(@NotNull String restaurant,
@NotNull String deliveryPlace,
@NotNull LocalDateTime deliveryTime,
@NotBlank String content) {
this.restaurant = restaurant;
this.deliveryPlace = deliveryPlace;
this.deliveryTime = deliveryTime;
this.content = content;
}

@Override
public BearEats toEntity(User user) {
return BearEats.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import com.dku.council.domain.with_dankook.model.entity.type.EatingAlone;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import javax.validation.constraints.NotBlank;

@Getter
@RequiredArgsConstructor
public class RequestCreateEatingAloneDto extends RequestCreateWithDankookDto<EatingAlone> {

@NotBlank
Expand All @@ -18,12 +20,6 @@ public class RequestCreateEatingAloneDto extends RequestCreateWithDankookDto<Eat
@Schema(description = "본문", example = "내용")
private final String content;

public RequestCreateEatingAloneDto(@NotBlank String title,
@NotBlank String content) {
this.title = title;
this.content = content;
}

@Override
public EatingAlone toEntity(User user) {
return EatingAlone.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import com.dku.council.domain.user.model.entity.User;
import com.dku.council.domain.with_dankook.model.entity.type.Study;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;

Expand All @@ -21,13 +23,13 @@ public class RequestCreateStudyDto extends RequestCreateWithDankookDto<Study> {
private final int minStudentId;

@NotNull
@JsonFormat(pattern = "yyyy-MM-dd HH:MM")
@Schema(description = "스터디 시작 시간", example = "2023-12-25 17:30")
@Schema(description = "스터디 시작 시간", example = "2023-12-25 17:30", type = "string")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private final LocalDateTime startTime;

@NotNull
@JsonFormat(pattern = "yyyy-MM-dd HH:MM")
@Schema(description = "스터디 끝나는 시간", example = "2023-12-25 18:30")
@Schema(description = "스터디 끝나는 시간", example = "2023-12-25 18:30", type = "string")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private final LocalDateTime endTime;

@Schema(description = "해시태그", example = "자격증")
Expand All @@ -37,12 +39,13 @@ public class RequestCreateStudyDto extends RequestCreateWithDankookDto<Study> {
@Schema(description = "본문", example = "내용")
private final String content;

public RequestCreateStudyDto (@NotBlank String title,
@NotBlank int minStudentId,
@NotBlank LocalDateTime startTime,
@NotBlank LocalDateTime endTime,
String tag,
@NotBlank String content) {
@JsonCreator
public RequestCreateStudyDto (@JsonProperty("title") @NotBlank String title,
@JsonProperty("minStudentId") @NotBlank int minStudentId,
@JsonProperty("startTime") @NotBlank LocalDateTime startTime,
@JsonProperty("endTime") @NotBlank LocalDateTime endTime,
@JsonProperty("tag") String tag,
@JsonProperty("content") @NotBlank String content) {
this.title = title;
this.minStudentId = minStudentId;
this.startTime = startTime;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.dku.council.domain.with_dankook.model.entity;

import com.dku.council.domain.chat.model.entity.ChatRoom;
import com.dku.council.domain.user.model.entity.User;
import com.dku.council.domain.with_dankook.model.WithDankookStatus;
import com.dku.council.global.base.BaseEntity;
Expand Down Expand Up @@ -36,6 +37,9 @@ public abstract class WithDankook extends BaseEntity {
@JoinColumn(name = "master_user_id")
private User masterUser;

@OneToMany(mappedBy = "withDankook", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ChatRoom> chatRooms = new ArrayList<>();

@OneToMany(mappedBy = "withDankook", cascade = CascadeType.ALL, orphanRemoval = true)
private List<WithDankookUser> users = new ArrayList<>();

Expand Down
Loading

0 comments on commit d7d11a7

Please sign in to comment.