Skip to content

Commit d513dc4

Browse files
authored
Merge pull request #68 from CommitField/feat/#20
Feat/#20
2 parents 90fe4a2 + df9a533 commit d513dc4

File tree

12 files changed

+307
-8
lines changed

12 files changed

+307
-8
lines changed

β€Žsrc/main/java/cmf/commitField/domain/chat/chatRoom/controller/ChatRoomController.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
package cmf.commitField.domain.chat.chatRoom.controller;
22

33
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
4+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
45
import cmf.commitField.domain.chat.chatRoom.service.ChatRoomService;
56
import cmf.commitField.domain.user.entity.CustomOAuth2User;
67
import cmf.commitField.global.globalDto.GlobalResponse;
8+
import cmf.commitField.global.security.LoginCheck;
79
import jakarta.validation.Valid;
810
import lombok.RequiredArgsConstructor;
11+
import org.springframework.data.domain.Pageable;
912
import org.springframework.security.core.Authentication;
1013
import org.springframework.security.core.context.SecurityContextHolder;
1114
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
1215
import org.springframework.web.bind.annotation.*;
1316

17+
import java.util.List;
18+
1419
@RestController
1520
@RequiredArgsConstructor
1621
@RequestMapping("/chat")
@@ -47,4 +52,80 @@ public GlobalResponse<Object> joinRoom(@PathVariable Long roomId) {
4752
throw new IllegalArgumentException("User not logged in.");
4853
}
4954
}
55+
56+
// 전체 리슀트
57+
@GetMapping("/room")
58+
@LoginCheck
59+
public GlobalResponse<Object> roomList(Pageable pageable) {
60+
List<ChatRoomDto> roomList = chatRoomService.getRoomList(pageable);
61+
return GlobalResponse.success(roomList);
62+
}
63+
64+
// μ‚¬μš©μž(μžμ‹ )κ°€ μƒμ„±ν•œ λ°© 리슀트 쑰회
65+
@GetMapping("/room/creator")
66+
@LoginCheck
67+
public GlobalResponse<Object> getByUserRoomList(Pageable pageable) {
68+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
69+
70+
if (authentication instanceof OAuth2AuthenticationToken) {
71+
CustomOAuth2User principal = (CustomOAuth2User) authentication.getPrincipal();
72+
Long userId = principal.getId(); // getId()λ₯Ό 톡해 userIdλ₯Ό μΆ”μΆœ
73+
74+
List<ChatRoomDto> userByRoomList = chatRoomService.getUserByRoomList(userId, pageable);
75+
return GlobalResponse.success(userByRoomList);
76+
} else {
77+
throw new IllegalArgumentException("User not logged in.");
78+
}
79+
}
80+
81+
// μ‚¬μš©μž(μžμ‹ )κ°€ λ“€μ–΄κ°€ μžˆλŠ” λ°© 리슀트 쑰회
82+
@GetMapping("/room/part")
83+
@LoginCheck
84+
public GlobalResponse<Object> getByUserRoomPartList(Pageable pageable) {
85+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
86+
87+
if (authentication instanceof OAuth2AuthenticationToken) {
88+
CustomOAuth2User principal = (CustomOAuth2User) authentication.getPrincipal();
89+
Long userId = principal.getId(); // getId()λ₯Ό 톡해 userIdλ₯Ό μΆ”μΆœ
90+
List<ChatRoomDto> userByRoomPartList = chatRoomService.getUserByRoomPartList(userId, pageable);
91+
return GlobalResponse.success(userByRoomPartList);
92+
} else {
93+
throw new IllegalArgumentException("User not logged in.");
94+
}
95+
}
96+
97+
// μ±„νŒ…λ°© λ‚˜κ°€κΈ°
98+
@DeleteMapping("/room/out/{roomId}")
99+
@LoginCheck
100+
public GlobalResponse<Object> outRoom(
101+
@PathVariable Long roomId) {
102+
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
103+
104+
if (authentication instanceof OAuth2AuthenticationToken) {
105+
CustomOAuth2User principal = (CustomOAuth2User) authentication.getPrincipal();
106+
Long userId = principal.getId(); // getId()λ₯Ό 톡해 userIdλ₯Ό μΆ”μΆœ
107+
chatRoomService.outRoom(userId, roomId);
108+
return GlobalResponse.success();
109+
} else {
110+
throw new IllegalArgumentException("User not logged in.");
111+
}
112+
}
113+
//
114+
// // μ±„νŒ…λ°© μ‚­μ œ
115+
// @DeleteMapping("/room/delete/{roomId}")
116+
// @LoginCheck
117+
// public ResponseEntity<Object> deleteRoom(
118+
// @PathVariable Long roomId) {
119+
// Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
120+
//
121+
// if (authentication instanceof OAuth2AuthenticationToken) {
122+
// CustomOAuth2User principal = (CustomOAuth2User) authentication.getPrincipal();
123+
// Long userId = principal.getId(); // getId()λ₯Ό 톡해 userIdλ₯Ό μΆ”μΆœ
124+
// chatRoomService.deleteRoom(userId, roomId);
125+
// return ResponseEntity.ok().body("success");
126+
// } else {
127+
// throw new IllegalArgumentException("User not logged in.");
128+
// }
129+
// }
130+
50131
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package cmf.commitField.domain.chat.chatRoom.controller.response;
2-
3-
public class ChatRoomResponse {
4-
}
1+
//package cmf.commitField.domain.chat.chatRoom.controller.response;
2+
//
3+
//public class ChatRoomResponse {
4+
//}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package cmf.commitField.domain.chat.chatRoom.dto;
2+
3+
import lombok.*;
4+
5+
@Getter
6+
@Setter
7+
@NoArgsConstructor
8+
@AllArgsConstructor
9+
@Builder
10+
public class ChatRoomDto {
11+
private Long id;
12+
13+
private String title;
14+
15+
private Long currentUserCount;
16+
17+
private Integer userCountMax;
18+
}

β€Žsrc/main/java/cmf/commitField/domain/chat/chatRoom/entity/ChatRoom.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,18 @@ public class ChatRoom extends BaseEntity {
3535

3636
@OneToMany(mappedBy = "chatRoom", fetch = FetchType.LAZY)
3737
private List<ChatMessage> chatMessages;
38+
39+
@Override
40+
public String toString() {
41+
return "ChatRoom{" +
42+
// BaseEntityμ—μ„œ 상속받은 id μ‚¬μš©
43+
"id=" + getId() +
44+
", title='" + title + '\'' +
45+
", tier='" + tier + '\'' +
46+
", roomCreator=" + roomCreator +
47+
", userCountMax=" + userCountMax +
48+
", user=" + (user != null ? user.getId() : "null") + // userκ°€ null일 수 있기 λ•Œλ¬Έμ— 체크
49+
", userChatRooms=" + (userChatRooms != null ? userChatRooms.size() : 0) + // userChatRooms λ¦¬μŠ€νŠΈκ°€ null일 수 있기 λ•Œλ¬Έμ— 체크
50+
'}';
51+
}
3852
}

β€Žsrc/main/java/cmf/commitField/domain/chat/chatRoom/repository/ChatRoomRepository.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,13 @@
33
import cmf.commitField.domain.chat.chatRoom.entity.ChatRoom;
44
import jakarta.persistence.LockModeType;
55
import jakarta.persistence.QueryHint;
6+
import org.springframework.data.domain.Page;
7+
import org.springframework.data.domain.Pageable;
68
import org.springframework.data.jpa.repository.JpaRepository;
79
import org.springframework.data.jpa.repository.Lock;
10+
import org.springframework.data.jpa.repository.Query;
811
import org.springframework.data.jpa.repository.QueryHints;
12+
import org.springframework.data.repository.query.Param;
913
import org.springframework.stereotype.Repository;
1014

1115
import java.util.Optional;
@@ -16,4 +20,12 @@ public interface ChatRoomRepository extends JpaRepository<ChatRoom, Long> {
1620
@Lock(LockModeType.PESSIMISTIC_WRITE)
1721
@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value ="1000")})
1822
Optional<ChatRoom> findById(Long aLong);
23+
24+
@Query("select c from ChatRoom c where c.roomCreator=:userId")
25+
Page<ChatRoom> findAllByUserId(@Param("userId")Long userId,Pageable pageable);
26+
27+
Page<ChatRoom> findAllByUserChatRoomsUserId(Long userId,Pageable pageable);
28+
29+
@Query(value = "SELECT ROOM_CREATOR FROM chat_room WHERE ID = ?", nativeQuery = true)
30+
Long findChatRoomByRoomCreator(Long roomId);
1931
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,26 @@
11
package cmf.commitField.domain.chat.chatRoom.service;
22

33
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
4+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
5+
import org.springframework.data.domain.Pageable;
6+
7+
import java.util.List;
48

59
public interface ChatRoomService {
610

711
void createRoom(ChatRoomRequest chatRoomRequest, Long userId); // userIdλ₯Ό 받도둝 μˆ˜μ •
812

913
void joinRoom(Long roomId, Long userId); // userIdλ₯Ό 받도둝 μˆ˜μ •
14+
15+
// μ±„νŒ…λ°© 전체 쑰회
16+
List<ChatRoomDto> getRoomList(Pageable pageable);
17+
18+
// μžμ‹ μ΄ μƒμ„±ν•œ λ°© 리슀트 쑰회
19+
List<ChatRoomDto> getUserByRoomList(Long userId, Pageable pageable);
20+
21+
List<ChatRoomDto> getUserByRoomPartList(Long userId, Pageable pageable);
22+
23+
void outRoom(Long userId, Long roomId);
24+
//
25+
// void deleteRoom(Long userId, Long roomId);
1026
}

β€Žsrc/main/java/cmf/commitField/domain/chat/chatRoom/service/ChatRoomServiceImpl.java

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package cmf.commitField.domain.chat.chatRoom.service;
22

3+
import cmf.commitField.domain.chat.chatMessage.repository.ChatMessageRepository;
34
import cmf.commitField.domain.chat.chatRoom.controller.request.ChatRoomRequest;
5+
import cmf.commitField.domain.chat.chatRoom.dto.ChatRoomDto;
46
import cmf.commitField.domain.chat.chatRoom.entity.ChatRoom;
57
import cmf.commitField.domain.chat.chatRoom.repository.ChatRoomRepository;
68
import cmf.commitField.domain.chat.userChatRoom.entity.UserChatRoom;
@@ -9,11 +11,16 @@
911
import cmf.commitField.domain.user.repository.UserRepository;
1012
import cmf.commitField.global.error.ErrorCode;
1113
import cmf.commitField.global.exception.CustomException;
12-
import jakarta.transaction.Transactional;
1314
import lombok.RequiredArgsConstructor;
15+
import org.springframework.data.domain.Page;
16+
import org.springframework.data.domain.Pageable;
1417
import org.springframework.stereotype.Service;
18+
import org.springframework.transaction.annotation.Transactional;
1519

1620
import java.time.LocalDateTime;
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
import java.util.Objects;
1724

1825
@Service
1926
@RequiredArgsConstructor
@@ -22,6 +29,7 @@ public class ChatRoomServiceImpl implements ChatRoomService {
2229
private final ChatRoomRepository chatRoomRepository;
2330
private final UserRepository userRepository;
2431
private final UserChatRoomRepository userChatRoomRepository;
32+
private final ChatMessageRepository chatMessageRepository;
2533

2634
@Override
2735
@Transactional
@@ -30,6 +38,11 @@ public void createRoom(ChatRoomRequest chatRoomRequest, Long userId) {
3038
User findUser = userRepository.findById(userId)
3139
.orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
3240

41+
// findUserκ°€ null이 아닐 경우, User의 IDλ₯Ό μ‚¬μš©
42+
if (findUser == null) {
43+
throw new CustomException(ErrorCode.NOT_FOUND_USER); // μ˜ˆμ™Έ 처리 μΆ”κ°€
44+
}
45+
3346
// ChatRoom 생성
3447
ChatRoom chatRoom = ChatRoom.builder()
3548
.roomCreator(findUser.getId())
@@ -74,4 +87,78 @@ public void joinRoom(Long roomId, Long userId) {
7487
.build();
7588
userChatRoomRepository.save(userChatRoom);
7689
}
90+
91+
// λ°© 쑰회 DTO λ³€ν™˜ λ©”μ„œλ“œ μΆ”μΆœ
92+
private static List<ChatRoomDto> getChatRoomDtos(Page<ChatRoom> all) {
93+
List<ChatRoomDto> chatRoomList = new ArrayList<>();
94+
95+
for (ChatRoom list : all) {
96+
ChatRoomDto dto = ChatRoomDto.builder()
97+
.id(list.getId())
98+
.title(list.getTitle())
99+
.currentUserCount((long) list.getUserChatRooms().size())
100+
.userCountMax(list.getUserCountMax())
101+
.build();
102+
103+
chatRoomList.add(dto);
104+
}
105+
return chatRoomList;
106+
}
107+
108+
// μ±„νŒ…λ°© 전체 쑰회
109+
@Override
110+
@Transactional(readOnly = true)
111+
public List<ChatRoomDto> getRoomList(Pageable pageable) {
112+
Page<ChatRoom> all = chatRoomRepository.findAll(pageable);
113+
return getChatRoomDtos(all);
114+
}
115+
116+
// μžμ‹ μ΄ μƒμ„±ν•œ λ°© 리슀트 쑰회
117+
@Override
118+
@Transactional(readOnly = true)
119+
public List<ChatRoomDto> getUserByRoomList(Long userId, Pageable pageable) {
120+
Page<ChatRoom> all = chatRoomRepository.findAllByUserId(userId, pageable);
121+
return getChatRoomDtos(all);
122+
}
123+
124+
// μžμ‹ μ΄ μ°Έμ—¬ν•œ λ°© 리슀트 쑰회
125+
@Override
126+
@Transactional(readOnly = true)
127+
public List<ChatRoomDto> getUserByRoomPartList(Long userId, Pageable pageable) {
128+
Page<ChatRoom> allByUserIdAndUserChatRooms = chatRoomRepository
129+
.findAllByUserChatRoomsUserId(userId, pageable);
130+
return getChatRoomDtos(allByUserIdAndUserChatRooms);
131+
}
132+
133+
@Override
134+
@Transactional(readOnly = true)
135+
public void outRoom(Long userId, Long roomId) {
136+
Long roomCreatorId = chatRoomRepository
137+
.findChatRoomByRoomCreator(roomId);
138+
// λ°©μž₯이 μ•„λ‹ˆλΌλ©΄
139+
if (!Objects.equals(roomCreatorId, userId)) {
140+
userChatRoomRepository.deleteUserChatRoomByUserId(userId);
141+
return;
142+
}
143+
// λ°©μž₯이라면 λ°© μ‚­μ œ
144+
userChatRoomRepository.deleteUserChatRoomByChatRoom_Id(roomId);
145+
chatRoomRepository.deleteById(roomId);
146+
}
147+
148+
//// chatMsgRepository.deleteById(roomId); λ°© μ‚­μ œ μ‹œ μ±„νŒ…λ„ λ‹€ μ‚­μ œ λ˜μ–΄μ•Ό 함.
149+
// @Override
150+
// @Transactional
151+
// public void deleteRoom(Long userId, Long roomId) {
152+
// Long roomCreatorId = chatRoomRepository
153+
// .findChatRoomByRoomCreator(roomId);
154+
// if (!Objects.equals(roomCreatorId, userId)) {
155+
// throw new CustomException(ErrorCode.NOT_ROOM_CREATOR);
156+
// }
157+
// userChatRoomRepository.deleteUserChatRoomByChatRoom_Id(roomId);
158+
// chatRoomRepository.deleteById(roomId);
159+
// μ±„νŒ… λ©”μ‹œμ§€ κ΅¬ν˜„ μ‹œ, λ°© μ‚­μ œν•  λ•Œ λ©”μ‹œμ§€λ„ 같이 μ‚­μ œλ˜λŠ” λ©”μ„œλ“œ κ΅¬ν˜„
160+
//}
161+
162+
163+
77164
}

β€Žsrc/main/java/cmf/commitField/domain/chat/userChatRoom/repository/UserChatRoomRepository.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.springframework.data.jpa.repository.Lock;
88
import org.springframework.data.jpa.repository.Query;
99
import org.springframework.data.jpa.repository.QueryHints;
10+
import org.springframework.data.repository.query.Param;
1011
import org.springframework.stereotype.Repository;
1112

1213
@Repository
@@ -16,6 +17,12 @@ public interface UserChatRoomRepository extends JpaRepository<UserChatRoom, Long
1617
@QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value = "1000")})
1718
Long countByChatRoomId(Long roomId); // 비관적 락
1819

19-
@Query("select count(*) from UserChatRoom u where u.chatRoom.id = ?1 ")
20-
Long countNonLockByChatRoomId(Long roomId); // test μš©λ„
20+
// @Query("select count(*) from UserChatRoom u where u.chatRoom.id = ?1 ")
21+
// Long countNonLockByChatRoomId(Long roomId); // test μš©λ„
22+
@Query("select count(*) from UserChatRoom u where u.chatRoom.id = :roomId")
23+
Long countNonLockByChatRoomId(@Param("roomId")Long roomId); // test μš©λ„
24+
25+
void deleteUserChatRoomByChatRoom_Id(Long chatRoomId);
26+
27+
void deleteUserChatRoomByUserId(Long userId);
2128
}

β€Žsrc/main/java/cmf/commitField/global/error/ErrorCode.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ public enum ErrorCode {
3535

3636
//chatroom
3737
NOT_FOUND_ROOM(HttpStatus.NOT_FOUND, "이미 μ‚­μ œλœ λ°©μ΄κ±°λ‚˜ 방을 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."),
38-
ROOM_USER_FULL(HttpStatus.BAD_REQUEST, "방에 μ‚¬μš©μžκ°€ λ‹€ μ°¨ μžˆμŠ΅λ‹ˆλ‹€.");
38+
ROOM_USER_FULL(HttpStatus.BAD_REQUEST, "방에 μ‚¬μš©μžκ°€ λ‹€ μ°¨ μžˆμŠ΅λ‹ˆλ‹€."),
39+
NONE_ROOM(HttpStatus.NOT_FOUND, "ν˜„μž¬ 방이 μ—†μŠ΅λ‹ˆλ‹€."),
40+
CHAT_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "μ±„νŒ… 전솑에 였λ₯˜κ°€ μžˆμŠ΅λ‹ˆλ‹€."),
41+
NOT_ROOM_CREATOR(HttpStatus.FORBIDDEN, "λ°© μƒμ„±μžκ°€ μ•„λ‹™λ‹ˆλ‹€.");
3942

4043
private final HttpStatus httpStatus;
4144
private final String message;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package cmf.commitField.global.security;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
@Target(ElementType.METHOD) // λ©”μ„œλ“œμ— 적용
9+
@Retention(RetentionPolicy.RUNTIME) // λŸ°νƒ€μž„ μ‹œμ— 적용
10+
public @interface LoginCheck {
11+
}

0 commit comments

Comments
Β (0)