From 467d14c1c5faa25161a127e60fed0f2ef3710d33 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 12:28:23 +0200 Subject: [PATCH] feat: new lines become notifications while the app runs (notifications, Phase 6) One dispatcher in common code reads lines above the identity's cursor, decides, groups per room and category and posts through a platform notifier: Android channels and MessagingStyle, UNUserNotificationCenter on iOS (not compiled here), and a desktop sink the tray fills in Phase 12. A tapped notification opens its room. Co-Authored-By: Claude Opus 5.5 --- .../src/androidMain/AndroidManifest.xml | 5 + .../kotlin/mobi/giza/android/MainActivity.kt | 17 ++ .../notifications/PlatformNotifier.android.kt | 165 +++++++++++++ .../composeResources/values/strings.xml | 11 + .../kotlin/mobi/giza/compose/GizaRuntime.kt | 41 ++++ .../notifications/NotificationContent.kt | 4 +- .../notifications/NotificationDispatcher.kt | 159 +++++++++++++ .../notifications/NotificationResources.kt | 40 ++++ .../compose/notifications/PlatformNotifier.kt | 80 +++++++ .../ui/composable/navigation/GizaNavHost.kt | 15 ++ .../notifications/PlatformNotifier.ios.kt | 99 ++++++++ .../notifications/PlatformNotifier.jvm.kt | 36 +++ .../NotificationDispatcherJvmTest.kt | 224 ++++++++++++++++++ 13 files changed, 895 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt create mode 100644 composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt create mode 100644 composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml index 30757806..e5195320 100644 --- a/composeApp/src/androidMain/AndroidManifest.xml +++ b/composeApp/src/androidMain/AndroidManifest.xml @@ -4,6 +4,10 @@ + + + @@ -18,6 +22,7 @@ android:theme="@android:style/Theme.Material.Light.NoActionBar"> diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt index 96ff9ca0..f0dd2823 100644 --- a/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt +++ b/composeApp/src/androidMain/kotlin/mobi/giza/android/MainActivity.kt @@ -1,11 +1,13 @@ package mobi.giza.android +import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.navigation.compose.rememberNavController import mobi.giza.compose.GizaApp +import mobi.giza.compose.notifications.NotificationTaps class MainActivity : ComponentActivity() { @@ -17,6 +19,8 @@ class MainActivity : ComponentActivity() { // process used to build a second set of repositories and a second PhoenixGlobal here. val runtime = (application as GizaApplication).runtime + tapped(intent) + setContent { val navController = rememberNavController() @@ -26,4 +30,17 @@ class MainActivity : ComponentActivity() { ) } } + + /** A notification tapped while this activity was already up (it is `singleTop`). */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + tapped(intent) + } + + /** Hands a tapped notification's room to the navigation host. Phase 6. */ + private fun tapped(intent: Intent?) { + val userPublicKey = intent?.getStringExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY) ?: return + val chatRoomId = intent.getStringExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID) ?: return + NotificationTaps.opened(userPublicKey, chatRoomId) + } } diff --git a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt new file mode 100644 index 00000000..38c60403 --- /dev/null +++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt @@ -0,0 +1,165 @@ +package mobi.giza.compose.notifications + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.app.Person +import androidx.core.content.ContextCompat +import mobi.giza.android.MainActivity +import mobi.giza.android.R +import mobi.giza.compose.PlatformContext + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = + AndroidNotifier(platformContext.applicationContext) + +/** + * Android's half of Phase 6: a channel per category, a `MessagingStyle` per room and category, + * tagged with the notification's key so a newer post replaces the older one, and a lock-screen + * version that names neither the room nor what was said (D9). + */ +class AndroidNotifier(private val context: Context) : PlatformNotifier { + + private val manager = NotificationManagerCompat.from(context) + + @Volatile + private var names: NotificationChannelNames? = null + + override suspend fun prepare(names: NotificationChannelNames) { + this.names = names + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val system = context.getSystemService(NotificationManager::class.java) ?: return + system.createNotificationChannels( + listOf( + NotificationChannel(CHANNEL_MESSAGES, names.messages, NotificationManager.IMPORTANCE_HIGH) + .apply { description = names.messagesDescription }, + NotificationChannel(CHANNEL_NEEDS_YOU, names.needsYou, NotificationManager.IMPORTANCE_HIGH) + .apply { description = names.needsYouDescription }, + NotificationChannel(CHANNEL_GROUP_ACTIVITY, names.groupActivity, NotificationManager.IMPORTANCE_DEFAULT) + .apply { description = names.groupActivityDescription }, + ) + ) + } + + override fun canPost(): Boolean { + if (!manager.areNotificationsEnabled()) return false + return Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + } + + override fun post(notification: RoomNotification) { + if (!canPost()) return + val names = names ?: return + + val me = Person.Builder().setName(names.you).setKey(notification.userPublicKey).build() + val style = NotificationCompat.MessagingStyle(me) + .setConversationTitle(notification.title) + .setGroupConversation(true) + notification.lines.forEach { line -> + val sender = line.senderName?.let { Person.Builder().setName(it).setKey(line.senderPublicKey).build() } + style.addMessage(line.text, line.at.toEpochMilliseconds(), sender) + } + + val locked = NotificationCompat.Builder(context, channelOf(notification.category)) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(names.newMessage) + .build() + + val built = NotificationCompat.Builder(context, channelOf(notification.category)) + .setSmallIcon(R.drawable.ic_launcher_monochrome) + .setStyle(style) + .setContentTitle(notification.title) + .setContentText(notification.lines.lastOrNull()?.text) + .setNumber(notification.total) + .setWhen(notification.lines.lastOrNull()?.at?.toEpochMilliseconds() ?: System.currentTimeMillis()) + .setShowWhen(true) + .setCategory( + if (notification.category == NotificationCategory.Messages) NotificationCompat.CATEGORY_MESSAGE + else NotificationCompat.CATEGORY_REMINDER + ) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(locked) + .setOnlyAlertOnce(false) + .setAutoCancel(true) + .setContentIntent(openRoom(notification)) + .build() + + try { + manager.notify(notification.key, NOTIFICATION_ID, built) + } catch (denied: SecurityException) { + // The permission was taken away between canPost and here. Nothing to do but not crash. + } + } + + override fun cancel(key: String) { + manager.cancel(key, NOTIFICATION_ID) + } + + private fun openRoom(notification: RoomNotification): PendingIntent { + val intent = Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) + .putExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY, notification.userPublicKey) + .putExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID, notification.chatRoomId) + return PendingIntent.getActivity( + context, + notification.key.hashCode(), + intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + } + + private fun channelOf(category: NotificationCategory) = when (category) { + NotificationCategory.Messages -> CHANNEL_MESSAGES + NotificationCategory.NeedsYou -> CHANNEL_NEEDS_YOU + NotificationCategory.GroupActivity -> CHANNEL_GROUP_ACTIVITY + } + + companion object { + const val CHANNEL_MESSAGES = "messages" + const val CHANNEL_NEEDS_YOU = "needs_you" + const val CHANNEL_GROUP_ACTIVITY = "group_activity" + + /** One id for all: the key is the tag, and a tag and id together name a notification. */ + private const val NOTIFICATION_ID = 1 + } +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission { + val context = LocalContext.current + fun granted(): Boolean = AndroidNotifier(context.applicationContext).canPost() + + var isGranted by remember { mutableStateOf(granted()) } + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { result -> + isGranted = result && granted() + } + + return remember(isGranted, launcher) { + object : NotificationPermission { + override val granted: Boolean = isGranted + + override fun request() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + launcher.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + isGranted = granted() + } + } + } + } +} diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 09abbd31..4be696a1 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -797,4 +797,15 @@ Unread: %1$d Conversations with unread messages: %1$d + New message + Note to self + Someone + You + %1$d more + Messages + What people say to you, in direct messages and groups + Needs you + A key ceremony or a signing session waiting for your approval + Group activity + Members joining and leaving, and ceremonies finishing diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt index d72da358..4ddfc99a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/GizaRuntime.kt @@ -9,7 +9,16 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import mobi.giza.compose.notifications.NotificationDispatcher +import mobi.giza.compose.notifications.NotificationResources +import mobi.giza.compose.notifications.PlatformNotifier +import mobi.giza.compose.notifications.VisibleConversation +import mobi.giza.compose.notifications.platformNotifier import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseConfederationRepository import mobi.giza.compose.database.repository.DatabaseDkgRepository @@ -118,6 +127,38 @@ class GizaRuntime( ) } + /** Where notifications are shown, on this platform. */ + val notifier: PlatformNotifier by lazy { platformNotifier(gizaGlobal.platformContext) } + + /** New lines into notifications, for the identity running. docs/notifications-and-background-sync.md. */ + val notificationDispatcher: NotificationDispatcher by lazy { + NotificationDispatcher( + database = auxDatabaseManager.auxDatabase, + notifier = notifier, + strings = { NotificationResources.strings() }, + appVisible = AppLifecycle.isForeground, + visibleChatRoomId = VisibleConversation.chatRoomId, + syncPending = { publicKey -> + nostrRepository.observePendingNegentropySynchronizeRequests(publicKey).map { it != null } + }, + ) + } + + /** + * The dispatcher, running for whichever identity is active and holds a key -- a public-key + * identity can open nothing, so has nothing to be told about (D6). Started on first read. + */ + val notifications: Job by lazy { + ioScope.launch { + runCatching { notifier.prepare(NotificationResources.channelNames()) } + .onFailure { logger.e("Could not prepare notification channels", it) } + activeIdentity.collectLatest { identity -> + if (identity?.nostrPrivateKey == null) return@collectLatest + notificationDispatcher.run(identity.nostrPublicKey) + } + } + } + companion object { private const val TAG = "GizaRuntime" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt index bcd33ec6..008ed058 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationContent.kt @@ -86,6 +86,8 @@ object NotificationContent { showMessageText: Boolean, profileName: String?, strings: NotificationStrings, + /** Names for senders the room's participant rows do not carry -- a NIP-17 peer's, say. */ + knownNames: Map = emptyMap(), ): RoomNotification { val ordered = lines.sortedBy { it.id } return RoomNotification( @@ -97,7 +99,7 @@ object NotificationContent { NotificationLine( messageId = line.id, senderPublicKey = line.senderPublicKey, - senderName = senderName(room, line.senderPublicKey) ?: strings.unknownSender.takeIf { category == NotificationCategory.Messages }, + senderName = senderName(room, line.senderPublicKey) ?: knownNames[line.senderPublicKey] ?: strings.unknownSender.takeIf { category == NotificationCategory.Messages }, text = if (category == NotificationCategory.Messages && !showMessageText) strings.newMessage else line.content, at = line.createdAt, ) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt new file mode 100644 index 00000000..c984ae24 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationDispatcher.kt @@ -0,0 +1,159 @@ +package mobi.giza.compose.notifications + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.Instant +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.transformLatest +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.database.GizaDatabase + +/** + * Turns new chat lines into notifications, from the table and never from the wire. + * docs/notifications-and-background-sync.md, D1-D3 and Phase 6. + * + * Whatever wrote the line -- the live subscription, a catch-up, the background pass, a ceremony + * step -- this reads it the same way: rows above the identity's cursor, through the policy, grouped + * per room and category, posted, and only then the cursor moved past them. A process killed between + * the post and the move re-posts the same room's notification on the next run, which replaces it, + * so nothing doubles. + * + * @param syncPending whether the identity still has catch-up queued; arming waits for it to stay + * false for [settleFor], so a first sync's history is never news (D3). + */ +class NotificationDispatcher( + private val database: GizaDatabase, + private val notifier: PlatformNotifier, + private val strings: suspend () -> NotificationStrings, + private val appVisible: StateFlow, + private val visibleChatRoomId: StateFlow, + private val syncPending: suspend (HexKey) -> Flow, + private val clock: () -> Instant = { Clock.System.now() }, + private val settleFor: Duration = 30.seconds, +) { + private val logger = Logger.withTag(TAG) + private val dao get() = database.notificationDao() + + /** What is showing, by key, so a new line is merged into its room's notification. */ + private val showing = mutableMapOf() + private val showingMutex = Mutex() + + /** Runs until cancelled: arms the identity once its first sync has settled, then dispatches. */ + suspend fun run(userPublicKey: HexKey): Unit = coroutineScope { + awaitArmed(userPublicKey) + launch { cancelWhatWasRead(userPublicKey) } + while (true) { + val cursor = dao.getLedger(userPublicKey)?.cursorMessageId ?: return@coroutineScope + dao.observeAfter(userPublicKey, cursor).first { it.isNotEmpty() } + dispatchPending(userPublicKey) + } + } + + /** Arms [userPublicKey] once its catch-up queue has stayed empty for [settleFor]. D3. */ + @OptIn(ExperimentalCoroutinesApi::class) + suspend fun awaitArmed(userPublicKey: HexKey) { + if (dao.getLedger(userPublicKey) != null) return + syncPending(userPublicKey) + .distinctUntilChanged() + .transformLatest { pending -> + if (!pending) { + delay(settleFor) + emit(Unit) + } + } + .first() + if (dao.arm(userPublicKey, clock())) logger.i { "Armed notifications for $userPublicKey" } + } + + /** + * Decides about every line above the cursor, posts what passes, moves the cursor past all of + * them, and returns what was posted. Does nothing for an identity that is not armed. + */ + suspend fun dispatchPending(userPublicKey: HexKey): List { + val posted = mutableListOf() + while (true) { + val ledger = dao.getLedger(userPublicKey) ?: return posted + val batch = dao.getAfter(userPublicKey, ledger.cursorMessageId) + if (batch.isEmpty()) return posted + + val rooms = batch.map { it.chatRoomId }.distinct() + .associateWith { database.chatRoomDao().findChatRoomById(it) } + val now = clock() + val text = strings() + + val passing = batch.mapNotNull { line -> + val room = rooms[line.chatRoomId] + when (val decision = NotificationPolicy.decide( + line = line, + room = room?.chatRoom, + settings = ledger.settings, + visibleChatRoomId = visibleChatRoomId.value, + appVisible = appVisible.value, + now = now, + )) { + is NotificationDecision.Post -> Triple(line, room!!, decision.category) + is NotificationDecision.Drop -> { + logger.d { "Line ${line.id} not posted: ${decision.reason}" } + null + } + } + } + + passing.groupBy { (line, _, category) -> line.chatRoomId to category } + .forEach { (_, group) -> + val (_, room, category) = group.first() + val unnamed = group.map { it.first.senderPublicKey }.distinct() + .filter { NotificationContent.senderName(room, it) == null } + val knownNames = if (unnamed.isEmpty()) emptyMap() else + database.profileDao().getProfileByPublicKeys(unnamed) + .associate { it.publicKey to it.humanReadableNameOrPubkey() } + val arrived = NotificationContent.build( + room = room, + category = category, + lines = group.map { it.first }, + showMessageText = ledger.settings.showMessageText, + profileName = null, + strings = text, + knownNames = knownNames, + ) + val merged = showingMutex.withLock { + NotificationContent.merge(showing[arrived.key], arrived).also { showing[it.key] = it } + } + notifier.post(merged) + posted += merged + } + + dao.advanceCursor(userPublicKey, batch.maxOf { it.id }) + } + } + + /** Takes a room's notifications away once the room has been read past them. D8. */ + private suspend fun cancelWhatWasRead(userPublicKey: HexKey) { + database.chatRoomDao().observeChatRoomListByUserPublicKey(userPublicKey).collect { rooms -> + val byId = rooms.associateBy { it.chatRoom.id } + val read = showingMutex.withLock { + showing.values.filter { notification -> + val room = byId[notification.chatRoomId]?.chatRoom + val newest = notification.lines.maxOfOrNull { it.messageId } ?: 0 + room == null || (room.lastReadMessageId ?: 0) >= newest + }.onEach { showing.remove(it.key) } + } + read.forEach { notifier.cancel(it.key) } + } + } + + companion object { + private const val TAG = "NotificationDispatcher" + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt new file mode 100644 index 00000000..e037a714 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt @@ -0,0 +1,40 @@ +package mobi.giza.compose.notifications + +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.notification_channel_group_activity +import mobi.giza.compose.resources.notification_channel_group_activity_description +import mobi.giza.compose.resources.notification_channel_messages +import mobi.giza.compose.resources.notification_channel_messages_description +import mobi.giza.compose.resources.notification_channel_needs_you +import mobi.giza.compose.resources.notification_channel_needs_you_description +import mobi.giza.compose.resources.notification_more +import mobi.giza.compose.resources.notification_new_message +import mobi.giza.compose.resources.notification_note_to_self +import mobi.giza.compose.resources.notification_someone +import mobi.giza.compose.resources.notification_you +import org.jetbrains.compose.resources.getString + +/** The catalogue's words for notifications, read outside any composition. */ +object NotificationResources { + + suspend fun strings(): NotificationStrings { + val more = getString(Res.string.notification_more) + return NotificationStrings( + newMessage = getString(Res.string.notification_new_message), + noteToSelf = getString(Res.string.notification_note_to_self), + unknownSender = getString(Res.string.notification_someone), + moreMessages = { count -> more.replace("%1\$d", count.toString()) }, + ) + } + + suspend fun channelNames(): NotificationChannelNames = NotificationChannelNames( + messages = getString(Res.string.notification_channel_messages), + messagesDescription = getString(Res.string.notification_channel_messages_description), + needsYou = getString(Res.string.notification_channel_needs_you), + needsYouDescription = getString(Res.string.notification_channel_needs_you_description), + groupActivity = getString(Res.string.notification_channel_group_activity), + groupActivityDescription = getString(Res.string.notification_channel_group_activity_description), + you = getString(Res.string.notification_you), + newMessage = getString(Res.string.notification_new_message), + ) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt new file mode 100644 index 00000000..fdb5e361 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt @@ -0,0 +1,80 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import mobi.giza.compose.PlatformContext + +/** The names a platform shows for each category, where it shows them (Android's channels). */ +data class NotificationChannelNames( + val messages: String, + val messagesDescription: String, + val needsYou: String, + val needsYouDescription: String, + val groupActivity: String, + val groupActivityDescription: String, + /** How the user is named in a conversation's own lines. */ + val you: String, + /** What a locked screen shows in place of a message. */ + val newMessage: String, +) + +/** + * Where a [RoomNotification] goes to be shown. One per platform; the dispatcher decides what to + * post and this only knows how. docs/notifications-and-background-sync.md, Phase 6. + */ +interface PlatformNotifier { + /** Creates whatever the platform needs before a first post -- Android's channels. Idempotent. */ + suspend fun prepare(names: NotificationChannelNames) {} + + /** Shows [notification], replacing any already showing under the same key. */ + fun post(notification: RoomNotification) + + /** Takes away the notification under [key], if one is showing. */ + fun cancel(key: String) + + /** Whether the platform will show what is posted at all. */ + fun canPost(): Boolean +} + +/** The notifier for this platform. */ +expect fun platformNotifier(platformContext: PlatformContext): PlatformNotifier + +/** Asking the platform for permission to notify, from a screen. */ +interface NotificationPermission { + val granted: Boolean + + /** Asks, where the platform asks; does nothing where it does not. */ + fun request() +} + +@Composable +expect fun rememberNotificationPermission(): NotificationPermission + +/** A notification somebody tapped: the room to open, for the identity it was posted for. */ +data class NotificationTap(val userPublicKey: String, val chatRoomId: String) + +/** + * Taps waiting to be turned into navigation. A platform puts one here -- from an intent, from a + * notification centre delegate -- and the navigation host takes it once the identity it is for is + * the one running. A singleton, because a tap can arrive before there is a host to hand it to. + */ +object NotificationTaps { + private val _pending = MutableStateFlow(null) + + val pending: StateFlow = _pending.asStateFlow() + + fun opened(userPublicKey: String, chatRoomId: String) { + _pending.value = NotificationTap(userPublicKey, chatRoomId) + } + + fun consumed(tap: NotificationTap) { + _pending.update { if (it == tap) null else it } + } + + /** The extras a platform carries a tap in. */ + const val EXTRA_USER_PUBLIC_KEY = "mobi.giza.notification.userPublicKey" + const val EXTRA_CHAT_ROOM_ID = "mobi.giza.notification.chatRoomId" +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt index 39cc3e56..ec310335 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/GizaNavHost.kt @@ -60,6 +60,7 @@ import mobi.giza.compose.database.repository.DatabaseMarmotRepository import mobi.giza.compose.database.repository.DatabaseNostrRepository import mobi.giza.compose.database.repository.DatabaseSearchRepository import mobi.giza.compose.GizaRuntime +import mobi.giza.compose.notifications.NotificationTaps import mobi.giza.compose.ui.composable.ActiveProfileScreen import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen import mobi.giza.compose.ui.composable.ChatRoomCreationScreen @@ -214,6 +215,7 @@ fun GizaNavHost( // One of each per process, started on first read and never cleared. val notaryViewModel: NotaryViewModel = runtime.notary val synchronizationViewModel: SynchronizationViewModel = runtime.synchronization + remember(runtime) { runtime.notifications } // TODO: Produce a synchronization UI element... @@ -399,6 +401,19 @@ fun GizaNavHost( ?: flowOf(0) }.collectAsState(0) + // A tapped notification's room, opened once the identity it is for is the one running. + // One for another profile waits for that profile. docs/notifications-and-background-sync.md, Phase 6. + LaunchedEffect(activeUserPublicKey) { + val publicKey = activeUserPublicKey ?: return@LaunchedEffect + NotificationTaps.pending.collect { tap -> + if (tap == null || tap.userPublicKey != publicKey) return@collect + NotificationTaps.consumed(tap) + navController.navigate( + ChatRoomMessagingRoute(activeUserPublicKey = publicKey, chatRoomId = tap.chatRoomId, relayHint = null) + ) + } + } + ProvideSigningCapability(sovereignWalletViewModel.activeIdentity) { GizaNavigationSuite( navController = navController, diff --git a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt new file mode 100644 index 00000000..50710e88 --- /dev/null +++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt @@ -0,0 +1,99 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import mobi.giza.compose.PlatformContext +import platform.UserNotifications.UNAuthorizationOptionAlert +import platform.UserNotifications.UNAuthorizationOptionBadge +import platform.UserNotifications.UNAuthorizationOptionSound +import platform.UserNotifications.UNAuthorizationStatusAuthorized +import platform.UserNotifications.UNAuthorizationStatusProvisional +import platform.UserNotifications.UNMutableNotificationContent +import platform.UserNotifications.UNNotificationRequest +import platform.UserNotifications.UNNotificationSound +import platform.UserNotifications.UNUserNotificationCenter +import kotlin.concurrent.Volatile + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = IosNotifier() + +/** + * iOS's half of Phase 6: one delivered notification per room and category, its identifier the key + * so a newer one replaces it, threaded by room. Lock-screen previews are the system's own setting + * and need nothing here (D9). Not compiled on the linux host this was written on; see the + * document's record. + */ +class IosNotifier : PlatformNotifier { + private val center = UNUserNotificationCenter.currentNotificationCenter() + + @Volatile + private var authorised = false + + override suspend fun prepare(names: NotificationChannelNames) { + center.getNotificationSettingsWithCompletionHandler { settings -> + authorised = settings?.authorizationStatus == UNAuthorizationStatusAuthorized || + settings?.authorizationStatus == UNAuthorizationStatusProvisional + } + } + + override fun canPost(): Boolean = authorised + + override fun post(notification: RoomNotification) { + val newest = notification.lines.lastOrNull() ?: return + val content = UNMutableNotificationContent().apply { + setTitle(notification.title) + setBody(listOfNotNull(newest.senderName, newest.text).joinToString(": ")) + setThreadIdentifier(notification.chatRoomId) + setSound(UNNotificationSound.defaultSound()) + setUserInfo( + mapOf( + NotificationTaps.EXTRA_USER_PUBLIC_KEY to notification.userPublicKey, + NotificationTaps.EXTRA_CHAT_ROOM_ID to notification.chatRoomId, + ) + ) + } + val request = UNNotificationRequest.requestWithIdentifier(notification.key, content, null) + center.addNotificationRequest(request, withCompletionHandler = null) + } + + override fun cancel(key: String) { + center.removeDeliveredNotificationsWithIdentifiers(listOf(key)) + } +} + +/** + * Called by the app delegate's `userNotificationCenter(_:didReceive:)` with the tapped + * notification's user info. docs/notifications-and-background-sync.md, Phase 11. + */ +fun notificationTapped(userInfo: Map) { + val userPublicKey = userInfo[NotificationTaps.EXTRA_USER_PUBLIC_KEY] as? String ?: return + val chatRoomId = userInfo[NotificationTaps.EXTRA_CHAT_ROOM_ID] as? String ?: return + NotificationTaps.opened(userPublicKey, chatRoomId) +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission { + var isGranted by remember { mutableStateOf(false) } + val center = remember { UNUserNotificationCenter.currentNotificationCenter() } + + remember { + center.getNotificationSettingsWithCompletionHandler { settings -> + isGranted = settings?.authorizationStatus == UNAuthorizationStatusAuthorized || + settings?.authorizationStatus == UNAuthorizationStatusProvisional + } + } + + return remember(isGranted) { + object : NotificationPermission { + override val granted: Boolean = isGranted + + override fun request() { + center.requestAuthorizationWithOptions( + UNAuthorizationOptionAlert or UNAuthorizationOptionSound or UNAuthorizationOptionBadge, + ) { granted, _ -> isGranted = granted } + } + } + } +} diff --git a/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt new file mode 100644 index 00000000..47933b98 --- /dev/null +++ b/composeApp/src/jvmMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.jvm.kt @@ -0,0 +1,36 @@ +package mobi.giza.compose.notifications + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import kotlin.concurrent.Volatile +import mobi.giza.compose.PlatformContext + +actual fun platformNotifier(platformContext: PlatformContext): PlatformNotifier = DesktopNotifier + +/** + * The desktop's notifier. A desktop notification needs a tray icon to come from, and the tray is + * built by `main()` (Phase 12), which hands this its [sink]. Until it does, nothing is shown. + */ +object DesktopNotifier : PlatformNotifier { + /** Shows a title and a body. Set by the tray; null while there is none. */ + @Volatile + var sink: ((title: String, body: String) -> Unit)? = null + + override fun canPost(): Boolean = sink != null + + override fun post(notification: RoomNotification) { + val newest = notification.lines.lastOrNull() ?: return + sink?.invoke(notification.title, listOfNotNull(newest.senderName, newest.text).joinToString(": ")) + } + + /** A tray notification cannot be taken back once shown. */ + override fun cancel(key: String) = Unit +} + +@Composable +actual fun rememberNotificationPermission(): NotificationPermission = remember { + object : NotificationPermission { + override val granted: Boolean = true + override fun request() = Unit + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt new file mode 100644 index 00000000..daec9d6f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/notifications/NotificationDispatcherJvmTest.kt @@ -0,0 +1,224 @@ +package mobi.giza.compose.notifications + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import java.util.Collections +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.milliseconds +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.managers.MarmotClientStandIn +import mobi.giza.compose.managers.MarmotStandIn + +/** Rows in, notifications out. docs/notifications-and-background-sync.md, Phase 6. */ +class NotificationDispatcherJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private class FakeNotifier : PlatformNotifier { + val posted: MutableList = Collections.synchronizedList(mutableListOf()) + val cancelled: MutableList = Collections.synchronizedList(mutableListOf()) + override fun post(notification: RoomNotification) { posted += notification } + override fun cancel(key: String) { cancelled += key } + override fun canPost() = true + } + + private val notifier = FakeNotifier() + private val pending = MutableStateFlow(false) + private val appVisible = MutableStateFlow(false) + private val visibleRoom = MutableStateFlow(null) + + private val strings = NotificationStrings("New message", "Note to self", "Someone", { "$it more" }) + + private val dispatcher = NotificationDispatcher( + database = db, + notifier = notifier, + strings = { strings }, + appVisible = appVisible, + visibleChatRoomId = visibleRoom, + syncPending = { pending }, + settleFor = 100.milliseconds, + ) + + private val user = "a".repeat(64) + private val peer = "b".repeat(64) + private val roomOne = "11".repeat(32) + private val roomTwo = "22".repeat(32) + + private suspend fun seed() { + listOf(user to "me", peer to "alice").forEach { (publicKey, name) -> + val eventId = publicKey.take(32).padEnd(64, 'c') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId)) + } + db.chatRoomDao().upsert(ChatRoom(id = roomOne, userPublicKey = user, subject = "Book club", description = null, mlsGroupState = null)) + db.chatRoomDao().upsert(ChatRoom(id = roomTwo, userPublicKey = user, subject = "Garden", description = null, mlsGroupState = null)) + } + + private suspend fun line( + room: String = roomOne, + text: String = "hello", + type: String = ChatMessage.TYPE_MESSAGE, + mine: Boolean = false, + ): Long = db.chatMessageDao().upsert( + ChatMessage( + senderPublicKey = if (mine) user else peer, + isUserMessage = mine, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + chatRoomId = room, + content = text, + messageType = type, + createdAt = Clock.System.now(), + ) + ) + + private suspend fun armNow() = dispatcher.awaitArmed(user) + + @Test + fun `nothing is posted for an identity that is not armed`() = runBlocking { + seed() + line() + assertTrue(dispatcher.dispatchPending(user).isEmpty()) + assertTrue(notifier.posted.isEmpty()) + } + + /** D3: arming waits for the catch-up to drain and stay drained, and history is never news. */ + @Test + fun `arming waits for the first sync to settle, and what it brought is not posted`() = runBlocking { + seed() + pending.value = true + val arming = launch(Dispatchers.Default) { armNow() } + + line(text = "history") + delay(300) + assertNull(db.notificationDao().getLedger(user), "armed while the first sync was still running") + + pending.value = false + withTimeout(5_000) { arming.join() } + assertNotNull(db.notificationDao().getLedger(user)) + + assertTrue(dispatcher.dispatchPending(user).isEmpty(), "the first sync's history was posted") + assertEquals(0, db.notificationDao().unreadCount(roomOne), "the first sync's history was left unread") + + line(text = "news") + val posted = dispatcher.dispatchPending(user).single() + assertEquals("Book club", posted.title) + assertEquals(listOf("news"), posted.lines.map { it.text }) + assertEquals("alice", posted.lines.single().senderName) + } + + @Test + fun `lines are grouped per room, merged into what is showing, and posted once`() = runBlocking { + seed() + armNow() + line(roomOne, "one") + line(roomOne, "two") + line(roomTwo, "elsewhere") + + val posted = dispatcher.dispatchPending(user) + assertEquals(setOf("Book club", "Garden"), posted.map { it.title }.toSet()) + assertEquals(2, posted.single { it.chatRoomId == roomOne }.total) + + assertTrue(dispatcher.dispatchPending(user).isEmpty(), "a line was posted twice") + + line(roomOne, "three") + val merged = dispatcher.dispatchPending(user).single() + assertEquals(3, merged.total) + assertEquals(listOf("one", "two", "three"), merged.lines.map { it.text }) + } + + @Test + fun `a dropped line still moves the cursor`() = runBlocking { + seed() + armNow() + db.notificationDao().setNotifications(roomOne, ChatRoom.NOTIFICATIONS_MUTED) + val muted = line(roomOne) + + assertTrue(dispatcher.dispatchPending(user).isEmpty()) + assertEquals(muted, db.notificationDao().getLedger(user)!!.cursorMessageId) + } + + @Test + fun `an approval waiting on this device is posted as needing you`() = runBlocking { + seed() + armNow() + line(type = ChatMessage.TYPE_FROST_APPROVAL_NEEDED, mine = true, text = "Your approval is needed") + val posted = dispatcher.dispatchPending(user).single() + assertEquals(NotificationCategory.NeedsYou, posted.category) + } + + @Test + fun `the room on screen is not posted while the app is in front`() = runBlocking { + seed() + armNow() + appVisible.value = true + visibleRoom.value = roomOne + line(roomOne) + line(roomTwo) + assertEquals(listOf(roomTwo), dispatcher.dispatchPending(user).map { it.chatRoomId }) + } + + /** D8: reading the room takes its notification away. */ + @Test + fun `reading a room cancels its notification`() = runBlocking { + seed() + val running = launch(Dispatchers.Default) { dispatcher.run(user) } + withTimeout(5_000) { while (db.notificationDao().getLedger(user) == null) delay(20) } + + line(roomOne) + withTimeout(5_000) { while (notifier.posted.isEmpty()) delay(20) } + val key = notifier.posted.single().key + + db.notificationDao().markAllRead(roomOne) + withTimeout(5_000) { while (key !in notifier.cancelled) delay(20) } + + running.cancelAndJoin() + } + + /** The whole of it, with a real client's message delivered through the app's ingest. */ + @Test + fun `a message from a Marmot client becomes a notification titled by its group`() = runBlocking { + val me = KeyPair() + val meHex = me.pubKey.toHexKey() + val client = MarmotClientStandIn() + val marmot = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + MarmotStandIn.seedProfile(db, meHex, "us") + MarmotStandIn.seedProfile(db, client.hex, "amethyst") + val roomId = client.inviteApp(db, marmot, me, client.createGroup("Hikers")) + + dispatcher.awaitArmed(meHex) + + val bundle = client.client.buildTextMessage(roomId, "summit at noon", persistOwn = false) + MarmotStandIn.storeInApp(db, me, bundle.outbound.signedEvent) + + val posted = dispatcher.dispatchPending(meHex).single() + assertEquals(roomId, posted.chatRoomId) + assertEquals("summit at noon", posted.lines.single().text) + assertEquals(NotificationCategory.Messages, posted.category) + } +}