Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,6 @@ class SettingEditorSaveSignalAndroidTest {

override fun onWithdrawSuccess() = Unit
},
startWithRecipientRegistration = false,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import com.afternote.afternote_fe.test.FailureArtifactRule
import com.afternote.core.domain.repository.UserRepository
import com.afternote.core.domain.testing.FakeUserRepository
import com.afternote.core.ui.Route
import com.afternote.core.ui.SettingStart
import com.afternote.core.ui.navigation.FeatureNavigationCallbacks
import com.afternote.core.ui.theme.AfternoteTheme
import com.afternote.feature.setting.presentation.navigation.SettingExternalActions
Expand Down Expand Up @@ -90,7 +91,7 @@ class SettingImplementedCoverageAndroidTest {

override fun onWithdrawSuccess() = Unit
},
startWithRecipientRegistration = startWithRecipientRegistration,
start = if (startWithRecipientRegistration) SettingStart.RECIPIENT_REGISTRATION else SettingStart.HOME,
)
}
}
Expand All @@ -114,7 +115,7 @@ class SettingImplementedCoverageAndroidTest {
/**
* 루트의 `composable<Route.Setting>` 이 entry 의 인자를 host 시작점으로 넘기는 한 줄을 실제 루트
* 그래프로 지난다. [launchHost] 는 host 를 직접 띄우므로 그 결선은 이 케이스만 본다 — 인자를
* 흘리면(`startWithRecipientRegistration = false` 고정) 설정 홈이 첫 화면이 되어 여기서 빨개진다.
* 흘리면(`start = SettingStart.HOME` 고정) 설정 홈이 첫 화면이 되어 여기서 빨개진다.
*/
@Test
fun appNavigation_settingRouteArgumentSelectsRegisterAsFirstScreen() {
Expand All @@ -126,7 +127,7 @@ class SettingImplementedCoverageAndroidTest {
activity.setContent {
AfternoteTheme {
AppNavigation(
startDestination = Route.Setting(startWithRecipientRegistration = true),
startDestination = Route.Setting(start = SettingStart.RECIPIENT_REGISTRATION),
appState = AppState(navController),
)
}
Expand Down
58 changes: 35 additions & 23 deletions app/src/main/java/com/afternote/afternote_fe/GlobalApplication.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package com.afternote.afternote_fe

import android.app.Activity
import android.app.Application
import android.os.Bundle
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import com.afternote.afternote_fe.messaging.FcmNotificationChannel
import com.afternote.afternote_fe.messaging.PushTargetSynchronizer
import com.afternote.afternote_fe.notification.DailyNotificationScheduleSynchronizer
import com.afternote.afternote_fe.update.ForceUpdateGate
import com.afternote.core.common.notification.LegacyDailyNotification
import com.afternote.core.network.di.CoilImageLoaderEntryPoint
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.android.HiltAndroidApp
Expand Down Expand Up @@ -37,14 +39,6 @@ class GlobalApplication :
@Inject
lateinit var forceUpdateGate: ForceUpdateGate

/**
* 데일리 알림 예약을 로그인 상태에 맞추는 관찰의 주체 (#2146).
*
* [pushTargetSynchronizer] 와 같은 이유로 여기 있다. 세션 판정이 Hilt 그래프에 있어 Initializer 에서는 못 본다.
*/
@Inject
lateinit var dailyNotificationScheduleSynchronizer: DailyNotificationScheduleSynchronizer

/** Hilt 가 만든 [ImageLoader] 를 Coil 앱 전역 싱글톤으로 등록 — 모든 AsyncImage 가 명시적 imageLoader 없이 이걸 사용. */
override fun newImageLoader(context: PlatformContext): ImageLoader =
EntryPointAccessors
Expand All @@ -54,8 +48,8 @@ class GlobalApplication :
override fun onCreate() {
super.onCreate()
FcmNotificationChannel.create(this)
LegacyDailyNotification.clear(this)
startPushTargetSync()
startDailyNotificationSync()
startForceUpdateCheck()
// 그 밖의 기동 초기화는 startup 패키지의 Initializer 에 둔다.
}
Expand All @@ -73,21 +67,18 @@ class GlobalApplication :
* 관찰은 앱 프로세스 수명 동안 유지돼야 해서 이 스코프는 취소하지 않는다.
*/
private fun startPushTargetSync() {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
scope.launch {
pushTargetSynchronizer.observeLogin()
}
}

/**
* 데일리 알림 예약을 로그인 상태에 맞춘다 (#2146).
*
* 자리가 여기인 이유는 [startPushTargetSync] 와 같다. 관찰은 앱 프로세스 수명 동안 유지돼야 해서
* 이 스코프도 취소하지 않는다.
*/
private fun startDailyNotificationSync() {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
dailyNotificationScheduleSynchronizer.observeLogin()
}
// 시스템 설정에서 알림을 끄거나 켜고 돌아오는 순간을 잡는다 (#2321). 권한이 그대로면 서버 호출이 없다.
registerActivityLifecycleCallbacks(
object : ActivityResumedCallbacks {
override fun onActivityResumed(activity: Activity) {
scope.launch { pushTargetSynchronizer.onForeground() }
}
},
)
}

/**
Expand All @@ -107,3 +98,24 @@ class GlobalApplication :
}
}
}

/** [Application.ActivityLifecycleCallbacks] 중 재개만 쓰려고 나머지를 비워 둔다. */
private interface ActivityResumedCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?,
) = Unit

override fun onActivityStarted(activity: Activity) = Unit

override fun onActivityPaused(activity: Activity) = Unit

override fun onActivityStopped(activity: Activity) = Unit

override fun onActivitySaveInstanceState(
activity: Activity,
outState: Bundle,
) = Unit

override fun onActivityDestroyed(activity: Activity) = Unit
}
80 changes: 80 additions & 0 deletions app/src/main/java/com/afternote/afternote_fe/MainViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@ import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.afternote.afternote_fe.notification.NotificationEntryRequest
import com.afternote.afternote_fe.notification.NotificationEntryResolution
import com.afternote.afternote_fe.notification.NotificationNavigation
import com.afternote.afternote_fe.notification.ServerNotificationDestination
import com.afternote.core.domain.repository.PendingReceiverInvitationStore
import com.afternote.core.domain.repository.auth.AuthRepository
import com.afternote.core.domain.repository.notification.NotificationEntry
import com.afternote.core.domain.repository.notification.NotificationRepository
import com.afternote.core.ui.Route
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject

@HiltViewModel
Expand All @@ -24,10 +31,19 @@ class MainViewModel
constructor(
authRepository: AuthRepository,
private val pendingInvitationStore: PendingReceiverInvitationStore,
private val notificationRepository: NotificationRepository,
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val pendingNotificationEntryState = MutableStateFlow<NotificationEntryRequest?>(null)

private val entryNoticeState = MutableStateFlow<NotificationEntry?>(null)

/**
* 앱 진입 보고가 돌려준, 사용자에게 보여 줄 것(쉬운 질문·절차 취소 안내). 보여 줄 게 없으면 null.
* 앱 셸이 보여 주고 [consumeEntryNotice] 로 비운다.
*/
internal val entryNotice: StateFlow<NotificationEntry?> = entryNoticeState.asStateFlow()

/** 아직 후속 목적지 adapter가 소비하지 않은 최신 알림 진입 이벤트. */
internal val pendingNotificationEntry: StateFlow<NotificationEntryRequest?> =
pendingNotificationEntryState.asStateFlow()
Expand Down Expand Up @@ -94,6 +110,37 @@ class MainViewModel
initialValue = null,
)

init {
reportEntryOnLogin(authRepository)
}

/**
* 로그인이 확정될 때마다(이미 로그인된 채 켜진 경우 포함) 서버에 앱 진입을 한 번 알린다 (#2321).
*
* 이 ViewModel 은 Activity 재생성을 넘어 살아남으므로 회전마다 다시 보내지 않는다. 서버는 이걸로
* 활동 시각을 갱신해 오래 비운 사용자의 보관 확인 절차를 취소하므로, 실패해도 다음 실행에 다시
* 보낼 뿐 화면을 막지 않는다.
*/
private fun reportEntryOnLogin(authRepository: AuthRepository) {
viewModelScope.launch {
authRepository.isLoggedIn.distinctUntilChanged().collect { loggedIn ->
if (!loggedIn) {
entryNoticeState.value = null
return@collect
}
notificationRepository
.reportEntry()
.onSuccess { entry ->
if (entry.easyQuestions.isNotEmpty() || entry.procedureCancelled) entryNoticeState.value = entry
}
}
}
}

internal fun consumeEntryNotice() {
entryNoticeState.value = null
}

/** 스킴 Intent 에서 뽑은 토큰을 보관한다. 같은 Intent 가 재생성으로 다시 와도 같은 값이라 무해하다. */
internal fun enqueueInvitationToken(token: String) {
viewModelScope.launch { pendingInvitationStore.save(token) }
Expand Down Expand Up @@ -130,7 +177,40 @@ class MainViewModel
pendingNotificationEntryState.value = null
}

/**
* 알림 진입이 지금 열어야 할 곳을 정한다 (#2321).
*
* 서버 알림이면 탭한 시점의 목적지를 서버에 다시 묻는다 — 대상이 지워졌거나 이미 답한 질문일 수
* 있다. 묻지 못하면(네트워크·시간 초과·오류) 알림이 싣고 온 목적지로 연다. 알림을 눌렀는데 아무
* 데도 안 가는 편이 더 나쁘다. 읽음 처리는 이동을 기다리게 하지 않는다.
*/
internal suspend fun resolveNotificationEntry(request: NotificationEntryRequest): NotificationEntryResolution {
val fallback =
NotificationEntryResolution(
navigation =
if (request.serverData.isEmpty()) {
NotificationNavigation.Tab(request.destination)
} else {
ServerNotificationDestination.resolve(request.serverData)
},
)
val notificationId = request.serverNotificationId ?: return fallback

viewModelScope.launch { notificationRepository.markRead(notificationId) }
val target =
withTimeoutOrNull(NOTIFICATION_TARGET_TIMEOUT_MILLIS) {
notificationRepository.target(notificationId).getOrNull()
} ?: return fallback

return NotificationEntryResolution(
navigation = ServerNotificationDestination.resolve(target.data),
deleted = target.deleted,
serverMessage = target.toast,
)
}

private companion object {
const val NOTIFICATION_TARGET_TIMEOUT_MILLIS = 3_000L
const val CONSUMED_NOTIFICATION_IDENTITY_KEY = "consumed_notification_entry_identity"
const val SETTLED_INVITATION_TOKEN_KEY = "settled_receiver_invitation_token"
const val INVITATION_AWAITING_LOGIN_KEY = "receiver_invitation_awaiting_login"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.afternote.afternote_fe.R
import com.afternote.afternote_fe.notification.NotificationIntentContract
import com.afternote.afternote_fe.notification.ServerNotificationDestination
import com.afternote.core.common.notification.NotificationDestination
import com.afternote.core.common.notification.NotificationPendingIntentFactory
import com.google.firebase.messaging.FirebaseMessagingService
Expand Down Expand Up @@ -53,6 +55,11 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() {
Log.d(TAG, "FCM installation unregistered")
}

/**
* 서버는 Android 로 notification 블록 없이 data-only 로 보낸다 (BE `NOTIFICATION_CONTRACT.md`).
* 그래서 백그라운드·종료 상태에서도 이 콜백이 불리고 앱이 알림을 직접 그린다 — 그래야 탭이
* [NotificationPendingIntentFactory] 를 거쳐 목적지로 이어진다.
*/
override fun onMessageReceived(message: RemoteMessage) {
val content =
FcmNotificationContentResolver.resolve(
Expand All @@ -62,7 +69,11 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() {
fallbackTitle = getString(R.string.fcm_notification_fallback_title),
) ?: return

val occurrenceId = FcmNotificationIdentity.occurrenceId(message.messageId)
val occurrenceId =
FcmNotificationIdentity.occurrenceId(
serverNotificationId = content.serverNotificationId,
messageId = message.messageId,
)

showNotification(
content = content,
Expand Down Expand Up @@ -95,16 +106,14 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() {
setContentText(body)
setStyle(NotificationCompat.BigTextStyle().bigText(body))
}
// 목적지 data 키 계약(Afternote/Afternote-BE#261)이 서기 전까지 FCM 은 홈을
// 명시한다. 키를 추측해 두면 BE 가 다른 이름을 고르는 순간 조용히 죽는 분기가
// 남는다 — 계약이 확정되면 여기서 data 를 읽어 NotificationDestination 으로
// 옮긴다.
NotificationPendingIntentFactory
.create(
context = this@AfternoteFirebaseMessagingService,
source = NOTIFICATION_SOURCE,
occurrenceId = occurrenceId,
destination = NotificationDestination.HOME,
destination = content.destination,
serverNotificationId = content.serverNotificationId,
serverData = content.serverData,
)?.let(::setContentIntent)
}.build()

Expand All @@ -123,18 +132,37 @@ class AfternoteFirebaseMessagingService : FirebaseMessagingService() {
private data class FcmNotificationContent(
val title: String,
val body: String?,
val destination: NotificationDestination,
val serverNotificationId: Long?,
val serverData: Map<String, String>,
)

private object FcmNotificationIdentity {
fun occurrenceId(messageId: String?): String =
messageId
?.takeIf(String::isNotBlank)
/**
* 서버 알림 ID 가 있으면 그것이 발생 식별자다 — FCM 이 같은 알림을 두 번 넘겨도 트레이에 한 장만
* 남고, 탭 소비 판정도 서버 알림 하나에 한 번이 된다. 없으면 FCM message id, 그것도 없으면 새 UUID.
*/
fun occurrenceId(
serverNotificationId: Long?,
messageId: String?,
): String =
serverNotificationId?.let { "notification:$it" }
?: messageId?.takeIf(String::isNotBlank)
?: UUID.randomUUID().toString()

/** NotificationManager의 `(tag, id)` identity를 프로세스 재시작 뒤에도 occurrence별로 유지한다. */
fun notificationTag(occurrenceId: String): String = "fcm:$occurrenceId"
}

/**
* FCM data v1 계약(BE `PushPayload`)을 읽는다. 모든 값은 문자열이다.
*
* 제목·본문은 notification 블록이 있으면 그쪽이 우선이다 — 서버는 이제 data 로만 보내지만, 콘솔에서 보낸
* 시험 메시지처럼 notification 블록을 단 메시지도 그대로 보여 준다.
*
* 목적지는 `schemaVersion` 이 이 앱이 아는 값일 때만 따른다. 모르는 판이면 키 뜻이 바뀌었을 수 있어
* 홈으로 연다. 알림 자체는 보여 준다 — 사용자에게 안 보이는 쪽이 더 나쁘다.
*/
private object FcmNotificationContentResolver {
fun resolve(
notificationTitle: String?,
Expand All @@ -146,14 +174,29 @@ private object FcmNotificationContentResolver {
val body = notificationBody.nonBlankOrNull() ?: data[KEY_BODY].nonBlankOrNull()
if (title == null && body == null) return null

val schemaVersion = data[KEY_SCHEMA_VERSION].nonBlankOrNull()
val knownSchema = schemaVersion == null || schemaVersion == SUPPORTED_SCHEMA_VERSION
val serverData =
if (knownSchema) data.filterKeys(NotificationIntentContract.SERVER_DATA_KEYS::contains) else emptyMap()

return FcmNotificationContent(
title = title ?: fallbackTitle,
body = body,
destination = ServerNotificationDestination.resolve(serverData).tab,
serverData = serverData,
serverNotificationId =
data[KEY_NOTIFICATION_ID]
.nonBlankOrNull()
?.toLongOrNull()
?.takeIf { it > 0L },
)
}

private fun String?.nonBlankOrNull(): String? = this?.trim()?.takeIf(String::isNotEmpty)

private const val KEY_TITLE = "title"
private const val KEY_BODY = "body"
private const val KEY_SCHEMA_VERSION = "schemaVersion"
private const val KEY_NOTIFICATION_ID = "notificationId"
private const val SUPPORTED_SCHEMA_VERSION = "1"
}
Loading
Loading