Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 57 additions & 62 deletions backend/src/main/java/io/f1/backend/domain/game/app/RoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import io.f1.backend.domain.game.model.Player;
import io.f1.backend.domain.game.model.Room;
import io.f1.backend.domain.game.model.RoomSetting;
import io.f1.backend.domain.game.model.RoomState;
import io.f1.backend.domain.game.store.RoomRepository;
import io.f1.backend.domain.game.store.UserRoomRepository;
import io.f1.backend.domain.game.websocket.DisconnectTaskManager;
Expand All @@ -45,18 +44,15 @@
import io.f1.backend.global.exception.CustomException;
import io.f1.backend.global.exception.errorcode.RoomErrorCode;
import io.f1.backend.global.exception.errorcode.UserErrorCode;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Slf4j
@Service
Expand Down Expand Up @@ -122,7 +118,7 @@ public void enterRoom(RoomValidationRequest request) {
return;
}

if (room.getState().equals(RoomState.PLAYING)) {
if (room.isPlaying()) {
throw new CustomException(RoomErrorCode.ROOM_GAME_IN_PROGRESS);
}

Expand All @@ -133,7 +129,7 @@ public void enterRoom(RoomValidationRequest request) {
}

if (room.getRoomSetting().locked()
&& !room.getRoomSetting().password().equals(request.password())) {
&& !room.getRoomSetting().password().equals(request.password())) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

room 내부 메서드로 분리하는게 좋아보입니다 !

throw new CustomException(RoomErrorCode.WRONG_PASSWORD);
}

Expand All @@ -145,8 +141,7 @@ private void exitIfInAnotherRoom(Room room, Long userId) {

Long joinedRoomId = userRoomRepository.getRoomId(userId);

if (joinedRoomId != null && !room.getId().equals(joinedRoomId)) {

if (joinedRoomId != null && !room.isSameRoom(joinedRoomId)) {
if (room.isPlaying()) {
changeConnectedStatus(userId, ConnectionState.DISCONNECTED);
} else {
Expand All @@ -165,7 +160,7 @@ public void initializeRoomSocket(Long roomId, UserPrincipal principal) {
}

/* 재연결 */
if (room.getPlayerState(userId).equals(ConnectionState.DISCONNECTED)) {
if (room.isPlayerInState(userId, ConnectionState.DISCONNECTED)) {
changeConnectedStatus(userId, ConnectionState.CONNECTED);
cancelTask(userId);
reconnectSendResponse(roomId, principal);
Expand All @@ -180,19 +175,19 @@ public void initializeRoomSocket(Long roomId, UserPrincipal principal) {
Quiz quiz = quizService.getQuizWithQuestionsById(quizId);

GameSettingResponse gameSettingResponse =
toGameSettingResponse(room.getGameSetting(), quiz);
toGameSettingResponse(room.getGameSetting(), quiz);

PlayerListResponse playerListResponse = toPlayerListResponse(room);

SystemNoticeResponse systemNoticeResponse =
ofPlayerEvent(player.getNickname(), RoomEventType.ENTER);
ofPlayerEvent(player.getNickname(), RoomEventType.ENTER);

String destination = getDestination(roomId);

userRoomRepository.addUser(player, room);

messageSender.sendPersonal(
getUserDestination(), MessageType.GAME_SETTING, gameSettingResponse, principal);
getUserDestination(), MessageType.GAME_SETTING, gameSettingResponse, principal);

messageSender.sendBroadcast(destination, MessageType.ROOM_SETTING, roomSettingResponse);
messageSender.sendBroadcast(destination, MessageType.PLAYER_LIST, playerListResponse);
Expand All @@ -217,34 +212,34 @@ public void exitRoom(Long roomId, UserPrincipal principal) {
cleanRoom(room, removePlayer);

messageSender.sendPersonal(
getUserDestination(),
MessageType.EXIT_SUCCESS,
new ExitSuccessResponse(true),
principal);
getUserDestination(),
MessageType.EXIT_SUCCESS,
new ExitSuccessResponse(true),
principal);

SystemNoticeResponse systemNoticeResponse =
ofPlayerEvent(removePlayer.nickname, RoomEventType.EXIT);
ofPlayerEvent(removePlayer.nickname, RoomEventType.EXIT);

PlayerListResponse playerListResponse = toPlayerListResponse(room);

messageSender.sendBroadcast(destination, MessageType.PLAYER_LIST, playerListResponse);
messageSender.sendBroadcast(
destination, MessageType.SYSTEM_NOTICE, systemNoticeResponse);
destination, MessageType.SYSTEM_NOTICE, systemNoticeResponse);
}
}

public RoomListResponse getAllRooms() {
List<Room> rooms = roomRepository.findAll();
List<RoomResponse> roomResponses =
rooms.stream()
.map(
room -> {
Long quizId = room.getGameSetting().getQuizId();
Quiz quiz = quizService.getQuizWithQuestionsById(quizId);

return toRoomResponse(room, quiz);
})
.toList();
rooms.stream()
.map(
room -> {
Long quizId = room.getGameSetting().getQuizId();
Quiz quiz = quizService.getQuizWithQuestionsById(quizId);

return toRoomResponse(room, quiz);
})
.toList();
return new RoomListResponse(roomResponses);
}

Expand All @@ -255,27 +250,27 @@ public void reconnectSendResponse(Long roomId, UserPrincipal principal) {
String userDestination = getUserDestination();

messageSender.sendBroadcast(
destination,
MessageType.SYSTEM_NOTICE,
ofPlayerEvent(principal.getUserNickname(), RoomEventType.RECONNECT));
destination,
MessageType.SYSTEM_NOTICE,
ofPlayerEvent(principal.getUserNickname(), RoomEventType.RECONNECT));

if (room.isPlaying()) {
messageSender.sendPersonal(
userDestination,
MessageType.SYSTEM_NOTICE,
ofPlayerEvent(
principal.getUserNickname(), RoomEventType.RECONNECT_PRIVATE_NOTICE),
principal);
userDestination,
MessageType.SYSTEM_NOTICE,
ofPlayerEvent(
principal.getUserNickname(), RoomEventType.RECONNECT_PRIVATE_NOTICE),
principal);
messageSender.sendPersonal(
userDestination,
MessageType.RANK_UPDATE,
toRankUpdateResponse(room),
principal);
userDestination,
MessageType.RANK_UPDATE,
toRankUpdateResponse(room),
principal);
messageSender.sendPersonal(
userDestination,
MessageType.GAME_START,
toGameStartResponse(room.getQuestions()),
principal);
userDestination,
MessageType.GAME_START,
toGameStartResponse(room.getQuestions()),
principal);
} else {
RoomSettingResponse roomSettingResponse = toRoomSettingResponse(room);

Expand All @@ -284,16 +279,16 @@ public void reconnectSendResponse(Long roomId, UserPrincipal principal) {
Quiz quiz = quizService.getQuizWithQuestionsById(quizId);

GameSettingResponse gameSettingResponse =
toGameSettingResponse(room.getGameSetting(), quiz);
toGameSettingResponse(room.getGameSetting(), quiz);

PlayerListResponse playerListResponse = toPlayerListResponse(room);

messageSender.sendPersonal(
userDestination, MessageType.ROOM_SETTING, roomSettingResponse, principal);
userDestination, MessageType.ROOM_SETTING, roomSettingResponse, principal);
messageSender.sendPersonal(
userDestination, MessageType.PLAYER_LIST, playerListResponse, principal);
userDestination, MessageType.PLAYER_LIST, playerListResponse, principal);
messageSender.sendPersonal(
userDestination, MessageType.GAME_SETTING, gameSettingResponse, principal);
userDestination, MessageType.GAME_SETTING, gameSettingResponse, principal);
}
}

Expand Down Expand Up @@ -329,8 +324,8 @@ private Player createPlayer() {

public Room findRoom(Long roomId) {
return roomRepository
.findRoom(roomId)
.orElseThrow(() -> new CustomException(RoomErrorCode.ROOM_NOT_FOUND));
.findRoom(roomId)
.orElseThrow(() -> new CustomException(RoomErrorCode.ROOM_NOT_FOUND));
}

private void removeRoom(Room room) {
Expand All @@ -344,14 +339,14 @@ private void changeHost(Room room, Player host) {
Map<Long, Player> playerMap = room.getPlayerMap();

Optional<Player> nextHost =
playerMap.entrySet().stream()
.filter(entry -> !entry.getKey().equals(host.getId()))
.filter(entry -> entry.getValue().getState() == ConnectionState.CONNECTED)
.map(Map.Entry::getValue)
.findFirst();
playerMap.entrySet().stream()
.filter(entry -> !entry.getKey().equals(host.getId()))
.filter(entry -> entry.getValue().getState() == ConnectionState.CONNECTED)
.map(Map.Entry::getValue)
.findFirst();

room.updateHost(
nextHost.orElseThrow(() -> new CustomException(RoomErrorCode.PLAYER_NOT_FOUND)));
nextHost.orElseThrow(() -> new CustomException(RoomErrorCode.PLAYER_NOT_FOUND)));
}

private String getUserDestination() {
Expand All @@ -371,12 +366,12 @@ public void exitRoomForDisconnectedPlayer(Long roomId, Player player) {
String destination = getDestination(roomId);

SystemNoticeResponse systemNoticeResponse =
ofPlayerEvent(player.nickname, RoomEventType.EXIT);
ofPlayerEvent(player.nickname, RoomEventType.EXIT);

messageSender.sendBroadcast(
destination, MessageType.SYSTEM_NOTICE, systemNoticeResponse);
destination, MessageType.SYSTEM_NOTICE, systemNoticeResponse);
messageSender.sendBroadcast(
destination, MessageType.PLAYER_LIST, toPlayerListResponse(room));
destination, MessageType.PLAYER_LIST, toPlayerListResponse(room));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,12 @@ public int getRound() {
public ConnectionState getPlayerState(Long userId) {
return playerMap.get(userId).getState();
}

public boolean isSameRoom(Long otherRoomId){
return Objects.equals(id, otherRoomId);
}

public boolean isPlayerInState(Long userId, ConnectionState state){
return getPlayerState(userId).equals(state);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,17 @@ public void scheduleDisconnectTask(Long userId, Runnable task) {
ScheduledFuture<?> scheduled = scheduler.schedule(task, 5, TimeUnit.SECONDS);

ScheduledFuture<?> prev = disconnectTasks.put(userId, scheduled);
if (prev != null && !prev.isDone()) {
prev.cancel(false);
}
cancelIfRunning(prev);
}

public void cancelDisconnectTask(Long userId) {
ScheduledFuture<?> task = disconnectTasks.remove(userId);
if (task != null && !task.isDone()) {
task.cancel(false);
cancelIfRunning(task);
}

private static void cancelIfRunning(ScheduledFuture<?> future) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

static 키워드는 없어도 될 것 같습니다 !

if (future != null && !future.isDone()) {
future.cancel(false);
}
}
}