From f98378ca5ec5b7fd291c70de87fb901283447c5d Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sat, 21 Nov 2026 20:41:08 +0200 Subject: [PATCH] feat: a group-signed profile or post sent to relays (group-nostr-profile, Phase 7) The broadcast screen comes back from Curare: the event named as the signing screen names it, a relay list the member edits, the raw JSON to copy, and each relay's answer under its row with the sum above. It sends through EventPublishTransport, reinstated and implemented by RelaysSocketManager, and never writes a NostrEvent, Profile or queue row for the group's event (D7, pinned in BroadcastLeavesNoRowJvmTest). With no group relay lists (D1), defaultRelaysFor seeds the app's publish set; it stays a function of the event so the lists can return. The one piece of Curare's GroupRelaySet it needed is RelayUrlInput. A Broadcast button sits under the profile card and under each post, open to every member, since the signature is already the group's (D4). Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 20 + .../network/relays/EventPublishTransport.kt | 33 + .../network/relays/RelaysSocketManager.kt | 4 +- .../mobi/giza/compose/nostr/RelayUrlInput.kt | 29 + .../BroadcastGroupSignedEventScreen.kt | 574 ++++++++++++++++++ .../ui/composable/GroupNostrProfileScreen.kt | 40 +- .../compose/ui/composable/GroupPostsScreen.kt | 38 +- .../ui/composable/navigation/GizaNavHost.kt | 22 + .../routes/BroadcastGroupSignedEventRoute.kt | 12 + .../composable/widgets/RelayOutcomeLabel.kt | 30 + .../widgets/buttons/BroadcastButton.kt | 38 ++ .../BroadcastGroupSignedEventViewModel.kt | 434 +++++++++++++ .../state/BroadcastGroupSignedEventUIState.kt | 18 + .../BroadcastGroupSignedEventScreenJvmTest.kt | 212 +++++++ .../GroupNostrProfileScreenJvmTest.kt | 38 +- .../ui/composable/GroupPostsScreenJvmTest.kt | 37 +- ...oadcastGroupSignedEventViewModelJvmTest.kt | 275 +++++++++ .../view/model/BroadcastLeavesNoRowJvmTest.kt | 144 +++++ 18 files changed, 1979 insertions(+), 19 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/EventPublishTransport.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RelayUrlInput.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreen.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/RelayOutcomeLabel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/buttons/BroadcastButton.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastLeavesNoRowJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 2ae879e0..c404f03c 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -628,4 +628,24 @@ No posts yet 1 post %1$d posts + + Accepted by %1$s of %2$s relays. + Add a relay to broadcast to. + Add relay + Broadcast + Copied the raw JSON + Copy raw JSON + eg. wss://relay.example.com + No relays to broadcast to. Add one above. + Accepted + Couldn't send: %1$s + No answer + Rejected: %1$s + Relays + Sending… + Relay URL + Sends the event to each relay below, exactly as the group signed it. Any member holding it can send it: the signature is the group's, not yours. + That isn't a relay address. Relays start with wss:// and cannot be on this device. + That relay is already in this list. + The app's own publishing relays are filled in. Add or remove relays before sending. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/EventPublishTransport.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/EventPublishTransport.kt new file mode 100644 index 00000000..02e36bb5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/EventPublishTransport.kt @@ -0,0 +1,33 @@ +package mobi.giza.compose.network.relays + +import kotlinx.coroutines.flow.Flow +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.network.dto.RelayDTO + +/** + * The slice of the relay layer a one-off publish needs. + * + * The same cut [LiveSubscriptionTransport] makes and for the same reason: + * [RelaysSocketManager] starts collecting relay lists in its `init` and cannot be + * stood up in a test, so a screen that hands it an event would otherwise have no + * way to check what it does with the answers. + * + * Everything the app publishes as *itself* goes through the + * `BroadcastNostrEventRequest` queue instead, which is durable and retried. This + * exists for the one thing that must not: an event the group signed. The queue + * hangs off a `NostrEvent` row, and a row for the group's event would put its post + * into the home feed and offer it to every relay the sync loop reconciles with -- + * see `BroadcastGroupSignedEventViewModel` for the whole of that argument. + */ +interface EventPublishTransport { + + /** + * Sends [nostrEvent] to each of [relays], opening a socket to any it does not + * already hold, and answers once per relay: the relay's OK, its rejection, or + * the error that stopped it being asked. + * + * @see RelayPool.publishEvent + */ + @Throws(mobi.giza.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) + suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/RelaysSocketManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/RelaysSocketManager.kt index 7b1e882d..4dfccc47 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/RelaysSocketManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/network/relays/RelaysSocketManager.kt @@ -32,7 +32,7 @@ class RelaysSocketManager( private val relayRepository: mobi.giza.compose.repository.RelayRepository, /** Injectable so that a test can drive the identity observer on a dispatcher it controls. */ private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO), -) : LiveSubscriptionTransport { +) : LiveSubscriptionTransport, EventPublishTransport { val logger = Logger.withTag("RelaysSocketManager") private val relayPoolsMutex = Mutex() @@ -116,7 +116,7 @@ class RelaysSocketManager( } @Throws(mobi.giza.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) - suspend fun publishEvent(nostrEvent: mobi.giza.compose.database.model.NostrEvent, relays: Set): Flow { + override suspend fun publishEvent(nostrEvent: mobi.giza.compose.database.model.NostrEvent, relays: Set): Flow { logger.d("publishEvent: $nostrEvent") return relayPool.publishEvent( nostrEvent = nostrEvent, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RelayUrlInput.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RelayUrlInput.kt new file mode 100644 index 00000000..fbd4b515 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/nostr/RelayUrlInput.kt @@ -0,0 +1,29 @@ +package mobi.giza.compose.nostr + +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.isLocalHost + +/** + * A relay a member typed, as one the group's signed work could be sent to. + * + * Lifted out of Curare's `GroupRelaySet`, whose relay lists were not brought back + * with the group's profile and posts (docs/group-nostr-profile-and-posts.md, D1): + * this is the one piece of it the broadcast screen needs. + */ +object RelayUrlInput { + /** + * [url] as a relay the group's event could be sent to, or null. + * + * Structural only, and deliberately narrow: `wss://` because what the group + * signed is read by strangers over the open network and `ws://` would send it in + * the clear, and no loopback because a relay only this device can reach is not + * a broadcast. Wisp's `RelayConfig.isValidUrl` refuses the same three things. + */ + fun relayUrlOrNull(url: String): NormalizedRelayUrl? { + val trimmed = url.trim() + if (!trimmed.startsWith("wss://", ignoreCase = true)) return null + + return RelayUrlNormalizer.normalizeOrNull(trimmed)?.takeUnless { it.isLocalHost() } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreen.kt new file mode 100644 index 00000000..d59a7c5f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreen.kt @@ -0,0 +1,574 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +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.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.text.input.clearText +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.CellTower +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Dns +import androidx.compose.material3.BottomAppBar +import androidx.compose.material3.BottomAppBarDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +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.runtime.rememberCoroutineScope +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalClipboardManager +import androidx.compose.ui.semantics.disabled +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextAlign +import androidx.lifecycle.viewmodel.compose.viewModel +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.accepted_by_n_of_m_relays +import mobi.giza.compose.resources.add_a_relay_to_broadcast_to +import mobi.giza.compose.resources.add_relay +import mobi.giza.compose.resources.broadcast +import mobi.giza.compose.resources.copied_the_raw_json +import mobi.giza.compose.resources.copy_raw_json +import mobi.giza.compose.resources.eg_wss_relay_example_com +import mobi.giza.compose.resources.no_relays_to_broadcast_to +import mobi.giza.compose.resources.relay_url +import mobi.giza.compose.resources.relays +import mobi.giza.compose.resources.sends_the_event_exactly_as_the_group_signed_it +import mobi.giza.compose.resources.signed_by_the_group_on +import mobi.giza.compose.resources.that_is_not_a_relay_address +import mobi.giza.compose.resources.that_relay_is_already_in_this_list +import mobi.giza.compose.resources.the_signed_event +import mobi.giza.compose.resources.the_app_s_publishing_relays_are_filled_in +import org.jetbrains.compose.resources.stringResource +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.text.ProposedEvent +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.ScreenStateTransition +import mobi.giza.compose.ui.composable.widgets.label +import mobi.giza.compose.ui.composable.widgets.rememberNotifier +import mobi.giza.compose.ui.composable.widgets.NavigateBackButton +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.BroadcastGroupSignedEventViewModel +import mobi.giza.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome +import mobi.giza.compose.ui.view.state.BroadcastGroupSignedEventUIState +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.ui.composable.widgets.buttons.ExtendedFab +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow +import kotlin.time.Instant + +/** + * One event the group signed, and the relays to send it to. + * + * The group's screen shows what the group has signed; this is where one of those + * leaves the device. The list starts at where the group has said it lives and the + * member can change it, the button sends to every relay in it at once, and each + * row then says what its relay answered -- accepted, rejected in the relay's own + * words, or nothing. The raw JSON is at the bottom for anyone who would rather + * hand it to some other tool. + * + * **The button sends rather than proposes.** Every other screen off the identity + * block opens a signing session, because what it makes is a statement by the + * group. This one moves a statement the group has already made, which any member + * holding it may do: the signature is the group's, and no share of the key is + * needed to repeat it. See `BroadcastGroupSignedEventViewModel` for why the send + * goes to the pool directly rather than through the app's broadcast queue. + */ +@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) +@Composable +fun BroadcastGroupSignedEventScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + signedEventId: HexKey, + initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState = + BroadcastGroupSignedEventUIState.Loading, + chatRepository: ChatRepository, + publishTransport: EventPublishTransport, + onNavigateBack: () -> Unit, +) { + val broadcastGroupSignedEventViewModel: BroadcastGroupSignedEventViewModel = viewModel( + factory = BroadcastGroupSignedEventViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + signedEventId = signedEventId, + initialBroadcastGroupSignedEventUIState = initialBroadcastGroupSignedEventUIState, + chatRepository = chatRepository, + publishTransport = publishTransport, + ) + ) + + val clipboardManager = LocalClipboardManager.current + + // Read out here rather than in a click handler: both are composable and an + // onClick lambda is not. + val notify = rememberNotifier(rememberCoroutineScope()) + val noRelays = stringResource(Res.string.add_a_relay_to_broadcast_to) + val copied = stringResource(Res.string.copied_the_raw_json) + + ScreenStateTransition(broadcastGroupSignedEventViewModel.broadcastGroupSignedEventUIState) { uiState -> + when (val broadcastGroupSignedEventUIState = uiState) { + is BroadcastGroupSignedEventUIState.Error -> { + // Nothing to retry: the room and the event came from navigation + // arguments, and reading them again with the same ones fails the + // same way. + ErrorState(message = broadcastGroupSignedEventUIState.message, onRetry = null) + } + + is BroadcastGroupSignedEventUIState.Loaded -> { + val signedEvent = broadcastGroupSignedEventUIState.signedEvent + val urlFieldState = rememberTextFieldState() + val isPending = broadcastGroupSignedEventViewModel.isActionPending.value + val relays = broadcastGroupSignedEventViewModel.relays + + // The list comes from the state rather than from whatever loaded + // it, so a screen handed a loaded state -- a preview, a layout + // test -- fills in the same as the app does. Once only, so a list + // the member emptied stays empty. + LaunchedEffect(broadcastGroupSignedEventUIState) { + broadcastGroupSignedEventViewModel.seedRelays(kind = signedEvent.kind) + } + + // A refusal is about what is in the field, so it goes the moment + // the field changes rather than sitting under a URL that has since + // been corrected. + LaunchedEffect(urlFieldState) { + snapshotFlow { urlFieldState.text.toString() } + .collect { broadcastGroupSignedEventViewModel.clearAddFailure() } + } + + // As the group signed it, byte for byte: what is copied is exactly + // what goes on the wire, because the point of copying it is to + // hand somebody something they can verify. + val json = signedEvent.toEvent().toJson() + val summary = ProposedEvent.summarize(signedEvent.toEvent()) + + val canSend = !isPending + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + modifier = Modifier.imePadding(), + topBar = { + TopAppBar( + title = { + broadcastGroupSignedEventUIState.localChatRoom.RenderChatRoomTitleText() + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + }, + bottomBar = { + BottomAppBar( + actions = {}, + floatingActionButton = { + ExtendedFab( + label = stringResource(Res.string.broadcast), + icon = { Icon(Icons.Default.CellTower, contentDescription = "Broadcast to these relays") }, + enabled = canSend, + onClick = { + broadcastGroupSignedEventViewModel.broadcast( + signedEvent = signedEvent, + // Stays on the screen: an empty list is + // a question rather than a mistake. + onNoRelays = { notify(noRelays) } + ) + } + ) + } + ) + } + ) { innerPadding -> + LazyColumn( + modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() + .padding(horizontal = MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + // What is being sent, in the words the signing screen used + // for it: a member deciding where a post goes is deciding + // about a post, and "kind 1" answers a question nobody asked. + item { + Column( + modifier = Modifier.fillMaxWidth() + .padding(top = MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text( + text = summary.label, + style = MaterialTheme.typography.titleMedium + ) + + Text( + text = summary.detail, + style = MaterialTheme.typography.bodyMedium, + maxLines = 4 + ) + + Text( + text = stringResource( + Res.string.signed_by_the_group_on, + signedEvent.createdAt.toFormattedTimeAndDateString() + ), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + item { + Text( + text = stringResource( + Res.string.sends_the_event_exactly_as_the_group_signed_it + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + item { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) + + Text( + text = stringResource(Res.string.relays), + style = MaterialTheme.typography.titleSmall + ) + + Text( + text = stringResource( + Res.string.the_app_s_publishing_relays_are_filled_in + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + item { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + OutlinedTextField( + modifier = Modifier.weight(1f) + .background(BottomAppBarDefaults.containerColor), + state = urlFieldState, + lineLimits = TextFieldLineLimits.SingleLine, + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent + ), + leadingIcon = { + Icon(Icons.Default.Dns, contentDescription = Decorative) + }, + label = { Text(stringResource(Res.string.relay_url)) }, + placeholder = { + Text(stringResource(Res.string.eg_wss_relay_example_com)) + }, + isError = broadcastGroupSignedEventViewModel.addFailure != null + ) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) + + IconButton( + onClick = { + if ( + broadcastGroupSignedEventViewModel.addRelay( + urlFieldState.text.toString() + ) + ) { + urlFieldState.clearText() + } + } + ) { + Icon( + Icons.Default.Add, + contentDescription = stringResource(Res.string.add_relay) + ) + } + } + + // Named rather than silent. An add button that does + // nothing for a URL it refuses is indistinguishable from + // a missed tap. + broadcastGroupSignedEventViewModel.addFailure?.let { failure -> + Text( + text = when (failure) { + BroadcastGroupSignedEventViewModel.AddFailure.NotARelay -> + stringResource(Res.string.that_is_not_a_relay_address) + BroadcastGroupSignedEventViewModel.AddFailure.AlreadyListed -> + stringResource( + Res.string.that_relay_is_already_in_this_list + ) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth() + ) + } + } + + // The last press, summed up, above the rows that break it + // down. Persistent rather than a snackbar, because it is + // the answer the member came for and a snackbar would be + // gone before the last relay had been read. + broadcastGroupSignedEventViewModel.lastBroadcast?.let { last -> + item { + Text( + text = stringResource( + Res.string.accepted_by_n_of_m_relays, + last.accepted, + last.asked + ), + style = MaterialTheme.typography.bodyMedium, + color = if (last.accepted == last.asked) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.error + } + ) + } + } + + if (relays.isEmpty()) { + item { + EmptyState( + message = stringResource(Res.string.no_relays_to_broadcast_to), + icon = Icons.Default.Dns + ) + } + } else { + items(items = relays, key = { it.url }) { relay -> + BroadcastRelayRow( + relay = relay, + outcome = broadcastGroupSignedEventViewModel.outcomes[relay], + // A row cannot leave while its relay is being + // asked: the answer would arrive for a relay + // that is no longer there to show it. + canRemove = !isPending, + onRemove = { + broadcastGroupSignedEventViewModel.removeRelay(relay) + } + ) + } + } + + item { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.sectionGap)) + + Text( + text = stringResource(Res.string.the_signed_event), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(MaterialTheme.spacing.relatedGap)) + + Surface( + modifier = Modifier.fillMaxWidth(), + color = MaterialTheme.colorScheme.surfaceVariant, + shape = MaterialTheme.shapes.small + ) { + Text( + text = json, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding) + ) + } + + Spacer(modifier = Modifier.height(MaterialTheme.spacing.itemGap)) + + FilledTonalButton( + onClick = { + clipboardManager.setText(AnnotatedString(json)) + notify(copied) + }, + modifier = Modifier.fillMaxWidth() + ) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space100)) + Text(text = stringResource(Res.string.copy_raw_json)) + } + + Spacer(modifier = Modifier.height(MaterialTheme.spacing.sectionGap)) + } + } + } + } + + BroadcastGroupSignedEventUIState.Loading -> { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.screenMargin), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) + ) { + Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) + + Text( + text = stringResource(Res.string.broadcast), + style = MaterialTheme.typography.bodyLarge, + textAlign = TextAlign.Center + ) + + LoadingDataIndicator(fillScreen = false) + } + } + } + } + + LaunchedEffect(true) { + if (initialBroadcastGroupSignedEventUIState == BroadcastGroupSignedEventUIState.Loading) { + broadcastGroupSignedEventViewModel.initiateBroadcastGroupSignedEvent() + } + } +} + +/** + * One relay to send to, and what it said the last time it was asked. + * + * The answer is on a second line under the host rather than in an icon, because + * the answers that matter are the relay's own words -- "blocked: not on the + * allow list" is something a member can act on, and a red icon is not. + */ +@Composable +private fun BroadcastRelayRow( + relay: NormalizedRelayUrl, + outcome: RelayOutcome?, + canRemove: Boolean, + onRemove: () -> Unit +) { + Row( + modifier = Modifier.fillMaxWidth().padding(vertical = MaterialTheme.spacing.relatedGap), + verticalAlignment = Alignment.CenterVertically + ) { + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text( + // The host rather than the whole URL: every relay here starts + // `wss://` -- nothing else is allowed in -- so the scheme is four + // characters of nothing in front of the part that differs. + text = relay.displayUrl(), + style = MaterialTheme.typography.bodyMedium + ) + + outcome?.let { + Text( + text = it.label(), + style = MaterialTheme.typography.bodySmall, + color = when (it) { + RelayOutcome.Accepted -> MaterialTheme.colorScheme.primary + is RelayOutcome.Rejected, is RelayOutcome.Failed -> + MaterialTheme.colorScheme.error + RelayOutcome.Sending, RelayOutcome.NoAnswer -> + MaterialTheme.colorScheme.onSurfaceVariant + } + ) + } + } + + IconButton(onClick = onRemove, enabled = canRemove) { + Icon( + Icons.Default.Delete, + contentDescription = "Remove relay", + // The button's own disabled colour while a send is out, rather + // than a red that promises a tap will do something. + tint = if (canRemove) MaterialTheme.colorScheme.error else LocalContentColor.current + ) + } + } +} + +@ConformancePreviews +@Composable +private fun BroadcastGroupSignedEventScreenPreview() { + val chatRoomId = "d4c3b2a1".repeat(8) + + GizaTheme { + Surface(modifier = Modifier.fillMaxSize()) { + BroadcastGroupSignedEventScreen( + activeUserPublicKey = "", + chatRoomId = chatRoomId, + relayHint = null, + signedEventId = "b".repeat(64), + initialBroadcastGroupSignedEventUIState = BroadcastGroupSignedEventUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = "", + subject = "Translation room", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ), + ), + signedEvent = GroupSignedEvent( + id = "b".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = TextNoteEvent.KIND, + tags = emptyArray(), + content = "The first chapter is out.", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000) + ), + ), + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = object : EventPublishTransport { + override suspend fun publishEvent( + nostrEvent: mobi.giza.compose.database.model.NostrEvent, + relays: Set + ): Flow = emptyFlow() + }, + onNavigateBack = {} + ) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt index 9540c8aa..e104bd84 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreen.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.ui.composable.widgets.buttons.BroadcastButton +import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -67,8 +69,8 @@ import kotlin.time.Instant * What the group says about itself on nostr, as the group signed it. * * Pushed from its row on the group's screen, which names the profile and - * nothing more. This is where it is read: the card and -- for a member holding - * a share of the key -- the way into the editor. A device that holds no profile + * nothing more. This is where it is read: the card, the broadcast under it, + * and -- for a member holding a share of the key -- the way into the editor. A device that holds no profile * for the group says so, and offers the editor from the same place. * * "Holds no profile", not "has none": the group's signed work is not handed to @@ -168,10 +170,33 @@ fun GroupNostrProfileScreen( ) { item { state.groupNostrProfile?.let { groupNostrProfile -> - GroupNostrProfileCard( - groupNostrProfile = groupNostrProfile, - publicKey = chatRoomId - ) + // The card and its broadcast button as one item, + // so the button stays under the event it sends + // however the list is arranged. + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally + ) { + GroupNostrProfileCard( + groupNostrProfile = groupNostrProfile, + publicKey = chatRoomId + ) + + // Not gated on a share: the signature is the + // group's, whoever repeats it (D4). + BroadcastButton( + onClick = { + onNavigateToRoute.invoke( + BroadcastGroupSignedEventRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + signedEventId = groupNostrProfile.signedEvent.id + ) + ) + } + ) + } } ?: EmptyState( message = stringResource( Res.string.this_device_holds_no_profile_for_this_group @@ -213,7 +238,8 @@ fun GroupNostrProfileScreen( * The signing date is here because a group's profile is standing state with no * other clue to its age -- and because the alternative reading, that this arrived * from a relay a moment ago, is exactly what has not happened. Nothing on this card - * was published by being signed -- see `GroupNostrProfile`. + * was published by being signed -- see `GroupNostrProfile` -- and the broadcast + * button under it is how it gets to a relay. */ @Composable private fun GroupNostrProfileCard( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt index c95d8b62..e66ce89b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreen.kt @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.composable +import mobi.giza.compose.ui.composable.widgets.buttons.BroadcastButton +import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -69,8 +71,9 @@ import kotlin.time.Instant * What the group has said publicly, as itself, newest first. * * Pushed from its row on the group's screen, which counts the posts and nothing - * more. This is where they are read: one card per post and -- for a member - * holding a share of the key -- the way into the composer. A device holding no + * more. This is where they are read: one card per post with a broadcast under + * it, and -- for a member holding a share of the key -- the way into the + * composer. A device holding no * posts says so, and offers the composer from the same place; a post signed * before this member joined is not passed on (docs/group-nostr-profile-and-posts.md, * D8), so "holds none" is all it can say. @@ -183,11 +186,32 @@ fun GroupPostsScreen( items = state.groupPosts, key = { post -> post.signedEvent.id } ) { post -> - GroupPostCard( - post = post, - publicKey = chatRoomId, - groupNostrProfile = state.groupNostrProfile - ) + // The card and its broadcast button as one item, + // so the button stays under the event it sends + // however the list is arranged. + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally + ) { + GroupPostCard( + post = post, + publicKey = chatRoomId, + groupNostrProfile = state.groupNostrProfile + ) + + BroadcastButton( + onClick = { + onNavigateToRoute.invoke( + BroadcastGroupSignedEventRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + signedEventId = post.signedEvent.id + ) + ) + } + ) + } } if (canPropose) { 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 80f1be18..b11ca0d0 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 @@ -1,5 +1,7 @@ package mobi.giza.compose.ui.composable.navigation +import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute +import mobi.giza.compose.ui.composable.BroadcastGroupSignedEventScreen import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute import mobi.giza.compose.ui.composable.navigation.routes.GroupPostsRoute import mobi.giza.compose.ui.composable.AddGroupPostScreen @@ -1312,6 +1314,26 @@ fun GizaNavHost( } ) } + // A group-signed event, sent to relays: docs/group-nostr-profile-and-posts.md. + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + BroadcastGroupSignedEventScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + relayHint = route.relayHint, + signedEventId = route.signedEventId, + chatRepository = databaseChatRepository, + // Handed the pool itself rather than a queue to write to: a + // group-signed event must not become a `NostrEvent` row, and + // the queue hangs off one (D7). See + // `BroadcastGroupSignedEventViewModel`. + publishTransport = synchronizationViewModel.relaysSocketManager, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route: ImplementationPendingRoute = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt new file mode 100644 index 00000000..864feb1d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt @@ -0,0 +1,12 @@ +package mobi.giza.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +@Serializable +data class BroadcastGroupSignedEventRoute( + val activeUserPublicKey: String, + val chatRoomId: String, // TODO: have this as a publicKey + val relayHint: String?, + /** The `GroupSignedEvent` to send, which is also the event id the group signed. */ + val signedEventId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/RelayOutcomeLabel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/RelayOutcomeLabel.kt new file mode 100644 index 00000000..7c32eb57 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/RelayOutcomeLabel.kt @@ -0,0 +1,30 @@ +package mobi.giza.compose.ui.composable.widgets + +import androidx.compose.runtime.Composable +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.relay_accepted +import mobi.giza.compose.resources.relay_could_not_send +import mobi.giza.compose.resources.relay_no_answer +import mobi.giza.compose.resources.relay_rejected +import mobi.giza.compose.resources.relay_sending +import org.jetbrains.compose.resources.stringResource +import mobi.giza.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome + +/** + * One relay's answer to a broadcast, in the words both screens that show one + * use for it: the row under a relay on `BroadcastGroupSignedEventScreen`, and + * the line under an entry that "Broadcast all" sent. + * + * A rejection and a failure carry the relay's own reason, because "blocked: + * not on the allow list" is something a member can act on and a red icon is + * not. One spelling for both screens, so a relay's answer reads the same + * whichever button sent to it. + */ +@Composable +fun RelayOutcome.label(): String = when (this) { + RelayOutcome.Sending -> stringResource(Res.string.relay_sending) + RelayOutcome.Accepted -> stringResource(Res.string.relay_accepted) + is RelayOutcome.Rejected -> stringResource(Res.string.relay_rejected, reason) + is RelayOutcome.Failed -> stringResource(Res.string.relay_could_not_send, reason) + RelayOutcome.NoAnswer -> stringResource(Res.string.relay_no_answer) +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/buttons/BroadcastButton.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/buttons/BroadcastButton.kt new file mode 100644 index 00000000..f47338fd --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/widgets/buttons/BroadcastButton.kt @@ -0,0 +1,38 @@ +package mobi.giza.compose.ui.composable.widgets.buttons + +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CellTower +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import mobi.giza.compose.resources.Res +import mobi.giza.compose.resources.broadcast +import org.jetbrains.compose.resources.stringResource +import mobi.giza.compose.ui.composable.widgets.Decorative +import mobi.giza.compose.ui.theme.spacing + +/** + * The way into `BroadcastGroupSignedEventScreen`, drawn the same under every + * event the group signed -- its profile, each relay list, each post, each schema + * and each entry -- so that it reads as one action on whichever screen it sits. + * + * Behind no gate anywhere it appears: sending what the group has already signed + * takes no share of the key, since the signature on it is the group's whoever + * repeats it. Only *making* a statement is gated, and that is the caller's + * concern. The icon is decorative because the label is beside it. + */ +@Composable +fun BroadcastButton(onClick: () -> Unit) { + TextButton(onClick = onClick) { + Icon(Icons.Default.CellTower, contentDescription = Decorative) + + Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) + + Text(stringResource(Res.string.broadcast)) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt new file mode 100644 index 00000000..61de7b49 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt @@ -0,0 +1,434 @@ +package mobi.giza.compose.ui.view.model + +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateMapOf +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 co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.Job +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.flow.take +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.exceptions.NostrPublishException +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.relays.RelayPool +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.RelayUrlInput +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.view.state.BroadcastGroupSignedEventUIState +import kotlin.time.Duration.Companion.milliseconds + +/** + * One event the group signed, sent to the relays a member picks. + * + * Signing and sending are two acts here, on purpose. `FrostSigningManager.complete` + * files what a quorum signed and applies it locally, and nothing leaves the device; + * this is the second act, taken by a member, one event at a time, to relays they + * can see and change before pressing the button. What goes on the wire is the + * event exactly as the group signed it -- the signature is the group's, so any + * member holding the event can send it and no share of the key is needed. + * + * ### Why not the broadcast queue + * + * Everything the app publishes as itself goes through `BroadcastNostrEventRequest`, + * which is durable, retried and drained in the background. It is not used here + * because it hangs off a `NostrEvent` row, and a row for the group's event is + * more than a queue entry: the home feed selects by kind, so the group's post + * would appear in it as if it were anybody's; and the sync loop offers every + * local event id to the relays it reconciles with, so the event would reach + * relays this screen never named. `GroupSignedEvent` explains at length why it is + * not a `NostrEvent`; this keeps that true. The cost is that a broadcast is only + * as durable as the button press -- what each relay said is shown, and a relay + * that did not answer is sent to again by pressing again. + * + * ### Where the relays come from + * + * [defaultRelaysFor]: the app's publish set. Curare seeds from the group's own + * relay lists where it has agreed them; Giza did not bring those back + * (docs/group-nostr-profile-and-posts.md, D1), so the member adds and removes + * before sending, and the seeded list is a suggestion rather than a rule. + */ +class BroadcastGroupSignedEventViewModel( + val chatRoomId: String, + val signedEventId: HexKey, + val activeUserPublicKey: HexKey, + val relayHint: String?, + initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState, + val chatRepository: ChatRepository, + val publishTransport: EventPublishTransport, +): ViewModel() { + + var broadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState by mutableStateOf( + initialBroadcastGroupSignedEventUIState + ) + private set + + val isActionPending: MutableState = mutableStateOf(false) + + /** + * The relays the event will be sent to, in the order they are shown. + * + * Held on the view model rather than in the composition, like the relay + * editor's working copy, so a rotation does not empty the list. + */ + val relays = mutableStateListOf() + + /** + * What each relay said the last time the button was pressed. + * + * Keyed by relay rather than kept as a list, because a relay removed after it + * answered takes its answer with it, and one added afterwards has none until + * the next press. + */ + val outcomes = mutableStateMapOf() + + /** + * Why the last add did not happen, or null. Cleared by the next keystroke. + * + * The same two refusals as the relay editor's, for the same reason: an add + * button that does nothing for a URL it refuses is indistinguishable from a + * missed tap. + */ + var addFailure: AddFailure? by mutableStateOf(null) + private set + + /** + * How the last press went, or null before the first one. + * + * Shown on the screen rather than flashed in a snackbar, because it is the + * answer the member came for and it should still be there after the rows + * under it have been read. Cleared when the next press starts. + */ + var lastBroadcast: BroadcastSummary? by mutableStateOf(null) + private set + + private var isSeeded = false + + /** [accepted] of [asked] relays said OK. */ + data class BroadcastSummary(val accepted: Int, val asked: Int) + + enum class AddFailure { + /** Not a `wss://` URL, or one pointing at this machine. */ + NotARelay, + + /** Already in the list, which is a no-op rather than a mistake. */ + AlreadyListed, + } + + /** One relay's answer to one press of the button. */ + sealed interface RelayOutcome { + /** Asked, and not yet answered. */ + data object Sending : RelayOutcome + + /** The relay's OK: it holds the event now, or already did. */ + data object Accepted : RelayOutcome + + /** The relay answered and said no, in its own words. */ + data class Rejected(val reason: String) : RelayOutcome + + /** The relay could not be asked: no connection, or one that dropped. */ + data class Failed(val reason: String) : RelayOutcome + + /** Asked, and still unanswered when the whole broadcast ran out of time. */ + data object NoAnswer : RelayOutcome + } + + fun initiateBroadcastGroupSignedEvent() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + val signedEvent = chatRepository.groupSignedEvent(chatRoomId, signedEventId) + + broadcastGroupSignedEventUIState = when { + localChatRoom == null -> + BroadcastGroupSignedEventUIState.Error("Couldn't find the chat room") + + signedEvent == null -> + BroadcastGroupSignedEventUIState.Error( + "This device doesn't hold that signed event" + ) + + else -> BroadcastGroupSignedEventUIState.Loaded( + localChatRoom = localChatRoom, + signedEvent = signedEvent, + ) + } + } + } + + /** + * Fills the list from what the group has said, once. + * + * Called from the screen rather than from the loader, for the reason the + * relay editor's `seedWorkingCopy` gives: a preview and a layout test hand a + * loaded state straight in. Once and only once, so a member who emptied the + * list on purpose does not find it refilled by a state the view model re-emits. + */ + fun seedRelays(kind: Kind) { + if (isSeeded) return + isSeeded = true + + relays.addAll(defaultRelaysFor(kind)) + } + + fun clearAddFailure() { + addFailure = null + } + + /** + * Adds [url] to the list, or says why it did not. + * + * True when the row appeared, which is the caller's cue to clear the field. + */ + fun addRelay(url: String): Boolean { + val relayUrl = RelayUrlInput.relayUrlOrNull(url) ?: run { + addFailure = AddFailure.NotARelay + return false + } + + if (relayUrl in relays) { + addFailure = AddFailure.AlreadyListed + return false + } + + relays.add(relayUrl) + addFailure = null + return true + } + + fun removeRelay(relayUrl: NormalizedRelayUrl) { + relays.remove(relayUrl) + outcomes.remove(relayUrl) + } + + /** + * Sends [signedEvent] to every relay in the list and records what each said. + * + * The send itself is [sendToRelays]; what is this screen's is the state + * around it. Each answer lands in [outcomes] as it arrives, so the rows fill in one + * by one rather than all at the end, and [lastBroadcast] sums it up once + * every row has settled. + * + * [onNoRelays] instead of a send to nobody: an empty list is a question + * rather than a mistake, and the pool would otherwise fall back to the + * *member's* relays, which is not what an empty list on this screen means. + * + * Returns the send, for a caller that has to wait for it, and null when + * nothing was sent. + */ + fun broadcast( + signedEvent: GroupSignedEvent, + onNoRelays: () -> Unit, + ): Job? { + // Guard against double submits. A second press while the first is out + // would answer each relay's OK twice and count it twice. + if (isActionPending.value) return null + + val targets = relays.toList() + if (targets.isEmpty()) { + onNoRelays.invoke() + return null + } + + isActionPending.value = true + lastBroadcast = null + outcomes.clear() + targets.forEach { outcomes[it] = RelayOutcome.Sending } + + return viewModelScope.launch(Dispatchers.IO) { + val settled = sendToRelays(publishTransport, signedEvent, targets) { relay, outcome -> + outcomes[relay] = outcome + } + + lastBroadcast = BroadcastSummary( + accepted = settled.count { it.value == RelayOutcome.Accepted }, + asked = targets.size, + ) + + isActionPending.value = false + } + } + + companion object { + private const val TAG = "BroadcastGroupSignedEventViewModel" + + private val logger = Logger.withTag(TAG) + + /** + * A ceiling on the whole broadcast, past the pool's own per-relay wait, + * so a socket that opens and then says nothing cannot hold the button + * down forever. The same bound the queue drainer puts on one attempt. + */ + val BROADCAST_TIMEOUT = (RelayPool.PUBLISH_TIMEOUT * 2).milliseconds + + /** + * Sends [signedEvent] to [targets] and says what each relay answered. + * + * One call to the pool for the whole list, which opens a socket to any + * relay it does not hold and answers once per relay -- an OK, a + * rejection with the relay's reason, or the error that stopped it being + * asked. Each answer goes to [onOutcome] as it arrives, so a caller + * showing rows can fill them in one by one rather than all at the end; + * a relay that has not answered when the whole thing runs out of time + * is marked so, which is different from having been refused, and one + * the pool refused to ask at all is marked failed with the pool's reason. + * + * Returns once every relay has settled, with the answers in the order + * [targets] gave them. + */ + suspend fun sendToRelays( + publishTransport: EventPublishTransport, + signedEvent: GroupSignedEvent, + targets: List, + onOutcome: (NormalizedRelayUrl, RelayOutcome) -> Unit = { _, _ -> }, + ): Map { + val outcomes = mutableMapOf() + + fun settle(relay: NormalizedRelayUrl, outcome: RelayOutcome) { + outcomes[relay] = outcome + onOutcome(relay, outcome) + } + + try { + withTimeout(BROADCAST_TIMEOUT) { + publishTransport.publishEvent( + nostrEvent = wireEventOf(signedEvent), + relays = targets.map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), + ) + // One answer per relay is all the pool ever gives, and the + // flow underneath never completes on its own. + .take(targets.size) + .collect { result -> + outcomeOf(targets, result)?.let { (relay, outcome) -> settle(relay, outcome) } + } + } + } catch (e: TimeoutCancellationException) { + // Ordinary: a relay that never answers is what the timeout is + // for. The relays still unanswered are settled below. + logger.w("Broadcast of ${signedEvent.id} ran out of time") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + // The pool refused the whole call rather than one relay's part of + // it, so every relay that was waiting gets the same answer. + logger.e("Broadcast of ${signedEvent.id} failed before any relay answered", e) + targets.forEach { relay -> + if (relay !in outcomes) settle(relay, RelayOutcome.Failed(e.message ?: "Could not send")) + } + } + + targets.forEach { relay -> + if (relay !in outcomes) settle(relay, RelayOutcome.NoAnswer) + } + + return targets.associateWith { outcomes.getValue(it) } + } + + /** + * One relay's answer, against the relay that was asked. + * + * Matched by host rather than by string, because the pool names a relay + * by the URL it first opened a socket with, and that may carry a + * trailing slash the caller's spelling does not. Null for an answer + * from a relay nobody asked, which is logged and dropped. + */ + private fun outcomeOf( + targets: List, + result: NostrPublishResult, + ): Pair? { + val answered = NormalizedRelayUrl(result.relayUrl).displayUrl() + val relay = targets.firstOrNull { it.displayUrl() == answered } ?: run { + logger.w("Answer from ${result.relayUrl}, which was not asked") + return null + } + + val error = result.error + val ok = result.result as? NostrIncomingMessage.OkMessage + + return relay to when { + // The pool wraps a relay's ["OK", id, false, reason] in this one + // exception type and nothing else in it, so the message is the + // relay's reason in the relay's words. + error is NostrPublishException -> RelayOutcome.Rejected(error.message ?: "Rejected") + error != null -> RelayOutcome.Failed(error.message ?: "Could not send") + ok?.success == true -> RelayOutcome.Accepted + else -> RelayOutcome.Failed("No OK from the relay") + } + } + + /** + * The event as the pool wants it, and nothing more. + * + * A `NostrEvent` built to be serialised and dropped -- it is never + * written to the table, which is the whole point of this screen sending + * directly rather than through the queue. The seven fields are the ones + * the id was hashed over, so what goes out is what the group signed. + */ + fun wireEventOf(signedEvent: GroupSignedEvent): NostrEvent = NostrEvent( + id = signedEvent.id, + pubKey = signedEvent.publicKey, + kind = signedEvent.kind, + tags = signedEvent.tags, + content = signedEvent.content, + sig = signedEvent.signature, + createdAt = signedEvent.createdAt, + ) + + /** + * Where an event of [kind] should go, before the member has said otherwise: + * the app's publish set, since a list of nothing would make the button a + * no-op until somebody typed a relay. + * + * A function of the event rather than a constant so the group's own relay + * lists, or a rule per kind, can come back without touching the screen + * (docs/group-nostr-profile-and-posts.md, D1). Curare's version reads the + * group's General list, adds the indexers for a relay list, and drops what + * the group blocked. + */ + @Suppress("UNUSED_PARAMETER") + fun defaultRelaysFor(kind: Kind): List = + Relays.eventPublishRelaySet.toList() + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + relayHint: String?, + signedEventId: HexKey, + initialBroadcastGroupSignedEventUIState: BroadcastGroupSignedEventUIState = + BroadcastGroupSignedEventUIState.Loading, + chatRepository: ChatRepository, + publishTransport: EventPublishTransport, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + BroadcastGroupSignedEventViewModel( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = relayHint, + signedEventId = signedEventId, + initialBroadcastGroupSignedEventUIState = initialBroadcastGroupSignedEventUIState, + chatRepository = chatRepository, + publishTransport = publishTransport, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt new file mode 100644 index 00000000..023057a0 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt @@ -0,0 +1,18 @@ +package mobi.giza.compose.ui.view.state + +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom + +sealed interface BroadcastGroupSignedEventUIState { + data class Loaded( + val localChatRoom: LocalChatRoom, + /** The event to send, as the group signed it. What goes on the wire is this, byte for byte. */ + val signedEvent: GroupSignedEvent, + ): BroadcastGroupSignedEventUIState + + data class Error( + val message: String + ): BroadcastGroupSignedEventUIState + + data object Loading: BroadcastGroupSignedEventUIState +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt new file mode 100644 index 00000000..198228fe --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt @@ -0,0 +1,212 @@ +package mobi.giza.compose.ui.composable + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +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.getBoundsInRoot +import androidx.compose.ui.test.onAllNodesWithContentDescription +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.runDesktopComposeUiTest +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.exceptions.NostrPublishException +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.composable.widgets.ProvideSnackbarHost +import mobi.giza.compose.ui.theme.GizaTheme +import mobi.giza.compose.ui.view.state.BroadcastGroupSignedEventUIState +import kotlin.test.Test +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * What the broadcast screen shows before, and after, the button. + * + * Before: the event named as the signing screen would name it, the app's own + * publishing relays already in the list, and a way to add one or take one out. After: + * each relay's answer under its own row, in the relay's words where it gave + * any, and the sum above them -- because the sum is what the member came for and + * the words are what they can act on. + */ +@OptIn(ExperimentalTestApi::class) +class BroadcastGroupSignedEventScreenJvmTest { + + private val chatRoomId = "d4c3b2a1".repeat(8) + + private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") + private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") + + /** A pool that answers as told and never opens a socket. */ + private class FakeTransport( + private val answers: List + ) : EventPublishTransport { + override suspend fun publishEvent( + nostrEvent: NostrEvent, + relays: Set + ): Flow = flowOf(*answers.toTypedArray()) + } + + @Test + fun `the event is named, the app's relays are filled in, and the JSON is there to copy`() = + render(state()) { + onNodeWithText("Post").assertIsDisplayed() + onNodeWithText("The first chapter is out.").assertIsDisplayed() + + // The app's publish set, as hosts: Giza did not bring back the group's + // relay lists (docs/group-nostr-profile-and-posts.md, D1). + val firstSeeded = Relays.eventPublishRelaySet.first().displayUrl() + onNodeWithText(firstSeeded).assertIsDisplayed() + onNodeWithText("The app's own publishing relays are filled in", substring = true).assertIsDisplayed() + + onNodeWithText("Broadcast").assertIsDisplayed() + onNodeWithText("Copy raw JSON").assertIsDisplayed() + + // The relays come before the JSON: the list is the screen's job and + // the JSON is for whoever would rather use a different tool. + val relays = onNodeWithText(firstSeeded).getBoundsInRoot().top + val json = onNodeWithText("The signed event").getBoundsInRoot().top + assertTrue(relays < json, "the JSON climbed above the relay list") + } + + @Test + fun `a relay can be added, and a bad one is refused by name`() = render(state()) { + onNodeWithText("Relay URL").performTextInput("wss://relay.three.example") + onNodeWithContentDescription("Add relay").performClick() + onNodeWithText("relay.three.example").assertIsDisplayed() + + onNodeWithText("Relay URL").performTextInput("not a relay") + onNodeWithContentDescription("Add relay").performClick() + onNodeWithText("That isn't a relay address.", substring = true).assertIsDisplayed() + } + + @Test + fun `after the button, each relay says what it answered and the sum sits above them`() = + render( + uiState = state(), + transport = FakeTransport( + listOf( + NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = true), + relayUrl = one.url, + ), + NostrPublishResult( + result = NostrIncomingMessage.OkMessage( + eventId = "b".repeat(64), + success = false, + message = "blocked: not on the allow list", + ), + error = NostrPublishException(message = "blocked: not on the allow list"), + relayUrl = two.url, + ), + ) + ) + ) { + emptyTheList() + listOf(one, two).forEach { relay -> + onNodeWithText("Relay URL").performTextInput(relay.url) + onNodeWithContentDescription("Add relay").performClick() + } + + onNodeWithContentDescription("Broadcast to these relays").performClick() + + waitUntil(timeoutMillis = 5_000) { + onAllNodesWithText("Accepted by 1 of 2 relays.").fetchSemanticsNodes().isNotEmpty() + } + + onNodeWithText("Accepted").assertIsDisplayed() + onNodeWithText("Rejected: blocked: not on the allow list").assertIsDisplayed() + + // The answer under the relay it came from, not in a list of its own. + val relayOne = onNodeWithText("relay.one.example").getBoundsInRoot().top + val accepted = onNodeWithText("Accepted").getBoundsInRoot().top + val relayTwo = onNodeWithText("relay.two.example").getBoundsInRoot().top + val rejected = onNodeWithText("Rejected: blocked: not on the allow list").getBoundsInRoot().top + assertTrue(relayOne < accepted && accepted < relayTwo, "the OK is not under its relay") + assertTrue(relayTwo < rejected, "the rejection is not under its relay") + } + + @Test + fun `an empty list asks nobody and says to add one`() = render(state()) { + emptyTheList() + + onNodeWithText("No relays to broadcast to. Add one above.").assertIsDisplayed() + } + + /** Removes every relay the screen seeded, one row at a time. */ + private fun ComposeUiTest.emptyTheList() { + while (onAllNodesWithContentDescription("Remove relay").fetchSemanticsNodes().isNotEmpty()) { + onAllNodesWithContentDescription("Remove relay")[0].performClick() + waitForIdle() + } + } + + private fun signedEvent() = GroupSignedEvent( + id = "b".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = TextNoteEvent.KIND, + tags = emptyArray(), + content = "The first chapter is out.", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ) + + private fun state() = BroadcastGroupSignedEventUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = chatRoomId, + userPublicKey = "a".repeat(64), + subject = "Translation room", + description = "A group translating hard books.", + initialGiftWrapPayloadId = "sdfaer", + mlsGroupState = "state" + ) + ), + signedEvent = signedEvent(), + ) + + private fun render( + uiState: BroadcastGroupSignedEventUIState, + transport: EventPublishTransport = FakeTransport(emptyList()), + assertions: ComposeUiTest.() -> Unit + ) = runDesktopComposeUiTest(width = 400, height = 3000) { + setContent { + GizaTheme { + ProvideSnackbarHost { + Box(modifier = Modifier.fillMaxSize()) { + BroadcastGroupSignedEventScreen( + activeUserPublicKey = "a".repeat(64), + chatRoomId = chatRoomId, + relayHint = null, + signedEventId = "b".repeat(64), + initialBroadcastGroupSignedEventUIState = uiState, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = transport, + onNavigateBack = {} + ) + } + } + } + } + + assertions() + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt index 058f8c72..38bfb0f2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt @@ -8,6 +8,7 @@ import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick @@ -18,6 +19,7 @@ import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.profile +import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute import mobi.giza.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.composable.widgets.LocalCanSign @@ -26,10 +28,11 @@ import mobi.giza.compose.ui.theme.GizaTheme import mobi.giza.compose.ui.view.state.GroupNostrProfileUIState import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertTrue /** - * The group's nostr profile on its own screen: what is drawn, and who is offered - * the editor. docs/group-nostr-profile-and-posts.md. + * The group's nostr profile on its own screen: what is drawn, what the broadcast + * under it sends, and who is offered the editor. docs/group-nostr-profile-and-posts.md. */ @OptIn(ExperimentalTestApi::class) class GroupNostrProfileScreenJvmTest { @@ -42,6 +45,37 @@ class GroupNostrProfileScreenJvmTest { onAllNodesWithText("Signed by the group on", substring = true).assertCountEquals(1) } + @Test + fun `the broadcast under the card sends the profile's event, share or no share`() { + var opened: Route? = null + + render(state(groupNostrProfile = profile, canSign = false), onNavigateToRoute = { opened = it }) { + // One, under the card it sends. Not gated on a share: the signature is + // the group's, whoever repeats it (D4). + val buttons = onAllNodesWithText("Broadcast") + buttons.assertCountEquals(1) + val card = onNodeWithText("group@example.com").getBoundsInRoot().top + assertTrue(card < buttons[0].getBoundsInRoot().top, "the broadcast is not under the card") + + buttons[0].performClick() + } + + assertEquals( + BroadcastGroupSignedEventRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + signedEventId = profile.signedEvent.id + ), + opened + ) + } + + @Test + fun `nothing held, nothing to broadcast`() = render(state(groupNostrProfile = null)) { + onAllNodesWithText("Broadcast").assertCountEquals(0) + } + /** docs/group-nostr-profile-and-posts.md, D6. */ @Test fun `a lightning address on the group's profile is not shown`() { diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt index 40ae2a83..b57bb205 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/composable/GroupPostsScreenJvmTest.kt @@ -21,6 +21,7 @@ import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.post import mobi.giza.compose.ui.composable.GroupSignedWorkFixtures.profile import mobi.giza.compose.ui.composable.navigation.routes.AddGroupPostRoute +import mobi.giza.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute 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 @@ -32,7 +33,8 @@ import kotlin.test.assertTrue /** * The group's posts on their own screen: newest first and whole, under the - * group's name, and the composer for a member holding a share. + * group's name, each with its broadcast, and the composer for a member holding + * a share. * docs/group-nostr-profile-and-posts.md. */ @OptIn(ExperimentalTestApi::class) @@ -63,6 +65,39 @@ class GroupPostsScreenJvmTest { onNodeWithText(chatRoomId.take(16).chunked(8).joinToString(" ")).assertIsDisplayed() } + @Test + fun `every post offers a broadcast under its card`() { + var opened: Route? = null + + render( + state(posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000)), canSign = false), + onNavigateToRoute = { opened = it } + ) { + val buttons = onAllNodesWithText("Broadcast") + buttons.assertCountEquals(2) + + val newest = onNodeWithText("The second thing").getBoundsInRoot().top + val oldest = onNodeWithText("The first thing").getBoundsInRoot().top + val first = buttons[0].getBoundsInRoot().top + val second = buttons[1].getBoundsInRoot().top + + assertTrue(newest < first && first < oldest, "the first post's broadcast is not under its card") + assertTrue(oldest < second, "the second post's broadcast is not under its card") + + buttons[1].performClick() + } + + assertEquals( + BroadcastGroupSignedEventRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null, + signedEventId = post("The first thing", 1_700_000_000).signedEvent.id + ), + opened + ) + } + @Test fun `a group that has posted nothing says so, and offers to post`() { var opened: Route? = null diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt new file mode 100644 index 00000000..425d3e98 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt @@ -0,0 +1,275 @@ +package mobi.giza.compose.ui.view.model + +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl +import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.jsonPrimitive +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.exceptions.NostrPublishException +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome +import mobi.giza.compose.ui.view.state.BroadcastGroupSignedEventUIState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * The three decisions the broadcast screen makes that nothing else can check. + * + * **Where an event goes before anyone says otherwise.** The seeded list is what a + * member who reads nothing and presses the button sends to: the app's publish set, + * since Giza did not bring back the group's relay lists + * (docs/group-nostr-profile-and-posts.md, D1). + * + * **What each relay's answer becomes.** The pool answers once per relay in three + * shapes -- an OK, a rejection wrapped in one exception type, and any other error + * -- and the rows show them as three different things because a member can act + * on "blocked: not on the allow list" and cannot act on a red icon. + * + * **What goes on the wire.** The seven fields the group hashed and nothing else, + * so a relay checking the id and the signature finds the event the group signed. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class BroadcastGroupSignedEventViewModelJvmTest { + private val chatRoomId = "d4c3b2a1".repeat(8) + + private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") + private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") + private val three = RelayUrlNormalizer.normalize("wss://relay.three.example") + + /** Answers each relay with whatever [answers] says, keyed by host, and remembers what it was handed. */ + private class FakeTransport( + private val answers: Map + ) : EventPublishTransport { + var sent: NostrEvent? = null + var askedRelays: Set = emptySet() + + override suspend fun publishEvent( + nostrEvent: NostrEvent, + relays: Set + ): Flow { + sent = nostrEvent + askedRelays = relays + return flowOf(*answers.values.toTypedArray()) + } + } + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private fun viewModel(transport: EventPublishTransport = FakeTransport(emptyMap())) = + BroadcastGroupSignedEventViewModel( + chatRoomId = chatRoomId, + signedEventId = "b".repeat(64), + activeUserPublicKey = "a".repeat(64), + relayHint = null, + initialBroadcastGroupSignedEventUIState = BroadcastGroupSignedEventUIState.Loading, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + publishTransport = transport, + ) + + private fun signedEvent(kind: Int = TextNoteEvent.KIND, tags: Array> = emptyArray()) = + GroupSignedEvent( + id = "b".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = kind, + tags = tags, + content = "The first chapter is out.", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ) + + private fun ok(relay: NormalizedRelayUrl) = NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = true), + relayUrl = relay.url, + ) + + private fun rejected(relay: NormalizedRelayUrl, reason: String) = NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = "b".repeat(64), success = false, message = reason), + error = NostrPublishException(message = reason), + relayUrl = relay.url, + ) + + private fun failed(relay: NormalizedRelayUrl, reason: String) = NostrPublishResult( + error = IllegalStateException(reason), + relayUrl = relay.url, + ) + + // -- where an event goes before anyone says otherwise ------------------------ + + /** docs/group-nostr-profile-and-posts.md, D1: no relay lists, so the app's own set. */ + @Test + fun `an event is seeded to the app's publish set, whatever its kind`() { + listOf(MetadataEvent.KIND, TextNoteEvent.KIND).forEach { kind -> + assertEquals( + Relays.eventPublishRelaySet.toList(), + BroadcastGroupSignedEventViewModel.defaultRelaysFor(kind), + "kind $kind", + ) + } + } + + @Test + fun `seeding happens once, so an emptied list stays empty`() { + val viewModel = viewModel() + val event = signedEvent() + + viewModel.seedRelays(event.kind) + viewModel.seedRelays(event.kind) + assertEquals(Relays.eventPublishRelaySet.toList(), viewModel.relays.toList()) + + viewModel.relays.toList().forEach(viewModel::removeRelay) + viewModel.seedRelays(event.kind) + assertEquals(emptyList(), viewModel.relays.toList()) + } + + // -- what may be added ---------------------------------------------------------- + + @Test + fun `an add is refused by name, and a good one clears the refusal`() { + val viewModel = viewModel() + + assertFalse(viewModel.addRelay("https://not-a-relay.example")) + assertEquals(BroadcastGroupSignedEventViewModel.AddFailure.NotARelay, viewModel.addFailure) + + assertTrue(viewModel.addRelay(one.url)) + assertNull(viewModel.addFailure) + + assertFalse(viewModel.addRelay(one.url)) + assertEquals(BroadcastGroupSignedEventViewModel.AddFailure.AlreadyListed, viewModel.addFailure) + + assertEquals(listOf(one), viewModel.relays.toList()) + } + + // -- what each relay's answer becomes --------------------------------------------- + + @Test + fun `each relay's answer lands on its own row, and the sum counts only the OKs`() { + val transport = FakeTransport( + mapOf( + "one" to ok(one), + "two" to rejected(two, "blocked: not on the allow list"), + "three" to failed(three, "Connection refused"), + ) + ) + val viewModel = viewModel(transport) + listOf(one, two, three).forEach { assertTrue(viewModel.addRelay(it.url)) } + + var toldNoRelays = false + val job = viewModel.broadcast(signedEvent(), onNoRelays = { toldNoRelays = true }) + runBlocking { withTimeout(5_000) { job!!.join() } } + + assertFalse(toldNoRelays) + assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) + assertEquals(RelayOutcome.Rejected("blocked: not on the allow list"), viewModel.outcomes[two]) + assertEquals(RelayOutcome.Failed("Connection refused"), viewModel.outcomes[three]) + assertEquals( + BroadcastGroupSignedEventViewModel.BroadcastSummary(accepted = 1, asked = 3), + viewModel.lastBroadcast, + ) + assertFalse(viewModel.isActionPending.value) + + // Asked as write relays: the pool would otherwise read from them too. + assertEquals( + setOf(one, two, three).map { RelayDTO(url = it.url, read = false, write = true) }.toSet(), + transport.askedRelays, + ) + } + + @Test + fun `an answer is matched by host, since the pool may spell the relay with a trailing slash`() { + val transport = FakeTransport( + mapOf("one" to ok(one).copy(relayUrl = one.url.trimEnd('/') + "/")) + ) + val viewModel = viewModel(transport) + assertTrue(viewModel.addRelay(one.url)) + + val job = viewModel.broadcast(signedEvent(), onNoRelays = {}) + runBlocking { withTimeout(5_000) { job!!.join() } } + + assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) + } + + @Test + fun `a relay that never answers is marked so, which is not the same as refused`() { + // The pool answers for one relay and then the flow ends, which is what a + // send that ran out of time looks like from here. + val transport = FakeTransport(mapOf("one" to ok(one))) + val viewModel = viewModel(transport) + assertTrue(viewModel.addRelay(one.url)) + assertTrue(viewModel.addRelay(two.url)) + + val job = viewModel.broadcast(signedEvent(), onNoRelays = {}) + runBlocking { withTimeout(5_000) { job!!.join() } } + + assertEquals(RelayOutcome.Accepted, viewModel.outcomes[one]) + assertEquals(RelayOutcome.NoAnswer, viewModel.outcomes[two]) + assertEquals( + BroadcastGroupSignedEventViewModel.BroadcastSummary(accepted = 1, asked = 2), + viewModel.lastBroadcast, + ) + } + + @Test + fun `an empty list asks nobody and says so`() { + val transport = FakeTransport(emptyMap()) + val viewModel = viewModel(transport) + + var toldNoRelays = false + val job = viewModel.broadcast(signedEvent(), onNoRelays = { toldNoRelays = true }) + + assertNull(job) + assertTrue(toldNoRelays) + assertNull(transport.sent) + assertFalse(viewModel.isActionPending.value) + } + + // -- what goes on the wire ------------------------------------------------------------ + + @Test + fun `what goes on the wire is the event the group signed, field for field`() { + val event = signedEvent( + kind = MetadataEvent.KIND, + tags = arrayOf(arrayOf("alt", "The group's profile")), + ) + + val wire = BroadcastGroupSignedEventViewModel.wireEventOf(event).toNostrJsonObject() + + assertEquals(event.id, wire["id"]!!.jsonPrimitive.content) + assertEquals(event.publicKey, wire["pubkey"]!!.jsonPrimitive.content) + assertEquals(event.createdAt.epochSeconds.toString(), wire["created_at"]!!.jsonPrimitive.content) + assertEquals(event.kind.toString(), wire["kind"]!!.jsonPrimitive.content) + assertEquals(event.content, wire["content"]!!.jsonPrimitive.content) + assertEquals(event.signature, wire["sig"]!!.jsonPrimitive.content) + assertEquals("""[["alt","The group's profile"]]""", wire["tags"].toString()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastLeavesNoRowJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastLeavesNoRowJvmTest.kt new file mode 100644 index 00000000..6320373b --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/BroadcastLeavesNoRowJvmTest.kt @@ -0,0 +1,144 @@ +package mobi.giza.compose.ui.view.model + +import androidx.room3.Room +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.GroupSignedEvent +import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Profile +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.network.dto.RelayDTO +import mobi.giza.compose.network.relays.EventPublishTransport +import mobi.giza.compose.network.relays.NostrPublishResult +import mobi.giza.compose.network.sockets.NostrIncomingMessage +import mobi.giza.compose.ui.view.state.BroadcastGroupSignedEventUIState + +/** + * A broadcast of the group's profile writes nothing to this device's tables + * (docs/group-nostr-profile-and-posts.md, D7). + * + * The whole reason the screen sends through the pool rather than the + * `BroadcastNostrEventRequest` queue: the queue hangs off a `NostrEvent` row, and a + * row for the group's event would put its post in the home feed, offer it to every + * relay the sync loop reconciles with, and -- for a kind:0 -- make a `Profile` row for + * the group's key through `NostrDao.toProfile`. Checked against the real repository + * and database, since what is being pinned is an absence there. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class BroadcastLeavesNoRowJvmTest { + + private val database: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val chatRoomId = "d4c3b2a1".repeat(8) + private val member = "a".repeat(64) + + private val profile = GroupSignedEvent( + id = "e".repeat(64), + chatRoomId = chatRoomId, + publicKey = chatRoomId, + kind = MetadataEvent.KIND, + tags = emptyArray(), + content = """{"name":"Translation collective"}""", + signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ) + + /** Answers every relay with an OK, and keeps what it was handed. */ + private class Transport : EventPublishTransport { + var sent: NostrEvent? = null + + override suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow { + sent = nostrEvent + return flowOf( + *relays.map { + NostrPublishResult( + result = NostrIncomingMessage.OkMessage(eventId = nostrEvent.id, success = true), + relayUrl = it.url, + ) + }.toTypedArray() + ) + } + } + + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + database.close() + } + + @Test + fun `a broadcast profile reaches the relays and leaves no event, profile or queue row`(): Unit = runBlocking { + // The room's owner, which a room row needs before it can be written. + val ownerEventId = "0e".repeat(32) + database.nostrEventDao().upsert( + NostrEvent(id = ownerEventId, pubKey = member, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + database.profileDao().upsert(Profile(publicKey = member, nostrEventId = ownerEventId)) + database.chatRoomDao().upsert( + ChatRoom(id = chatRoomId, userPublicKey = member, subject = "Translation room", description = null, mlsGroupState = "state") + ) + database.groupSignedEventDao().record(profile) + + val transport = Transport() + val viewModel = BroadcastGroupSignedEventViewModel( + chatRoomId = chatRoomId, + signedEventId = profile.id, + activeUserPublicKey = member, + relayHint = null, + initialBroadcastGroupSignedEventUIState = BroadcastGroupSignedEventUIState.Loading, + chatRepository = DatabaseChatRepository(database, CoroutineScope(Dispatchers.Default)), + publishTransport = transport, + ) + + viewModel.initiateBroadcastGroupSignedEvent() + val loaded = withTimeout(5_000) { + var state = viewModel.broadcastGroupSignedEventUIState + while (state !is BroadcastGroupSignedEventUIState.Loaded) { + assertIs(state, "the event did not load") + delay(10) + state = viewModel.broadcastGroupSignedEventUIState + } + state + } + + viewModel.seedRelays(loaded.signedEvent.kind) + val send = assertNotNull(viewModel.broadcast(loaded.signedEvent, onNoRelays = {})) + withTimeout(5_000) { send.join() } + + assertEquals(profile.id, transport.sent?.id, "the relays were handed the group's event") + assertEquals(viewModel.relays.size, viewModel.lastBroadcast?.accepted) + + assertNull(database.nostrEventDao().getNostrEventById(profile.id), "a NostrEvent row for the group's event") + assertNull(database.profileDao().getProfileByPublicKey(chatRoomId), "a Profile row for the group's key") + assertTrue( + database.broadcastNostrEventRequestDao().getBroadcastNostrEventRequestsByNostrEventId(profile.id).isEmpty(), + "a queued broadcast", + ) + } +}