Skip to content

Commit

Permalink
Merge pull request #121 from Team-Shaka/feat/120
Browse files Browse the repository at this point in the history
✨ Feat: 한 유저당 하나의 FCM Token 값을 저장하도록 수정
  • Loading branch information
HyoBN authored Sep 8, 2024
2 parents 08a8d18 + 7a918e5 commit d39929b
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ public interface FcmTokenRepository extends JpaRepository<FcmToken, Long> {

void deleteAllByUser(User user);

void deleteByUser(User user);

boolean existsByUser(User user);

boolean existsByUserAndToken(User user, String token);

List<FcmToken> findAllByUser(User user);
// List<FcmToken> findAllByUser(User user);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class FcmToken extends BaseDateTimeEntity {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@OneToOne
private User user;

private String token;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public enum GlobalErrorCode implements BaseErrorCode{
PHONE_AUTH_TIMEOUT(BAD_REQUEST, "NCP400_3", "인증 시간이 초과되었습니다."),

FCM_ALREADY_EXISTS_TOKEN(BAD_REQUEST, "FCM400_1", "이미 저장되어 있는 FCM 토큰입니다."),
FCM_TOKEN_NOT_EXISTS(BAD_REQUEST,"FCM400_2", "해당 유저의 FCM Token 이 존재하지 않습니다."),
FCM_ACCESS_TOKEN_REQUEST_ERROR(INTERNAL_SERVER_ERROR, "FCM500_2", "서버 에러, FCM 서버에 AccessToken 요청할 때 에러 발생."),
FCM_SEND_MESSAGE_ERROR(INTERNAL_SERVER_ERROR , "FCM500_3", "서버 에러, FCM 서버에 메시지를 전송할 때 에러 발생. FcmToken이 유효한지 확인해주세요."), ;

Expand Down
61 changes: 32 additions & 29 deletions src/main/java/treehouse/server/global/fcm/service/FcmService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.google.firebase.messaging.FirebaseMessagingException;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -19,10 +20,11 @@
import treehouse.server.global.fcm.dto.FCMDto;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
//@Transactional(readOnly = true)
public class FcmService {
Logger logger = LoggerFactory.getLogger(FcmService.class);

Expand All @@ -49,53 +51,54 @@ public void testFCMService(String fcmToken)

@Transactional(readOnly = false)
public UserResponseDTO.saveFcmToken saveFcmToken(User user, FCMDto.saveFcmTokenDto request) {
boolean isSuccess = false;
logger.error("토큰 값 : {}",request.getFcmToken());
if (fcmTokenRepository.existsByUserAndToken(user, request.getFcmToken())) {
throw new FcmException(GlobalErrorCode.FCM_ALREADY_EXISTS_TOKEN);
}else{
boolean isSuccess = true;
logger.info("토큰 값 : {}", request.getFcmToken());


// 한 user 당 가장 최신의 fcm token 값 하나만 db 에 저장하도록 수정
if (fcmTokenRepository.existsByUser(user)) {
FcmToken fcmToken = fcmTokenRepository.findByUser(user).orElseThrow(() -> new FcmException(GlobalErrorCode.FCM_TOKEN_NOT_EXISTS));
fcmToken.update(request.getFcmToken());
} else {
fcmTokenRepository.save(FcmToken.builder()
.user(user)
.token(request.getFcmToken())
.build()
);
isSuccess = true;
}
return UserMapper.toSaveFcmToken(user, isSuccess);
}


public void sendFcmMessage(User receiver, String title, String body) {

List<FcmToken> fcmTokenList = fcmTokenRepository.findAllByUser(receiver);
if (fcmTokenList.isEmpty()) {
return;
}
FcmToken fcmToken = fcmTokenRepository.findByUser(receiver).orElseThrow(() -> new FcmException(GlobalErrorCode.FCM_TOKEN_NOT_EXISTS));

for (FcmToken fcmToken : fcmTokenList) {
String token = fcmToken.getToken();
logger.info("전송하고자 하는 FCM 토큰 값 : " + token);
Message message = Message.builder()
.setToken(token)
.setNotification(
Notification.builder()
.setTitle(title)
.setBody(body)
.build())
.build();
try {
String response = FirebaseMessaging.getInstance().send(message);
logger.info("the response of request FCM : {}",response);
} catch (FirebaseMessagingException e) {
throw new FcmException(GlobalErrorCode.FCM_SEND_MESSAGE_ERROR);
}
}
String token = fcmToken.getToken();
logger.info("전송하고자 하는 FCM 토큰 값 : " + token);

Message message = Message.builder()
.setToken(token)
.setNotification(
Notification.builder()
.setTitle(title)
.setBody(body)
.build())
.build();

try {
String response = FirebaseMessaging.getInstance().send(message);
logger.info("the response of request FCM : {}",response);
} catch (FirebaseMessagingException e) {
logger.error("FCM 푸시 알림 전송 실패, 이유 : {}", e.getMessage());
throw new FcmException(GlobalErrorCode.FCM_SEND_MESSAGE_ERROR);
}

}

@Transactional
public void deleteAllFcmToken(User user) {
fcmTokenRepository.deleteAllByUser(user);
}

}

0 comments on commit d39929b

Please sign in to comment.