Skip to content

Commit

Permalink
Merge pull request #128 from KUIT-Space/hotfix/#127/안읽은-메시지-버그-수정
Browse files Browse the repository at this point in the history
Hotfix/#127: 안읽은 메시지 버그 수정
  • Loading branch information
hyunn522 authored Aug 19, 2024
2 parents f32e7ac + 0341a2b commit b7a9437
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ public BaseResponse<CreateChatRoomResponse> createChatRoom(
return new BaseResponse<>(chatRoomService.createChatRoom(userId, spaceId, createChatRoomRequest, chatRoomImgUrl));
}

/**
* 특정 유저가 채팅방에서 떠난 시간 저장
*/
@PostMapping("/{chatRoomId}/leave")
public BaseResponse<ChatSuccessResponse> updateLastReadTime(
@JwtLoginAuth Long userId,
@PathVariable Long spaceId,
@PathVariable Long chatRoomId) {
return new BaseResponse<>(chatRoomService.updateLastReadTime(userId, spaceId, chatRoomId));
}

/**
* 특정 채팅방의 모든 유저 정보 조회
*/
Expand Down
24 changes: 13 additions & 11 deletions src/main/java/space/space_spring/controller/ChattingController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.springframework.messaging.handler.annotation.*;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import space.space_spring.argumentResolver.userSpace.CheckUserSpace;
Expand Down Expand Up @@ -47,15 +49,15 @@ public ChatMessageLogResponse subscribeChatRoom (@DestinationVariable Long chatR
}

// socket disconnect 시 호출
@EventListener
@CheckUserSpace(required = false)
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();

Long userId = (Long) sessionAttributes.get("userId");
Long chatRoomId = (Long) sessionAttributes.get("chatRoomId");

userChatRoomService.saveLastReadTime(userId, chatRoomId);
}
// @EventListener
// @CheckUserSpace(required = false)
// public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
// StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
// Map<String, Object> sessionAttributes = headerAccessor.getSessionAttributes();
//
// Long userId = (Long) sessionAttributes.get("userId");
// Long chatRoomId = (Long) sessionAttributes.get("chatRoomId");
// log.info("userId: " + userId + " chatRoomid: " + chatRoomId);
// userChatRoomService.saveLastReadTime(userId, chatRoomId);
// }
}
32 changes: 27 additions & 5 deletions src/main/java/space/space_spring/service/ChatRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,18 @@ public ReadChatRoomResponse readChatRooms(Long userId, Long spaceId) {

// TODO 4: chatRoom 리스트에서 active만 find
List<ChatRoom> activeChatRooms = chatRoomList.stream()
.filter(userChatRoom -> "ACTIVE".equals(userChatRoom.getStatus()))
.filter(chatRoom -> "ACTIVE".equals(chatRoom.getStatus()))
.toList();

return ReadChatRoomResponse.of(activeChatRooms.stream()
.map(cr -> {
// TODO 5: 각 채팅방의 마지막으로 업데이트된 메시지 정보 find
// TODO 5: userChatRoom active인지 확인
UserChatRoom userChatRoom = userChatRoomDao.findByUserAndChatRoom(userByUserId, cr);
if (!userChatRoom.getStatus().equals("ACTIVE")) {
return null;
}

// TODO 6: 각 채팅방의 마지막으로 업데이트된 메시지 정보 find
ChatMessage lastMsg = chattingDao.findTopByChatRoomIdOrderByCreatedAtDesc(cr.getId());

LocalDateTime lastUpdateTime = cr.getCreatedAt().atZone(ZoneId.of("Asia/Seoul")).toLocalDateTime();
Expand All @@ -68,19 +74,22 @@ public ReadChatRoomResponse readChatRooms(Long userId, Long spaceId) {
if (lastMsg != null) {
lastUpdateTime = lastMsg.getCreatedAt();
lastContent = lastMsg.getContent();
log.info("마지막으로 업데이트된 시간: " + lastUpdateTime + " 마지막으로 읽은 내용 : " + lastContent);
}

// TODO 6: 각 채팅방의 안읽은 메시지 개수 계산
UserChatRoom userChatRoom = userChatRoomDao.findByUserAndChatRoom(userByUserId, cr);
// TODO 7: 각 채팅방의 안읽은 메시지 개수 계산
LocalDateTime lastReadTime = userChatRoom.getLastReadTime().atZone(ZoneId.of("Asia/Seoul")).toLocalDateTime();
log.info("마지막으로 읽은 시간: " + lastReadTime);
int unreadMsgCount = chattingDao.countByChatRoomIdAndCreatedAtBetween(
cr.getId(),
lastReadTime,
lastUpdateTime
);
log.info("안읽은 메시지 개수: " + unreadMsgCount);

return ChatRoomResponse.of(cr, lastContent, String.valueOf(lastUpdateTime), unreadMsgCount);
})
.filter(Objects::nonNull) // null 값을 제거
.toList()
);
}
Expand Down Expand Up @@ -135,6 +144,20 @@ public ReadChatRoomMemberResponse readChatRoomMembers(Long spaceId, Long chatRoo
return ReadChatRoomMemberResponse.of(userList);
}

@Transactional
public ChatSuccessResponse updateLastReadTime(Long userId, Long spaceId, Long chatRoomId) {
User userByUserId = userUtils.findUserByUserId(userId);
ChatRoom chatRoomByChatRoomId = chatRoomDao.findById(chatRoomId)
.orElseThrow(() -> new CustomException(CHATROOM_NOT_EXIST));

UserChatRoom targetChatRoom = userChatRoomDao.findByUserAndChatRoom(userByUserId, chatRoomByChatRoomId);
targetChatRoom.setLastReadTime(LocalDateTime.now());
userChatRoomDao.save(targetChatRoom);
log.info("userId: " + userId + " socket disconnect 시 마지막으로 읽은 시간: " + targetChatRoom.getLastReadTime());

return ChatSuccessResponse.of(true);
}

@Transactional
public ChatSuccessResponse joinChatRoom(Long chatRoomId, JoinChatRoomRequest joinChatRoomRequest) {
List<Long> memberIdList = joinChatRoomRequest.getMemberList();
Expand Down Expand Up @@ -204,5 +227,4 @@ private boolean isUserInChatRoom(User userByUserId, ChatRoom chatRoomByChatRoomI
List<UserChatRoom> chatRoomList = userChatRoomDao.findByChatRoom(chatRoomByChatRoomId);
return chatRoomList.stream().anyMatch(userChatRoom -> userChatRoom.getUser().equals(userByUserId));
}

}
24 changes: 14 additions & 10 deletions src/main/java/space/space_spring/service/UserChatRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@
import space.space_spring.entity.ChatRoom;
import space.space_spring.entity.User;
import space.space_spring.entity.UserChatRoom;
import space.space_spring.exception.CustomException;
import space.space_spring.util.user.UserUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Optional;

import static space.space_spring.response.status.BaseExceptionResponseStatus.CHATROOM_NOT_EXIST;

@Service
@RequiredArgsConstructor
@Slf4j
Expand All @@ -25,14 +28,15 @@ public class UserChatRoomService {
private final ChatRoomDao chatRoomDao;
private final UserChatRoomDao userChatRoomDao;

@Transactional
public void saveLastReadTime(Long userId, Long chatRoomId) {
User userByUserId = userUtils.findUserByUserId(userId);
Optional<ChatRoom> chatRoomByChatRoomId = chatRoomDao.findById(chatRoomId);

chatRoomByChatRoomId.ifPresent(chatRoom -> {
UserChatRoom targetChatRoom = userChatRoomDao.findByUserAndChatRoom(userByUserId, chatRoom);
targetChatRoom.setLastReadTime(LocalDateTime.now());
});
}
// @Transactional
// public void saveLastReadTime(Long userId, Long chatRoomId) {
// User userByUserId = userUtils.findUserByUserId(userId);
// ChatRoom chatRoomByChatRoomId = chatRoomDao.findById(chatRoomId)
// .orElseThrow(() -> new CustomException(CHATROOM_NOT_EXIST));
//
// UserChatRoom targetChatRoom = userChatRoomDao.findByUserAndChatRoom(userByUserId, chatRoomByChatRoomId);
// targetChatRoom.setLastReadTime(LocalDateTime.now());
//// userChatRoomDao.save(targetChatRoom);
// log.info("socket disconnect 시 마지막으로 읽은 시간" + targetChatRoom.getLastReadTime());
// }
}

0 comments on commit b7a9437

Please sign in to comment.