Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into feat/#63
  • Loading branch information
mingzooo committed Feb 14, 2024
2 parents 5413ee1 + c2df04e commit 7b5b024
Show file tree
Hide file tree
Showing 19 changed files with 150 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import chattingserver.dto.RoomMessageDto;
import chattingserver.dto.response.ChatMessageResponseDto;
import chattingserver.dto.response.RoomResponseDto;
import chattingserver.dto.response.UserListResponseDto;
import chattingserver.service.ChatMessageService;
import chattingserver.service.RoomService;
import chattingserver.util.constant.MessageType;
Expand Down Expand Up @@ -40,7 +41,7 @@ public void sendMessage(ChatMessageDto chatMessageDto) {
if (chatMessageDto.getMessageType() == MessageType.ENTRANCE) {
log.info("producers.sendMessage.if MessageType == ENTRANCE");
RoomResponseDto roomResponseDto = roomService.getRoomInfo(chatMessageDto.getRoomId());
List<Long> receivers = roomResponseDto.getUsers().stream().map(User::getUid).collect(Collectors.toList());
List<Long> receivers = roomResponseDto.getUsers().stream().map(UserListResponseDto::getUid).collect(Collectors.toList());
receivers.remove(chatMessageDto.getSenderId());
sendRoomMessage(RoomMessageDto.builder()
.receivers(receivers)
Expand All @@ -67,6 +68,7 @@ public void sendRoomMessage(RoomMessageDto roomMessageDto) {
completableFuture.whenComplete((result, ex) -> {
if (ex == null) {
log.info("메시지 전송 성공=[" + roomMessageDto.getRoomResponseDto().getId() + "] with offset=[" + result.getRecordMetadata().offset() + "]");
log.info("roomMessageDto={}", roomMessageDto.toString());
} else {
log.info("메시지 전송 불가=[" + roomMessageDto.getRoomResponseDto().getId() + "] 원인 : " + ex.getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import chattingserver.config.kafka.Producers;
import chattingserver.dto.ChatMessageDto;
import chattingserver.dto.request.UserEntranceRequestDto;
import chattingserver.dto.response.CommonAPIMessage;
import chattingserver.dto.response.ReEnterResponseDto;
import chattingserver.service.ChatMessageService;
import chattingserver.service.RoomService;
import chattingserver.util.constant.ErrorCode;
Expand All @@ -23,6 +23,7 @@
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.web.bind.annotation.*;


@Tag(name = "chat", description = "채팅 API")
@RequiredArgsConstructor
@RestController
Expand Down Expand Up @@ -62,14 +63,21 @@ public void sendMessage(@Valid @RequestBody ChatMessageDto chatMessageDto) {
log.info("메시지 전송 완료 - message={}", chatMessageDto);
}

@Operation(summary = "채팅방 새 메시지 조회")
@Operation(summary = "참여중인 채팅방 재입장, 새 메시지 조회")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "채팅방 새 메시지 조회 성공", content = @Content(schema = @Schema(implementation = CommonAPIMessage.class)))})
@GetMapping("/api/v1/new-message/{roomId}/{readMsgId}")
public ResponseEntity<CommonAPIMessage> newMessagesAtRoom(@PathVariable String roomId, @PathVariable String readMsgId) {
@ApiResponse(responseCode = "200", description = "채팅방 입장, 새 메시지 조회 성공", content = @Content(schema = @Schema(implementation = CommonAPIMessage.class)))})
@GetMapping("/api/v1/rooms/joined/{roomId}")
public ResponseEntity<CommonAPIMessage> newMessagesAtRoom(@PathVariable String roomId, @RequestParam String readMsgId) {
CommonAPIMessage apiMessage = new CommonAPIMessage();
apiMessage.setMessage(CommonAPIMessage.ResultEnum.success);
apiMessage.setData(chatMessageService.getNewMessages(roomId, readMsgId));

ReEnterResponseDto responseDto = ReEnterResponseDto.builder()
.beforeMessages(chatMessageService.getMessagesBefore(roomId, readMsgId))
.newMessages(chatMessageService.getNewMessages(roomId, readMsgId))
.build();

apiMessage.setData(responseDto);

return new ResponseEntity<>(apiMessage, HttpStatus.OK);
}

Expand Down Expand Up @@ -99,9 +107,4 @@ public void join(ChatMessageDto message) {
producers.sendMessage(chatMessageService.join(message));
}

@PostMapping("/api/v1/permanent-leave/{roomId}")
public void permanentLeaving(@PathVariable String roomId, @RequestBody UserEntranceRequestDto userDto) {

producers.sendMessage(chatMessageService.permanentLeaving(roomId, userDto));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import chattingserver.dto.RoomMessageDto;
import chattingserver.dto.request.ReadMessageUpdateRequestDto;
import chattingserver.dto.request.RoomCreateRequestDto;
import chattingserver.dto.request.UserEntranceRequestDto;
import chattingserver.dto.response.CommonAPIMessage;
import chattingserver.dto.response.JoinedRoomResponseDto;
import chattingserver.dto.response.RoomResponseDto;
import chattingserver.dto.response.UserListResponseDto;
import chattingserver.service.ChatMessageService;
import chattingserver.service.RoomService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
Expand All @@ -33,6 +36,7 @@
public class RoomController {

private final RoomService roomService;
private final ChatMessageService chatMessageService;
private final Producers producers;

@Operation(summary = "채팅방 생성 API", description = "신규 채팅방 생성", responses = {
Expand All @@ -44,7 +48,7 @@ public ResponseEntity<CommonAPIMessage> groupCreation(@Valid @RequestBody RoomCr
RoomResponseDto roomResponseDto = roomService.create(roomCreateRequestDto);

producers.sendRoomMessage(RoomMessageDto.builder()
.receivers(roomResponseDto.getUsers().stream().map(User::getUid).collect(Collectors.toList()))
.receivers(roomResponseDto.getUsers().stream().map(UserListResponseDto::getUid).collect(Collectors.toList()))
.roomResponseDto(roomResponseDto)
.build());

Expand All @@ -55,17 +59,18 @@ public ResponseEntity<CommonAPIMessage> groupCreation(@Valid @RequestBody RoomCr
return new ResponseEntity<>(apiMessage, HttpStatus.CREATED);
}

@Operation(summary = "채팅방 나가기", description = "그룹 채팅방에서 유저 삭제", responses = {
@Operation(summary = "채팅방 영구적으로 나가기", description = "그룹 채팅방에서 유저 삭제", responses = {
@ApiResponse(responseCode = "200", description = "삭제 성공", content = @Content(schema = @Schema(implementation = CommonAPIMessage.class)))})
@DeleteMapping("/exit/{roomId}")
public ResponseEntity<CommonAPIMessage> outOfTheRoom(@PathVariable(value = "roomId") String roomId, @RequestParam Long uid) {
if (roomService.exitRoom(roomId, uid)) {
@PostMapping("/exit/{roomId}")
public ResponseEntity<CommonAPIMessage> outOfTheRoom(@PathVariable(value = "roomId") String roomId, @RequestBody UserEntranceRequestDto userDto) {
producers.sendMessage(chatMessageService.permanentLeaving(roomId, userDto));
if (roomService.exitRoom(roomId, userDto.getUid())) {
return new ResponseEntity<>(new CommonAPIMessage(CommonAPIMessage.ResultEnum.success, new HashMap<String, String>() {{
put("roomId", roomId);
}}), HttpStatus.OK);
}
return new ResponseEntity<>(new CommonAPIMessage(CommonAPIMessage.ResultEnum.failed, new HashMap<String, String>() {{
log.error("exitRoom 채팅방 나가기 실패 roomId: {}, userId: {}", roomId, uid);
log.error("exitRoom 채팅방 나가기 실패 roomId: {}, userId: {}", roomId, userDto.getUid());
put("roomId", roomId);
}}), HttpStatus.BAD_REQUEST);
}
Expand All @@ -82,7 +87,7 @@ public ResponseEntity<CommonAPIMessage> chatRoomInfo(@PathVariable(value = "room

@Operation(summary = "모든 채팅방 정보 조회 API", description = "모든 채팅방 정보 조회", responses = {
@ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = RoomResponseDto.class)))})
@GetMapping("/rooms")
@GetMapping("/")
public ResponseEntity<CommonAPIMessage> getAllChatRoomInfos() {
CommonAPIMessage apiMessage = new CommonAPIMessage();
apiMessage.setMessage(CommonAPIMessage.ResultEnum.success);
Expand All @@ -101,7 +106,7 @@ public ResponseEntity<CommonAPIMessage> myChatRooms(@RequestParam(required = tru
return new ResponseEntity<>(apiMessage,HttpStatus.OK);
}

@Operation(summary = "채팅방 리스트 조회", description = "특정 유저가 참여할 수 있는 채팅방 리스트 조회", responses = {
@Operation(summary = "참여 가능한 채팅방 리스트 조회", description = "특정 유저가 참여할 수 있는 채팅방 리스트 조회", responses = {
@ApiResponse(responseCode = "200", description = "조회 성공", content = @Content(schema = @Schema(implementation = CommonAPIMessage.class)))})
@GetMapping("/unjoined")
public ResponseEntity<CommonAPIMessage> unjoinedChatRooms(@RequestParam(required = true) Long uid) {
Expand All @@ -112,8 +117,8 @@ public ResponseEntity<CommonAPIMessage> unjoinedChatRooms(@RequestParam(required
return new ResponseEntity<>(apiMessage, HttpStatus.OK);
}

@Operation(summary = "마지막 읽은 메시지 id 저장")
@PutMapping("/last-message")
@Operation(summary = "채팅방 잠시 나가기, 마지막 읽은 메시지 id 저장", description = "잠시 나가기 (완전히 나가기 아님)")
@PutMapping("/leave")
public ResponseEntity<CommonAPIMessage> updateLastReadMsgId(@RequestBody ReadMessageUpdateRequestDto readMessageUpdateRequestDto){
return new ResponseEntity<>(roomService.updateLastReadMsgId(readMessageUpdateRequestDto), HttpStatus.OK);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
public class LastMessage {
private String messageId;
private Long senderId;
private String nickName;
private String senderProfileImage;
private String content;
private LocalDateTime createdAt;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@ public class Playlist {
private String id;
private String name;
private List<Music> musics;

public Music getFirstMusic() {
return musics.get(0); // 무조건 있음 신뢰
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class Room {
private String id;
private String roomName;
private Playlist playlist;
private String thumbnailImage;

private List<User> users;
private LocalDateTime createdAt;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ public class RoomCreateRequestDto {
private String nickName;
@NotBlank
private Playlist playlist;

public String getThumbnailImage() {
return this.playlist.getFirstMusic().getThumbnail();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package chattingserver.dto.request;

import jakarta.validation.constraints.NotBlank;
import lombok.*;

@Builder
Expand All @@ -9,7 +10,9 @@
@ToString
public class UserEntranceRequestDto {

@NotBlank
private Long uid;
@NotBlank
private String nickName;
private String profileImage;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
public class JoinedRoomResponseDto {
private String roomId;
private String roomName;
private String thumbnailImage;
private List<User> users;
private LastMessage lastMessage;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package chattingserver.dto.response;

import lombok.*;

import java.util.List;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ReEnterResponseDto {
private List<ChatMessageResponseDto> beforeMessages;
private List<ChatMessageResponseDto> newMessages;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ public class RoomResponseDto {
private String id;
private String roomName;
private long userCount;
private List<User> users;
private List<UserListResponseDto> users;
private Playlist playlist;
private String thumbnailImage;
private LocalDateTime createdAt;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package chattingserver.dto.response;

import lombok.*;

import java.time.LocalDateTime;

@Getter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor

public class UserListResponseDto {
private Long uid;
private String nickName;
private String profileImage;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ public interface ChatMessageRepositoryCustom {
List<ChatMessage> getNewMessages(String roomId, String readMsgId);

ChatMessage getLastMessage(String roomId);
List<ChatMessage> findPreviousMessages(String roomId, String readMsgId, int limit);

}
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,12 @@ public ChatMessage getLastMessage(String roomId) {
}
return chatMessage;
}

@Override
public List<ChatMessage> findPreviousMessages(String roomId, String readMsgId, int limit) {
Query query = new Query();
query.addCriteria(Criteria.where("roomId").is(roomId).and("_id").lt(readMsgId)); // 이전 메시지만 가져오도록 쿼리 설정
query.limit(20); // 최대 20개의 메시지 가져오도록 제한 설정
return mongoTemplate.find(query, ChatMessage.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ public void run(ApplicationArguments args) throws Exception {
User dummyUser1 = User.builder()
.uid(1L)
.nickName("유저닉네임1")
.profileImage("userprofileimage1.url")
.profileImage("https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png")
.enteredAt(LocalDateTime.now())
.build();

User dummyUser2 = User.builder()
.uid(2L)
.nickName("유저닉네임2")
.profileImage("userprofileimage2.url")
.profileImage("")
.enteredAt(LocalDateTime.now())
.build();

Expand All @@ -48,14 +48,14 @@ public void run(ApplicationArguments args) throws Exception {
.title("음원1")
.artist("아티스트1")
.playtime("12:34")
.thumbnail("thumbnail-1.url")
.thumbnail("https://marketplace.canva.com/EAFHtE880QY/1/0/1600w/canva-blue-and-red-modern-music-youtube-thumbnail-cBAYqTj4TLk.jpg")
.build();

Music dummyMusic2 = Music.builder()
.title("음원2")
.artist("아티스트2")
.playtime("01:23")
.thumbnail("thumbnail-2.url")
.thumbnail("https://marketplace.canva.com/EAFOwKVP0Ck/1/0/1600w/canva-blue-orange-colorful-aesthetic-minimalist-lofi-music-youtube-thumbnail-ETT-krmERlk.jpg")
.build();

List<Music> dummyMusics = new ArrayList<>();
Expand All @@ -73,7 +73,9 @@ public void run(ApplicationArguments args) throws Exception {
Room dummyRoom = Room.builder()
.roomName(dummyPlaylist.getName())
.playlist(dummyPlaylist)
.thumbnailImage(dummyPlaylist.getFirstMusic().getThumbnail())
.users(users)
.createdAt(LocalDateTime.now())
.build();

roomRepository.save(dummyRoom);
Expand Down Expand Up @@ -105,14 +107,14 @@ public void run(ApplicationArguments args) throws Exception {
User dummyUser3 = User.builder()
.uid(3L)
.nickName("유저닉네임3")
.profileImage("userprofileimage3.url")
.profileImage("https://t4.ftcdn.net/jpg/03/64/21/11/360_F_364211147_1qgLVxv1Tcq0Ohz3FawUfrtONzz8nq3e.jpg")
.enteredAt(LocalDateTime.now())
.build();

User dummyUser4 = User.builder()
.uid(3L)
.nickName("유저닉네임4")
.profileImage("userprofileimage24url")
.profileImage("https://images.pexels.com/photos/771742/pexels-photo-771742.jpeg?cs=srgb&dl=pexels-mohamed-abdelghaffar-771742.jpg&fm=jpg")
.enteredAt(LocalDateTime.now())
.build();

Expand All @@ -122,15 +124,15 @@ public void run(ApplicationArguments args) throws Exception {
users2.add(dummyUser1);

Music dummyMusic3 = Music.builder()
.title("음원1")
.artist("아티스트1")
.title("음원3")
.artist("아티스트3")
.playtime("12:34")
.thumbnail("thumbnail-1.url")
.thumbnail("https://content.wepik.com/statics/13638236/preview-page0.jpg")
.build();

List<Music> dummyMusics2 = new ArrayList<>();
dummyMusics.add(dummyMusic1);
dummyMusics.add(dummyMusic3);
dummyMusics2.add(dummyMusic1);
dummyMusics2.add(dummyMusic3);


Playlist dummyPlaylist2 = Playlist.builder()
Expand All @@ -139,11 +141,16 @@ public void run(ApplicationArguments args) throws Exception {
.musics(dummyMusics2)
.build();

log.info("dummyPlaylist2={}", dummyPlaylist2.toString());
log.info("dummyPlaylist2 firstMusic={}", dummyPlaylist2.getFirstMusic().toString());

// room build
Room dummyRoom2 = Room.builder()
.roomName(dummyPlaylist2.getName())
.playlist(dummyPlaylist2)
.thumbnailImage(dummyPlaylist2.getFirstMusic().getThumbnail())
.users(users2)
.createdAt(LocalDateTime.now())
.build();

roomRepository.save(dummyRoom2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public UpdateResult updateLastReadMsgId(ReadMessageUpdateRequestDto requestDto)
.andOperator(Criteria.where("users").elemMatch(Criteria.where("uid").is(requestDto.getUid())))
);

Update update = new Update().set("users.$.lastReadMsgId", requestDto.getMessageId());
Update update = new Update().set("users.$.lastReadMessageId", requestDto.getMessageId());

return mongoTemplate.updateFirst(query, update, Room.class);
}
Expand Down
Loading

0 comments on commit 7b5b024

Please sign in to comment.