From 12a93bd4d78368e078a53df3aa8be3c029b5a0d1 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 22 Nov 2026 02:00:09 +0200 Subject: [PATCH] feat: the group's inbox, seen (group-inbox, Phase 7) Three screens, each with a way back, readableContent, the four states and the transition between them: the inbox (its conversations, newest first, with who they are with and what is unread; mail this device cannot open, counted with why; an inbox the group has not yet announced saying nobody can write to it; and for an admin promoted after the first key, why earlier mail is missing), a conversation (theirs on the leading edge, the group's replies marked as the group's), and the inbox's settings (setting one up with where mail should arrive, the key generation by generation, the ceremony with who it waits on and Abandon, and Rotate the inbox key). The group's screen gets an Inbox row with the unread count on a device that holds the key, the ceremony while it runs, or Set up an inbox for an admin who could start one. A member who is not an admin sees no row. The ceremony's own screen planned for Phase 4 is the settings screen's ceremony card. m3Audit at its budgets; compileDebugKotlinAndroid builds. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 33 ++ .../repository/DatabaseChatRepository.kt | 13 + .../DatabaseGroupInboxRepository.kt | 80 +++++ .../giza/compose/repository/ChatRepository.kt | 6 + .../repository/GroupInboxRepository.kt | 63 ++++ .../ui/composable/ChatRoomDetailScreen.kt | 71 +++++ .../GroupInboxConversationScreen.kt | 199 ++++++++++++ .../compose/ui/composable/GroupInboxScreen.kt | 255 +++++++++++++++ .../ui/composable/GroupInboxSettingsScreen.kt | 300 ++++++++++++++++++ .../ui/composable/navigation/GizaNavHost.kt | 45 +++ .../navigation/routes/GroupInboxRoute.kt | 31 ++ .../ui/view/model/ChatRoomDetailViewModel.kt | 1 + .../ui/view/model/GroupInboxViewModel.kt | 167 ++++++++++ .../ui/view/state/ChatRoomDetailUIState.kt | 2 + .../ui/view/state/GroupInboxUIState.kt | 54 ++++ .../compose/ui/view/state/InboxRowSummary.kt | 13 + .../compose/managers/GroupInboxRowJvmTest.kt | 54 ++++ .../ui/composable/GroupInboxScreenJvmTest.kt | 185 +++++++++++ 18 files changed, 1572 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b9b806df..97a00b66 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -740,4 +740,37 @@ %1$s: %2$d of %3$d admins to sign Formed This is the room of the confederation %1$s. Its key is held by the admins of its groups together. Until the confederation can sign, who is in this room cannot change. + + Inbox + Inbox settings + No new messages + 1 new message + %1$d new messages + Set up an inbox + Let anyone on nostr write to the group privately + The admins are making the group's inbox key + Couldn't find the group + Nobody has written to the group yet. + Messages sent before you held the group's inbox key aren't on this device. + 1 message this device can't open + %1$d messages this device can't open + It was sent to the group's npub by an app that doesn't know the group's inbox key, or to a key from before you were an admin. + The group hasn't signed its inbox announcement yet, so nobody can write to it. + The group + The group: %1$s + %1$s and the group + The group's admins will make a key together. Every admin holds it and can read what arrives. Nobody can write to the group until it signs its announcement, and the group signs every reply. + Where mail should arrive + One relay per line, starting wss:// + Key %1$d, %2$s + Announced: anyone can write to it + Waiting for the group to sign its announcement + Retired, kept to open older mail + Mail arrives on %1$s + Waiting on %1$s + Rotate the inbox key + Makes a new key with the current admins. Mail sent to the old key can still be read by the admins who held it, and a removed admin keeps what they already read. + Couldn't start the ceremony + The inbox key ceremony started + None of those is a relay a stranger could reach diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 016b4102..a18dfc99 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -263,6 +263,19 @@ class DatabaseChatRepository( null } + override suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? { + if (!mobi.giza.compose.ExperimentalFeatures.groupInbox || localChatRoom.chatRoom.mlsGroupState == null) return null + val roomId = localChatRoom.chatRoom.id + val user = localChatRoom.chatRoom.userPublicKey + val holds = database.inboxKeyDao().getKeys(roomId, user).any { it.secretKey != null } + val running = database.inboxKeyDao().getRunningCeremoniesIn(roomId).any { it.userPublicKey == user && it.isParticipant() } + val canSetUp = !holds && !running && + mobi.giza.compose.managers.InboxKeyRitualManager.refusal(database, localChatRoom, user) == null + if (!holds && !running && !canSetUp) return null + val unread = if (holds) database.groupInboxDao().getMessages(roomId).count { !it.outgoing && it.readAt == null } else 0 + return mobi.giza.compose.ui.view.state.InboxRowSummary(holdsKey = holds, unread = unread, ceremonyRunning = running, canSetUp = canSetUp) + } + override suspend fun confederationProposalCount(chatRoomId: String): Int = database.confederationDao().getProposalsNaming(chatRoomId).size diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt index 75fbcae3..0f6db750 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseGroupInboxRepository.kt @@ -2,21 +2,33 @@ package mobi.giza.compose.database.repository import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map +import kotlin.time.Clock import kotlin.time.Instant import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.identity.Identity import mobi.giza.compose.managers.GroupInboxManager import mobi.giza.compose.managers.InboxAnnouncements +import mobi.giza.compose.managers.InboxKeyRitualManager +import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents import mobi.giza.compose.repository.GroupInboxRepository class DatabaseGroupInboxRepository( private val database: GizaDatabase, @Suppress("unused") private val scope: CoroutineScope, + /** The identity the app runs as: its key takes part in the ceremonies it starts. */ + private val activeIdentity: StateFlow = MutableStateFlow(null), ) : GroupInboxRepository { override fun observeUnpublished(): Flow> = database.groupInboxDao().observeUnpublished() @@ -32,4 +44,72 @@ class DatabaseGroupInboxRepository( override suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? = GroupInboxManager.receive(database, wrap, userPublicKey) + + override fun observeConversations(chatRoomId: String): Flow> = + database.groupInboxDao().observeMessages(chatRoomId).map { messages -> + val names = namesOf(messages.flatMap { it.participantList() }.distinct()) + messages.groupBy { it.conversationId }.map { (id, inConversation) -> + val newest = inConversation.maxBy { it.createdAt } + val participants = newest.participantList() + GroupInboxRepository.ConversationSummary( + conversationId = id, + participants = participants, + names = participants.map { names[it] ?: it.take(8) }, + lastText = Event.fromJsonOrNull(newest.rumorJson)?.content.orEmpty(), + lastAt = newest.createdAt, + lastOutgoing = newest.outgoing, + unread = inConversation.count { !it.outgoing && it.readAt == null }, + ) + }.sortedByDescending { it.lastAt } + } + + override fun observeConversation(chatRoomId: String, conversationId: String): Flow> = + database.groupInboxDao().observeConversation(chatRoomId, conversationId) + + override fun observeUnopenedCount(chatRoomId: String): Flow = + database.groupInboxDao().observeUnopenedCount(chatRoomId) + + override fun observeStatus(localChatRoom: LocalChatRoom, userPublicKey: HexKey): Flow { + val roomId = localChatRoom.chatRoom.id + return combine( + database.inboxKeyDao().observeKeys(roomId, userPublicKey), + database.inboxKeyDao().observeLatestCeremony(roomId, userPublicKey), + ) { keys, ceremony -> + GroupInboxRepository.Status( + keys = keys, + ceremony = ceremony, + announcedKey = InboxAnnouncements.announcedKey(database, roomId), + relays = InboxAnnouncements.relaysOf(database, roomId), + setUpRefusal = InboxKeyRitualManager.refusal(database, localChatRoom, userPublicKey), + waitingOn = ceremony?.takeIf { it.isRunning }?.let { waitingOn(it) }.orEmpty(), + ) + } + } + + /** The admins a running ceremony has not heard a host key from: who to knock on the door of. */ + private suspend fun waitingOn(ceremony: InboxKeyCeremony): List { + val heard = database.inboxKeyDao().getMessages(ceremony.id) + .filter { it.kind == InboxKeyRitualEvents.HOST_KEY }.map { it.senderPublicKey }.toSet() + val silent = ceremony.participants().filter { it !in heard } + val names = namesOf(silent) + return silent.map { names[it] ?: it.take(8) } + } + + override suspend fun markRead(chatRoomId: String, conversationId: String) = + database.groupInboxDao().markConversationRead(chatRoomId, conversationId, Clock.System.now()) + + override suspend fun namesOf(publicKeys: List): Map = + database.profileDao().getProfileByPublicKeys(publicKeys).associate { it.publicKey to it.humanReadableNameOrPubkey() } + + private fun secret(): ByteArray = + activeIdentity.value?.nostrPrivateKey?.value?.toByteArray() ?: throw IllegalStateException("This identity cannot sign") + + override suspend fun setUp(localChatRoom: LocalChatRoom, relays: List): InboxKeyCeremony = + InboxKeyRitualManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, secret(), relays) + + override suspend fun rotate(localChatRoom: LocalChatRoom): InboxKeyCeremony = + InboxKeyRitualManager.propose(database, localChatRoom, localChatRoom.chatRoom.userPublicKey, secret()) + + override suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = + InboxKeyRitualManager.abandon(database, localChatRoom, ceremonyId) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index a43e518e..5275835c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -135,6 +135,12 @@ interface ChatRepository { /** How many confederation proposals naming [chatRoomId] this device holds. docs/confederation.md. */ suspend fun confederationProposalCount(chatRoomId: String): Int = 0 + /** + * The group's inbox as its row on the group's screen shows it, or null where this device + * has nothing of it to show (docs/group-inbox.md, D9). + */ + suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? = null + /** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */ suspend fun confederationOfRoom(chatRoomId: String): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt index bcb9c4ba..4fb6a9a7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/GroupInboxRepository.kt @@ -4,9 +4,14 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf import kotlin.time.Instant import mobi.giza.compose.database.model.GroupInboxMessage import mobi.giza.compose.database.model.GroupInboxPublication +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyCeremony +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom /** The group's inbox, as the screens and the sync see it (docs/group-inbox.md). */ interface GroupInboxRepository { @@ -26,4 +31,62 @@ interface GroupInboxRepository { /** Files a gift wrap heard on a relay for one of [userPublicKey]'s groups. */ suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? + + // ---- the screens (Phase 7) ---------------------------------------------------------------- + + /** One conversation in a group's inbox, as its list shows it. */ + data class ConversationSummary( + val conversationId: String, + val participants: List, + val names: List, + val lastText: String, + val lastAt: Long, + val lastOutgoing: Boolean, + val unread: Int, + ) + + /** What a group's inbox is on this device: its keys, its newest ceremony, what it announced. */ + data class Status( + val keys: List, + val ceremony: InboxKeyCeremony?, + /** The key the group's newest signed 10044 names, or null if it has announced none. */ + val announcedKey: HexKey?, + val relays: List, + /** Why this identity cannot start a ceremony now, or null if it can. */ + val setUpRefusal: String?, + /** The admins a running ceremony waits on, by name. */ + val waitingOn: List, + ) { + val heldKey: InboxKey? get() = keys.firstOrNull { it.secretKey != null } + } + + fun observeConversations(chatRoomId: String): Flow> = emptyFlow() + + fun observeConversation(chatRoomId: String, conversationId: String): Flow> = flowOf(emptyList()) + + fun observeUnopenedCount(chatRoomId: String): Flow = flowOf(0) + + fun observeStatus(localChatRoom: LocalChatRoom, userPublicKey: HexKey): Flow = emptyFlow() + + suspend fun markRead(chatRoomId: String, conversationId: String) = Unit + + suspend fun namesOf(publicKeys: List): Map = emptyMap() + + /** Starts the first inbox key ceremony, with mail to arrive on [relays]. */ + suspend fun setUp(localChatRoom: LocalChatRoom, relays: List): InboxKeyCeremony = + throw UnsupportedOperationException() + + /** Starts a ceremony for the next generation of the key (D14). */ + suspend fun rotate(localChatRoom: LocalChatRoom): InboxKeyCeremony = throw UnsupportedOperationException() + + suspend fun abandon(localChatRoom: LocalChatRoom, ceremonyId: String): Boolean = false + + companion object { + val NO_OP = object : GroupInboxRepository { + override fun observeUnpublished(): Flow> = flowOf(emptyList()) + override suspend fun markPublished(eventId: HexKey, at: Instant) = Unit + override fun observeRoutes(userPublicKey: HexKey): Flow> = flowOf(emptyList()) + override suspend fun receive(wrap: Event, userPublicKey: HexKey): GroupInboxMessage? = null + } + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 79fb2290..c1ff5fc5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -9,6 +9,17 @@ import mobi.giza.compose.resources.one_post import mobi.giza.compose.resources.no_posts_yet import mobi.giza.compose.resources.posts import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.resources.inbox +import mobi.giza.compose.resources.set_up_an_inbox +import mobi.giza.compose.resources.no_new_messages +import mobi.giza.compose.resources.one_new_message +import mobi.giza.compose.resources.n_new_messages +import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key +import mobi.giza.compose.resources.let_anyone_on_nostr_write_to_the_group_privately +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.view.state.InboxRowSummary +import androidx.compose.material.icons.filled.Mail import mobi.giza.compose.ui.composable.navigation.routes.ConfederationsRoute import mobi.giza.compose.ExperimentalFeatures import androidx.compose.material.icons.filled.Hub @@ -713,6 +724,26 @@ fun ChatRoomDetailScreen( ) } + // The group's inbox (docs/group-inbox.md, D9): on a device that + // holds its key, or whose identity could set one up. A member + // who is not an admin sees no row at all. + chatRoomDetailUIState.inbox?.let { inbox -> + item { + GroupInboxRow( + inbox = inbox, + onClick = { + onNavigateToRoute.invoke( + if (inbox.holdsKey) { + GroupInboxRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = relayHint) + } else { + GroupInboxSettingsRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, relayHint = relayHint) + } + ) + } + ) + } + } + // The confederations naming this group, and the way into // proposing one (docs/confederation.md). Every member can // read them; the screen behind it gates proposing. @@ -2148,6 +2179,46 @@ private fun GroupPostsRow( } } +/** + * The row that opens the group's inbox, with how much is unread; or, where this device holds no + * key yet, the way to set one up or the ceremony making it. docs/group-inbox.md. + */ +@Composable +private fun GroupInboxRow( + inbox: InboxRowSummary, + onClick: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = onClick + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.Mail, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(if (inbox.holdsKey || inbox.ceremonyRunning) Res.string.inbox else Res.string.set_up_an_inbox)) + }, + supportingContent = { + Text( + text = when { + inbox.holdsKey -> when (inbox.unread) { + 0 -> stringResource(Res.string.no_new_messages) + 1 -> stringResource(Res.string.one_new_message) + else -> stringResource(Res.string.n_new_messages, inbox.unread) + } + inbox.ceremonyRunning -> stringResource(Res.string.the_admins_are_making_the_inbox_key) + else -> stringResource(Res.string.let_anyone_on_nostr_write_to_the_group_privately) + } + ) + } + ) + } +} + /** The row that opens a group's confederations: how many proposals name it. docs/confederation.md. */ @Composable private fun ConfederationsRow( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt new file mode 100644 index 00000000..d6bab16a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxConversationScreen.kt @@ -0,0 +1,199 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet +import mobi.giza.compose.resources.the_group +import mobi.giza.compose.resources.you_and_the_group +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxConversationViewModel +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import org.jetbrains.compose.resources.stringResource + +/** + * One conversation in the group's inbox (docs/group-inbox.md, D8 and D10): what the people in it + * wrote, and what the group answered, in the order they were written. A reply is the group's, + * not the admin's who drafted it, so it is marked as the group's. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxConversationScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + conversationId: String, + initialUIState: GroupInboxConversationUIState = GroupInboxConversationUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, + /** Below the conversation: the way to reply, when there is one (Phase 8). */ + composer: @Composable (GroupInboxConversationUIState.Loaded) -> Unit = {}, +) { + val viewModel: GroupInboxConversationViewModel = viewModel( + factory = GroupInboxConversationViewModel.factory(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxConversationUIState.Loading) viewModel.initiate() + } + val title = (viewModel.uiState as? GroupInboxConversationUIState.Loaded)?.names?.joinToString(", ") + ?.let { stringResource(Res.string.you_and_the_group, it) } + ?: stringResource(Res.string.the_group) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupInboxConversationUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxConversationUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxConversationUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + if (state.lines.isEmpty()) { + EmptyState( + modifier = Modifier.weight(1f), + message = stringResource(Res.string.nobody_has_written_to_the_group_yet), + ) + } else { + LazyColumn( + modifier = Modifier.weight(1f).fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + items(state.lines, key = { it.rumorId }) { line -> MessageCard(line) } + } + } + composer(state) + } + } + } + } +} + +/** One message: theirs on the leading edge, the group's on the trailing one, in its own colours. */ +@Composable +private fun MessageCard(line: GroupInboxConversationUIState.Line) { + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = if (line.outgoing) Alignment.End else Alignment.Start, + ) { + Card( + modifier = Modifier.widthIn(max = MaterialTheme.spacing.space400 * 8), + colors = if (line.outgoing) { + CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + ) + } else { + CardDefaults.cardColors() + }, + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text( + text = if (line.outgoing) stringResource(Res.string.the_group) else line.senderName, + style = MaterialTheme.typography.labelMedium, + ) + Text(text = line.text, style = MaterialTheme.typography.bodyMedium) + Text( + text = Instant.fromEpochSeconds(line.createdAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + ) + } + } + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxConversationScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxConversationScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + conversationId = "c1", + initialUIState = GroupInboxConversationUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + names = listOf("Zola"), + lines = listOf( + GroupInboxConversationUIState.Line("r1", "Can I join the reading group?", 1_700_000_000, outgoing = false, senderName = "Zola"), + GroupInboxConversationUIState.Line("r2", "Yes. We meet on Thursdays.", 1_700_003_600, outgoing = true, senderName = ""), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt new file mode 100644 index 00000000..63d110f9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreen.kt @@ -0,0 +1,255 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.Lock +import androidx.compose.material.icons.filled.Mail +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Badge +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.earlier_mail_is_not_on_this_device +import mobi.giza.compose.resources.inbox +import mobi.giza.compose.resources.inbox_settings +import mobi.giza.compose.resources.n_messages_this_device_can_t_open +import mobi.giza.compose.resources.nobody_has_written_to_the_group_yet +import mobi.giza.compose.resources.one_message_this_device_can_t_open +import mobi.giza.compose.resources.the_group_wrote +import mobi.giza.compose.resources.the_group_hasn_t_announced_its_inbox +import mobi.giza.compose.resources.why_a_message_can_t_be_opened +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.EmptyState +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxViewModel +import mobi.giza.compose.ui.view.state.GroupInboxUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The group's inbox: the conversations people have started with the group by writing to its + * npub, newest first (docs/group-inbox.md, D8 and D9). + * + * Reached from the group's screen, and only on a device that holds the inbox key. Says what it + * cannot do as plainly as what it can: mail no key here opens is counted with why, and an inbox + * the group has made but not yet announced says nobody can write to it yet. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialUIState: GroupInboxUIState = GroupInboxUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupInboxViewModel = viewModel( + factory = GroupInboxViewModel.factory(chatRoomId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxUIState.Loading) viewModel.initiate() + } + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.inbox), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + actions = { + IconButton(onClick = { onNavigateToRoute(GroupInboxSettingsRoute(activeUserPublicKey, chatRoomId, relayHint)) }) { + Icon(Icons.Default.Settings, contentDescription = stringResource(Res.string.inbox_settings)) + } + }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + // Nothing to retry: the room came from a navigation argument. + is GroupInboxUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxUIState.Loaded -> LazyColumn( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + val status = state.status + if (status.announcedKey == null) { + item { NoticeCard(Icons.Default.Lock, stringResource(Res.string.the_group_hasn_t_announced_its_inbox)) } + } + if (state.unopenable > 0) { + item { + NoticeCard( + Icons.Default.Lock, + if (state.unopenable == 1) stringResource(Res.string.one_message_this_device_can_t_open) + else stringResource(Res.string.n_messages_this_device_can_t_open, state.unopenable), + stringResource(Res.string.why_a_message_can_t_be_opened), + ) + } + } + if (state.conversations.isEmpty()) { + item { + // D15: a promoted admin's first key opens nothing sent before it. + val joinedLate = status.keys.isNotEmpty() && status.keys.minOf { it.generation } > 0 + EmptyState( + message = stringResource( + if (joinedLate) Res.string.earlier_mail_is_not_on_this_device + else Res.string.nobody_has_written_to_the_group_yet + ) + ) + } + } else { + items(state.conversations, key = { it.conversationId }) { conversation -> + ConversationRow( + conversation = conversation, + onClick = { + onNavigateToRoute( + GroupInboxConversationRoute(activeUserPublicKey, chatRoomId, relayHint, conversation.conversationId) + ) + }, + ) + } + } + } + } + } + } +} + +@Composable +private fun NoticeCard(icon: androidx.compose.ui.graphics.vector.ImageVector, headline: String, supporting: String? = null) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(icon, contentDescription = Decorative) }, + headlineContent = { Text(headline) }, + supportingContent = supporting?.let { { Text(it) } }, + ) + } +} + +/** One conversation: who it is with, the last line and when, and how much is unread. */ +@Composable +private fun ConversationRow(conversation: GroupInboxRepository.ConversationSummary, onClick: () -> Unit) { + val lastLine = if (conversation.lastOutgoing) { + stringResource(Res.string.the_group_wrote, conversation.lastText) + } else { + conversation.lastText + } + Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) { + ListItem( + leadingContent = { Icon(Icons.Default.Mail, contentDescription = Decorative) }, + headlineContent = { + Text(conversation.names.joinToString(", "), maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + supportingContent = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(lastLine, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text( + Instant.fromEpochSeconds(conversation.lastAt).toFormattedTimeAndDateString(), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + }, + trailingContent = { + if (conversation.unread > 0) { + Badge { Text(conversation.unread.toString()) } + } else { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + } + }, + ) + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialUIState = GroupInboxUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + conversations = listOf( + GroupInboxRepository.ConversationSummary( + conversationId = "c1", participants = listOf("b".repeat(64)), names = listOf("Zola"), + lastText = "Can I join the reading group?", lastAt = 1_700_000_000, lastOutgoing = false, unread = 1, + ) + ), + unopenable = 2, + status = GroupInboxRepository.Status( + keys = emptyList(), ceremony = null, announcedKey = null, relays = emptyList(), setUpRefusal = null, waitingOn = emptyList(), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt new file mode 100644 index 00000000..064c573f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupInboxSettingsScreen.kt @@ -0,0 +1,300 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Autorenew +import androidx.compose.material.icons.filled.HourglassTop +import androidx.compose.material.icons.filled.Key +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.ListItem +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.InboxKeyCeremonyStage +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.nostr.RelayUrlInput +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.abandon +import mobi.giza.compose.resources.announced_anyone_can_write_to_it +import mobi.giza.compose.resources.couldn_t_find_the_group +import mobi.giza.compose.resources.couldn_t_start_the_ceremony +import mobi.giza.compose.resources.inbox_key_generation +import mobi.giza.compose.resources.inbox_settings +import mobi.giza.compose.resources.inbox_setup_explainer +import mobi.giza.compose.resources.mail_arrives_on +import mobi.giza.compose.resources.no_inbox_relays_were_valid +import mobi.giza.compose.resources.one_relay_per_line +import mobi.giza.compose.resources.retired_kept_to_open_older_mail +import mobi.giza.compose.resources.rotate_explainer +import mobi.giza.compose.resources.rotate_the_inbox_key +import mobi.giza.compose.resources.set_up_an_inbox +import mobi.giza.compose.resources.the_admins_are_making_the_inbox_key +import mobi.giza.compose.resources.the_ceremony_ended +import mobi.giza.compose.resources.the_inbox_key_ceremony_started +import mobi.giza.compose.resources.try_again +import mobi.giza.compose.resources.waiting_for_the_group_to_sign_its_announcement +import mobi.giza.compose.resources.waiting_on +import mobi.giza.compose.resources.where_mail_should_arrive +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.composable.widgets.ErrorState +import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.theme.ConformancePreviews +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.theme.readableContent +import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.ui.view.model.GroupInboxSettingsViewModel +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import org.jetbrains.compose.resources.stringResource + +/** + * The group's inbox key (docs/group-inbox.md, D2 to D7 and D14): setting one up, which is an + * admin starting the ceremony that makes it; where it stands, generation by generation; the + * ceremony while it runs, with who it waits on; and rotating it. + * + * Nothing here is the decision to have an inbox. That is the group signing its announcement, + * which the ceremony's coordinator asks for when the key is made, and which every member who + * holds a share is asked about on the signing screen. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupInboxSettingsScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + initialUIState: GroupInboxSettingsUIState = GroupInboxSettingsUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupInboxSettingsViewModel = viewModel( + factory = GroupInboxSettingsViewModel.factory(chatRoomId, initialUIState, chatRepository, inboxRepository) + ) + LaunchedEffect(true) { + if (initialUIState == GroupInboxSettingsUIState.Loading) viewModel.initiate() + } + val notify = rememberNotifier(rememberCoroutineScope()) + val started = stringResource(Res.string.the_inbox_key_ceremony_started) + val noRelays = stringResource(Res.string.no_inbox_relays_were_valid) + val couldNotStart = stringResource(Res.string.couldn_t_start_the_ceremony) + val report: (String?) -> Unit = { failure -> notify(if (failure == null) started else couldNotStart) } + val canSign = LocalCanSign.current + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.inbox_settings), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) }, + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupInboxSettingsUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = stringResource(Res.string.couldn_t_find_the_group), + onRetry = null, + ) + + GroupInboxSettingsUIState.Loading -> Column( + modifier = Modifier.fillMaxWidth().padding(padding).padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + LoadingDataIndicator(fillScreen = false) + } + + is GroupInboxSettingsUIState.Loaded -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap), + ) { + val status = state.status + val ceremony = status.ceremony + val running = ceremony?.isRunning == true + val visibleKeys = status.keys.filter { it.state != InboxKeyState.WIPED } + + if (visibleKeys.isEmpty() && !running) { + SetUp( + busy = state.busy, + refusal = status.setUpRefusal, + canSign = canSign, + onSetUp = { text -> + val relays = text.lines().mapNotNull { RelayUrlInput.relayUrlOrNull(it) } + if (relays.isEmpty()) notify(noRelays) else viewModel.setUp(relays, report) + }, + ) + } + + visibleKeys.forEach { key -> + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.Key, contentDescription = Decorative) }, + headlineContent = { + Text(stringResource(Res.string.inbox_key_generation, key.generation, fingerprint(key.publicKey))) + }, + supportingContent = { + Text( + when (key.state) { + InboxKeyState.ANNOUNCED -> stringResource(Res.string.announced_anyone_can_write_to_it) + InboxKeyState.RETIRED -> stringResource(Res.string.retired_kept_to_open_older_mail) + else -> stringResource(Res.string.waiting_for_the_group_to_sign_its_announcement) + } + ) + }, + ) + } + } + + if (status.relays.isNotEmpty()) { + Text( + text = stringResource(Res.string.mail_arrives_on, status.relays.joinToString(", ") { it.url.removePrefix("wss://").trimEnd('/') }), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + if (ceremony != null && running) { + Card(modifier = Modifier.fillMaxWidth()) { + ListItem( + leadingContent = { Icon(Icons.Default.HourglassTop, contentDescription = Decorative) }, + headlineContent = { Text(stringResource(Res.string.the_admins_are_making_the_inbox_key)) }, + supportingContent = status.waitingOn.takeIf { it.isNotEmpty() }?.let { names -> + { Text(stringResource(Res.string.waiting_on, names.joinToString(", "))) } + }, + trailingContent = if (ceremony.isParticipant() && canSign) { + { TextButton(onClick = { viewModel.abandon(ceremony.id) {} }, enabled = !state.busy) { Text(stringResource(Res.string.abandon)) } } + } else { + null + }, + ) + } + } else if (ceremony?.stage == InboxKeyCeremonyStage.FAILED && visibleKeys.isNotEmpty()) { + Text( + text = stringResource(Res.string.the_ceremony_ended, ceremony.failureReason.orEmpty()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } + + if (visibleKeys.isNotEmpty() && !running) { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + Text(stringResource(Res.string.rotate_explainer), style = MaterialTheme.typography.bodyMedium) + status.setUpRefusal?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + OutlinedButton( + onClick = { viewModel.rotate(report) }, + enabled = status.setUpRefusal == null && !state.busy && canSign, + ) { + Icon(Icons.Default.Autorenew, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + Text( + stringResource( + if (ceremony?.stage == InboxKeyCeremonyStage.FAILED) Res.string.try_again else Res.string.rotate_the_inbox_key + ) + ) + } + } + } + } + } + } + } +} + +/** A key as a person can compare it across devices: its first and last eight characters. */ +private fun fingerprint(key: HexKey): String = key.take(8) + "\u2026" + key.takeLast(8) + +/** Starting the first ceremony: what it does, where mail should arrive, and the button. */ +@Composable +private fun SetUp(busy: Boolean, refusal: String?, canSign: Boolean, onSetUp: (String) -> Unit) { + var relays by remember { mutableStateOf(Relays.DefaultDMRelayList.joinToString("\n") { it.url }) } + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + Text(stringResource(Res.string.inbox_setup_explainer), style = MaterialTheme.typography.bodyLarge) + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + value = relays, + onValueChange = { relays = it }, + label = { Text(stringResource(Res.string.where_mail_should_arrive)) }, + supportingText = { Text(stringResource(Res.string.one_relay_per_line)) }, + minLines = 2, + ) + refusal?.let { + Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Button(onClick = { onSetUp(relays) }, enabled = refusal == null && !busy && canSign) { + Text(stringResource(Res.string.set_up_an_inbox)) + } + } +} + +@ConformancePreviews +@Composable +private fun GroupInboxSettingsScreenPreview() { + val chatRoomId = "d".repeat(64) + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + GroupInboxSettingsScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + initialUIState = GroupInboxSettingsUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "#Ekklesia", description = null, mlsGroupState = "state") + ), + status = GroupInboxRepository.Status( + keys = emptyList(), ceremony = null, announcedKey = null, relays = emptyList(), setUpRefusal = null, waitingOn = emptyList(), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, + onNavigateBack = {}, + ) + } + } +} 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 5845867a..90f490c8 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 @@ -14,6 +14,12 @@ import mobi.giza.compose.ui.composable.navigation.routes.ProposeConfederationRou import mobi.giza.compose.ui.composable.ConfederationsScreen import mobi.giza.compose.ui.composable.ProposeConfederationScreen import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.GroupInboxScreen +import mobi.giza.compose.ui.composable.GroupInboxConversationScreen +import mobi.giza.compose.ui.composable.GroupInboxSettingsScreen import mobi.giza.compose.ui.composable.AddGroupPostScreen import mobi.giza.compose.ui.composable.GroupPostsScreen import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute @@ -228,6 +234,7 @@ fun GizaNavHost( DatabaseGroupInboxRepository( database = auxDatabaseManager.auxDatabase, applicationIOScope, + activeIdentity = sovereignWalletViewModel.activeIdentity, ) } val databaseMarmotRepository = remember { @@ -1373,6 +1380,44 @@ fun GizaNavHost( } ) } + // The group's inbox (docs/group-inbox.md, Phase 7). + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxConversationScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + conversationId = route.conversationId, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + GroupInboxSettingsScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + chatRepository = databaseChatRepository, + inboxRepository = databaseGroupInboxRepository, + onNavigateToRoute = { actionRoute -> navController.navigate(route = actionRoute) }, + onNavigateBack = { navController.popBackStack() }, + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt new file mode 100644 index 00000000..009f732a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/GroupInboxRoute.kt @@ -0,0 +1,31 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The group's inbox: its conversations, on an admin's device. docs/group-inbox.md, Phase 7. */ +@Serializable +data class GroupInboxRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): Route() + +/** One conversation in the group's inbox, and the way to reply to it. docs/group-inbox.md. */ +@Serializable +data class GroupInboxConversationRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String?, + val conversationId: String, +): Route() + +/** + * The group's inbox key: setting one up, the ceremony that makes it, what the group announced, + * and rotating it. docs/group-inbox.md. + */ +@Serializable +data class GroupInboxSettingsRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index d048388b..1f82f28a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -133,6 +133,7 @@ class ChatRoomDetailViewModel( groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), groupPosts = chatRepository.groupPosts(chatRoomId), confederationProposalCount = chatRepository.confederationProposalCount(chatRoomId), + inbox = chatRepository.inboxSummary(localChatRoom), confederationName = chatRepository.confederationOfRoom(chatRoomId), canProposeAsGroup = canSign && roomIsOpen, subgroupsNeedAWallet = canSign && subgroupsNeedAWallet, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt new file mode 100644 index 00000000..5effbc10 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/GroupInboxViewModel.kt @@ -0,0 +1,167 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import mobi.giza.compose.ui.view.state.GroupInboxUIState + +/** + * The group's inbox, watched rather than read once: mail arrives while the screen is open, and + * the point of the screen is to see it (docs/group-inbox.md, Phase 7). + */ +class GroupInboxViewModel( + val chatRoomId: String, + initialUIState: GroupInboxUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxUIState.Error("Couldn't find the group") + return@launch + } + combine( + inboxRepository.observeConversations(chatRoomId), + inboxRepository.observeUnopenedCount(chatRoomId), + inboxRepository.observeStatus(room, room.chatRoom.userPublicKey), + ) { conversations, unopenable, status -> + GroupInboxUIState.Loaded(room, conversations, unopenable, status) + }.collect { uiState = it } + } + } + + companion object { + fun factory( + chatRoomId: String, + initialUIState: GroupInboxUIState = GroupInboxUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxViewModel(chatRoomId, initialUIState, chatRepository, inboxRepository) } + } + } +} + +/** One conversation in the group's inbox, marked read as it is shown (docs/group-inbox.md, Phase 7). */ +class GroupInboxConversationViewModel( + val chatRoomId: String, + val conversationId: String, + initialUIState: GroupInboxConversationUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxConversationUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxConversationUIState.Error("Couldn't find the group") + return@launch + } + inboxRepository.observeConversation(chatRoomId, conversationId).collect { messages -> + val participants = messages.lastOrNull()?.participantList().orEmpty() + val names = inboxRepository.namesOf(participants) + uiState = GroupInboxConversationUIState.Loaded( + localChatRoom = room, + names = participants.map { names[it] ?: it.take(8) }, + lines = messages.map { message -> + GroupInboxConversationUIState.Line( + rumorId = message.rumorId, + text = Event.fromJsonOrNull(message.rumorJson)?.content.orEmpty(), + createdAt = message.createdAt, + outgoing = message.outgoing, + senderName = if (message.outgoing) "" else names[message.senderPublicKey] ?: message.senderPublicKey.take(8), + ) + }, + ) + if (messages.any { !it.outgoing && it.readAt == null }) inboxRepository.markRead(chatRoomId, conversationId) + } + } + } + + companion object { + fun factory( + chatRoomId: String, + conversationId: String, + initialUIState: GroupInboxConversationUIState = GroupInboxConversationUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxConversationViewModel(chatRoomId, conversationId, initialUIState, chatRepository, inboxRepository) } + } + } +} + +/** The group's inbox key: setting one up, its ceremony, rotating it (docs/group-inbox.md, Phase 7). */ +class GroupInboxSettingsViewModel( + val chatRoomId: String, + initialUIState: GroupInboxSettingsUIState, + val chatRepository: ChatRepository, + val inboxRepository: GroupInboxRepository, +): ViewModel() { + var uiState: GroupInboxSettingsUIState by mutableStateOf(initialUIState) + private set + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: run { + uiState = GroupInboxSettingsUIState.Error("Couldn't find the group") + return@launch + } + inboxRepository.observeStatus(room, room.chatRoom.userPublicKey).collect { status -> + val busy = (uiState as? GroupInboxSettingsUIState.Loaded)?.busy ?: false + uiState = GroupInboxSettingsUIState.Loaded(room, status, busy) + } + } + } + + private fun act(onDone: (String?) -> Unit, action: suspend (GroupInboxSettingsUIState.Loaded) -> Unit) { + val loaded = uiState as? GroupInboxSettingsUIState.Loaded ?: return + if (loaded.busy) return + uiState = loaded.copy(busy = true) + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { action(loaded) }.exceptionOrNull() + (uiState as? GroupInboxSettingsUIState.Loaded)?.let { uiState = it.copy(busy = false) } + onDone(failure?.let { it.message ?: it::class.simpleName.orEmpty() }) + } + } + + /** Starts the first ceremony. [onDone] gets null, or why it could not. */ + fun setUp(relays: List, onDone: (String?) -> Unit) = + act(onDone) { inboxRepository.setUp(it.localChatRoom, relays) } + + fun rotate(onDone: (String?) -> Unit) = act(onDone) { inboxRepository.rotate(it.localChatRoom) } + + fun abandon(ceremonyId: String, onDone: (String?) -> Unit) = + act(onDone) { inboxRepository.abandon(it.localChatRoom, ceremonyId) } + + companion object { + fun factory( + chatRoomId: String, + initialUIState: GroupInboxSettingsUIState = GroupInboxSettingsUIState.Loading, + chatRepository: ChatRepository, + inboxRepository: GroupInboxRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { GroupInboxSettingsViewModel(chatRoomId, initialUIState, chatRepository, inboxRepository) } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 03a951bd..5a1033fe 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -74,6 +74,8 @@ sealed interface ChatRoomDetailUIState { val groupPosts: List = emptyList(), /** How many confederation proposals naming this group this device holds. docs/confederation.md. */ val confederationProposalCount: Int = 0, + /** The group's inbox, for its row; null where this device has nothing of it to show. */ + val inbox: InboxRowSummary? = null, /** The confederation whose room this is, by name: its membership is fixed until it can sign. */ val confederationName: String? = null, /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt new file mode 100644 index 00000000..84ba89a9 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/GroupInboxUIState.kt @@ -0,0 +1,54 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.GroupInboxRepository + +/** The group's inbox screen (docs/group-inbox.md, Phase 7). */ +sealed interface GroupInboxUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val conversations: List, + /** Wraps addressed to the group that no key this device holds opens (D8). */ + val unopenable: Int, + val status: GroupInboxRepository.Status, + ): GroupInboxUIState + + data class Error(val message: String): GroupInboxUIState + + data object Loading: GroupInboxUIState +} + +/** One conversation in the group's inbox (docs/group-inbox.md, Phase 7 and 8). */ +sealed interface GroupInboxConversationUIState { + data class Line( + val rumorId: String, + val text: String, + val createdAt: Long, + val outgoing: Boolean, + val senderName: String, + ) + + data class Loaded( + val localChatRoom: LocalChatRoom, + val names: List, + val lines: List, + ): GroupInboxConversationUIState + + data class Error(val message: String): GroupInboxConversationUIState + + data object Loading: GroupInboxConversationUIState +} + +/** The group's inbox key and its ceremony (docs/group-inbox.md, Phase 7). */ +sealed interface GroupInboxSettingsUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + val status: GroupInboxRepository.Status, + /** Whether a request this screen made is still on its way. */ + val busy: Boolean = false, + ): GroupInboxSettingsUIState + + data class Error(val message: String): GroupInboxSettingsUIState + + data object Loading: GroupInboxSettingsUIState +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt new file mode 100644 index 00000000..74e7854a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/InboxRowSummary.kt @@ -0,0 +1,13 @@ +package mobi.giza.compose.ui.view.state + +/** + * The group's inbox as its row on the group's screen shows it (docs/group-inbox.md, Phase 7). + * Only on a device that holds the inbox key, has a ceremony running, or could start one: a + * member who is not an admin sees nothing of the inbox (D9). + */ +data class InboxRowSummary( + val holdsKey: Boolean, + val unread: Int, + val ceremonyRunning: Boolean, + val canSetUp: Boolean, +) diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt new file mode 100644 index 00000000..8115c83a --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/GroupInboxRowJvmTest.kt @@ -0,0 +1,54 @@ +package mobi.giza.compose.managers + +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.ExperimentalFeatures +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.ui.view.state.InboxRowSummary + +/** + * Who sees the group's inbox row (docs/group-inbox.md, D9): an admin who could set one up, an + * admin while the ceremony runs, an admin who holds the key with what is unread -- and a member + * who is not an admin, nobody. + */ +class GroupInboxRowJvmTest { + private val harness = GroupInboxHarness(watchers = listOf("dineo")) + + @AfterTest + fun close() = harness.close() + + private suspend fun GroupInboxHarness.Device.row(): InboxRowSummary? = + DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)).inboxSummary(room()) + + @Test + fun `an admin is offered to set one up, a member is shown nothing`() = runBlocking { + val alice = harness.device("alice") + val dineo = harness.device("dineo") + assertEquals(InboxRowSummary(holdsKey = false, unread = 0, ceremonyRunning = false, canSetUp = true), alice.row()) + assertNull(dineo.row()) + } + + @Test + fun `a running ceremony, then the key, show on the row`() = runBlocking { + val (alice, bob, carol) = listOf("alice", "bob", "carol").map { harness.device(it) } + InboxKeyRitualManager.propose(alice.db, alice.room(), alice.publicKey, alice.secret) + assertEquals(true, alice.row()?.ceremonyRunning) + harness.pump(alice, bob, carol) + val row = assertNotNull(bob.row()) + assertEquals(true, row.holdsKey) + assertEquals(0, row.unread) + } + + @Test + fun `a release build shows no row`() = runBlocking { + val alice = harness.device("alice") + ExperimentalFeatures.groupInboxOverride = false + assertNull(alice.row()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt new file mode 100644 index 00000000..5b23b15e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupInboxScreenJvmTest.kt @@ -0,0 +1,185 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.test.ComposeUiTest +import androidx.compose.ui.test.ExperimentalTestApi +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.runDesktopComposeUiTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.InboxKey +import mobi.giza.compose.database.model.InboxKeyState +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.GroupInboxRepository +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxConversationRoute +import mobi.giza.compose.ui.composable.navigation.routes.GroupInboxSettingsRoute +import mobi.giza.compose.ui.composable.navigation.routes.Route +import mobi.giza.compose.ui.composable.widgets.LocalCanSign +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.GroupInboxConversationUIState +import mobi.giza.compose.ui.view.state.GroupInboxSettingsUIState +import mobi.giza.compose.ui.view.state.GroupInboxUIState + +/** + * The group's inbox on screen (docs/group-inbox.md, Phase 7): its conversations, what it cannot + * open and why, what an empty one means, and setting one up. + */ +@OptIn(ExperimentalTestApi::class) +class GroupInboxScreenJvmTest { + private val chatRoomId = "d".repeat(64) + private val me = "a".repeat(64) + private val room = LocalChatRoom(ChatRoom(id = chatRoomId, userPublicKey = me, subject = "#Ekklesia", description = null, mlsGroupState = "state")) + + private fun key(generation: Int, state: InboxKeyState = InboxKeyState.ANNOUNCED) = InboxKey( + chatRoomId = chatRoomId, userPublicKey = me, generation = generation, publicKey = "e".repeat(64), + secretKey = "5".repeat(64), recoveryData = null, ceremonyId = "c".repeat(64), state = state, + ) + + private fun status(keys: List = listOf(key(0)), announced: String? = "e".repeat(64), refusal: String? = null) = + GroupInboxRepository.Status(keys = keys, ceremony = null, announcedKey = announced, relays = emptyList(), setUpRefusal = refusal, waitingOn = emptyList()) + + private fun conversation(name: String, text: String, unread: Int = 0) = GroupInboxRepository.ConversationSummary( + conversationId = "conversation-$name", participants = listOf("b".repeat(64)), names = listOf(name), + lastText = text, lastAt = 1_700_000_000, lastOutgoing = false, unread = unread, + ) + + private fun renderInbox(state: GroupInboxUIState, onRoute: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + GroupInboxScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = onRoute, onNavigateBack = {}, + ) + } + } + } + } + assertions() + } + + @Test + fun `a conversation shows who it is with and opens on a tap`() { + var opened: Route? = null + renderInbox(GroupInboxUIState.Loaded(room, listOf(conversation("Zola", "Can I join?", unread = 2)), 0, status()), { opened = it }) { + onNodeWithText("Zola").assertIsDisplayed() + onNodeWithText("Can I join?").assertIsDisplayed() + onNodeWithText("2").assertIsDisplayed() + onNodeWithText("Zola").performClick() + } + assertEquals(GroupInboxConversationRoute(me, chatRoomId, null, "conversation-Zola"), opened) + } + + @Test + fun `mail no key opens is counted, with why`() = renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 2, status())) { + onNodeWithText("2 messages this device can't open").assertIsDisplayed() + onNodeWithText("It was sent to the group's npub", substring = true).assertIsDisplayed() + } + + @Test + fun `an empty inbox says nobody has written`() = renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status())) { + onNodeWithText("Nobody has written to the group yet.").assertIsDisplayed() + } + + @Test + fun `an admin who joined after the first key is told why earlier mail is missing`() = + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status(keys = listOf(key(2))))) { + onNodeWithText("Messages sent before you held the group's inbox key aren't on this device.").assertIsDisplayed() + } + + @Test + fun `an inbox the group has not announced says nobody can write to it yet`() = + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status(keys = listOf(key(0, InboxKeyState.HELD)), announced = null))) { + onNodeWithText("The group hasn't signed its inbox announcement yet, so nobody can write to it.").assertIsDisplayed() + } + + @Test + fun `the settings are a tap away`() { + var opened: Route? = null + renderInbox(GroupInboxUIState.Loaded(room, emptyList(), 0, status()), { opened = it }) { + onNodeWithContentDescription("Inbox settings").performClick() + } + assertIs(opened) + } + + @Test + fun `a conversation marks the group's replies as the group's`() = runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + GroupInboxConversationScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, conversationId = "c", + initialUIState = GroupInboxConversationUIState.Loaded( + room, listOf("Zola"), + listOf( + GroupInboxConversationUIState.Line("1", "Can I join?", 1_700_000_000, outgoing = false, senderName = "Zola"), + GroupInboxConversationUIState.Line("2", "Yes, on Thursday.", 1_700_000_100, outgoing = true, senderName = ""), + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + } + } + onNodeWithText("Zola and the group").assertIsDisplayed() + onNodeWithText("Yes, on Thursday.").assertIsDisplayed() + onNodeWithText("The group").assertIsDisplayed() + } + + private fun renderSettings(state: GroupInboxSettingsUIState, canSign: Boolean = true, assertions: ComposeUiTest.() -> Unit) = + runDesktopComposeUiTest(width = 400, height = 1600) { + setContent { + GizaTheme { + ProvideSnackbarHost { + CompositionLocalProvider(LocalCanSign provides canSign) { + GroupInboxSettingsScreen( + activeUserPublicKey = me, chatRoomId = chatRoomId, relayHint = null, initialUIState = state, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, inboxRepository = GroupInboxRepository.NO_OP, + onNavigateToRoute = {}, onNavigateBack = {}, + ) + } + } + } + } + assertions() + } + + @Test + fun `with no key, the settings offer to set one up and say what it means`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = emptyList(), announced = null))) { + onNodeWithText("Set up an inbox").assertIsDisplayed() + onNodeWithText("Every admin holds it and can read what arrives", substring = true).assertIsDisplayed() + onNodeWithText("Where mail should arrive").assertIsDisplayed() + } + + @Test + fun `a refusal is said, and the button is not offered`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = emptyList(), announced = null, refusal = "Only an admin can set up the group's inbox"))) { + onNodeWithText("Only an admin can set up the group's inbox").assertIsDisplayed() + onNodeWithText("Set up an inbox").assertIsNotEnabled() + } + + @Test + fun `with a key, the settings show it and offer to rotate it`() = + renderSettings(GroupInboxSettingsUIState.Loaded(room, status(keys = listOf(key(1), key(0, InboxKeyState.RETIRED))))) { + onNodeWithText("Key 1, eeeeeeee…eeeeeeee").assertIsDisplayed() + onNodeWithText("Announced: anyone can write to it").assertIsDisplayed() + onNodeWithText("Retired, kept to open older mail").assertIsDisplayed() + onNodeWithText("Rotate the inbox key").assertIsDisplayed() + } +}