Skip to content

Commit

Permalink
🌟 ::
Browse files Browse the repository at this point in the history
  • Loading branch information
gurdl0525 committed Nov 22, 2023
1 parent 15f58b2 commit db6f509
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 45 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ jobs:
docker pull ${{ secrets.DOCKER_REPOSITORY }}
docker stop onui-server
docker rm onui-server
docker run -dp ${{ secrets.HOST_PORT }}:${{ secrets.DOCKER_CONTAINER_PORT }} --name onui-server --env-file .env ${{ secrets.DOCKER_REPOSITORY }}
docker run -dp ${{ secrets.HOST_PORT }}:${{ secrets.DOCKER_CONTAINER_PORT }} --name onui-server --env-file .env ${{ secrets.DOCKER_REPOSITORY }} --secret ${{ secrets.FCM_JSON_PATH }}
docker rmi $(docker images -f "dangling=true" -q)
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,7 @@ out/
.env

### copose ###
Docker-compose.yml
Docker-compose.yml

### onui-fcm.json ###
onui-fcm.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.example.onui.domain.mission.presentation.dto.request.CreateMissionReq
import com.example.onui.domain.mission.presentation.dto.response.MissionResponse
import com.example.onui.domain.mission.service.MissionService
import com.example.onui.domain.user.service.UserService
import com.example.onui.infra.fcm.FCMScheduling
import com.vane.badwordfiltering.BadWordFiltering
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
Expand All @@ -16,7 +17,8 @@ import javax.validation.Valid
class AdminController(
private val userService: UserService,
private val missionService: MissionService,
private val badWordFiltering: BadWordFiltering
private val badWordFiltering: BadWordFiltering,
private val fcmScheduling: FCMScheduling
) {

@PostMapping("/theme")
Expand Down Expand Up @@ -45,4 +47,7 @@ class AdminController(
) {
badWordFiltering.add(text)
}

@PostMapping("/fcm")
fun postFCM() { fcmScheduling.essentailHost() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ class MissionScheduling(

val randomMissions = missionRepository.findAllByMissionType(MissionType.RANDOM)

userRepository.findAll().parallelStream().forEach { missionService.assignMission(it, randomMissions) }
userRepository.findAll().forEach { missionService.assignMission(it, randomMissions) }
}
}
43 changes: 43 additions & 0 deletions src/main/kotlin/com/example/onui/global/config/FCMConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.example.onui.global.config

import com.example.onui.global.env.FCMProperty
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.File
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.io.path.Path


@Configuration
class FCMConfig(
private val fcmProperty: FCMProperty
) {

@Bean
fun firebaseMessaging(): FirebaseMessaging {
val rfToken: InputStream = Files.newInputStream(Paths.get(fcmProperty.path))
var firebaseApp: FirebaseApp? = null
val firebaseAppList = FirebaseApp.getApps()
if (firebaseAppList != null && firebaseAppList.isNotEmpty()) {
for (app in firebaseAppList) {
if (app.name == FirebaseApp.DEFAULT_APP_NAME) {
firebaseApp = app
}
}
} else {
val options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(rfToken).createScoped(fcmProperty.scope))
.build()
firebaseApp = FirebaseApp.initializeApp(options)
}
return FirebaseMessaging.getInstance(firebaseApp)
}
}
7 changes: 4 additions & 3 deletions src/main/kotlin/com/example/onui/infra/fcm/FCMScheduling.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional(readOnly = true)
class FCMScheduling(
private val notificationService: NotificationService,
private val userRepository: UserRepository
) {

@Transactional
@Scheduled(cron = "0 20 8 * * ?", zone = "Asia/Seoul")
@Scheduled(cron = "0 30 8 * * ?", zone = "Asia/Seoul")
fun essentailHost() {
userRepository.findAll().parallelStream().peek {
userRepository.findAll().forEach {
notificationService.sendByTokenList(
it.deviceToken, "감정 기록하실 때가 됐어요!", "사용자님 오늘도 오누이에 감정을 기록해보아요!!"
)
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,52 @@ import com.google.firebase.messaging.*
import mu.KotlinLogging
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
import java.time.LocalDateTime
import javax.annotation.PostConstruct

@Service
class NotificationServiceImpl(
private val fcmProperty: FCMProperty
private val firebaseMessaging: FirebaseMessaging
) : NotificationService {

private companion object {
val logger = KotlinLogging.logger { }
val logger = KotlinLogging.logger { }
}

@PostConstruct
fun init() {
try {
val options = FirebaseOptions.builder()
.setCredentials(
GoogleCredentials
.fromStream(ClassPathResource(fcmProperty.path).getInputStream())
.createScoped(listOf(fcmProperty.scope))
)
.build()
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(options)
}
} catch (e: IOException) {
logger.error{ e.message }
throw RuntimeException(e.message)
}
}

// 알림 보내기
@Transactional
override fun sendByTokenList(tokenList: MutableSet<String>, title: String, body: String) {

val messages: MutableList<Message> = tokenList.stream().map {
val messages: List<Message> = tokenList.map {
Message.builder()
.putData("time", LocalDateTime.now().toString())
.setNotification(Notification.builder().setTitle(title).setBody(body).build())
.setToken(it)
.build()
}.toList()

FirebaseMessaging.getInstance().sendAll(messages)
try {
val response: BatchResponse = firebaseMessaging.sendAll(messages)


if ((messages.size - response.successCount) > 0) {
val responses: MutableList<SendResponse> = response.responses;
val failedTokens: MutableList<String> = mutableListOf()

var i = 0
while (i < responses.size) {
if (!responses[i].isSuccessful) {
failedTokens.add(tokenList.elementAt(i))
}
i += 1
}
logger.error { "List of tokens are not valid FCM token : $failedTokens" }
}
} catch (e: FirebaseMessagingException) {
logger.error { "cannot send to memberList push message. error info : ${e.message}" }
} catch (e: Exception) {
logger.error { e.localizedMessage }
}
}
}
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,5 @@ gpt:

fcm:
key:
path: onui-fcm.json
path: ${FCM_JSON_PATH}
scope: https://www.googleapis.com/auth/cloud-platform
13 changes: 0 additions & 13 deletions src/main/resources/onui-fcm.json

This file was deleted.

0 comments on commit db6f509

Please sign in to comment.