Skip to content

Commit

Permalink
Merge pull request #146 from ALOC-UOS/fix/chat
Browse files Browse the repository at this point in the history
πŸ› Fix room id getter setter
  • Loading branch information
baebae02 authored Sep 16, 2024
2 parents e680763 + 39a9d3f commit 89c6baa
Show file tree
Hide file tree
Showing 6 changed files with 60 additions and 79 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message)
log.info("Received message from session {}: {}", session.getId(), message.getPayload());
String payload = message.getPayload();
ChatMessage chatMessage = ChatMessage.of(payload);
chatService.handleAction(chatMessage.getRoomId(), session, chatMessage);
chatService.handleAction(session, chatMessage);
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
log.info("Connection closed: {} with status {}", session.getId(), status);
chatService.leaveAllRooms(session);
chatService.leaveRoom(session);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,4 @@ public class ChatController {
public ChatRoom createRoom(@RequestParam String name) {
return chatService.createRoom(name);
}

@GetMapping
public List<ChatRoom> getAll() {
return chatService.findAll();
}
}
4 changes: 0 additions & 4 deletions src/main/java/com/aloc/aloc/chat/dto/ChatMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ public class ChatMessage {
@NotNull(message = "Message type is required")
private MessageType type;

@NotBlank(message = "Room ID is required")
private String roomId;

@NotBlank(message = "Sender is required")
private String sender;
private SenderInfo senderInfo;
Expand All @@ -37,7 +34,6 @@ public static ChatMessage of(String payload) {
try {
return objectMapper.readValue(payload, ChatMessage.class);
} catch (IOException e) {
System.out.println(payload);
throw new RuntimeException("Failed to parse ChatMessage", e);
}
}
Expand Down
32 changes: 13 additions & 19 deletions src/main/java/com/aloc/aloc/chat/dto/ChatRoom.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,21 @@

import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Getter
@Slf4j
public class ChatRoom {
private final String roomId;
private String roomId;
private final String name;
private final Set<WebSocketSession> sessions = new HashSet<>();
private final ObjectMapper objectMapper = new ObjectMapper();
private final ConcurrentHashMap<WebSocketSession, String> userMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, SenderInfo> userInfoMap = new ConcurrentHashMap<>();
@Builder
public ChatRoom(String roomId, String name) {
this.roomId = roomId;
public ChatRoom(String name) {
this.name = name;
this.roomId = UUID.randomUUID().toString();
}

public void sendMessage(TextMessage message) {
Expand All @@ -45,16 +47,15 @@ private void sendMessageToSession(WebSocketSession session, TextMessage message)
}

public void join(WebSocketSession session, String sender, SenderInfo senderInfo) {
sessions.add(session);
try {
sessions.add(session);
System.out.println(session);
System.out.println(sessions);
userMap.put(session, sender);
userInfoMap.put(sender, senderInfo);
sendUserListToAll();
} catch (Exception e) {
System.out.println(session);
System.out.println(sender);
System.out.println(senderInfo);
throw new RuntimeException("Failed to join user", e);
log.error("Failed to join user", e);
}
}

Expand All @@ -64,10 +65,6 @@ public void leave(WebSocketSession session) {
sendUserListToAll();
}

public Set<String> getUserList() {
return new HashSet<>(userMap.values());
}

private void sendUserListToAll() {
try {
List<SenderTotalInfo> userList = userInfoMap.entrySet().stream()
Expand All @@ -81,14 +78,11 @@ private void sendUserListToAll() {
}
}

public static ChatRoom of(String name) {
return ChatRoom.builder()
.name(name)
.roomId(UUID.randomUUID().toString())
.build();
}

public boolean hasSession(WebSocketSession session) {
return sessions.contains(session);
}

public void setRoomId(String roomId) {
this.roomId = roomId;
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.aloc.aloc.chat.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Repository;

Expand All @@ -14,7 +13,7 @@
@RequiredArgsConstructor
@Repository
public class ChatRepository {
private final Map<String, ChatRoom> chatRooms;
private final Map<String, ChatRoom> chatRooms = new ConcurrentHashMap<>();

public void save(String roomId, ChatRoom chatRoom) {
chatRooms.put(roomId, chatRoom);
Expand All @@ -23,8 +22,4 @@ public void save(String roomId, ChatRoom chatRoom) {
public ChatRoom findById(String roomId) {
return chatRooms.get(roomId);
}

public List<ChatRoom> findAll() {
return new ArrayList<>(chatRooms.values());
}
}
85 changes: 43 additions & 42 deletions src/main/java/com/aloc/aloc/chat/service/ChatService.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
package com.aloc.aloc.chat.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.aloc.aloc.chat.dto.ChatMessage;
import com.aloc.aloc.chat.dto.ChatMessage.MessageType;
import com.aloc.aloc.chat.dto.ChatRoom;
import com.aloc.aloc.chat.dto.SenderInfo;
import com.aloc.aloc.chat.repository.ChatRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

Expand All @@ -25,44 +22,57 @@ public class ChatService {

private final ChatRepository chatRepository;
private final ObjectMapper objectMapper;
private static final String DEFAULT_ROOM_ID = "defaultRoom";

public List<ChatRoom> findAll() {
return chatRepository.findAll();
@PostConstruct
public void init() {
if (findRoomById(DEFAULT_ROOM_ID) == null) {
createRoom("Default Chat Room");
}
}

public ChatRoom findRoomById(String roomId) {
if (roomId == null || roomId.isEmpty()) {
throw new IllegalArgumentException("Room ID must not be null");
log.error("Room ID must not be null");
}
return chatRepository.findById(roomId);
}

public ChatRoom getDefaultRoom() {
ChatRoom room = findRoomById(DEFAULT_ROOM_ID);
if (room == null) {
room = createRoom("Default Chat Room");
room.setRoomId(DEFAULT_ROOM_ID);
chatRepository.save(DEFAULT_ROOM_ID, room);
}
return room;
}

public ChatRoom createRoom(String name) {
ChatRoom chatRoom = ChatRoom.of(name);
ChatRoom chatRoom = ChatRoom.builder()
.name(name)
.build();
chatRepository.save(chatRoom.getRoomId(), chatRoom);
return chatRoom;
}

public void handleAction(
String roomId,
WebSocketSession session,
ChatMessage chatMessage
) throws JsonProcessingException {
ChatRoom room = findRoomById(roomId);
ChatRoom room = getDefaultRoom();
if (!isSessionValid(session)) {
log.error("WebSocket session is not valid or closed");
return;
}

if (room == null) {
throw new RuntimeException("Room not found: " + roomId);
}

if (isEnterRoom(room, chatMessage.getSender(), chatMessage.getSenderInfo())) {
boolean isNewUser = isNewUser(room, session);
if (isNewUser) {
room.join(session, chatMessage.getSender(), chatMessage.getSenderInfo());
chatMessage.setMessage("μƒˆλ‘œμš΄ 뢄이 λ“±μž₯ν–ˆμ–΄μš” πŸ™‹πŸ»");
chatMessage.setSender("μ•Œλ¦Ό");
chatMessage.setType(MessageType.NOTICE);
ChatMessage joinMessage = new ChatMessage();
joinMessage.setMessage("μ‚¬μš©μžκ°€ μ±„νŒ…λ°©μ— λ“€μ–΄μ™”μŠ΅λ‹ˆλ‹€. πŸ™‹πŸ»β€");
joinMessage.setSender("μ•Œλ¦Ό");
joinMessage.setType(MessageType.NOTICE);
room.sendMessage(new TextMessage(objectMapper.writeValueAsString(joinMessage)));
}

TextMessage textMessage = new TextMessage(objectMapper.writeValueAsString(chatMessage));
Expand All @@ -73,31 +83,22 @@ private boolean isSessionValid(WebSocketSession session) {
return session != null && session.isOpen();
}

private boolean isEnterRoom(ChatRoom room, String sender, SenderInfo senderInfo) {
Set<String> userList = room.getUserList();
boolean isNewUser = userList.stream()
.noneMatch(existingUser -> existingUser.equals(sender));

if (isNewUser) {
userList.add(sender);
}
return isNewUser;
private boolean isNewUser(ChatRoom room, WebSocketSession session) {
return !room.hasSession(session);
}

public void leaveAllRooms(WebSocketSession session) {
List<ChatRoom> rooms = findAll();
for (ChatRoom room : rooms) {
if (room.hasSession(session)) {
room.leave(session);
ChatMessage leaveMessage = new ChatMessage();
leaveMessage.setType(MessageType.LEAVE);
leaveMessage.setSender("System");
leaveMessage.setMessage("μ‚¬μš©μžκ°€ μ±„νŒ…λ°©μ„ λ‚˜κ°”μŠ΅λ‹ˆλ‹€.");
try {
handleAction(room.getRoomId(), session, leaveMessage);
} catch (Exception e) {
log.error("Error sending leave message", e);
}
public void leaveRoom(WebSocketSession session) {
ChatRoom room = getDefaultRoom();
if (room.hasSession(session)) {
room.leave(session);
ChatMessage leaveMessage = new ChatMessage();
leaveMessage.setType(MessageType.LEAVE);
leaveMessage.setSender("System");
leaveMessage.setMessage("μ‚¬μš©μžκ°€ μ±„νŒ…λ°©μ„ λ‚˜κ°”μŠ΅λ‹ˆλ‹€.");
try {
handleAction(session, leaveMessage);
} catch (Exception e) {
log.error("Error sending leave message", e);
}
}
}
Expand Down

0 comments on commit 89c6baa

Please sign in to comment.