Skip to content

Commit

Permalink
Merge pull request #128 from pjhcsols/chat
Browse files Browse the repository at this point in the history
feat:[#28] Chat 관련 WebSecurity 설정
  • Loading branch information
pjhcsols authored Nov 15, 2024
2 parents a53763e + a42e06c commit b7dc5fc
Show file tree
Hide file tree
Showing 5 changed files with 42 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.helpmeCookies.chat.service.ChatMessageService;
import com.helpmeCookies.chat.service.ChatRoomService;
import com.helpmeCookies.chat.util.ImageStorageUtil;
import com.helpmeCookies.global.ApiResponse.ApiResponse;
import com.helpmeCookies.global.ApiResponse.SuccessCode;
import com.helpmeCookies.global.exception.chat.ChatRoomIdNotFoundException;
import com.helpmeCookies.user.service.UserService;
import lombok.RequiredArgsConstructor;
Expand All @@ -26,32 +28,34 @@ public class ChatMessageController {
private final ImageStorageUtil imageStorageUtil;

@GetMapping("/messages")
public List<ChatMessage> getAllMessages() {
return chatMessageService.getAllMessages();
public ResponseEntity<ApiResponse<List<ChatMessage>>> getAllMessages() {
List<ChatMessage> messages = chatMessageService.getAllMessages();
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, messages));
}

@GetMapping("/rooms/{chatRoomId}/messages")
public List<ChatMessage> getMessagesByChatRoom(@PathVariable Long chatRoomId) {
public ResponseEntity<ApiResponse<List<ChatMessage>>> getMessagesByChatRoom(@PathVariable Long chatRoomId) {
ChatRoom chatRoom = chatRoomService.findById(chatRoomId)
.orElseThrow(() -> new ChatRoomIdNotFoundException(chatRoomId));

return chatMessageService.getMessagesByChatRoom(chatRoom);
List<ChatMessage> messages = chatMessageService.getMessagesByChatRoom(chatRoom);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, messages));
}

@PostMapping("/image/convert")
public ResponseEntity<byte[]> convertImageUrlToBase64(@RequestParam String imagePath) throws IOException {

public ResponseEntity<ApiResponse<byte[]>> convertImageUrlToBase64(@RequestParam String imagePath) throws IOException {
byte[] imageBytes = chatMessageService.convertImageUrlToBytes(imagePath);

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");

return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, imageBytes));
}

@DeleteMapping("/messages/{id}")
public void deleteMessage(@PathVariable Long id) {
public ResponseEntity<ApiResponse<Void>> deleteMessage(@PathVariable Long id) {
chatMessageService.deleteMessage(id);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}
}

Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
package com.helpmeCookies.chat.controller;


import com.helpmeCookies.chat.dto.ChatMessageDto;
import com.helpmeCookies.chat.dto.ChatRoomInfo;
import com.helpmeCookies.chat.entity.ChatRoom;
import com.helpmeCookies.chat.entity.MessageType;
import com.helpmeCookies.chat.service.ChatMessageService;
import com.helpmeCookies.chat.service.ChatRoomService;
import com.helpmeCookies.chat.util.ImageStorageUtil;
import com.helpmeCookies.global.ApiResponse.ApiResponse;
import com.helpmeCookies.global.ApiResponse.SuccessCode;
import com.helpmeCookies.global.exception.user.UserNotFoundException;
import com.helpmeCookies.user.entity.User;
import com.helpmeCookies.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/v1/chat/rooms")
public class ChatRoomController {
private final ChatRoomService chatRoomService;
Expand All @@ -27,7 +31,7 @@ public class ChatRoomController {
private final ChatMessageService chatMessageService;

@PostMapping
public ChatRoom createChatRoom(
public ResponseEntity<ApiResponse<ChatRoom>> createChatRoom(
@RequestParam String userEmail1,
@RequestParam String userEmail2
) throws UserNotFoundException {
Expand All @@ -38,45 +42,49 @@ public ChatRoom createChatRoom(

ChatRoom chatRoom = chatRoomService.createChatRoom(user1, user2);

// 환영 메시지 생성
String welcomeMessageContent = "Welcome, " + user2.getEmail() + "!";
ChatMessageDto chatMessageDto = new ChatMessageDto(user1.getEmail(), welcomeMessageContent, MessageType.ENTER);
chatMessageService.saveMessage(chatRoom.getId(), chatMessageDto);

return chatRoom;
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, chatRoom));
}

@GetMapping("/{chatRoomId}")
public ChatRoom getChatRoom(@PathVariable Long chatRoomId) {
return chatRoomService.getChatRoomById(chatRoomId);
public ResponseEntity<ApiResponse<ChatRoom>> getChatRoom(@PathVariable Long chatRoomId) {
ChatRoom chatRoom = chatRoomService.getChatRoomById(chatRoomId);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, chatRoom));
}

@DeleteMapping("/{chatRoomId}")
public void deleteChatRoom(@PathVariable Long chatRoomId) {
public ResponseEntity<ApiResponse<Void>> deleteChatRoom(@PathVariable Long chatRoomId) {
chatRoomService.deleteChatRoom(chatRoomId);

imageStorageUtil.deleteChatFolder("chatRoom_" + chatRoomId);

return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}

@GetMapping("/user/{userId}")
public List<ChatRoomInfo> getUserChatRooms(@PathVariable Long userId) {
return chatRoomService.getChatRoomsByUserId(userId).stream()
public ResponseEntity<ApiResponse<List<ChatRoomInfo>>> getUserChatRooms(@PathVariable Long userId) {
List<ChatRoomInfo> chatRooms = chatRoomService.getChatRoomsByUserId(userId).stream()
.map(chatRoom -> new ChatRoomInfo(chatRoom.getId(), chatRoom.getTitle()))
.collect(Collectors.toList());

return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, chatRooms));
}

@PatchMapping("/{chatRoomId}/title")
public void setChatRoomTitle(@PathVariable Long chatRoomId,
@RequestParam Long userId,
@RequestParam String title) {

public ResponseEntity<ApiResponse<Void>> setChatRoomTitle(
@PathVariable Long chatRoomId,
@RequestParam Long userId,
@RequestParam String title
) {
chatRoomService.setChatRoomTitleIfUserMatches(chatRoomId, userId, title);
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK));
}

@GetMapping
public List<ChatRoom> getAllChatRooms() {
return chatRoomService.getAllChatRooms();
public ResponseEntity<ApiResponse<List<ChatRoom>>> getAllChatRooms() {
List<ChatRoom> chatRooms = chatRoomService.getAllChatRooms();
return ResponseEntity.ok(ApiResponse.success(SuccessCode.OK, chatRooms));
}

}

Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,8 @@ public WebSocketChatController(SimpMessageSendingOperations messagingTemplate,

@MessageMapping("/chat/{chatRoomId}")
public void chat(@DestinationVariable Long chatRoomId, @RequestBody ChatMessageDto messageDto) {
// 메시지를 서비스로 처리
ChatMessage savedMessage = chatMessageService.saveMessage(chatRoomId, messageDto);

// WebSocket을 통해 메시지를 전송
messagingTemplate.convertAndSend("/v1/sub/chat/rooms/" + chatRoomId, savedMessage);
}

Expand All @@ -55,14 +53,11 @@ public void sendFile(@DestinationVariable Long chatRoomId,
@RequestParam String fileBase64,
@RequestParam String userEmail) {
try {
// Base64 데이터를 이미지 파일로 변환 및 저장
ChatMessage message = chatMessageService.saveFileMessage(chatRoomId, userEmail, fileBase64);

// 이미지 바이트로 변환 후 Base64 인코딩
byte[] imageBytes = chatMessageService.convertImageUrlToBytes(message.getContent());
String encodedContent = ChatMessageDto.getImageContent(imageBytes);

// 채팅 메시지 DTO 생성
ChatMessageDto chatMessageDto = new ChatMessageDto(
message.getChatRoom().getId(),
message.getSender().getEmail(),
Expand All @@ -71,21 +66,18 @@ public void sendFile(@DestinationVariable Long chatRoomId,
MessageType.IMAGE
);

// WebSocket을 통해 채팅 메시지 전송
messagingTemplate.convertAndSend("/api/sub/chat/rooms/" + chatRoomId, chatMessageDto);
} catch (UserNotFoundException | IOException e) {
// 에러 처리 및 로그

log.error("파일 전송 중 오류 발생: " + e.getMessage(), e);
}
}


@SubscribeMapping("/chat/rooms/{chatRoomId}/list")
public List<ChatMessage> sendInitialMessages(@DestinationVariable Long chatRoomId) {
// chatRoomId로 ChatRoom 객체를 조회
ChatRoom chatRoom = chatRoomService.getChatRoomById(chatRoomId);

// 채팅방에 속한 메시지를 시간순으로 가져옴
return chatMessageService.getMessagesByChatRoom(chatRoom);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package com.helpmeCookies.global.config;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
"/v1/products/**",
"/v1/reviews/**",
"/ws/**",
"/v1/artists/**"
"/v1/artists/**",
"v1/chat/**"
).permitAll()
.anyRequest().authenticated()
).exceptionHandling((exception) -> exception
Expand Down

0 comments on commit b7dc5fc

Please sign in to comment.