This commit is contained in:
Халимов Рустам
2026-04-15 02:40:52 +03:00
parent 9560a9235f
commit 8409c51842
16 changed files with 207 additions and 34 deletions
@@ -0,0 +1,54 @@
package chats.data.remote.signalr
import android.content.Context
import core.notifications.data.ActiveChatTracker
import core.notifications.data.NotificationHelper
import core.security.TokenManager
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SignalRNotificationObserver @Inject constructor(
private val signalrClient: ChatHubClient,
private val activeChatTracker: ActiveChatTracker,
private val tokenManager: TokenManager,
@ApplicationContext private val context: Context
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var isStarted = false
fun start() {
if (isStarted) return
isStarted = true
signalrClient.events
.filterIsInstance<ChatEvent.NewMessage>()
.onEach { event ->
val currentUserId = tokenManager.getUserId()
val message = event.message
// Don't show if it's our message
if (message.senderId == currentUserId) return@onEach
// Don't show if this chat is currently open
if (activeChatTracker.currentChatId.value == message.chatId) return@onEach
NotificationHelper.showNotification(
context = context,
title = message.sender?.displayName ?: "Новое сообщение",
body = message.content ?: "Вам прислали вложение",
type = "chat",
chatId = message.chatId,
notificationId = message.id.hashCode()
)
}
.launchIn(scope)
}
}