11package com .dmu .debug_visual .config ;
22
33import com .dmu .debug_visual .collab .domain .entity .CodeSession ;
4+ import com .dmu .debug_visual .collab .domain .entity .Room ;
45import com .dmu .debug_visual .collab .domain .repository .CodeSessionRepository ;
6+ import com .dmu .debug_visual .collab .domain .repository .RoomRepository ;
57import com .dmu .debug_visual .collab .service .RoomService ;
68import com .dmu .debug_visual .collab .service .WebSocketRoomService ;
79import com .dmu .debug_visual .security .CustomUserDetails ;
@@ -26,6 +28,7 @@ public class WebSocketEventListener {
2628
2729 private final WebSocketRoomService webSocketRoomService ;
2830 private final RoomService roomService ;
31+ private final RoomRepository roomRepository ;
2932 private final CodeSessionRepository codeSessionRepository ;
3033
3134 @ EventListener
@@ -40,24 +43,34 @@ public void handleWebSocketSubscribeListener(SessionSubscribeEvent event) {
4043 try {
4144 String roomId = destination .split ("/" )[3 ];
4245
46+ // ✨ 1. (핵심 수정!) 메모리에 방이 없으면, DB에서 정보를 가져와 활성화시킵니다.
47+ if (webSocketRoomService .findActiveRoomById (roomId ) == null ) {
48+ Room dbRoom = roomRepository .findByRoomId (roomId )
49+ .orElseThrow (() -> new RuntimeException ("Subscribing to a non-existent room: " + roomId ));
50+ webSocketRoomService .activateRoom (roomId , dbRoom .getOwner ().getUserId ());
51+ log .info ("Room {} activated in memory." , roomId );
52+ }
53+
54+ // 2. 이제 안전하게 메모리에 실시간 사용자 추가
4355 Authentication authentication = (Authentication ) userPrincipal ;
4456 CustomUserDetails userDetails = (CustomUserDetails ) authentication .getPrincipal ();
4557 String userId = userDetails .getUsername ();
46-
4758 webSocketRoomService .addParticipant (roomId , userId );
4859
60+ // 3. 퇴장 이벤트를 위해 세션에 정보 저장
4961 Map <String , Object > sessionAttributes = Objects .requireNonNull (headerAccessor .getSessionAttributes ());
5062 sessionAttributes .put ("roomId" , roomId );
5163 sessionAttributes .put ("userId" , userId );
5264
53- // 만약 구독 주소에 "/session/"이 포함되어 있다면, 세션 참여자로도 등록합니다.
65+ // ... (세션 ID 저장 로직은 그대로)
5466 if (destination .contains ("/session/" )) {
5567 String sessionId = destination .split ("/" )[5 ];
56- sessionAttributes .put ("sessionId" , sessionId ); // 퇴장 시 사용하기 위해 세션 ID 저장
68+ sessionAttributes .put ("sessionId" , sessionId );
5769 webSocketRoomService .addSessionParticipant (sessionId , userId );
5870 log .info ("User {} joined session {}" , userId , sessionId );
5971 }
6072
73+ // 4. 변경된 상태를 모두에게 방송
6174 roomService .broadcastRoomState (roomId );
6275
6376 } catch (Exception e ) {
@@ -80,27 +93,25 @@ public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
8093 if (roomId != null && userId != null ) {
8194 log .info ("[퇴장] 사용자: {}, 방: {}" , userId , roomId );
8295
96+ // 1. 메모리에서 방/세션 참여자 모두 제거
8397 webSocketRoomService .removeParticipant (roomId , userId );
84-
85- // --- 세션 자동 비활성화 로직 ---
8698 if (sessionId != null ) {
8799 webSocketRoomService .removeSessionParticipant (sessionId , userId );
100+ }
88101
89- // 방금 나간 사람이 마지막 참여자였는지 확인
90- if (webSocketRoomService .isSessionEmpty (sessionId )) {
91- log .info ("Last user left session {}. Deactivating session." , sessionId );
92-
93- // DB에서 세션을 찾아 상태를 INACTIVE로 변경
94- codeSessionRepository .findBySessionId (sessionId ).ifPresent (session -> {
95- session .updateStatus (CodeSession .SessionStatus .INACTIVE );
96- log .info ("Session {} status updated to INACTIVE in DB." , sessionId );
97- });
98- }
102+ // 2. 세션 자동 비활성화 로직
103+ if (sessionId != null && webSocketRoomService .isSessionEmpty (sessionId )) {
104+ log .info ("Last user left session {}. Deactivating session." , sessionId );
105+ codeSessionRepository .findBySessionId (sessionId ).ifPresent (session -> {
106+ session .updateStatus (CodeSession .SessionStatus .INACTIVE );
107+ log .info ("Session {} status updated to INACTIVE in DB." , sessionId );
108+ });
99109 }
100110
101- // 변경된 방 상태(참여자 감소)를 모두에게 알림
111+ // 3. 최종적으로 변경된 상태를 모두에게 방송
102112 roomService .broadcastRoomState (roomId );
103113 }
104114 }
105115 }
106- }
116+ }
117+
0 commit comments