Skip to content

Commit

Permalink
Merge pull request EveryUniv#94 from kjungw1025/dev_deploy
Browse files Browse the repository at this point in the history
feat: 채팅방 메시지에 시간 표시 기능 추가
  • Loading branch information
kjungw1025 authored Feb 1, 2024
2 parents 14c07e9 + 16f90e5 commit 2cb169b
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "채팅", description = "채팅 송/수신 관련 api")
Expand Down Expand Up @@ -66,24 +67,24 @@ public void enterUser(@Payload RequestChatDto chat,

// 채팅방에 유저 추가 및 UserUUID 반환
String username = chatService.addUser(chat.getRoomId(), chat.getSender());
log.info("enterUser에서 uuid " + username);
log.info("enterUser에서 roomId " + chat.getRoomId());
log.info("enterUser에서 userId " + chat.getUserId());

// 반환 결과를 socket session 에 userUUID 로 저장
headerAccessor.getSessionAttributes().put("username", username);
headerAccessor.getSessionAttributes().put("userId", chat.getUserId());
headerAccessor.getSessionAttributes().put("roomId", chat.getRoomId());

String enterMessage = chat.getSender() + " 님 입장!!";
LocalDateTime messageTime = LocalDateTime.now();

// 입장 메시지 저장
chatRoomMessageService.create(chat.getRoomId(), chat.getType().toString(), chat.getUserId(), chat.getSender(), enterMessage);
chatRoomMessageService.create(chat.getRoomId(), chat.getType().toString(), chat.getUserId(), chat.getSender(), enterMessage, messageTime);

Message message = Message.builder()
.type(chat.getType())
.roomId(chat.getRoomId())
.sender(chat.getSender())
.message(enterMessage)
.messageTime(messageTime)
.build();

sender.send(topic, message);
Expand All @@ -96,15 +97,16 @@ public void enterUser(@Payload RequestChatDto chat,
*/
@MessageMapping("/chat/sendMessage")
public void sendMessage(@Payload RequestChatDto chat) {
log.info("CHAT {}", chat);
LocalDateTime messageTime = LocalDateTime.now();

chatRoomMessageService.create(chat.getRoomId(), chat.getType().toString(), chat.getUserId(), chat.getSender(), chat.getMessage());
chatRoomMessageService.create(chat.getRoomId(), chat.getType().toString(), chat.getUserId(), chat.getSender(), chat.getMessage(), messageTime);

Message message = Message.builder()
.type(chat.getType())
.roomId(chat.getRoomId())
.sender(chat.getSender())
.message(chat.getMessage())
.messageTime(messageTime)
.build();

sender.send(topic, message);
Expand Down Expand Up @@ -140,14 +142,17 @@ public void webSocketDisconnectListener(SessionDisconnectEvent event) {
log.info("User Disconnected : ", username);

String exitMessage = username + " 님 퇴장!!";
LocalDateTime messageTime = LocalDateTime.now();

// 퇴장 메시지 저장
chatRoomMessageService.create(roomId, MessageType.LEAVE.toString(), userId, username, exitMessage);
chatRoomMessageService.create(roomId, MessageType.LEAVE.toString(), userId, username, exitMessage, messageTime);
// builder 어노테이션 활용
Message message = Message.builder()
.type(MessageType.LEAVE)
.sender(username)
.roomId(roomId)
.message(exitMessage)
.messageTime(messageTime)
.build();

sender.send(topic, message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import lombok.ToString;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;

@Getter
@NoArgsConstructor
Expand All @@ -24,14 +25,19 @@ public class Message {
@NotNull
private String message;

@NotNull
private LocalDateTime messageTime;

@Builder
private Message(MessageType type,
String roomId,
String sender,
String message) {
String message,
LocalDateTime messageTime) {
this.type = type;
this.roomId = roomId;
this.sender = sender;
this.message = message;
this.messageTime = messageTime;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.dku.council.domain.chat.service;

import com.dku.council.domain.chat.model.dto.Message;
import com.dku.council.domain.chat.model.dto.response.ResponseChatDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
Expand All @@ -20,6 +21,8 @@ public class MessageReceiver {
public void receiveMessage(String stringChat) throws JsonProcessingException {

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Message message = objectMapper.readValue(stringChat, Message.class);
log.info("Consumed Message : " + stringChat);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.dku.council.domain.chat.service;

import com.dku.council.domain.chat.model.dto.Message;
import com.dku.council.domain.chat.model.dto.response.ResponseChatDto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
Expand All @@ -20,6 +21,8 @@ public void send(String topic, Message data) {

// 메시지를 KafkaTemplate 를 사용하여 지정된 토픽으로 전송
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
try {
String stringChat = objectMapper.writeValueAsString(data);
log.info("MessageSender Message -> String형 : " + stringChat);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,16 @@ public void create(String roomId,
String messageType,
Long userId,
String userNickname,
String content) {
String content,
LocalDateTime messageTime) {

ChatRoomMessage chatRoomMessage = new ChatRoomMessage();
chatRoomMessage.setRoomId(roomId);
chatRoomMessage.setMessageType(messageType);
chatRoomMessage.setUserId(userId);
chatRoomMessage.setUserNickname(userNickname);
chatRoomMessage.setContent(content);
chatRoomMessage.setCreatedAt(LocalDateTime.now().atZone(seoulZoneId).toLocalDateTime());
chatRoomMessage.setCreatedAt(messageTime.atZone(seoulZoneId).toLocalDateTime());

chatRoomMessageRepository.save(chatRoomMessage);
}
Expand Down
31 changes: 28 additions & 3 deletions src/main/resources/static/js/chatroom/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function getPreviousMessageList() {
sender: data[i]["userNickname"],
message: data[i]["content"],
type: data[i]["messageType"],
createdAt: data[i]["createdAt"]
messageTime: data[i]["createdAt"]
};
console.log(previousChatMessage);
previousMessageReceived(JSON.stringify(previousChatMessage));
Expand Down Expand Up @@ -159,18 +159,24 @@ function previousMessageReceived(message) {
}

function addMessageToTheChatRoom(chat, messageElement) {
if (chat.type === 'ENTER' || chat.type === 'LEAVE') { // chatType 이 enter 라면 아래 내용
if (chat.type === 'ENTER' || chat.type === 'LEAVE') { // chatType 이 enter, leave 라면 아래 내용
messageElement.classList.add('event-message');
getUserList();

} else { // chatType 이 talk 라면 아래 내용
messageElement.classList.add('chat-message');

let timeElement = document.createElement('span');
let timeText = document.createTextNode(formatLocalDateTime(chat.messageTime));
timeElement.appendChild(timeText);
messageElement.appendChild(timeElement);

messageElement.appendChild(document.createElement('br'));

let avatarElement = document.createElement('i');
let avatarText = document.createTextNode(chat.sender[0]);
avatarElement.appendChild(avatarText);
avatarElement.style['background-color'] = getAvatarColor(chat.sender);

messageElement.appendChild(avatarElement);

let usernameElement = document.createElement('span');
Expand Down Expand Up @@ -223,6 +229,25 @@ function getAvatarColor(messageSender) {
return colors[index];
}

function formatLocalDateTime(dateTimeString) {
// 주어진 문자열을 Date 객체로 변환
const dateTime = new Date(dateTimeString);

// 시간대 추출
const hours = dateTime.getHours();
const minutes = dateTime.getMinutes();

// 오전/오후 구분
const meridiem = hours >= 12 ? "오후" : "오전";

// 시간 변환 (24시간 형식에서 12시간 형식으로 변환)
const formattedHours = hours % 12 || 12;

// 시간대와 시간을 문자열로 결합
return `${meridiem} ${formattedHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
}


document.addEventListener('DOMContentLoaded', function () {
connect();
});
Expand Down

0 comments on commit 2cb169b

Please sign in to comment.