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

✨ Feature - FCM Notification #57

Merged
merged 2 commits into from
Dec 6, 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
3 changes: 3 additions & 0 deletions server-api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ dependencies {
implementation 'com.atlassian.commonmark:commonmark:0.17.0'
implementation 'org.jsoup:jsoup:1.18.1'

// Firebase
implementation 'com.google.firebase:firebase-admin:9.4.2'

// Test
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.dongguk.dscd.wooahan.api.core.config;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Configuration
public class FirebaseConfig {

@Bean
FirebaseMessaging firebaseMessaging() throws IOException {
ClassPathResource resource = new ClassPathResource("firebase/firebase-admin-key.json");
InputStream refreshToken = resource.getInputStream();

FirebaseApp firebaseApp = null;

List<FirebaseApp> firebaseAppList = FirebaseApp.getApps();

if (firebaseAppList != null && !firebaseAppList.isEmpty()) {
for (FirebaseApp app : firebaseAppList) {
if (app.getName().equals(FirebaseApp.DEFAULT_APP_NAME)) {
firebaseApp = app;
}
}
} else {
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(refreshToken))
.build();

firebaseApp = FirebaseApp.initializeApp(options);

}

assert firebaseApp != null;
return FirebaseMessaging.getInstance(firebaseApp);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.dongguk.dscd.wooahan.api.notification.controller;

import lombok.RequiredArgsConstructor;
import org.dongguk.dscd.wooahan.api.core.dto.ResponseDto;
import org.dongguk.dscd.wooahan.api.notification.service.NotificationService;
import org.dongguk.dscd.wooahan.api.user.domain.type.ETime;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

// 시연용 controller TODO: 시연 후 삭제 예정

@RestController
@RequiredArgsConstructor
public class NotificationController {

private final NotificationService notificationService;

@PostMapping("/v1/users/{userId}/notifications")
public ResponseDto<?> sendNotification(
@PathVariable UUID userId,
@RequestParam ETime time
) {
notificationService.sendPushNotification(userId, time);

return ResponseDto.ok(null);
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package org.dongguk.dscd.wooahan.api.notification.service;

import com.google.firebase.messaging.*;
import lombok.RequiredArgsConstructor;
import org.dongguk.dscd.wooahan.api.core.exception.error.ErrorCode;
import org.dongguk.dscd.wooahan.api.core.exception.type.CommonException;
import org.dongguk.dscd.wooahan.api.user.domain.mysql.User;
import org.dongguk.dscd.wooahan.api.user.domain.type.ETime;
import org.dongguk.dscd.wooahan.api.user.repository.mysql.UserRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class NotificationService {

private final UserRepository userRepository;

private static final String BREAKFAST_NOTIFICATION_CONTENT_FORM = "%s님 아침 약 드실 시간이에요!";
private static final String LUNCH_NOTIFICATION_CONTENT_FORM = "%s님 점심 약 드실 시간이에요!";
private static final String DINNER_NOTIFICATION_CONTENT_FORM = "%s님 저녁 약 드실 시간이에요!";

@Scheduled(cron = "0 0/5 5-9 * * *")
public void sendPushNotificationOnBreakfast() {
// 1. 현재 시간 조회
LocalTime nowTime = LocalTime.now()
.withMinute((LocalTime.now().getMinute() / 15) * 15)
.withSecond(0).withNano(0);

// 2. 현재 시간에 알림을 받아야 하는 사용자 목록 조회
List<User> recieverList = userRepository.findAllByBreakfastTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
nowTime,
true
);

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.BREAKFAST))
.toList();

// 4. 알림 메시지 전송
for (Message message : messageList) {
try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}
}

@Scheduled(cron = "0 0/5 10-14 * * *")
public void sendPushNotificationOnLunch() {
// 1. 현재 시간 조회
LocalTime nowTime = LocalTime.now()
.withMinute((LocalTime.now().getMinute() / 15) * 15)
.withSecond(0).withNano(0);

// 2. 현재 시간에 알림을 받아야 하는 사용자 목록 조회
List<User> recieverList = userRepository.findAllByLunchTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
nowTime,
true
);

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.LUNCH))
.toList();

// 4. 알림 메시지 전송
for (Message message : messageList) {
try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}
}

@Scheduled(cron = "0 0/5 15-19 * * *")
public void sendPushNotificationOnDinner() {
// 1. 현재 시간 조회
LocalTime nowTime = LocalTime.now()
.withMinute((LocalTime.now().getMinute() / 15) * 15)
.withSecond(0).withNano(0);

// 2. 현재 시간에 알림을 받아야 하는 사용자 목록 조회
List<User> recieverList = userRepository.findAllByDinnerTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
nowTime,
true
);

// 3. 사용자 목록을 통해 알림 메시지 생성
List<Message> messageList = recieverList.stream()
.map(user -> convertToMap(user, ETime.DINNER))
.toList();

// 4. 알림 메시지 전송
for (Message message : messageList) {
try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}
}

Message convertToMap(User user, ETime time) {
String content = switch (time) {
case BREAKFAST -> String.format(BREAKFAST_NOTIFICATION_CONTENT_FORM, user.getNickname());
case LUNCH -> String.format(LUNCH_NOTIFICATION_CONTENT_FORM, user.getNickname());
case DINNER -> String.format(DINNER_NOTIFICATION_CONTENT_FORM, user.getNickname());
};

return Message.builder()
.setToken(user.getDeviceToken())
.setNotification(
Notification.builder()
.setTitle("우아한")
.setBody(content)
.build()
)
.setApnsConfig(
ApnsConfig.builder()
.setAps(
Aps.builder()
.setSound("default")
.build()
)
.build()
)
.build();
}

public void sendPushNotification(
UUID userId,
ETime time
) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new CommonException(ErrorCode.NOT_FOUND_USER));

Message message = convertToMap(user, time);

try {
FirebaseMessaging.getInstance().send(message);
} catch (FirebaseMessagingException ignore) {
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,26 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

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

@Repository
public interface UserRepository extends JpaRepository<User, UUID> {

List<User> findAllByBreakfastTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
LocalTime nowTime,
Boolean isAllowedServiceNotification
);

List<User> findAllByLunchTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
LocalTime nowTime,
Boolean isAllowedServiceNotification
);

List<User> findAllByDinnerTimeAndIsAllowedNotificationAndDeviceTokenIsNotNull(
LocalTime nowTime,
Boolean isAllowedServiceNotification
);

}