diff --git a/composeApp/src/androidMain/AndroidManifest.xml b/composeApp/src/androidMain/AndroidManifest.xml
index 2d6b97b8..c94d4578 100644
--- a/composeApp/src/androidMain/AndroidManifest.xml
+++ b/composeApp/src/androidMain/AndroidManifest.xml
@@ -36,6 +36,10 @@
+
+
NotificationActions.markRead(runtime, chatRoomId, key)
+ NotificationActions.ACTION_REPLY -> {
+ val text = RemoteInput.getResultsFromIntent(intent)
+ ?.getCharSequence(NotificationActions.REPLY_INPUT)
+ ?.toString()
+ .orEmpty()
+ NotificationActions.reply(runtime, userPublicKey, chatRoomId, key, text)
+ }
+ }
+ } finally {
+ pending.finish()
+ }
+ }
+ }
+
+ private companion object {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ }
+}
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
index 38c60403..034dbcd0 100644
--- a/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt
+++ b/composeApp/src/androidMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.android.kt
@@ -19,6 +19,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.Person
+import androidx.core.app.RemoteInput
import androidx.core.content.ContextCompat
import mobi.giza.android.MainActivity
import mobi.giza.android.R
@@ -97,6 +98,14 @@ class AndroidNotifier(private val context: Context) : PlatformNotifier {
.setOnlyAlertOnce(false)
.setAutoCancel(true)
.setContentIntent(openRoom(notification))
+ .apply {
+ // Only what somebody said can be answered or set aside from here. An approval is
+ // opened, never decided in the shade. Phase 13.
+ if (notification.category == NotificationCategory.Messages) {
+ addAction(markReadAction(notification, names))
+ addAction(replyAction(notification, names))
+ }
+ }
.build()
try {
@@ -123,6 +132,43 @@ class AndroidNotifier(private val context: Context) : PlatformNotifier {
)
}
+ private fun actionIntent(action: String, notification: RoomNotification): Intent =
+ Intent(context, NotificationActionReceiver::class.java)
+ .setAction(action)
+ .putExtra(NotificationTaps.EXTRA_USER_PUBLIC_KEY, notification.userPublicKey)
+ .putExtra(NotificationTaps.EXTRA_CHAT_ROOM_ID, notification.chatRoomId)
+ .putExtra(NotificationActions.EXTRA_KEY, notification.key)
+
+ private fun markReadAction(notification: RoomNotification, names: NotificationChannelNames): NotificationCompat.Action {
+ val pending = PendingIntent.getBroadcast(
+ context,
+ (notification.key + NotificationActions.ACTION_MARK_READ).hashCode(),
+ actionIntent(NotificationActions.ACTION_MARK_READ, notification),
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ return NotificationCompat.Action.Builder(0, names.markRead, pending)
+ .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
+ .setShowsUserInterface(false)
+ .build()
+ }
+
+ private fun replyAction(notification: RoomNotification, names: NotificationChannelNames): NotificationCompat.Action {
+ // Mutable: the system writes the typed text into this intent.
+ val pending = PendingIntent.getBroadcast(
+ context,
+ (notification.key + NotificationActions.ACTION_REPLY).hashCode(),
+ actionIntent(NotificationActions.ACTION_REPLY, notification),
+ PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
+ )
+ val input = RemoteInput.Builder(NotificationActions.REPLY_INPUT).setLabel(names.replyHint).build()
+ return NotificationCompat.Action.Builder(0, names.reply, pending)
+ .addRemoteInput(input)
+ .setAllowGeneratedReplies(false)
+ .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
+ .setShowsUserInterface(false)
+ .build()
+ }
+
private fun channelOf(category: NotificationCategory) = when (category) {
NotificationCategory.Messages -> CHANNEL_MESSAGES
NotificationCategory.NeedsYou -> CHANNEL_NEEDS_YOU
diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 20972ab2..c59dd7ff 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -835,4 +835,7 @@
Quit
Giza is still running
It keeps checking for messages until you quit it from the tray.
+ Mark as read
+ Reply
+ Message
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt
index e880161d..64d4b633 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/BackgroundSyncPass.kt
@@ -128,6 +128,49 @@ class BackgroundSyncPass(
}
}
+ /**
+ * Runs [work] as [userPublicKey], from a notification's action with no screen up, and waits for
+ * what it queued to be sent: the reply typed into a notification. False when that profile is
+ * not the one this device would run as -- another is open, or the default is someone else --
+ * because sending as somebody the user did not choose is worse than not sending. Phase 13.
+ *
+ * Takes the same lock as [run], waiting rather than leaving, so a reply and a sync never both
+ * activate and deactivate the profile under each other.
+ */
+ suspend fun withProfile(userPublicKey: HexKey, deadline: Duration, work: suspend () -> Boolean): Boolean {
+ mutex.lock()
+ try {
+ val running = activeIdentity.value
+ val identity = when {
+ running == null -> loadDefaultIdentity()?.takeIf { it.nostrPublicKey == userPublicKey } ?: return false
+ running.nostrPublicKey == userPublicKey && running.nostrPrivateKey != null -> running
+ else -> return false
+ }
+ val activatedHere = running == null
+ try {
+ startEngines()
+ if (activatedHere) activeIdentity.value = identity
+ if (!work()) return false
+ withTimeoutOrNull(deadline) {
+ outboundQueued(userPublicKey)
+ .distinctUntilChanged()
+ .transformLatest { queued ->
+ if (queued == 0) emit(Unit) else {
+ delay(quietFor)
+ emit(Unit)
+ }
+ }
+ .first()
+ }
+ return true
+ } finally {
+ if (activatedHere && !isVisible.value && activeIdentity.value == identity) activeIdentity.value = null
+ }
+ } finally {
+ mutex.unlock()
+ }
+ }
+
/**
* Waits at least [minimum] -- long enough for subscriptions to reach EOSE, which no queue
* records -- and until the sync queue is empty and the outbound queue has not moved, both for
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt
new file mode 100644
index 00000000..e96dccd8
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationActions.kt
@@ -0,0 +1,42 @@
+package mobi.giza.compose.notifications
+
+import co.touchlab.kermit.Logger
+import kotlin.time.Duration.Companion.seconds
+import mobi.giza.compose.GizaRuntime
+
+/**
+ * What a notification's buttons do, the same on every platform that has them.
+ * docs/notifications-and-background-sync.md, Phase 13.
+ *
+ * Not Approve. Approving a signing session from a notification shade, without seeing what is being
+ * signed, is exactly what the approval screens exist to prevent.
+ */
+object NotificationActions {
+ private val logger = Logger.withTag("NotificationActions")
+
+ const val ACTION_MARK_READ = "mobi.giza.notification.markRead"
+ const val ACTION_REPLY = "mobi.giza.notification.reply"
+ const val EXTRA_KEY = "mobi.giza.notification.key"
+ const val REPLY_INPUT = "mobi.giza.notification.replyText"
+
+ suspend fun markRead(runtime: GizaRuntime, chatRoomId: String, key: String) {
+ runtime.chatRepository.markChatRoomRead(chatRoomId)
+ runtime.notifier.cancel(key)
+ }
+
+ /**
+ * Sends [text] into [chatRoomId] as [userPublicKey], waits for it to leave, and takes the
+ * notification away. False, and the notification left where it was, when it could not be sent.
+ */
+ suspend fun reply(runtime: GizaRuntime, userPublicKey: String, chatRoomId: String, key: String, text: String): Boolean {
+ if (text.isBlank()) return false
+ val sent = runtime.backgroundSync.withProfile(userPublicKey, deadline = 25.seconds) {
+ val room = runtime.chatRepository.getChatRoomByIdentifier(chatRoomId) ?: return@withProfile false
+ runtime.chatRepository.sendChatMessage(text = text, localChatRoom = room)
+ runtime.chatRepository.markChatRoomRead(chatRoomId)
+ true
+ }
+ if (sent) runtime.notifier.cancel(key) else logger.w { "A reply into $chatRoomId could not be sent" }
+ return sent
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt
index e037a714..7e12ddbb 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/NotificationResources.kt
@@ -1,6 +1,9 @@
package mobi.giza.compose.notifications
import mobi.giza.compose.resources.Res
+import mobi.giza.compose.resources.action_mark_read
+import mobi.giza.compose.resources.action_reply
+import mobi.giza.compose.resources.action_reply_hint
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
@@ -36,5 +39,8 @@ object NotificationResources {
groupActivityDescription = getString(Res.string.notification_channel_group_activity_description),
you = getString(Res.string.notification_you),
newMessage = getString(Res.string.notification_new_message),
+ markRead = getString(Res.string.action_mark_read),
+ reply = getString(Res.string.action_reply),
+ replyHint = getString(Res.string.action_reply_hint),
)
}
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt
index fdb5e361..5864fee9 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.kt
@@ -19,6 +19,10 @@ data class NotificationChannelNames(
val you: String,
/** What a locked screen shows in place of a message. */
val newMessage: String,
+ /** The actions on a message notification (Phase 13). */
+ val markRead: String = "",
+ val reply: String = "",
+ val replyHint: String = "",
)
/**
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
index 50710e88..00d83b21 100644
--- a/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt
+++ b/composeApp/src/iosMain/kotlin/mobi/giza/compose/notifications/PlatformNotifier.ios.kt
@@ -6,6 +6,15 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import mobi.giza.compose.PlatformContext
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import platform.UserNotifications.UNNotificationAction
+import platform.UserNotifications.UNNotificationActionOptionNone
+import platform.UserNotifications.UNNotificationCategory
+import platform.UserNotifications.UNNotificationCategoryOptionNone
+import platform.UserNotifications.UNTextInputNotificationAction
import platform.UserNotifications.UNAuthorizationOptionAlert
import platform.UserNotifications.UNAuthorizationOptionBadge
import platform.UserNotifications.UNAuthorizationOptionSound
@@ -32,6 +41,19 @@ class IosNotifier : PlatformNotifier {
private var authorised = false
override suspend fun prepare(names: NotificationChannelNames) {
+ // Mark as read and Reply on what somebody said; nothing on an approval, which is opened,
+ // never decided from the lock screen. Phase 13.
+ val markRead = UNNotificationAction.actionWithIdentifier(
+ NotificationActions.ACTION_MARK_READ, names.markRead, UNNotificationActionOptionNone,
+ )
+ val reply = UNTextInputNotificationAction.actionWithIdentifier(
+ NotificationActions.ACTION_REPLY, names.reply, UNNotificationActionOptionNone, names.reply, names.replyHint,
+ )
+ val messages = UNNotificationCategory.categoryWithIdentifier(
+ CATEGORY_MESSAGES, listOf(markRead, reply), emptyList(), UNNotificationCategoryOptionNone,
+ )
+ center.setNotificationCategories(setOf(messages))
+
center.getNotificationSettingsWithCompletionHandler { settings ->
authorised = settings?.authorizationStatus == UNAuthorizationStatusAuthorized ||
settings?.authorizationStatus == UNAuthorizationStatusProvisional
@@ -46,11 +68,13 @@ class IosNotifier : PlatformNotifier {
setTitle(notification.title)
setBody(listOfNotNull(newest.senderName, newest.text).joinToString(": "))
setThreadIdentifier(notification.chatRoomId)
+ if (notification.category == NotificationCategory.Messages) setCategoryIdentifier(CATEGORY_MESSAGES)
setSound(UNNotificationSound.defaultSound())
setUserInfo(
mapOf(
NotificationTaps.EXTRA_USER_PUBLIC_KEY to notification.userPublicKey,
NotificationTaps.EXTRA_CHAT_ROOM_ID to notification.chatRoomId,
+ NotificationActions.EXTRA_KEY to notification.key,
)
)
}
@@ -61,6 +85,34 @@ class IosNotifier : PlatformNotifier {
override fun cancel(key: String) {
center.removeDeliveredNotificationsWithIdentifiers(listOf(key))
}
+
+ companion object {
+ const val CATEGORY_MESSAGES = "messages"
+ }
+}
+
+private val actionScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+/**
+ * Called by the app delegate for Mark as read and Reply, with the typed text for a reply.
+ * [onDone] is called once, when the work is over, so the delegate can call its completion handler.
+ */
+fun notificationAction(actionIdentifier: String, userInfo: Map, text: String?, onDone: () -> Unit) {
+ val userPublicKey = userInfo[NotificationTaps.EXTRA_USER_PUBLIC_KEY] as? String
+ val chatRoomId = userInfo[NotificationTaps.EXTRA_CHAT_ROOM_ID] as? String
+ val key = userInfo[NotificationActions.EXTRA_KEY] as? String
+ if (userPublicKey == null || chatRoomId == null || key == null) return onDone()
+ actionScope.launch {
+ try {
+ val runtime = mobi.giza.compose.gizaRuntime()
+ when (actionIdentifier) {
+ NotificationActions.ACTION_MARK_READ -> NotificationActions.markRead(runtime, chatRoomId, key)
+ NotificationActions.ACTION_REPLY -> NotificationActions.reply(runtime, userPublicKey, chatRoomId, key, text.orEmpty())
+ }
+ } finally {
+ onDone()
+ }
+ }
}
/**
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt
index 91f65165..f7248276 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/BackgroundSyncPassJvmTest.kt
@@ -230,4 +230,39 @@ class BackgroundSyncPassJvmTest {
syncPending.value = false
assertEquals(BackgroundSyncPass.Outcome.Completed, first.await())
}
+
+ // -- a notification's reply (Phase 13) -------------------------------------------------
+
+ @Test
+ fun `a reply runs as the default profile, waits for it to leave, and puts the profile back`() = runBlocking {
+ seed()
+ var ranAs: Identity? = null
+ val sending = async(Dispatchers.Default) {
+ pass().withProfile(user, 30.seconds) {
+ ranAs = active.value
+ outbound.value = 1
+ true
+ }
+ }
+ // Under quietFor: a queue that has not moved for that long is treated as stuck, by design.
+ while (ranAs == null) delay(5)
+ delay(50)
+ assertTrue(sending.isActive, "returned before what it queued had left")
+ outbound.value = 0
+
+ assertTrue(sending.await())
+ assertSame(identity, ranAs)
+ assertNull(active.value)
+ }
+
+ @Test
+ fun `a reply is never sent as somebody else`() = runBlocking {
+ seed()
+ var ran = false
+ assertEquals(false, pass().withProfile("c".repeat(64), 5.seconds) { ran = true; true }, "the default profile is someone else")
+ active.value = pass(defaultIdentity = null).let { identity }
+ assertEquals(false, pass().withProfile("c".repeat(64), 5.seconds) { ran = true; true }, "another profile is open")
+ assertEquals(false, ran)
+ assertSame(identity, active.value, "the open profile was touched")
+ }
}
diff --git a/iosApp/iosApp/iOSApp.swift b/iosApp/iosApp/iOSApp.swift
index ff1ba0c8..bbadd9c9 100644
--- a/iosApp/iosApp/iOSApp.swift
+++ b/iosApp/iosApp/iOSApp.swift
@@ -31,8 +31,24 @@ class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDele
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void
) {
- PlatformNotifier_iosKt.notificationTapped(userInfo: response.notification.request.content.userInfo)
- completionHandler()
+ let userInfo = response.notification.request.content.userInfo
+ switch response.actionIdentifier {
+ case UNNotificationDefaultActionIdentifier:
+ PlatformNotifier_iosKt.notificationTapped(userInfo: userInfo)
+ completionHandler()
+ case UNNotificationDismissActionIdentifier:
+ completionHandler()
+ default:
+ // Mark as read, or Reply with what was typed. Phase 13.
+ let text = (response as? UNTextInputNotificationResponse)?.userText
+ PlatformNotifier_iosKt.notificationAction(
+ actionIdentifier: response.actionIdentifier,
+ userInfo: userInfo,
+ text: text
+ ) {
+ completionHandler()
+ }
+ }
}
}