Skip to content

Commit

Permalink
Merge pull request #5 from team-onui/develop
Browse files Browse the repository at this point in the history
🌟 :: fcm
  • Loading branch information
gurdl0525 authored Nov 20, 2023
2 parents faba04c + bcc5898 commit 374ac80
Show file tree
Hide file tree
Showing 14 changed files with 152 additions and 6 deletions.
3 changes: 3 additions & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ dependencies {

// bad word filter
implementation("io.github.vaneproject:badwordfiltering:1.0.0")

//firebase
implementation("com.google.firebase:firebase-admin:9.1.1")
}

dependencyManagement {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ class AnalysisServiceImpl(
override fun test() {

val user = userFacade.getCurrentUser()

diaryRepository.deleteAllByUser(user)

val now = LocalDateTime.now()

var i = now.minusDays(30);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,12 @@ class AuthServiceImpl(
}
userRepository.delete(user)
}

@Transactional
fun applyDeviceToken(token: String) {

val user = userFacade.getCurrentUser()

user.applyDeviceToken(token)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ class GoogleAuthServiceImpl(

userRepository.findBySub(req.sub) ?: userRepository.save(
User(
req.sub,
req.name!!,
sub = req.sub,
name = req.name!!,
DEFAULT,
themeRepository.findByIdOrNull(DEFAULT_ID)!!
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ interface DiaryRepository : JpaRepository<Diary, UUID?> {
fun existsByIdAndIsPosted(id: UUID, isPosted: Boolean): Boolean

fun findByIdAndIsPosted(id: UUID, isPosted: Boolean): Diary?

fun deleteAllByUser(user: User)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import com.querydsl.jpa.impl.JPAQueryFactory
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime

@Service
@Transactional(readOnly = true)
Expand All @@ -17,17 +19,17 @@ class QDiaryRepositoryImpl(

override fun findThreeDayAgoByUser(user: User) = queryFactory.selectFrom(diary)
.orderBy(diary.createdAt.desc())
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.now().minusDays(3))))
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.of(LocalDate.now().minusDays(3), LocalTime.of(0,0,0)))))
.limit(3)
.fetch().toMutableList()

override fun findSevenDayAgoByUser(user: User) = queryFactory.selectFrom(diary)
.orderBy(diary.createdAt.desc())
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.now().minusDays(7))))
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.of(LocalDate.now().minusDays(7), LocalTime.of(0,0,0)))))
.fetch().map { it.toResponse() }.toMutableList()

override fun findOneMonthAgoByUser(user: User) = queryFactory.selectFrom(diary)
.orderBy(diary.createdAt.desc())
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.now().minusDays(30L))))
.where(diary.user.eq(user).and(diary.createdAt.after(LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.of(0,0,0)))))
.fetch().toMutableList()
}
8 changes: 8 additions & 0 deletions src/main/kotlin/com/example/onui/domain/user/entity/User.kt
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ class User(
var boughtTheme: MutableList<BoughtTheme> = arrayListOf()
protected set

@ElementCollection
var deviceToken: MutableSet<String> = mutableSetOf()
protected set

fun applyDeviceToken(token: String) {
this.deviceToken.add(token)
}

fun toResponse() = UserProfileResponse(
this.sub,
this.name,
Expand Down
11 changes: 11 additions & 0 deletions src/main/kotlin/com/example/onui/global/env/FCMProperty.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.onui.global.env

import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding

@ConstructorBinding
@ConfigurationProperties("fcm.key")
data class FCMProperty(
val path: String,
val scope: String
)
23 changes: 23 additions & 0 deletions src/main/kotlin/com/example/onui/infra/fcm/FCMScheduling.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.onui.infra.fcm

import com.example.onui.domain.user.repository.UserRepository
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class FCMScheduling(
private val notificationService: NotificationService,
private val userRepository: UserRepository
) {

@Transactional
@Scheduled(cron = "0 20 8 * * ?", zone = "Asia/Seoul")
fun essentailHost() {
userRepository.findAll().parallelStream().peek {
notificationService.sendByTokenList(
it.deviceToken, "감정 기록하실 때가 됐어요!", "사용자님 오늘도 오누이에 감정을 기록해보아요!!"
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.onui.infra.fcm

interface NotificationService {

fun sendByTokenList(tokenList: MutableSet<String>, title: String, body: String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.example.onui.infra.fcm

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.*
import mu.KotlinLogging
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.io.IOException
import java.time.LocalDateTime
import javax.annotation.PostConstruct

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

private companion object {
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)
}
}

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

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

FirebaseMessaging.getInstance().sendAll(messages)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.onui.infra.fcm.dto.reqeust

data class FCMNotificationRequest (
val title: String,
val message: String
)
7 changes: 6 additions & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,9 @@ cloud:
region: ap-northeast-2

gpt:
secret-key: ${GPT_KEY}
secret-key: ${GPT_KEY}

fcm:
key:
path: onui-fcm.json
scope: https://www.googleapis.com/auth/cloud-platform
13 changes: 13 additions & 0 deletions src/main/resources/onui-fcm.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"type": "service_account",
"project_id": "onui-399708",
"private_key_id": "ed3eeefe4fd58acbb799bee0b440c68265331a44",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDrmqmC9DZIMt4G\ndBh6u4D7M5u9tx3rgfLWZw5XIM0q7R9ax0HrEJZ+kfxO+5qIBDjdyBZnvZtvV8in\n/LIbj/zhBUrMu3uU4nHen03o/so9dgEzW8j8ln2PJHUz3DorpkzfmUQakdUgbOgE\nJxJSTHltVVZgOBiyItB3U6bO3EgWUSw64SI96sqc/jHXhzXHwJFC/xZNatgxJqKb\nqzhflwurC9a1VTZVaxipxsV4GqB/OlmvMSp4RvbWsUTOzI94+2QMrv0LtNnEj4WJ\nV3WOBf4+KEXpnGEQe26I3pzx5mpJ6kr5FbRjjyHyytu702klYsiu4amxUQmSU1Dj\n7HdaAG/LAgMBAAECggEAbCc03mEF1BHJuxOrMxgE5wuzWB0J1pTyKTroqdVsaWKt\nrInguCwGsbaJKKa2Mu8hPan+owO2qR+WhIrrJdzsvE0mH6KG4fsrQ4NEjAr+QsV7\nWpytQEpC/CVDyhkz+Nqf2lrsmPfN6tMjlNhswCvL6AUvH/9QUuHJaaWUY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m355A==\n-----END PRIVATE KEY-----\n",
"client_email": "[email protected]",
"client_id": "107821224243694744575",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-jgwl3%40onui-399708.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}

0 comments on commit 374ac80

Please sign in to comment.