Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat]: 푸시알람 구현 #39

Merged
merged 7 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -315,4 +315,5 @@ gradle-app.setting
# Java heap dump
*.hprof

**/resources/*
# End of https://www.toptal.com/developers/gitignore/api/macos,intellij,intellij+iml,intellij+all,gradle,java
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.12.3'
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.3'
//FCM
implementation 'com.google.firebase:firebase-admin:9.2.0'
}

tasks.named('bootBuildImage') {
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/com/onnoff/onnoff/OnnoffApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableFeignClients(defaultConfiguration = FeignConfig.class)
@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
public class OnnoffApplication {

public static void main(String[] args) {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/onnoff/onnoff/auth/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@ public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new UserInterceptor(userService, jwtUtil))
.addPathPatterns("/**") // 스프링 경로는 /*와 /**이 다름
.excludePathPatterns("/swagger-ui/**", "/v3/api-docs/**", "/oauth2/**", "/on/**", "/health", "/token/**");
.excludePathPatterns("/swagger-ui/**", "/v3/api-docs/**", "/oauth2/**", "/on/**", "/health", "/token/**" , "/message/**");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
private final static String[] ignorePrefix = {"/swagger-ui", "/v3/api-docs", "/oauth2", "/on", "/health", "/token/validate"};
private final static String[] ignorePrefix = {"/swagger-ui", "/v3/api-docs", "/oauth2", "/on", "/health", "/token/validate" , "/message"};
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
log.info("url ={}", request.getRequestURI());
Expand All @@ -44,11 +44,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
accessToken = authHeader.substring(7);
}
if (jwtTokenProvider.verifyToken(accessToken)){
log.info("jwt Filter 인증성공");
log.info("인증성공");
filterChain.doFilter(request, response);
}
else{
log.info("jwt Filter 인증실패");
log.info("인증실패");
response.sendError(HttpStatus.UNAUTHORIZED.value());
}
}
Expand Down
43 changes: 43 additions & 0 deletions src/main/java/com/onnoff/onnoff/config/FirebaseConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.onnoff.onnoff.config;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

@Configuration
@Slf4j
public class FirebaseConfig {
private final Logger logger = LoggerFactory.getLogger(FirebaseConfig.class);
@Value("${fcm.firebase-sdk-path}") // your firebase sdk path
private String firebaseSdkPath;
@Value("${fcm.project-id}")
private String projectId;
@PostConstruct
public void initialize() {
try {
ClassPathResource resource = new ClassPathResource(firebaseSdkPath);
InputStream serviceAccount = resource.getInputStream();
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options);
log.info("Successfully firebase application initialized!");
}
} catch (FileNotFoundException e) {
logger.error("Firebase ServiceAccountKey FileNotFoundException" + e.getMessage());
} catch (IOException e) {
logger.error("FirebaseOptions IOException" + e.getMessage());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.onnoff.onnoff.domain.push.controller;

import com.onnoff.onnoff.domain.push.service.FcmSendNotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@Slf4j
public class FcmController {
private final FcmSendNotificationService fcmSendNotificationService;

@GetMapping("/message/test")
public ResponseEntity pushTest(){
fcmSendNotificationService.sendTestNotification();
return ResponseEntity.ok("good");
}
}
24 changes: 24 additions & 0 deletions src/main/java/com/onnoff/onnoff/domain/push/dto/FcmServiceDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.onnoff.onnoff.domain.push.dto;

import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
public class FcmServiceDto {
private String username;
private Long contentId;
private NotificationType type;
private String title;
private String content;

public static FcmServiceDto of(String username, Long contentId, NotificationType type, String title, String content){
FcmServiceDto dto = new FcmServiceDto();
dto.username = username;
dto.contentId = contentId;
dto.type = type;
dto.title = title;
dto.content = content;
return dto;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.onnoff.onnoff.domain.push.dto;

import com.google.firebase.messaging.Notification;
import com.onnoff.onnoff.domain.user.User;
import lombok.Builder;

@Builder
public record NotificationMessage(
String title,
String message,
NotificationType type
) {
public static NotificationMessage toGoHomeNotification(User user) {
return NotificationMessage.builder()
.title(user.getNickname() + "님, 이제 퇴근하실 시간이에요.")
.message("")
.type(NotificationType.NOTIFY)
.build();
}
public static NotificationMessage toGoHomeNotificationTest() {
return NotificationMessage.builder()
.title("예진" + "님, 이제 퇴근하실 시간이에요.")
.message("")
.type(NotificationType.NOTIFY)
.build();
}


public Notification toNotification() {
return Notification.builder()
.setTitle(title)
.setBody(message)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.onnoff.onnoff.domain.push.dto;

public enum NotificationType {
NOTIFY
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.onnoff.onnoff.domain.push.service;

import com.google.firebase.messaging.Message;
import com.onnoff.onnoff.domain.push.dto.NotificationMessage;
import com.onnoff.onnoff.domain.user.User;
import com.onnoff.onnoff.domain.user.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class FcmSendNotificationService {
private final FcmService fcmService;
private final UserRepository userRepository;
public void sendTestNotification() {
NotificationMessage notificationMessage =
NotificationMessage.toGoHomeNotificationTest();
final Message message =
fcmService.createMessage("testtoken", notificationMessage);
fcmService.send(message);
}
//1분 단위로 푸시알람 보내는 함수
@Scheduled(cron = "0 * * * * *", zone = "Asia/Seoul")
public void sendGoHomeNotificationByMinute() {
LocalDateTime currentTime = LocalDateTime.now();
LocalTime startTime = currentTime.minusSeconds(30).toLocalTime();
LocalTime endTime = currentTime.plusSeconds(30).toLocalTime();
List<User> userList = userRepository.findByPushNotificationTimeBetween(startTime, endTime);
for (User user : userList) {
NotificationMessage notificationMessage = NotificationMessage.toGoHomeNotification(user);
Message message = fcmService.createMessage(user.getFcmToken(), notificationMessage);
fcmService.send(message);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

궁금해서 그런데 여기서 가져온 fcmToken은 푸시 알림 동의 했을때 set 되는건가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 온보딩에서 푸시 알람 동의했을 때 프론트 측에서 한 번에 유저 정보 업데이트 api 요청할 때 담아서 보내주고, 이를 기반으로 백이 디비에 업데이트 하는 식으로 로직 이해하고 있습니다 ~

}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.onnoff.onnoff.domain.push.service;

import com.google.firebase.messaging.*;
import com.onnoff.onnoff.domain.push.dto.NotificationMessage;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Builder
@RequiredArgsConstructor
public class FcmService {
public void send(Message message) {
FirebaseMessaging.getInstance()
.sendAsync(message);
}
public Message createMessage(String deviceToken, NotificationMessage notificationMessage) {
return Message.builder()
.setToken(deviceToken)
.setNotification(notificationMessage.toNotification())
.putData("title", notificationMessage.title())
.putData("body", notificationMessage.message())
.putData("type", notificationMessage.type().name())
.build();
}

//다음 행동 유도가 필요할 때 path를 쓴다..!
public Message createMessage(String deviceToken, NotificationMessage notificationMessage, String path) {

Notification notification = notificationMessage.toNotification();
return Message.builder()
.setToken(deviceToken)
.setNotification(notification)
.setApnsConfig(
ApnsConfig.builder()
.setAps(
Aps.builder()
.setSound("default")
.build()
)
.build()
)
.putData("title", notificationMessage.title())
.putData("body", notificationMessage.message())
.putData("type", notificationMessage.type().name())
.putData("path", path)
.putData("sound", "default")
.build();
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/onnoff/onnoff/domain/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import org.hibernate.annotations.DynamicInsert;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

Expand Down Expand Up @@ -67,6 +68,9 @@ public class User extends BaseEntity {

private String fcmToken;

@Column(nullable = true)
private LocalTime pushNotificationTime;

private String appleRefreshToken;

@Enumerated(EnumType.STRING)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
import com.onnoff.onnoff.domain.user.User;
import org.springframework.data.jpa.repository.JpaRepository;

import java.time.LocalTime;
import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByOauthId(String oauthId);

List<User> findByPushNotificationTimeBetween(LocalTime startTime, LocalTime endTime);

}
Loading