Skip to content

Commit

Permalink
Merge pull request #107 from Team-Shaka/feat/104
Browse files Browse the repository at this point in the history
Feat/104 FCM 푸시 알림 관련 로직 추가, API 추가
  • Loading branch information
HyoBN authored Aug 27, 2024
2 parents 308466f + c07e65b commit aaf44c8
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
import treehouse.server.api.notification.presentation.dto.NotificationRequestDTO;
import treehouse.server.api.notification.presentation.dto.NotificationResponseDTO;
import treehouse.server.api.treehouse.implementation.TreehouseQueryAdapter;
import treehouse.server.api.user.implement.UserQueryAdapter;
import treehouse.server.global.entity.User.User;
import treehouse.server.global.entity.member.Member;
import treehouse.server.global.entity.notification.Notification;
import treehouse.server.global.entity.treeHouse.TreeHouse;
import treehouse.server.global.fcm.service.FcmService;

import java.util.Comparator;
import java.util.List;
Expand All @@ -31,6 +33,8 @@ public class NotificationService {

private final TreehouseQueryAdapter treehouseQueryAdapter;

private final FcmService fcmService;

/**
* 알림 생성하는 로직
* @param user
Expand All @@ -42,8 +46,9 @@ public void createNotification(User user, Long treehouseId, NotificationRequestD
TreeHouse treeHouse = treehouseQueryAdapter.getTreehouseById(treehouseId);
Member sender = memberQueryAdapter.findByUserAndTreehouse(user, treeHouse);
Member receiver = memberQueryAdapter.findById(request.getReceiverId());

Notification notification = NotificationMapper.toNotification(sender, receiver, request, reactionName);

fcmService.sendFcmMessage(receiver.getUser(), notification.getTitle(), notification.getBody());
notificationCommandAdapter.createNotification(notification);
}

Expand Down
15 changes: 15 additions & 0 deletions src/main/java/treehouse/server/api/user/business/UserMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import jakarta.annotation.PostConstruct;
import lombok.*;
import org.springframework.stereotype.Component;
import treehouse.server.api.user.presentation.dto.UserRequestDTO;
import treehouse.server.api.user.presentation.dto.UserResponseDTO;
import treehouse.server.global.entity.User.User;
import treehouse.server.global.entity.User.UserRole;
Expand Down Expand Up @@ -80,4 +81,18 @@ public static UserResponseDTO.withdraw toWithdraw(User user) {
.userId(user.getId())
.build();
}

public static UserResponseDTO.pushAgree toPushAgree(User user, UserRequestDTO.pushAgreeDto request) {
return UserResponseDTO.pushAgree.builder()
.userId(user.getId())
.isPushAgree(request.isPushAgree())
.build();
}

public static UserResponseDTO.saveFcmToken toSaveFcmToken(User user, boolean isSuccess) {
return UserResponseDTO.saveFcmToken.builder()
.userId(user.getId())
.isSaveFcmToken(isSuccess)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import treehouse.server.global.exception.GlobalErrorCode;
import treehouse.server.global.exception.ThrowClass.AuthException;
import treehouse.server.global.exception.ThrowClass.GeneralException;
import treehouse.server.global.fcm.service.FcmService;
import treehouse.server.global.redis.service.RedisService;
import treehouse.server.global.security.jwt.dto.TokenDTO;
import treehouse.server.global.security.provider.TokenProvider;
Expand All @@ -39,6 +40,8 @@ public class UserService {
private final InvitationQueryAdapter invitationQueryAdapter;
private final UserRepository userRepository;

private final FcmService fcmService;

@Transactional(readOnly = true)
public UserResponseDTO.checkName checkName(UserRequestDTO.checkName request){
return UserMapper.toCheckNameDTO(userQueryAdapter.checkName(request));
Expand Down Expand Up @@ -97,4 +100,10 @@ public UserResponseDTO.withdraw withdraw(User user) {

return UserMapper.toWithdraw(user);
}

@Transactional
public UserResponseDTO.pushAgree updatePushAgree(User user, UserRequestDTO.pushAgreeDto request){
boolean pushAgree = user.updatePushAgree(request.isPushAgree());
return UserMapper.toPushAgree(user, request);
}
}
23 changes: 23 additions & 0 deletions src/main/java/treehouse/server/api/user/presentation/UserApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import treehouse.server.api.user.presentation.dto.UserResponseDTO;
import treehouse.server.global.common.CommonResponse;
import treehouse.server.global.entity.User.User;
import treehouse.server.global.fcm.dto.FCMDto;
import treehouse.server.global.fcm.service.FcmService;
import treehouse.server.global.security.handler.annotation.AuthMember;

@RestController
Expand All @@ -23,6 +25,7 @@
public class UserApi {

private final UserService userService;
private final FcmService fcmService;

@PostMapping("/checkName")
@Operation(summary = "아이디 중복 체크 ✅", description = "서비스에서 사용할 유저이름을 중복 체크합니다.")
Expand Down Expand Up @@ -69,6 +72,26 @@ public CommonResponse<UserResponseDTO.checkUserStatus> checkPhoneAuth(
public CommonResponse<UserResponseDTO.withdraw> withdraw(
@AuthMember @Parameter(hidden = true) User user
){
fcmService.deleteAllFcmToken(user);
return CommonResponse.onSuccess(userService.withdraw(user));
}

@PostMapping("/push-agree")
@Operation(summary = "푸시 알림 동의 API 🔑✅️", description = "푸시 알림 동의 API입니다.")
public CommonResponse<UserResponseDTO.pushAgree> pushAgree(
@AuthMember @Parameter(hidden = true) User user,
@RequestBody UserRequestDTO.pushAgreeDto request
){
return CommonResponse.onSuccess(userService.updatePushAgree(user,request));
}


@PostMapping("/fcm-token")
@Operation(summary = "FCM 토큰 저장 API 🔑✅️", description = "FCM 토큰 저장 API입니다.")
public CommonResponse<UserResponseDTO.saveFcmToken> saveFcmToken(
@AuthMember @Parameter(hidden = true) User user,
@RequestBody FCMDto.saveFcmTokenDto request
){
return CommonResponse.onSuccess(fcmService.saveFcmToken(user,request));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.*;


public class UserRequestDTO {
Expand Down Expand Up @@ -64,4 +61,9 @@ public String toString() {
public static class checkUserStatus {
private String phoneNumber;
}

@Getter
public static class pushAgreeDto{
boolean pushAgree;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,22 @@ public static class loginMember {
public static class withdraw {
private Long userId;
}

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class pushAgree {
private Long userId;
private boolean isPushAgree;
}

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public static class saveFcmToken {
private Long userId;
private boolean isSaveFcmToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import treehouse.server.global.entity.common.BaseDateTimeEntity;

@Getter
@Builder
Expand All @@ -12,7 +13,7 @@
@DynamicUpdate
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class FcmToken {
public class FcmToken extends BaseDateTimeEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ public enum GlobalErrorCode implements BaseErrorCode{
PHONE_AUTH_WRONG(BAD_REQUEST, "NCP400_2", "잘못된 인증 번호 입니다."),
PHONE_AUTH_TIMEOUT(BAD_REQUEST, "NCP400_3", "인증 시간이 초과되었습니다."),

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

;

Expand Down
25 changes: 25 additions & 0 deletions src/main/java/treehouse/server/global/fcm/service/FcmService.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,14 @@
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import treehouse.server.api.user.business.UserMapper;
import treehouse.server.api.user.persistence.FcmTokenRepository;
import treehouse.server.api.user.presentation.dto.UserResponseDTO;
import treehouse.server.global.entity.User.FcmToken;
import treehouse.server.global.entity.User.User;
import treehouse.server.global.exception.GlobalErrorCode;
import treehouse.server.global.exception.ThrowClass.FcmException;
import treehouse.server.global.fcm.dto.FCMDto;

import java.util.List;

Expand Down Expand Up @@ -44,6 +47,23 @@ 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{
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) {
if (receiver.isPushAgree() == false) {
Expand Down Expand Up @@ -76,4 +96,9 @@ public void sendFcmMessage(User receiver, String title, String body) {


}

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

0 comments on commit aaf44c8

Please sign in to comment.