Skip to content

Commit

Permalink
Merge pull request #84 from sgdevcamp2023/feat/#70_2
Browse files Browse the repository at this point in the history
Feat/#70 2 채팅방 신규 입장, 재입장시 현재 스트리밍 해야하는 대상 음원 식별자를 응답에 포함하도록 로직 추가, 변경
  • Loading branch information
suakang17 authored Feb 19, 2024
2 parents e430ddd + 3621913 commit b9b0a86
Show file tree
Hide file tree
Showing 9 changed files with 108 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import chattingserver.dto.response.ReEnterResponseDto;
import chattingserver.service.ChatMessageService;
import chattingserver.service.RoomService;
//import chattingserver.util.constant.ErrorCode;
import com.lalala.exception.BusinessException;
import com.lalala.exception.ErrorCode;
import com.lalala.response.BaseResponse;
Expand All @@ -27,6 +26,7 @@
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.*;

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


Expand All @@ -46,8 +46,6 @@ public class ChatController {
@Operation(summary = "웹소켓 메시지 전송")
public void sendSocketMessage(@Valid @RequestBody ChatMessageDto chatMessageDto) {
if (!roomService.isExistingRoom(chatMessageDto.getRoomId())) {
// log.error("메시지 전송 에러 : 존재하지 않는 방입니다. roomId={}", chatMessageDto.getRoomId());
// throw new CustomAPIException(ErrorCode.ROOM_NOT_FOUND_ERROR, "채팅방 id=" + chatMessageDto.getRoomId());
throw new BusinessException("존재하지 않는 채팅방입니다. 채팅방 id=" + chatMessageDto.getRoomId(), ErrorCode.UNKNOWN_ERROR);
}
ChatMessageDto savedMessage = chatMessageService.saveChatMessage(chatMessageDto);
Expand Down Expand Up @@ -80,6 +78,7 @@ public ResponseEntity<BaseResponse<ReEnterResponseDto>> newMessagesAtRoom(@PathV
ReEnterResponseDto responseDto = ReEnterResponseDto.builder()
.beforeMessages(chatMessageService.getMessagesBefore(roomId, readMsgId))
.newMessages(chatMessageService.getNewMessages(roomId, readMsgId))
.currentMusicId(chatMessageService.getCurrentMusicId(roomId))
.build();

return ResponseEntity.ok(BaseResponse.from(HttpStatus.OK, "채팅방 재입장 성공, 새 메시지 조회 성공", responseDto));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import lombok.*;

import java.time.Duration;
import java.util.List;

@Getter
@ToString
@Builder
Expand All @@ -13,4 +16,45 @@ public class Music {
private String artist;
private String playtime;
private String thumbnail;

static class PlayTimeDuration {
private final Duration minutes;
private final Duration seconds;

private PlayTimeDuration(
final Long minutes,
final Long seconds
) {
this.minutes = Duration.ofMinutes(minutes);
this.seconds = Duration.ofSeconds(seconds);
}

public Duration getPlayTimeDuration() {
return minutes.plus(seconds);
}

public static PlayTimeDuration from(final List<String> parsedPlaytime) {
return new PlayTimeDuration(
Long.parseLong(parsedPlaytime.get(0)),
Long.parseLong(parsedPlaytime.get(1))
);
}
}

static class PlayTimeParser {
private PlayTimeParser() {}

public static List<String> parse(String playtime) {
return List.of(
playtime.split(":")[0],
playtime.split(":")[1]
);
}
}

public Duration getPlayTimeDuration() {
final List<String> parsedPlaytime = PlayTimeParser.parse(playtime);
final PlayTimeDuration playTimeDuration = PlayTimeDuration.from(parsedPlaytime);
return playTimeDuration.getPlayTimeDuration();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.*;

import java.time.Duration;
import java.util.List;

@Getter
Expand Down Expand Up @@ -30,4 +31,13 @@ public User getPlaylistOwner() {
.profileImage(playlistOwnerProfileImage)
.build();
}


public Duration getTotalPlaylistTime() {
return this.getMusics().stream()
.map(Music::getPlayTimeDuration)
.reduce(Duration.ZERO, Duration::plus);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Stream;

@Document(collection = "rooms")
@Builder
Expand All @@ -20,6 +22,8 @@ public class Room {
private String id;
private String roomName;
private Playlist playlist;
private Duration playlistDuration;

private String thumbnailImage;

private List<User> users;
Expand All @@ -30,4 +34,6 @@ public void setMembers(List<User> users) {
this.users = users;
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ public class ChatMessageDto {
@NotBlank
private String content;
private LocalDateTime createdAt;
private Long currentMusicId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@
public class ReEnterResponseDto {
private List<ChatMessageResponseDto> beforeMessages;
private List<ChatMessageResponseDto> newMessages;
private Long currentMusicId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public void run(ApplicationArguments args) throws Exception {
Room dummyRoom = Room.builder()
.roomName(dummyPlaylist.getName())
.playlist(dummyPlaylist)
.playlistDuration(dummyPlaylist.getTotalPlaylistTime())
.thumbnailImage(dummyPlaylist.getFirstMusic().getThumbnail())
.users(users)
.playlistOwner(dummyUser1)
Expand Down Expand Up @@ -158,6 +159,7 @@ public void run(ApplicationArguments args) throws Exception {
Room dummyRoom2 = Room.builder()
.roomName(dummyPlaylist2.getName())
.playlist(dummyPlaylist2)
.playlistDuration(dummyPlaylist2.getTotalPlaylistTime())
.thumbnailImage(dummyPlaylist2.getFirstMusic().getThumbnail())
.users(users2)
.playlistOwner(dummyUser3)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package chattingserver.service;

import chattingserver.domain.chat.ChatMessage;
import chattingserver.domain.room.Music;
import chattingserver.domain.room.Room;
import chattingserver.domain.room.User;
import chattingserver.dto.ChatMessageDto;
Expand All @@ -16,14 +17,15 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
Expand Down Expand Up @@ -80,12 +82,7 @@ public List<ChatMessageResponseDto> getAllMessagesAtRoom(String roomId) {
public Page<ChatMessageResponseDto> chatMessagePagination(String roomId, int page) {
Page<ChatMessage> messagePage = chatMessageRepository.findByRoomIdWithPagingAndFiltering(roomId, page, SIZE);
log.info("특정 채팅방 메시지 페이지네이션 조회 성공 roomId={}", roomId);
return messagePage.map(new Function<ChatMessage, ChatMessageResponseDto>() {
@Override
public ChatMessageResponseDto apply(ChatMessage message) {
return entityToResponseDtoConverter.convertToResponseMessage(message);
}
});
return messagePage.map(entityToResponseDtoConverter::convertToResponseMessage);
}

public void deleteChat(String id) {
Expand Down Expand Up @@ -122,7 +119,11 @@ public ChatMessageDto join(ChatMessageDto chatMessageDto) {

roomRepository.addUserToRoom(room.getId(), joinedUser);

return entityToResponseDtoConverter.convertMessage(message);
ChatMessageDto chatMessageDto1 = entityToResponseDtoConverter.convertMessage(message);
chatMessageDto1.setCurrentMusicId(getCurrentMusicId(room.getId()));

log.info(chatMessageDto1.toString());
return chatMessageDto1;
} catch (Exception e) {
log.error("트랜잭션 오류: {}", e.getMessage());
// TODO 트랜잭션 롤백 또는 예외 처리 로직 추가
Expand Down Expand Up @@ -170,4 +171,36 @@ public List<ChatMessageResponseDto> getMessagesBefore(String roomId, String read
return messages.stream().map(entityToResponseDtoConverter::convertToResponseMessage).collect(Collectors.toList());
}

public Long getCurrentMusicId(String roomId) {
Optional<Room> optionalRoom = roomRepository.findById(roomId);
if (optionalRoom.isEmpty()) {
throw new BusinessException("존재하지 않는 채팅방입니다.", ErrorCode.UNKNOWN_ERROR);
}

Room room = optionalRoom.get();

Duration elapsedTime = Duration.between(room.getCreatedAt(), LocalDateTime.now());

Duration totalPlaylistTime = room.getPlaylistDuration();

log.info("room={}", room);
log.info("elapsedTime={}", elapsedTime.toString());
log.info("totalPlaylistTime: playlist={}, playlistTime={}", room.getPlaylist().toString(), totalPlaylistTime);

long currentPlaylistTimeInSeconds = elapsedTime.abs().getSeconds() % totalPlaylistTime.getSeconds();

log.info("currentPlaylistTimeInSeconds={}", currentPlaylistTimeInSeconds);

Duration playlistTime = Duration.ZERO;
List<Music> playlist = room.getPlaylist().getMusics();
for (Music music : playlist) {
playlistTime = playlistTime.plus(music.getPlayTimeDuration());
if (playlistTime.getSeconds() >= currentPlaylistTimeInSeconds) {
log.info("music.getId()={}", music.getId());
return music.getId();
}
}

throw new BusinessException("해당하는 음원이 없습니다.", ErrorCode.UNKNOWN_ERROR);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public RoomResponseDto create(RoomCreateRequestDto roomCreateRequestDto) {
Room room = Room.builder()
.roomName(roomCreateRequestDto.getPlaylist().getName())
.playlist(roomCreateRequestDto.getPlaylist())
.playlistDuration(roomCreateRequestDto.getPlaylist().getTotalPlaylistTime())
.thumbnailImage(roomCreateRequestDto.getThumbnailImage())
.playlistOwner(owner)
.users(users)
Expand Down

0 comments on commit b9b0a86

Please sign in to comment.