Skip to content

Commit

Permalink
Merge pull request #13 from KAKAO-TOUR-API-CONTEST/devyj
Browse files Browse the repository at this point in the history
Devyj
  • Loading branch information
yyujin1231 authored Aug 22, 2024
2 parents d11d5b0 + 6670e5c commit f0c7016
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 136 deletions.
17 changes: 16 additions & 1 deletion src/main/java/com/example/ai_jeju/config/WebSocketConfig.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
package com.example.ai_jeju.config;

import com.example.ai_jeju.handler.StompHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.*;

@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Autowired
private final StompHandler stompHandler;

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/sub");
Expand All @@ -18,7 +26,14 @@ public void configureMessageBroker(MessageBrokerRegistry config) {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws/chat").setAllowedOriginPatterns("*").withSockJS();;
registry.addEndpoint("/ws/chat").setAllowedOriginPatterns("*").withSockJS();

}

@Override
public void configureClientInboundChannel(ChannelRegistration registration) {

registration.interceptors(stompHandler);
}

}
82 changes: 50 additions & 32 deletions src/main/java/com/example/ai_jeju/controller/ChatController.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
import com.example.ai_jeju.domain.ChatMessage;
import com.example.ai_jeju.domain.ChatRoom;
import com.example.ai_jeju.dto.ChatMessageDto;
import com.example.ai_jeju.jwt.TokenProvider;
import com.example.ai_jeju.repository.ChatMessageRepository;
import com.example.ai_jeju.repository.ChatRoomRepository;
import com.example.ai_jeju.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
Expand All @@ -19,6 +21,7 @@
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RequiredArgsConstructor
Expand All @@ -29,59 +32,74 @@ public class ChatController {
private final SimpMessageSendingOperations messagingTemplate;
private final ChatRoomRepository chatRoomRepository;
private final ChatMessageRepository chatMessageRepository;
private final TokenProvider tokenProvider;

@Autowired
private ChatService chatService;

@MessageMapping("/chat/message")
public void message(ChatMessageDto messageDto) {
public void message(ChatMessageDto messageDto, @Header("simpSessionAttributes") Map<String, Object> sessionAttributes) {
if (messageDto == null) {
log.error("Received null message");
return;
}

log.info("Received message: " + messageDto.toString());

// 메시지 타입에 따라 처리
switch (messageDto.getType()) {
case ENTER:
messageDto.setMessage(messageDto.getSender() + "님이 입장하셨습니다.");
break;
case EXIT:
messageDto.setMessage(messageDto.getSender() + "님이 퇴장하셨습니다.");
break;
default:
break;
try {
String nickname = (String) sessionAttributes.get("nickname");
log.info("Received message: " + messageDto.toString());

// sender가 null일 경우 세션에서 추출한 nickname을 sender로 설정
if (messageDto.getSender() == null) {
messageDto.setSender(nickname);
}

switch (messageDto.getType()) {
case ENTER:
messageDto.setMessage(nickname + "님이 입장하셨습니다.");
break;
case EXIT:
messageDto.setMessage(nickname + "님이 퇴장하셨습니다.");
break;
default:
break;
}

ChatMessage chatMessage = ChatMessage.builder()
.roomId(messageDto.getRoomId())
.sender(messageDto.getSender()) // nickname이 sender로 설정됨
.message(messageDto.getMessage())
.timestamp(LocalDateTime.now())
.type(messageDto.getType().name())
.build();
chatMessageRepository.save(chatMessage);

log.info("Sending message to /sub/chat/room/" + messageDto.getRoomId() + ": " + messageDto.toString());
messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
} catch (Exception e) {
log.error("Error processing message", e);
}

// 메시지 저장
ChatMessage chatMessage = ChatMessage.builder()
.roomId(messageDto.getRoomId())
.sender(messageDto.getSender())
.message(messageDto.getMessage())
.timestamp(LocalDateTime.now())
.type(messageDto.getType().name())
.build();
chatMessageRepository.save(chatMessage);

log.info("Sending message to /sub/chat/room/" + messageDto.getRoomId() + ": " + messageDto.toString());
messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
}

@GetMapping("/chatroom")
public String chat(@RequestParam("roomId") String roomId, Model model) {
model.addAttribute("roomId", roomId);
return "chat"; // chat.html 파일을 반환
}

//@GetMapping("/chatroom")
//public String chat(@RequestParam("roomId") String roomId, Model model) {
// model.addAttribute("roomId", roomId);
// return "chat"; // chat.html 파일을 반환
//}

@GetMapping("/chat/previous")
@ResponseBody
public List<ChatMessage> getPreviousMessages(
@RequestParam("roomId") String roomId,
@RequestParam(value = "lastMessageId", required = false) Optional<Long> lastMessageId) {
@RequestParam(value = "lastMessageid", required = false) Optional<Long> lastMessageId) {
return chatService.previousMessages(roomId, lastMessageId.orElse(null));
}

@GetMapping("/chat/allprevious")
@ResponseBody
public List<ChatMessage> getAllMessages(@RequestParam("roomId") String roomId) {
return chatService.getAllMessages(roomId);
}



Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ public String chatRooms() {
return "chatrooms";
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public Long registerUser(@RequestBody SignUpRequest signUpRequest, HttpServletRe
}

@GetMapping("/checks")
public Long CheckIfUser(@RequestParam String email, HttpServletRequest request, HttpServletResponse response){
public Long CheckIfUser(@RequestParam(name = "email") String email, HttpServletRequest request, HttpServletResponse response){
return userService.checkIfUser(email,request,response);
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/example/ai_jeju/domain/ChatMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ public class ChatMessage {
private String message;
private String type;
private LocalDateTime timestamp;
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/example/ai_jeju/domain/RefreshToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class RefreshToken {
@Column(name = "id", updatable = false, unique = true)
private Long id;

@Column
@Column(name = "refresh_token", columnDefinition = "LONGTEXT")
String refresh_token;

@Column
Expand Down
96 changes: 0 additions & 96 deletions src/main/java/com/example/ai_jeju/jwt/TokenProvider.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

@Repository
public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {
List<ChatMessage> findByRoomId(String roomId);
List<ChatMessage> findByRoomIdOrderByIdAsc(String roomId);
List<ChatMessage> findTop10ByRoomIdOrderByIdDesc(String roomId);

List<ChatMessage> findTop10ByRoomIdAndIdLessThanOrderByIdDesc(String roomId, Long id);
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/com/example/ai_jeju/service/ChatService.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ public class ChatService {
@Autowired
private ChatMessageRepository chatMessageRepository;

public List<ChatMessage> getAllMessages(String roomId) {
return chatMessageRepository.findByRoomIdOrderByIdAsc(roomId);
}

public List<ChatMessage> previousMessages(String roomId, Long lastMessageId) {
if (lastMessageId == null) {
// 마지막 메시지 ID가 없으면 해당 채팅방의 최신 메시지 10개 가져오기
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,7 @@ spring.cloud.aws.region.static=ap-northeast-2

#graphQL ?? ??
spring.graphql.graphiql.enabled=true

logging.level.root=INFO
logging.level.com.example=DEBUG

2 changes: 1 addition & 1 deletion src/main/resources/templates/chat.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,4 @@ <h3 id="room-name"></h3>
connect();
</script>
</body>
</html>
</html>
2 changes: 1 addition & 1 deletion src/main/resources/templates/chatrooms.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,4 @@
});
</script>
</body>
</html>
</html>

0 comments on commit f0c7016

Please sign in to comment.