|
| 1 | +package org.dfbf.soundlink.domain.chat.service; |
| 2 | + |
| 3 | +import lombok.RequiredArgsConstructor; |
| 4 | +import org.dfbf.soundlink.domain.chat.entity.redis.ChatRequest; |
| 5 | +import org.dfbf.soundlink.domain.chat.dto.ChatReqDto; |
| 6 | +import org.dfbf.soundlink.domain.chat.entity.ChatRoom; |
| 7 | +import org.dfbf.soundlink.domain.chat.exception.ChatRoomNotFoundException; |
| 8 | +import org.dfbf.soundlink.domain.chat.exception.UnauthorizedAccessException; |
| 9 | +import org.dfbf.soundlink.domain.chat.repository.ChatRoomRepository; |
| 10 | +import org.dfbf.soundlink.domain.emotionRecord.entity.EmotionRecord; |
| 11 | +import org.dfbf.soundlink.domain.emotionRecord.exception.EmotionRecordNotFoundException; |
| 12 | +import org.dfbf.soundlink.domain.emotionRecord.exception.UserNotFoundException; |
| 13 | +import org.dfbf.soundlink.domain.emotionRecord.repository.EmotionRecordRepository; |
| 14 | +import org.dfbf.soundlink.domain.user.entity.User; |
| 15 | +import org.dfbf.soundlink.domain.user.repository.UserRepository; |
| 16 | +import org.dfbf.soundlink.global.comm.enums.RoomStatus; |
| 17 | +import org.dfbf.soundlink.global.exception.ErrorCode; |
| 18 | +import org.dfbf.soundlink.global.exception.ResponseResult; |
| 19 | +import org.springframework.dao.DataIntegrityViolationException; |
| 20 | +import org.springframework.data.redis.core.RedisTemplate; |
| 21 | +import org.springframework.security.core.annotation.AuthenticationPrincipal; |
| 22 | +import org.springframework.stereotype.Service; |
| 23 | +import org.springframework.transaction.annotation.Transactional; |
| 24 | + |
| 25 | +import java.time.Duration; |
| 26 | +import java.sql.Timestamp; |
| 27 | + |
| 28 | +@Service |
| 29 | +@RequiredArgsConstructor |
| 30 | +public class ChatRoomService { |
| 31 | + |
| 32 | + private final RedisTemplate<String, Object> redisTemplate; |
| 33 | + private final EmotionRecordRepository emotionRecordRepository; |
| 34 | + private final ChatRoomRepository chatRoomRepository; |
| 35 | + private final UserRepository userRepository; |
| 36 | + |
| 37 | + private static final String CHAT_REQUEST_KEY = "chatRequest"; |
| 38 | + |
| 39 | + // 요청을 Redis에 저장 (TTL: 60초) |
| 40 | + public ResponseResult saveRequestToRedis(Long requestUserId, Long emotionRecordId) { |
| 41 | + try { |
| 42 | + // 응답자의 ID를 EmotionRecord에서 가져옴 |
| 43 | + Long responseUserId = emotionRecordRepository.findById(emotionRecordId) |
| 44 | + .orElseThrow(EmotionRecordNotFoundException::new) |
| 45 | + .getUser() |
| 46 | + .getUserId(); |
| 47 | + |
| 48 | + // 요청자와 응답자가 같은 경우 |
| 49 | + if (requestUserId.equals(responseUserId)) { |
| 50 | + return new ResponseResult(400, "You can't chat with yourself."); |
| 51 | + } |
| 52 | + |
| 53 | + // Redis에 이미 requestUserId가 포함되어 있는 경우 |
| 54 | + if (!redisTemplate.keys(CHAT_REQUEST_KEY + requestUserId + "to*").isEmpty()) { |
| 55 | + String firstKey = redisTemplate.keys(CHAT_REQUEST_KEY + requestUserId + "to*").iterator().next(); // 첫 번째 키 가져오기 |
| 56 | + Long ttl = redisTemplate.getExpire(firstKey); |
| 57 | + return new ResponseResult(400, ttl + "초 후에 다시 시도해주세요."); |
| 58 | + } |
| 59 | + |
| 60 | + // Key & Request 객체 생성 |
| 61 | + String key = CHAT_REQUEST_KEY + requestUserId + "to" + emotionRecordId; |
| 62 | + ChatRequest chatRequest = new ChatRequest(requestUserId, responseUserId, emotionRecordId); |
| 63 | + |
| 64 | + // Redis 저장 |
| 65 | + redisTemplate.opsForValue().set(key, chatRequest, Duration.ofSeconds(61)); |
| 66 | + |
| 67 | + return new ResponseResult(ErrorCode.SUCCESS); |
| 68 | + } catch (EmotionRecordNotFoundException e) { |
| 69 | + return new ResponseResult(ErrorCode.FAIL_TO_FIND_EMOTION_RECORD); |
| 70 | + } catch (Exception e) { |
| 71 | + return new ResponseResult(400, "Chat request failed."); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + // 요청을 삭제 |
| 76 | + public ResponseResult deleteRequestFromRedis(Long requestUserId, Long emotionRecordId) { |
| 77 | + try { |
| 78 | + // Key 생성 |
| 79 | + String key = CHAT_REQUEST_KEY + requestUserId + "to" + emotionRecordId; |
| 80 | + |
| 81 | + // Redis에 Key가 존재하는 경우 삭제 (KEY가 없는 경우 400) |
| 82 | + if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) { |
| 83 | + redisTemplate.delete(key); |
| 84 | + return new ResponseResult(ErrorCode.SUCCESS); |
| 85 | + } else { |
| 86 | + return new ResponseResult(400, "ChatRequest not found or expired."); |
| 87 | + } |
| 88 | + |
| 89 | + } catch (EmotionRecordNotFoundException e) { |
| 90 | + return new ResponseResult(ErrorCode.FAIL_TO_FIND_EMOTION_RECORD); |
| 91 | + } catch (Exception e) { |
| 92 | + return new ResponseResult(400, "Chat request failed."); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + @Transactional |
| 97 | + public ResponseResult createChatRoom(Long userId, Long recordId) { |
| 98 | + try { |
| 99 | + // 요청 보내는사람 |
| 100 | + User requestUserId = userRepository.findById(userId) |
| 101 | + .orElseThrow(UserNotFoundException::new); |
| 102 | + |
| 103 | + // 감정기록 조회 |
| 104 | + EmotionRecord emotionRecord = emotionRecordRepository.findById(recordId) |
| 105 | + .orElseThrow(EmotionRecordNotFoundException::new); |
| 106 | + |
| 107 | + // 이미 존재하는 채팅방인지 확인 |
| 108 | + if(chatRoomRepository.existsByRequestUserIdAndRecordId(requestUserId,emotionRecord)){ |
| 109 | + return new ResponseResult(ErrorCode.CHAT_FAILED, "이미 존재하는 채팅방입니다."); |
| 110 | + } |
| 111 | + |
| 112 | + Long responseUserId = emotionRecord.getUser().getUserId(); |
| 113 | + |
| 114 | + ChatRoom chatRoom = ChatRoom.builder() |
| 115 | + .requestUserId(requestUserId) |
| 116 | + .recordId(emotionRecord) |
| 117 | + .status(RoomStatus.WAITING) //상태 : 대기 |
| 118 | + .startTime(new Timestamp(System.currentTimeMillis())) |
| 119 | + .endTime(null) |
| 120 | + .build(); |
| 121 | + |
| 122 | + // DB에 저장 |
| 123 | + chatRoomRepository.save(chatRoom); |
| 124 | + |
| 125 | + ChatReqDto chatReqDto = new ChatReqDto(userId, responseUserId); |
| 126 | + |
| 127 | + // 레디스에 저장 |
| 128 | + redisTemplate.opsForValue().set("Room::"+chatRoom.getChatRoomId(), String.valueOf(chatReqDto)); |
| 129 | + |
| 130 | + return new ResponseResult(ErrorCode.SUCCESS, chatRoom); |
| 131 | + } catch (Exception e) { |
| 132 | + return new ResponseResult(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage()); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + // 채팅방 닫기 |
| 137 | + @Transactional |
| 138 | + public ResponseResult closeChatRoom(@AuthenticationPrincipal Long userId, Long chatRoomId) { |
| 139 | + try { |
| 140 | + ChatRoom chatRoom = chatRoomRepository.findById(chatRoomId) |
| 141 | + .orElseThrow(ChatRoomNotFoundException::new); |
| 142 | + |
| 143 | + // 요청자 또는 응답자가 아니면 예외 처리 |
| 144 | + if(!chatRoom.getRequestUserId().getUserId().equals(userId) && |
| 145 | + !chatRoom.getRecordId().getUser().getUserId().equals(userId)) { |
| 146 | + throw new UnauthorizedAccessException(); // 권한이 없을 경우 예외 발생 |
| 147 | + } |
| 148 | + |
| 149 | + chatRoom.updateChatRoomStatus(RoomStatus.CLOSED); // 삳태 '닫기'로 변경 |
| 150 | + chatRoomRepository.save(chatRoom); // DB에 저장 |
| 151 | + |
| 152 | + redisTemplate.delete("Room::"+chatRoomId); // 레디스에서 삭제 |
| 153 | + return new ResponseResult(ErrorCode.SUCCESS); |
| 154 | + } catch (Exception e) { |
| 155 | + return new ResponseResult(ErrorCode.INTERNAL_SERVER_ERROR, e.getMessage()); |
| 156 | + } |
| 157 | + } |
| 158 | +} |
0 commit comments