Migrates to Encrypted Push Notifications

This commit is contained in:
Vitor Pamplona
2023-09-08 16:16:26 -04:00
parent 939eb1bd8d
commit b4f1c4d13e
5 changed files with 147 additions and 98 deletions
@@ -1,6 +1,7 @@
package com.vitorpamplona.amethyst.service.notifications
import android.app.NotificationManager
import android.util.LruCache
import androidx.core.content.ContextCompat
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
@@ -8,6 +9,7 @@ import com.vitorpamplona.amethyst.LocalPreferences
import com.vitorpamplona.amethyst.service.notifications.NotificationUtils.getOrCreateDMChannel
import com.vitorpamplona.amethyst.service.notifications.NotificationUtils.getOrCreateZapChannel
import com.vitorpamplona.quartz.events.Event
import com.vitorpamplona.quartz.events.GiftWrapEvent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -15,19 +17,34 @@ import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
class PushNotificationReceiverService : FirebaseMessagingService() {
val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val eventCache = LruCache<String, String>(100)
// this is called when a message is received
override fun onMessageReceived(remoteMessage: RemoteMessage) {
scope.launch(Dispatchers.IO) {
remoteMessage.data.let {
val eventStr = remoteMessage.data["event"] ?: return@let
val event = Event.fromJson(eventStr)
EventNotificationConsumer(applicationContext).consume(event)
parseMessage(remoteMessage.data)?.let {
receiveIfNew(it)
}
}
}
private suspend fun parseMessage(params: Map<String, String>): GiftWrapEvent? {
params["encryptedEvent"]?.let { eventStr ->
(Event.fromJson(eventStr) as? GiftWrapEvent)?.let {
return it
}
}
return null
}
private suspend fun receiveIfNew(event: GiftWrapEvent) {
if (eventCache.get(event.id) == null) {
eventCache.put(event.id, event.id)
EventNotificationConsumer(applicationContext).consume(event)
}
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()