Skip to content

Commit

Permalink
Merge pull request #106 from Dear-project/refactor/#104
Browse files Browse the repository at this point in the history
refactor: matching
  • Loading branch information
LimiteDiTempo authored Oct 2, 2024
2 parents f2fa30c + 6476ea1 commit 510dc27
Show file tree
Hide file tree
Showing 28 changed files with 174 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.dear.global.infra.google.OcrService;
import com.dear.global.response.Response;
import com.dear.global.response.ResponseData;
import com.google.firebase.messaging.FirebaseMessagingException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Email;
Expand All @@ -20,6 +21,7 @@
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

@Tag(name = "인증", description = "인증")
@RestController
Expand All @@ -39,7 +41,7 @@ public Response signup(@Validated @RequestBody SignupRequest request) {

@Operation(summary = "회원 인증", description = "회원 인증")
@PostMapping
public ResponseData<JsonWebTokenResponse> auth(@Validated @RequestBody AuthenticationRequest authRequest) {
public ResponseData<JsonWebTokenResponse> auth(@Validated @RequestBody AuthenticationRequest authRequest) throws ExecutionException, InterruptedException, FirebaseMessagingException {
return ResponseData.of(HttpStatus.OK,"로그인 성공",authService.auth(authRequest));
}

Expand Down
5 changes: 4 additions & 1 deletion src/main/java/com/dear/domain/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
import com.dear.domain.auth.dto.request.EmailVerifyRequest;
import com.dear.domain.auth.dto.request.SignupRequest;
import com.dear.domain.auth.dto.response.JsonWebTokenResponse;
import com.google.firebase.messaging.FirebaseMessagingException;

import java.util.concurrent.ExecutionException;

public interface AuthService {
void signup(SignupRequest request);

JsonWebTokenResponse auth(AuthenticationRequest request);
JsonWebTokenResponse auth(AuthenticationRequest request) throws ExecutionException, InterruptedException, FirebaseMessagingException;

JsonWebTokenResponse refresh(String token);

Expand Down
26 changes: 22 additions & 4 deletions src/main/java/com/dear/domain/auth/service/AuthServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
import com.dear.global.common.jwt.exception.TokenTypeException;
import com.dear.global.common.repository.UserSecurity;
import com.dear.global.security.auth.principal.CustomUserDetails;
import com.dear.global.service.RedisUtils;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.TopicManagementResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.RequiredArgsConstructor;
Expand All @@ -37,7 +41,10 @@
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

@Service
@Transactional(rollbackFor = Exception.class)
Expand All @@ -59,8 +66,7 @@ public void signup(SignupRequest request) {
}

@Override
public JsonWebTokenResponse auth(AuthenticationRequest request) {
System.out.println("---------------------");
public JsonWebTokenResponse auth(AuthenticationRequest request) throws ExecutionException, InterruptedException, FirebaseMessagingException {
UserEntity userEntity = userRepository.findByEmail(request.getEmail())
.orElseThrow(() -> UserNotFoundException.EXCEPTION);
if (!new BCryptPasswordEncoder().matches(request.getPassword(), userEntity.getPassword())) {
Expand Down Expand Up @@ -149,9 +155,21 @@ private String createAuthCode() {
}
}

private void saveFCMToken(String token) {
private void saveFCMToken(String token){
if (token != null) {
redisTemplate.opsForValue().set(userSecurity.getUser().getName(), token);
subscribeToTopic(userSecurity.getUser().getSchoolId().getSeq(),token);
redisTemplate.opsForValue().set(userSecurity.getUser().getEmail(), token, Duration.ofDays(7L));
}
}

public void subscribeToTopic(String topic, String registrationTokens){
try{
List<String> tokens = new ArrayList<>();
tokens.add(registrationTokens);
FirebaseMessaging.getInstance().subscribeToTopic(tokens, topic);
}catch (Exception e){
e.printStackTrace();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ public ChatRoomEntity toEntity(Room room){
.build();
}

public Room toRoom(CreateRoomRequest request, Long userId){
public Room toRoom(Long joinedUserId, String roomName, Long userId){
return Room.builder()
.adminId(userId)
.chatName(request.getRoomName())
.chatName(roomName)
.createdAt(LocalDateTime.now())
.joinedUserId(request.getJoinUserId())
.joinedUserId(joinedUserId)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.dear.domain.chat.presentation.dto.request.SearchRoomRequest;
import com.dear.domain.chat.presentation.dto.response.RoomResponse;
import com.dear.domain.chat.service.chat.ChatRoomService;
import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -24,8 +25,8 @@ public class ChatController {

@PostMapping("/create")
public String createRoom(
@RequestBody CreateRoomRequest createRoomRequest) {
return chatRoomService.createChatRoom(createRoomRequest);
@RequestBody CreateRoomRequest createRoomRequest) throws FirebaseMessagingException {
return chatRoomService.createChatRoom(createRoomRequest.getJoinUserId(), createRoomRequest.getRoomName());
}

@GetMapping("/search")
Expand All @@ -47,4 +48,5 @@ public List<RoomResponse> getRooms(Long userId) {
System.out.println("userId = " + userId);
return chatRoomService.getRooms(userId);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.dear.domain.chat.presentation.dto.ChatMessageDto;
import com.dear.domain.chat.service.message.MessageService;
import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpAttributesContextHolder;
Expand All @@ -14,7 +15,7 @@ public class RabbitController {
private final MessageService messageService;

@MessageMapping("chat.message")
public void send(ChatMessageDto chat) {
public void send(ChatMessageDto chat) throws FirebaseMessagingException {
// messageService.sendAndSaveMessage(chat,3L);
Object userIdObj = SimpAttributesContextHolder.currentAttributes().getAttribute("user-id");
if (userIdObj instanceof String) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@
import com.dear.domain.chat.presentation.dto.request.CreateRoomRequest;
import com.dear.domain.chat.presentation.dto.request.SearchRoomRequest;
import com.dear.domain.chat.presentation.dto.response.RoomResponse;
import com.google.firebase.messaging.FirebaseMessagingException;

import java.util.List;

public interface ChatRoomService {

String createChatRoom(CreateRoomRequest createRoomRequest);
String createChatRoom(Long joinedUserId, String roomName) throws FirebaseMessagingException;

RoomResponse getRoom(String roomId, Long userId);

List<RoomResponse> getRooms(Long userId);

void leftRoom(Long userId, String roomId);
void leftRoom(Long userId, String roomId) throws FirebaseMessagingException;

List<RoomResponse> searchRoomNameIn(SearchRoomRequest searchRoomRequest, Long userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.dear.domain.chat.service.message.MessageService;
import com.dear.global.common.repository.UserSecurity;
import com.dear.global.exception.CustomException;
import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -50,21 +51,16 @@ private RoomResponse toResponse(ChatRoomEntity chatRoomEntity, Long userId) {

@Transactional
@Override
public String createChatRoom(CreateRoomRequest createRoomRequest) {
createRoomRequest.setJoinUserId(createRoomRequest.getJoinUserId());

if (createRoomRequest.getRoomName().isEmpty()) {
createRoomRequest.setRoomName(createRoomRequest.getRoomName());
}
public String createChatRoom(Long joinedUserId, String roomName) throws FirebaseMessagingException {

ChatRoomEntity savedRoom = chatRoomRepository.save(
chatRoomMapper.toEntity(
chatRoomMapper.toRoom(createRoomRequest, userSecurity.getUser().getId())
chatRoomMapper.toRoom(joinedUserId,roomName, userSecurity.getUser().getId())
)
);

messageService.sendAndSaveMessage(
new ChatMessageDto(Type.ENTER, savedRoom.getId().toString(), "come on"),userSecurity.getUser().getId()
new ChatMessageDto(Type.ENTER, savedRoom.getId().toString(),joinedUserId + " 님과의 전설적인 채팅이 시작되었어요"),userSecurity.getUser().getId()
);

return savedRoom.getId().toString();
Expand All @@ -88,7 +84,7 @@ public List<RoomResponse> getRooms(Long joinedUserId) {

@Transactional
@Override
public void leftRoom(Long userId, String roomId) {
public void leftRoom(Long userId, String roomId) throws FirebaseMessagingException {
ChatRoomEntity chatRoomEntity = findChatRoomById(roomId);

chatRoomEntity.setJoinedUserId(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import com.dear.domain.chat.domain.chat.dto.Message;
import com.dear.domain.chat.presentation.dto.ChatMessageDto;
import com.dear.domain.chat.presentation.dto.response.GetMessageResponse;
import com.google.firebase.messaging.FirebaseMessagingException;
import org.springframework.data.domain.Pageable;

public interface MessageService {

void sendAndSaveMessage(ChatMessageDto chatMessageDto, Long userId);
void sendAndSaveMessage(ChatMessageDto chatMessageDto, Long userId) throws FirebaseMessagingException;
Message saveMessage(ChatMessageDto chatMessageDto, Long userId);
MessageEntity getMessage(String roomId);
GetMessageResponse getMessages(String chatRoomId, Long userId, Pageable pageable);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
import com.dear.domain.chat.exception.ChatError;
import com.dear.domain.chat.presentation.dto.ChatMessageDto;
import com.dear.domain.chat.presentation.dto.response.GetMessageResponse;
import com.dear.domain.firebase.dto.request.SendMessageRequest;
import com.dear.domain.firebase.service.FCMService;
import com.dear.global.common.repository.UserSecurity;
import com.dear.global.exception.CustomException;
import com.google.firebase.messaging.FirebaseMessagingException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
Expand All @@ -35,14 +39,21 @@ public class MessageServiceImpl implements MessageService {
private final MessageMapper messageMapper;
private final RoomInfoRepository roomInfoRepository;
private final RabbitTemplate rabbitTemplate;
private final FCMService fcmService;
private final UserSecurity userSecurity;

@Override
@Transactional
public void sendAndSaveMessage(ChatMessageDto chatMessageDto, Long userId) {
public void sendAndSaveMessage(ChatMessageDto chatMessageDto, Long userId) throws FirebaseMessagingException {
Message message = saveMessage(chatMessageDto,userId);
rabbitTemplate.convertAndSend(
"chat.exchange", "room." + chatMessageDto.getRoomId(), message
);
fcmService.sendMessage(new SendMessageRequest(
userSecurity.getUser().getEmail(),
message.getUserId().toString(),
message.getMessage()
));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.dear.domain.firebase.dto.request;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
public class SendMessageRequest {
private String targetToken;
private String email;
private String title;
private String body;
}

This file was deleted.

11 changes: 7 additions & 4 deletions src/main/java/com/dear/domain/firebase/service/FCMService.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,23 @@
import com.google.firebase.messaging.Notification;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class FCMService{
private final StringRedisTemplate redisTemplate;

public Response sendMessage(SendMessageRequest request) throws FirebaseMessagingException {

Message message = makeMessage(request.getTargetToken(), request.getTitle(), request.getBody());
public void sendMessage(SendMessageRequest request) throws FirebaseMessagingException {
String token = redisTemplate.opsForValue().get(request.getEmail());
Message message = makeMessage(token,request.getTitle(), request.getBody());

try{
FirebaseMessaging.getInstance().send(message);
return Response.of(HttpStatus.OK,"메세지 발싸");
log.info("메세지 발싸");
}catch (Exception e){
log.error("푸쉬 발송 중 에러 ::::::::::: " + e.getMessage());
throw e;
Expand All @@ -35,6 +37,7 @@ public void sendTopicMessage(String topic, String title, String body) throws Fir

try{
FirebaseMessaging.getInstance().send(message);
log.info("메세지 발싸");
}catch (Exception e){
log.error("푸쉬 발송 중 에러 ::::::::::: " + e.getMessage());
throw e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@
public class MatchingRequest{
@NotNull
private Long subjectId;
@NotEmpty
private String message;

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.dear.global.common.dto.request.PageRequest;
import com.dear.global.response.Response;
import com.dear.global.response.ResponseData;
import com.google.firebase.messaging.FirebaseMessagingException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
Expand Down Expand Up @@ -50,7 +51,7 @@ public Response rejectRequest(@Valid @RequestBody MatchingRequest request){

@PostMapping("/accept")
@Operation(summary = "매칭 승인", description = "매칭 요청을 승인합니다.")
public Response acceptRequest(@Valid @RequestBody MatchingRequest request){
public Response acceptRequest(@Valid @RequestBody MatchingRequest request) throws FirebaseMessagingException {
matchingService.matching(request);
return Response.of(HttpStatus.OK, "매칭 성공");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import com.dear.domain.matching.dto.Matching;
import com.dear.domain.matching.dto.request.MatchingRequest;
import com.dear.global.common.dto.request.PageRequest;
import com.google.firebase.messaging.FirebaseMessagingException;

import java.util.List;

public interface MatchingService {

void matching(MatchingRequest matchingRequest);
void matching(MatchingRequest matchingRequest) throws FirebaseMessagingException;
void finale(MatchingRequest matchingRequest);
List<Matching> findRequest(PageRequest pageRequest);
void reject(MatchingRequest matchingRequest);
Expand Down
Loading

0 comments on commit 510dc27

Please sign in to comment.