From b21f4c4d2cc4015b55869aca504f8af235553c38 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 17:56:58 +0200 Subject: [PATCH] refactor(groups): remove the group's nostr profile, relays and posts The group's detail screen loses its "Nostr profile", "Relays" and "Posts" rows, and the six screens behind them go with them: the profile, its editor, the relay lists, their editor, the posts and the composer. So do the readers they stood on (GroupNostrProfile, GroupRelayList, GroupPost), their ChatRepository methods, and 97 strings. Two things go that were not named, because nothing else reaches them. BroadcastGroupSignedEventScreen was only opened from those three screens, so the app no longer sends a group-signed event to a relay, and EventPublishTransport goes with it. "Propose event" accepted only a profile, a post or a relay list, so it would refuse every paste; ProposeGroupEventScreen and GroupEventProposal are removed, and with them the detail screen's canEditNostrProfile gate. What is left of that block is the wallet row, shown in Marmot rooms only. The transcript keeps what it already holds. The three message types stay as private legacy names in GROUP_IDENTITY_TYPES, as the curated-lists types did, so rows already written stay system lines. A profile or relay list arriving in a room now applies to nothing, so a signing session an older build opened for one ends without a raw-JSON bubble. A kind:1 falls through to "unsupported", which is what it was before posts existed. ProposedEvent no longer describes the three kinds. GroupSignedWorkRowsJvmTest now covers the wallet row and the absence of the removed rows. The chronicle tests still use a profile, a relay list and a post as their kinds; they compare GroupSignedEvent rows, which are unchanged, so only ChronicleTestKinds' account of why is corrected. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 97 --- .../compose/database/model/ChatMessage.kt | 207 +------ .../database/model/GroupSignedEvent.kt | 6 - .../repository/DatabaseChatRepository.kt | 57 -- .../compose/managers/FrostSigningManager.kt | 5 +- .../network/relays/EventPublishTransport.kt | 33 - .../network/relays/RelaysSocketManager.kt | 4 +- .../bennu/compose/nostr/GroupEventProposal.kt | 177 ------ .../bennu/compose/nostr/GroupNostrProfile.kt | 196 ------ .../bennu/compose/nostr/GroupPost.kt | 121 ---- .../bennu/compose/nostr/GroupRelayList.kt | 279 --------- .../compose/nostr/chronicle/ChronicleEvent.kt | 3 +- .../bennu/compose/nostr/wallet/GroupWallet.kt | 10 +- .../nostr/wallet/GroupWalletStatementEvent.kt | 5 +- .../compose/repository/ChatRepository.kt | 57 -- .../bennu/compose/text/ProposedEvent.kt | 40 +- .../ui/composable/AddGroupPostScreen.kt | 310 ---------- .../BroadcastGroupSignedEventScreen.kt | 582 ------------------ .../ui/composable/ChatRoomDetailScreen.kt | 214 +------ .../composable/EditGroupNostrProfileScreen.kt | 398 ------------ .../ui/composable/EditGroupRelaysScreen.kt | 551 ----------------- .../ui/composable/GroupNostrProfileScreen.kt | 353 ----------- .../compose/ui/composable/GroupPostsScreen.kt | 352 ----------- .../ui/composable/GroupRelaysScreen.kt | 327 ---------- .../ui/composable/ProposeGroupEventScreen.kt | 423 ------------- .../ui/composable/navigation/BennuNavHost.kt | 176 ------ .../navigation/routes/AddGroupPostRoute.kt | 10 - .../routes/BroadcastGroupSignedEventRoute.kt | 12 - .../routes/EditGroupNostrProfileRoute.kt | 10 - .../navigation/routes/EditGroupRelaysRoute.kt | 10 - .../routes/GroupNostrProfileRoute.kt | 19 - .../navigation/routes/GroupPostsRoute.kt | 15 - .../navigation/routes/GroupRelaysRoute.kt | 15 - .../routes/ProposeGroupEventRoute.kt | 11 - .../composable/widgets/RelayOutcomeLabel.kt | 30 - .../widgets/buttons/BroadcastButton.kt | 38 -- .../composable/widgets/chat/ChatTranscript.kt | 14 +- .../widgets/profile/ProfileAvatar.kt | 6 +- .../ui/view/model/AddGroupPostViewModel.kt | 154 ----- .../BroadcastGroupSignedEventViewModel.kt | 485 --------------- .../ui/view/model/ChatRoomDetailViewModel.kt | 4 - .../model/EditGroupNostrProfileViewModel.kt | 161 ----- .../ui/view/model/EditGroupRelaysViewModel.kt | 299 --------- .../view/model/GroupNostrProfileViewModel.kt | 71 --- .../ui/view/model/GroupPostsViewModel.kt | 64 -- .../ui/view/model/GroupRelaysViewModel.kt | 62 -- .../view/model/ProposeGroupEventViewModel.kt | 158 ----- .../ui/view/state/AddGroupPostUIState.kt | 33 - .../state/BroadcastGroupSignedEventUIState.kt | 26 - .../ui/view/state/ChatRoomDetailUIState.kt | 56 +- .../state/EditGroupNostrProfileUIState.kt | 34 - .../ui/view/state/EditGroupRelaysUIState.kt | 33 - .../ui/view/state/GroupNostrProfileUIState.kt | 35 -- .../ui/view/state/GroupPostsUIState.kt | 40 -- .../ui/view/state/GroupRelaysUIState.kt | 31 - .../ui/view/state/ProposeGroupEventUIState.kt | 32 - .../compose/nostr/GroupEventProposalTest.kt | 300 --------- .../compose/nostr/GroupNostrProfileTest.kt | 438 ------------- .../bennu/compose/nostr/GroupPostTest.kt | 307 --------- .../bennu/compose/nostr/GroupRelayListTest.kt | 398 ------------ .../nostr/chronicle/ChronicleTestKinds.kt | 13 +- .../bennu/compose/text/ProposedEventTest.kt | 60 +- .../BroadcastGroupSignedEventScreenJvmTest.kt | 240 -------- .../GroupNostrProfileScreenJvmTest.kt | 153 ----- .../ui/composable/GroupPostsScreenJvmTest.kt | 167 ----- .../ui/composable/GroupRelaysScreenJvmTest.kt | 139 ----- .../ui/composable/GroupSignedWorkFixtures.kt | 97 +-- .../composable/GroupSignedWorkRowsJvmTest.kt | 199 ++---- .../ProposeGroupEventScreenJvmTest.kt | 115 ---- ...oadcastGroupSignedEventViewModelJvmTest.kt | 373 ----------- .../model/EditGroupRelaysViewModelJvmTest.kt | 224 ------- docs/group-chain-wallet.md | 11 +- docs/npub-profile-preview.md | 2 +- 73 files changed, 139 insertions(+), 10048 deletions(-) delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt delete mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt delete mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt delete mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt delete mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt delete mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt delete mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 56a7741e..41d12dac 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -377,104 +377,7 @@ Check the combined result and confirm it The group has its key — finish setting it up Open - Nostr profile - This group hasn't said anything about itself on Nostr yet. - - Not described yet - Edit Nostr profile - Propose Nostr profile - What the group says about itself on Nostr - The group signs this, so it takes a quorum. An empty field unsays what the group had said. - This group has no shared key, so it cannot sign a profile. Run a shared key ceremony first. - Signed by the group on %1$s - No name on this profile - About - Picture url - Website - Nostr address - Lightning address - eg. Translation collective - eg. A group translating hard books into Sesotho - eg. https://example.com/group.png - eg. https://example.com - eg. group@example.com - eg. group@getalby.com - Couldn't ask the group to sign this profile. - Relays - Edit relays - Not set yet - No relays in this list - - %1$s of %2$s lists agreed - Where the group lives on Nostr - The group signs each list, so it takes a quorum. Only the lists you change are proposed. - This group has no shared key, so it cannot sign a relay list. Run a shared key ceremony first. - Relay url - eg. wss://relay.example.com - Add relay - That isn't a relay address. Relays start with wss:// and cannot be on this device. - That relay is already in this list. - Propose relays - Nothing has changed, so there is nothing to propose. - Couldn't ask the group to sign these relays. - Read - Write - General - Messages - Search - Blocked - Where the group publishes, and where a reader should look for it. - Where a message addressed to the group should be sent. - The relays a search of the group's work runs against. - Relays the group will not talk to. - A group signs and cannot decrypt, so every list here is public — including the blocked one, which most clients keep private. - Signed %1$s - Posts - Add post - Propose post - This group hasn't posted anything yet. - - No posts yet - 1 post - %1$s posts - What should the group say? - The group signs a post, so it takes a quorum. It goes out in the group's name, not yours. - This group has no shared key, so it cannot sign a post. Run a shared key ceremony first. - A post needs something to say. - Couldn't ask the group to sign this post. - Posted %1$s - A reply - Propose event - Paste an unsigned Nostr event for the group to sign. It is filed by kind: a profile (kind 0), a post (kind 1) or a relay list. - The group signs it, so it takes a quorum. The author is the group and the time is now, whatever the paste says about either. - This group has no shared key, so it cannot sign an event. Run a shared key ceremony first. - Couldn't ask the group to sign this event. - Unsigned event - {"kind": 1, "tags": [], "content": "…"} - What the group would sign - Kind %1$s - That isn't JSON. - An event is a JSON object with a kind, tags and content. - An event needs a kind. - Kind %1$s has nowhere to go on the group's screen. It can file kinds %2$s. - Tags must be a list of lists of strings. - Content must be text. - The content isn't a profile. A kind 0 carries a JSON object of profile fields. Ask again - - Broadcast - 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. - Where the group has said it lives is filled in. Add or remove relays before sending. - No relays to broadcast to. Add one above. - Add a relay to broadcast to. - Sending… - Accepted - Rejected: %1$s - Couldn't send: %1$s - No answer - Accepted by %1$s of %2$s relays. - Copy raw JSON - Copied the raw JSON A password-protected key (ncryptsec) is not supported yet. Decrypt it in the app it came from and paste the nsec. Enter a recovery phrase or an nsec to sign in. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index b82033cd..1c7104d5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -23,9 +23,10 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupRelaySet +import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent +import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent +import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent +import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent import com.vitorpamplona.quartz.nipC7Chats.ChatEvent import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents @@ -411,53 +412,6 @@ data class ChatMessage( */ const val TYPE_SUBGROUP_CERTIFIED = "subgroupCertified" - /** - * The group signed what it says about itself on nostr. - * - * A system line rather than a bubble, for the reason every group-signed - * line is one: nobody said it, the group signed it. Whoever filled the - * form in proposed it and a quorum agreed, and the transcript of that - * happening is the signing session's own -- this is the line saying what - * the group now is, which is worth having in the room because a rename is - * the kind of thing members should not have to go looking for. - * - * Written only for a profile the *room* signed. A kind:0 authored by - * anybody else that reaches this room is a member's own profile - * travelling as a rumor, which is not the group saying anything. - */ - const val TYPE_GROUP_PROFILE_SIGNED = "groupProfileSigned" - - /** - * The group signed where it lives on nostr. - * - * One line per list, so a session that changed three of them writes three. - * They are not three accounts of one thing -- each names which list was - * agreed, which is the part a reader needs -- and `applyInnerEvent` is - * handed one event at a time with no way to know it was in a batch anyway. - */ - const val TYPE_GROUP_RELAYS_SIGNED = "groupRelaysSigned" - - /** - * Every line about the group's own nostr identity, for the one check the - * transcript dispatches on. - * - * The profile and the relay lists together, because they are the same kind - * of statement -- the group's account of itself, signed by the group -- and - * the transcript does the same thing with both. A type missing from here - * renders as a chat bubble, silently, looking exactly like somebody having - * said "The group is now called Translation collective". - */ - /** - * The group signed something to say publicly, in its own name. - * - * A system line rather than a bubble, like the other two -- nobody said it, - * the group signed it -- and the line names the post rather than repeating - * it, because the post itself is on the group's screen where it can be read - * whole. A quote here would be the same words twice with the second copy - * unable to say who agreed to them. - */ - const val TYPE_GROUP_POST_SIGNED = "groupPostSigned" - /** * Lines the curated-lists feature wrote: the group signing a list's schema, * and an entry into one. The feature is gone and nothing writes either any @@ -468,6 +422,15 @@ data class ChatMessage( private const val TYPE_LEGACY_GROUP_SCHEMA_SIGNED = "groupSchemaSigned" private const val TYPE_LEGACY_GROUP_ENTRY_CURATED = "groupEntryCurated" + /** + * Lines the group's nostr profile, relay lists and posts wrote. Those + * features are gone too, and these stay for the same reason: rows already + * in a transcript carry them and have to stay system lines. + */ + private const val TYPE_LEGACY_GROUP_PROFILE_SIGNED = "groupProfileSigned" + private const val TYPE_LEGACY_GROUP_RELAYS_SIGNED = "groupRelaysSigned" + private const val TYPE_LEGACY_GROUP_POST_SIGNED = "groupPostSigned" + /** * The group opened a wallet. * @@ -485,10 +448,15 @@ data class ChatMessage( */ const val TYPE_GROUP_TRANSACTION_CONFIRMED = "groupTransactionConfirmed" + /** + * Every line the group signed, for the one check the transcript + * dispatches on. A type missing from here renders as a chat bubble, + * silently, looking exactly like somebody having said it. + */ val GROUP_IDENTITY_TYPES = setOf( - TYPE_GROUP_PROFILE_SIGNED, - TYPE_GROUP_RELAYS_SIGNED, - TYPE_GROUP_POST_SIGNED, + TYPE_LEGACY_GROUP_PROFILE_SIGNED, + TYPE_LEGACY_GROUP_RELAYS_SIGNED, + TYPE_LEGACY_GROUP_POST_SIGNED, TYPE_LEGACY_GROUP_SCHEMA_SIGNED, TYPE_LEGACY_GROUP_ENTRY_CURATED, TYPE_GROUP_WALLET_OPENED, @@ -1094,10 +1062,8 @@ data class ChatMessage( createdAt: Instant, groupSignedEventId: HexKey? = null, ): ChatMessage? { - // The last resort, named because one arm reaches it deliberately rather - // than by falling off the end: a kind:1 the room did not sign is a - // member's own note travelling through the room, and it has always - // rendered as this. See the `TextNoteEvent` arm. + // The last resort: raw JSON in a bubble, the only trace an + // unrecognised payload leaves. fun unsupported() = ChatMessage( giftWrapPayloadId = null, messageType = "unsupported", @@ -1219,103 +1185,6 @@ data class ChatMessage( ) } - // The group saying who it is on nostr. A room's id is the pubkey - // it signs as, so a group has an identity from the moment it has a - // key; this is the kind:0 describing it, signed by the group's own - // quorum like everything else it says. - // - // **Only when the room itself signed it.** This arm is reached both - // from a completed signing session, where the author is the room by - // construction, and from an arriving inner event, where any member - // could have sent a rumor of this kind -- and it cannot tell which. - // A member's own kind:0 travelling through a room is their profile, - // not the group's, and gets no line here. - // - // No row is written. The event is already on file as a - // `GroupSignedEvent` -- `FrostSigningManager.complete` records the - // batch before it applies it -- and `GroupNostrProfile` reads the - // group's profile straight off those. A `Profile` row is not an - // option anyway: it hangs off `NostrEvent` by foreign key, and a - // group-signed event is not one. - MetadataEvent.KIND -> { - if (!event.pubKey.equals(groupId, ignoreCase = true)) return null - - val profile = GroupNostrProfile.of( - signedEvent = GroupSignedEvent.fromEvent(event, chatRoomId = groupId), - chatRoomId = groupId, - ) ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_PROFILE_SIGNED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = profile.name()?.let { "The group is now called $it" } - ?: "The group signed a new profile for itself" - ) - } - - // The group saying something publicly, in its own name -- which - // is a different thing from a member saying something in the room. - // A room's messages are `ChatEvent`s; this is a kind:1 authored by - // the room's own key, so any reader can check the group said it and - // that no single member could have. - // - // Verified like the arms below and for the same reason: a rumor - // carries an empty signature and any pubkey its sender likes, so an - // author check alone would let one member put words in the group's - // mouth in its own transcript. - // - // **Unlike those arms, a kind:1 that fails falls through to - // `unsupported` rather than vanishing.** A member's kind:0 or relay - // list passing through a room is identity plumbing nobody sent on - // purpose and silence is the right treatment; a kind:1 is content, - // somebody meant it, and it has rendered as an unsupported event - // since before any of this existed. Dropping it here would be this - // change quietly deleting messages it has no business touching. - TextNoteEvent.KIND -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return unsupported() - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_POST_SIGNED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group posted in its own name" - ) - } - - // The group saying where it lives on nostr: which relays carry - // its work, take its messages, answer a search of it, and which it - // will not talk to. - // - // **Verified, not just attributed.** This arm is reached from a - // completed signing session, where the author is the room by - // construction, and from an arriving inner event, where it is - // whatever the sender wrote -- and it cannot tell which. A rumor - // carries an empty signature and any pubkey its sender likes, so an - // author check alone would let one member put "the group signed its - // general relay list" in the transcript. `verifies` is what makes - // the line mean what it says: the room's key over these tags. - // - // A member's own relay list travelling through the room fails the - // author half and gets no line, which is right -- it is their list, - // not the group's. - // - // No row is written, and nothing is parsed beyond the check. The - // events are already on file as `GroupSignedEvent` and - // `GroupRelayList` reads the lists straight off those; this arm - // exists so a signed relay list is a line in the transcript rather - // than raw JSON in a bubble. // The group opening a wallet. Checked the whole way -- the room's // signature, and the statement rederiving from the room's own key -- // because a line saying "the group opened a wallet" is a line people @@ -1341,25 +1210,17 @@ data class ChatMessage( ) } - in GroupRelaySet.KINDS -> { - val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) - if (!signed.verifies()) return null - - val set = GroupRelaySet.entries.firstOrNull { it.kind == event.kind } - ?: return null - - ChatMessage( - giftWrapPayloadId = null, - messageType = TYPE_GROUP_RELAYS_SIGNED, - marmotGroupEventId = marmotGroupEventId, - marmotInnerEventId = marmotInnerEventId, - senderPublicKey = senderPublicKey, - isUserMessage = isUserMessage, - chatRoomId = groupId, - createdAt = createdAt, - content = "The group signed its ${set.name.lowercase()} relay list" - ) - } + // A profile or a relay list -- the group's or a member's own -- + // travelling through the room. The app no longer reads either as + // the group's, and both are identity plumbing nobody sends into a + // room on purpose, so neither is a line nor a raw-JSON bubble: a + // signing session an older build opened for one ends in silence. + // A kind:1 is content, and keeps the bubble it always had. + MetadataEvent.KIND, + AdvertisedRelayListEvent.KIND, + ChatMessageRelayListEvent.KIND, + SearchRelayListEvent.KIND, + BlockedRelayListEvent.KIND -> null // v2's two non-chat kinds. A kind:1210 that arrives is one member's // assertion about what the group's state became, and this device diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt index e53667de..6a229ee4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/GroupSignedEvent.kt @@ -36,12 +36,6 @@ import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent * columns are `NostrEvent`'s so that what is stored is an event rather than a * summary of one, which is what makes [verifies] answerable from the row alone. * - * The one way one reaches a relay is a member sending it there by hand -- from - * `BroadcastGroupSignedEventScreen`, or every accepted entry at once from the - * entries screen -- and that path serialises the row straight to the pool - * without ever making a `NostrEvent` of it -- see - * `BroadcastGroupSignedEventViewModel` for why a row would be the wrong shape. - * * ### The derivation path * * [publicKey] is the group's threshold key walked to [derivationPath], and for a diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index 67f0128e..72f1d565 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -19,10 +19,6 @@ import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.database.model.ChatMessage import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -39,8 +35,6 @@ import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray import com.vitorpamplona.quartz.nip01Core.core.Kind import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync @@ -143,50 +137,6 @@ class DatabaseChatRepository( null } - override suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? = try { - GroupNostrProfile.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, MetadataEvent.KIND), - chatRoomId = chatRoomId, - ) - } catch (e: Throwable) { - // Reading one parses content off the wire and checks a signature, and a - // room that shows no profile is wrong and survivable where one that will - // not open is neither -- the same trade the readings above make. - logger.e("Error reading the nostr profile of $chatRoomId", e) - null - } - - override suspend fun groupRelayLists(chatRoomId: String): List = try { - // One query per set rather than one for the room: the four kinds are - // indexed and a room's whole signed history is every artifact, chunk and - // translation it has ever agreed. - GroupRelaySet.entries.map { set -> - GroupRelayList.newestAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, set.kind), - chatRoomId = chatRoomId, - set = set, - ) - } - } catch (e: Throwable) { - logger.e("Error reading the relay lists of $chatRoomId", e) - // Four unsigned, empty sets: the screen draws "not set yet" rather than - // failing to draw, which is the trade every reading above makes. - GroupRelayList.allAmong(emptyList(), chatRoomId) - } - - override suspend fun groupPosts(chatRoomId: String): List = try { - GroupPost.newestFirstAmong( - signedEvents = database.groupSignedEventDao() - .getByChatRoomIdAndKind(chatRoomId, TextNoteEvent.KIND), - chatRoomId = chatRoomId, - ) - } catch (e: Throwable) { - logger.e("Error reading the posts of $chatRoomId", e) - emptyList() - } - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try { GroupWalletManager.walletFor(database, chatRoomId, chain) } catch (e: Throwable) { @@ -201,13 +151,6 @@ class DatabaseChatRepository( null } - override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { - database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } - } catch (e: Throwable) { - logger.e("Error reading the signed event $id of $chatRoomId", e) - null - } - override suspend fun canSign(chatRoomId: String): Boolean = try { FrostSigningManager.canSign(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index b56c419d..7618d490 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -959,7 +959,7 @@ object FrostSigningManager { * transaction nobody can mine, and `correctlySpends` is the only check that * asks the question the network will. Nothing is applied and nothing is * filed as a `GroupSignedEvent` -- this is not an event, and the chronicle - * and the broadcast screen read that table. + * reads that table. */ private suspend fun completeSpend( database: BennuDatabase, @@ -1593,8 +1593,7 @@ object FrostSigningManager { // wire from here: a signed event authored by the threshold key cannot // travel as an inner event anyway, because the outbound pipeline // re-authors rumors as their sender and would strip the group's - // signature off. Sending one to relays is a member's separate act, - // from `BroadcastGroupSignedEventScreen`, off the recorded row. + // signature off. signedEvents.forEach { applySignedEvent(database, session, it, recorded) } announce( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt deleted file mode 100644 index a6a8fd2b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/EventPublishTransport.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.network.relays - -import kotlinx.coroutines.flow.Flow -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.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(com.machankura.bennu.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) - suspend fun publishEvent(nostrEvent: NostrEvent, relays: Set): Flow -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt index 1c85c200..1b45855e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/network/relays/RelaysSocketManager.kt @@ -32,7 +32,7 @@ class RelaysSocketManager( private val relayRepository: com.machankura.bennu.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, EventPublishTransport { +) : LiveSubscriptionTransport { val logger = Logger.withTag("RelaysSocketManager") private val relayPoolsMutex = Mutex() @@ -116,7 +116,7 @@ class RelaysSocketManager( } @Throws(com.machankura.bennu.compose.exceptions.NostrPublishException::class, kotlin.coroutines.cancellation.CancellationException::class) - override suspend fun publishEvent(nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, relays: Set): Flow { + suspend fun publishEvent(nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, relays: Set): Flow { logger.d("publishEvent: $nostrEvent") return relayPool.publishEvent( nostrEvent = nostrEvent, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt deleted file mode 100644 index b8b49037..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposal.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.network.serialization.CommonJson -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import kotlinx.serialization.json.JsonArray -import kotlinx.serialization.json.JsonElement -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.intOrNull - -/** - * An unsigned event a member pasted for the group to sign, read and checked - * before a quorum is asked for it. - * - * The typed editors -- the profile form, the post composer, the relay - * editor -- each build one kind of event and know what it needs. This is the - * untyped way in: the event as JSON, the way another tool prints it, pasted - * whole. What comes out is the same thing the editors - * produce, a kind, tags and content for `FrostSigningRepository.proposeSigning`, - * and it is filed the same way when the quorum signs: `FrostSigningManager.complete` - * records it as a `GroupSignedEvent` and the group's screen reads its profile, - * posts and relay lists straight off those by kind. - * - * ### What is ignored - * - * `id`, `pubkey`, `sig` and `created_at`. The group is the author -- the - * session resolves the room's key and hashes the id over it -- and the time is - * when the session opens, which is what every typed editor does too. A pasted - * `created_at` in particular has to go: the kinds here are replaceable or - * addressable, so a stale one would make the new event *older* than the last and - * the proposal would look as though it did nothing. The screen says so. - * - * ### What is refused, and why before rather than after - * - * Only kinds the group's screen has a place for, and only events that place - * would accept. A signature is the most expensive thing this app does, and the - * readers refuse rather than repair: a kind 0 whose content is not a profile - * or a blank post would each be signed, filed and shown nowhere, with nothing - * to tell the member their quorum was spent on nothing. So every check a reader makes is made here first, on the paste. - */ -object GroupEventProposal { - /** - * The kinds a pasted event may be: exactly the ones the group's screen reads. - * - * Not the kinds `ChatMessage.applyInnerEvent` has an arm for. A subgroup - * certificate or a key state event has invariants a paste cannot be trusted - * to meet and a place in the room's life that a form is not. The line is - * "has a section on the - * group's screen", because that is where a member goes to see it landed. - */ - val ACCEPTED_KINDS: Set = - setOf(MetadataEvent.KIND, TextNoteEvent.KIND) + GroupRelaySet.KINDS - - sealed interface Reading - - /** An event the group could sign and the screen could show. */ - class Ready( - val kind: Kind, - val tags: Array>, - val content: String, - ) : Reading { - /** - * The event as the signing screen will describe it, for a preview before - * the button is pressed. The id, author and signature are placeholders: - * `ProposedEvent.summarize` reads none of them. - */ - fun preview(): Event = Event( - id = "", - pubKey = "", - createdAt = 0, - kind = kind, - tags = tags, - content = content, - sig = "", - ) - } - - /** Why the paste cannot be proposed as it is. */ - sealed interface Refused : Reading { - data object NotJson : Refused - - /** JSON, but an array, a string, a number -- anything but an object. */ - data object NotAnObject : Refused - - data object NoKind : Refused - - data class KindNotAccepted(val kind: Kind) : Refused - - /** `tags` present but not a list of lists of strings. */ - data object TagsMalformed : Refused - - /** `content` present but not a string. */ - data object ContentNotText : Refused - - /** A kind 0 whose content will not parse as a profile. */ - data object ProfileUnreadable : Refused - - /** A kind 1 with nothing to say, which the posts reader would drop. */ - data object PostBlank : Refused - } - - private const val KEY_KIND = "kind" - private const val KEY_TAGS = "tags" - private const val KEY_CONTENT = "content" - - /** The paste as something the group could sign, or the reason it is not. */ - fun read(json: String): Reading { - val element = runCatching { CommonJson.parseToJsonElement(json) }.getOrNull() - ?: return Refused.NotJson - - val obj = element as? JsonObject ?: return Refused.NotAnObject - - // A number or a numeric string: relays write the former and a hand - // types either, and there is nothing to be gained by refusing "1". - val kind = (obj[KEY_KIND] as? JsonPrimitive)?.intOrNull ?: return Refused.NoKind - if (kind !in ACCEPTED_KINDS) return Refused.KindNotAccepted(kind) - - val tags = when (val raw = obj[KEY_TAGS]) { - null -> emptyArray() - else -> readTags(raw) ?: return Refused.TagsMalformed - } - - val content = when (val raw = obj[KEY_CONTENT]) { - null -> "" - else -> (raw as? JsonPrimitive)?.takeIf { it.isString }?.content - ?: return Refused.ContentNotText - } - - return when (kind) { - // An empty kind 0 is a profile the group has wiped, which it is - // entitled to do; content that is not JSON is not a profile at all. - // The same line `GroupNostrProfile.of` draws. - MetadataEvent.KIND -> if (metadataOf(tags, content) == null) { - Refused.ProfileUnreadable - } else { - Ready(kind, tags, content) - } - - // The line `AddGroupPostViewModel.proposePost` draws, for the reason - // it gives: a blank post cannot be told from a broken one and, kind:1 - // not being replaceable, cannot be un-said. - TextNoteEvent.KIND -> if (content.isBlank()) { - Refused.PostBlank - } else { - Ready(kind, tags, content) - } - - // A relay list with no relay in it is a list the group has withdrawn, - // which the relays card shows as "no relays" rather than as nothing. - else -> Ready(kind, tags, content) - } - } - - private fun readTags(raw: JsonElement): Array>? { - val outer = raw as? JsonArray ?: return null - - return outer.map { tag -> - val inner = tag as? JsonArray ?: return null - inner.map { value -> - (value as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull ?: return null - }.toTypedArray() - }.toTypedArray() - } - - private fun metadataOf(tags: Array>, content: String) = MetadataEvent( - id = "", - pubKey = "", - createdAt = 0, - tags = tags, - content = content, - sig = "", - ).contactMetaData() -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt deleted file mode 100644 index 011964df..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfile.kt +++ /dev/null @@ -1,196 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import kotlin.time.Instant - -/** - * The kind:0 a group signed about itself, as the group signed it. - * - * A Marmot room's id *is* the nostr pubkey it signs as -- see - * `docs/shared-key-derivation.md`, where those are one value -- so the group has - * an identity on nostr whether or not it has ever said anything about it. This is - * what it says: a name, a picture, a line about what the group is for, authored by - * the group rather than by whichever member typed it. - * - * ### Why this reads off [GroupSignedEvent] and not off `Profile` - * - * A `Profile` row hangs off a `NostrEvent` by foreign key, and a group-signed - * event is not a `NostrEvent`: no member sent it, it never travelled on the wire - * as itself, and the outbound pipeline would re-author it as its sender and strip - * the group's signature off. See `GroupSignedEvent`, which exists for exactly the - * events in that position. So the group's profile lives where the group's other - * signed statements live, and this is the reading of it. - * - * The consequence worth stating: **nothing here reaches a relay by being signed.** - * A member's kind:0 is published and is how the rest of nostr learns their name; a - * group's is signed and kept, and every device that followed the signing session - * -- or was handed the event afterwards -- holds it. It reaches a relay when a - * member sends it there from `BroadcastGroupSignedEventScreen`, which serialises - * the signed row directly rather than making a `NostrEvent` row for an event no - * member authored -- a decision this still does not make. - * - * ### What a reading has to earn - * - * [GroupSignedEvent.verifies] and nothing less: the author has to be the room, the - * id has to be the hash of the fields beside it, and the signature has to verify. - * That is what makes this the *group's* profile rather than a kind:0 that happened - * to be filed against the room -- and it is checkable from the row alone, with no - * ceremony or key state to consult first. - * - * A room never derived from its group's key signs as the bare threshold key rather - * than as its own id, so it has no profile *for its own pubkey* and gets none - * here. That is the derivation's limit rather than this reader's, and it is the - * same limit `GroupSignedEvent.verifies` documents. - */ -data class GroupNostrProfile( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, - /** Its content parsed: the fields nostr clients read a profile out of. */ - val metadata: UserMetadata, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is what decides the newest of two. */ - val signedAt: Instant get() = signedEvent.createdAt - - /** - * What to call the group, or null when it has published no name. - * - * `display_name` before `name`, which is what `UserMetadata.anyName` does and - * what every other nostr client does. Null rather than the pubkey: a caller - * showing this beside the pubkey would otherwise show it twice. - */ - fun name(): String? = metadata.anyName()?.takeIf { it.isNotBlank() } - - fun about(): String? = metadata.about?.takeIf { it.isNotBlank() } - - fun picture(): String? = metadata.picture?.takeIf { it.isNotBlank() } - - fun banner(): String? = metadata.banner?.takeIf { it.isNotBlank() } - - fun website(): String? = metadata.website?.takeIf { it.isNotBlank() } - - fun nip05(): String? = metadata.nip05?.takeIf { it.isNotBlank() } - - fun lud16(): String? = metadata.lud16?.takeIf { it.isNotBlank() } - - /** The event as the group signed it, for [MetadataEvent.updateFromPast]. */ - fun asMetadataEvent(): MetadataEvent = signedEvent.toEvent().let { event -> - MetadataEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } - - companion object { - /** - * The reading of one signed event, or null when it is not one of these. - * - * Three ways to be null and they are all the same refusal: the wrong kind, - * a signature that does not check out as [chatRoomId]'s, or content that - * will not parse as a profile. A caller gets a profile the group really - * signed or gets nothing. - */ - fun of(signedEvent: GroupSignedEvent, chatRoomId: String): GroupNostrProfile? { - if (signedEvent.kind != MetadataEvent.KIND) return null - if (!signedEvent.verifies()) return null - - // An empty kind:0 parses to an empty profile rather than to null -- - // wiping a profile is a thing groups are entitled to do, and quartz - // reads it as the blank one it is. Null here is a parse failure. - val metadata = MetadataEvent( - id = signedEvent.id, - pubKey = signedEvent.publicKey, - createdAt = signedEvent.createdAt.epochSeconds, - tags = signedEvent.tags, - content = signedEvent.content, - sig = signedEvent.signature, - ).contactMetaData() ?: return null - - return GroupNostrProfile(signedEvent = signedEvent, metadata = metadata) - } - - /** - * The newest profile [chatRoomId] signed among [signedEvents], or null if - * it signed none. - * - * Newest by the timestamp the group signed at, with the id breaking a tie, - * because kind:0 is replaceable: a group that edits its profile signs a - * second one and the second is the answer. Two devices reading the same - * events in whatever order the queries hand them over have to agree on - * which, and a tie on the second is not rare enough to leave to luck. - * - * Takes the events rather than fetching them so the same question can be - * asked of a query's result or of a flow's emission. - */ - fun newestAmong( - signedEvents: List, - chatRoomId: String, - ): GroupNostrProfile? = - signedEvents - .asSequence() - .mapNotNull { of(it, chatRoomId) } - .maxWithOrNull( - compareBy({ it.signedAt }, { it.signedEvent.id }) - ) - - /** - * The event to ask the group to sign for a profile with these fields. - * - * Built from [latest] where the group has one, so a field this app does not - * offer -- a birthday, a CLINK offer, whatever a future NIP adds -- survives - * an edit instead of being dropped by it. That is `updateFromPast`'s whole - * job, and reaching for `createNew` on a group that already has a profile - * would quietly wipe every such field. - * - * Blank means delete, which is `MetadataEvent`'s own rule for these - * arguments: an empty string removes the key and null leaves it alone. The - * screen sends what its fields hold, so clearing one clears it in the - * profile -- which is the only way to *un*-say something a group has said. - * - * [name] is written to both `name` and `display_name`, which are the two - * fields readers pick a name out of and which disagree at their peril. A - * group whose `display_name` was set by some other tool and whose `name` was - * edited here would keep answering to the old one in every client that - * prefers `display_name` -- an edit that visibly does not take. One field on - * the form, both keys in the event. - */ - fun template( - latest: GroupNostrProfile?, - name: String, - about: String, - picture: String, - website: String, - nip05: String, - lud16: String, - ): EventTemplate = latest?.let { - MetadataEvent.updateFromPast( - latest = it.asMetadataEvent(), - name = name, - displayName = name, - about = about, - picture = picture, - website = website, - nip05 = nip05, - lnAddress = lud16, - ) - } ?: MetadataEvent.createNew( - name = name, - displayName = name, - about = about, - picture = picture, - website = website, - nip05 = nip05, - lnAddress = lud16, - ) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt deleted file mode 100644 index a21ad3c8..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupPost.kt +++ /dev/null @@ -1,121 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import kotlin.time.Instant - -/** - * A kind:1 the group signed: something it said publicly, as itself. - * - * The room's id is the pubkey it signs as, so a note authored by that key is the - * *group* posting rather than a member posting in the group. Those are different - * things and the room already has the second one -- the transcript. This is the - * first: a statement the group put a quorum's signature to, which any reader can - * check came from the group and not from whoever typed it. - * - * ### Why this is not a `Post` row - * - * `Post` hangs off both `NostrEvent` and `Profile` by foreign key, and a group has - * neither: a group-signed event is not a `NostrEvent` -- see `GroupNostrProfile`, - * which gives the reasoning at length -- and the group has no `Profile` row for the - * same reason. So a group's posts live where the group's other signed statements - * live, and this is the reading of them. - * - * ### Nothing here has reached a relay - * - * The same caveat `GroupNostrProfile` and `GroupRelayList` carry, and it bites - * hardest here: a post is the one kind of statement whose entire purpose is to be - * read by people outside the group. `FrostSigningManager.complete` applies signed - * events locally and puts nothing on the wire, so for now a group's posts are - * visible to its members and to nobody else. The relay lists beside them say where - * they should go; sending them is a job that does not exist yet. - */ -data class GroupPost( - /** The group's statement, whole, with the signature that makes it one. */ - val signedEvent: GroupSignedEvent, -) { - /** The group's nostr identity, which for a derived room is also its id. */ - val publicKey: HexKey get() = signedEvent.publicKey - - /** When the group signed it, which is the order posts are read in. */ - val postedAt: Instant get() = signedEvent.createdAt - - /** What the group said. */ - val content: String get() = signedEvent.content - - /** - * Whether this is the group speaking rather than answering. - * - * A kind:1 with no `e` tag starts a thread; one with them is a reply. Nothing - * here writes a reply yet -- the composer builds a bare note -- so this exists - * to keep an imported or chronicled reply from being drawn as an announcement. - */ - fun isNewThread(): Boolean = asTextNoteEvent().isNewThread() - - /** The event as the group signed it. */ - fun asTextNoteEvent(): TextNoteEvent = signedEvent.toEvent().let { event -> - TextNoteEvent( - id = event.id, - pubKey = event.pubKey, - createdAt = event.createdAt, - tags = event.tags, - content = event.content, - sig = event.sig, - ) - } - - companion object { - /** - * The reading of one signed event, or null when it is not one of these. - * - * The same gate the profile and the relay lists use: the wrong kind, or a - * signature that does not check out as [chatRoomId]'s, and a caller gets - * nothing. A kind:1 a member sent into the room is that member's note, not - * the group's, and fails on the author. - */ - fun of(signedEvent: GroupSignedEvent, chatRoomId: String): GroupPost? { - if (signedEvent.kind != TextNoteEvent.KIND) return null - if (!signedEvent.verifies()) return null - - return GroupPost(signedEvent) - } - - /** - * Every post [chatRoomId] signed among [signedEvents], newest first. - * - * Newest first because that is how a feed is read, and the id breaks a tie - * so two devices holding the same posts show them in the same order. Unlike - * a profile or a relay list these accumulate rather than replace: kind:1 is - * not replaceable, so a second post stands beside the first. - * - * Blank posts are dropped. A signed note with nothing in it renders as an - * empty card that cannot be told from a broken one, and the composer will - * not produce one -- so anything that reaches here empty came from - * somewhere this app does not control. - */ - fun newestFirstAmong( - signedEvents: List, - chatRoomId: String, - ): List = - signedEvents - .mapNotNull { of(it, chatRoomId) } - .filter { it.content.isNotBlank() } - .sortedWith(compareByDescending { it.postedAt }.thenByDescending { - it.signedEvent.id - }) - - /** - * The event to ask the group to sign for a post saying [note]. - * - * A bare kind:1: no reply tags, no mentions, no subject. What the group is - * doing here is speaking, and every tag `TextNoteEvent.build` can add - * describes a relationship to something else -- a thread to reply into, a - * pubkey to notify -- which a group's first way of posting does not have - * and should not guess at. - */ - fun template(note: String): EventTemplate = - TextNoteEvent.build(note = note.trim()) - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt deleted file mode 100644 index ec817e28..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/GroupRelayList.kt +++ /dev/null @@ -1,279 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.vitorpamplona.quartz.nip01Core.core.Kind -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.displayUrl -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.isLocalHost -import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate -import com.vitorpamplona.quartz.nip17Dm.settings.ChatMessageRelayListEvent -import com.vitorpamplona.quartz.nip50Search.SearchRelayListEvent -import com.vitorpamplona.quartz.nip51Lists.relayLists.BlockedRelayListEvent -import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayInfo -import com.vitorpamplona.quartz.nip65RelayList.tags.AdvertisedRelayType -import kotlin.time.Instant -import com.vitorpamplona.quartz.nip51Lists.relayLists.tags.RelayTag as Nip51RelayTag -import com.vitorpamplona.quartz.nip17Dm.settings.tags.RelayTag as Nip17RelayTag - -/** - * Where a group lives on nostr, as the group itself has said. - * - * A Marmot room's id is the pubkey it signs as, so the group is an author like any - * other and the same four relay lists apply to it: where it publishes and is read - * from, where its messages arrive, where it can be searched for, and what it will - * not talk to. Each is a replaceable event of its own kind, so each is agreed -- - * and can be missing -- separately. - * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], for the - * reasons `GroupNostrProfile` gives at length: a group-signed event is not a - * `NostrEvent`, and only an event the room itself authored is the group speaking. - * - * ### Nothing here reaches a relay by being signed - * - * The lists say where the group's work *should* go; sending it there is a separate - * act, taken by a member one event at a time from `BroadcastGroupSignedEventScreen`, - * and the General list is what that screen fills its relay picker from. See - * `GroupNostrProfile`, which carries the same caveat for the same reason. - * - * ### Public tags only, and not by preference - * - * NIP-51 puts a relay list's entries in the encrypted half by default -- a blocked - * list especially, since who you refuse to talk to is nobody's business. A group - * cannot use it. The encryption is NIP-44 to the author's own key, and there is no - * ECDH for a FROST threshold key here: the group can sign and cannot decrypt. So - * every list is written in public tags, which is a real difference from what a - * person's client would write and is worth knowing before blocking anything. - */ -data class GroupRelayList( - val set: GroupRelaySet, - /** - * The group's statement, or null for a set it has never agreed. - * - * Null and an empty [relays] are different states: never said, versus said and - * said nothing. A group that signs an empty list has withdrawn the one it had. - */ - val signedEvent: GroupSignedEvent?, - val relays: List, -) { - /** When the group signed it, or null for a set it has never agreed. */ - val signedAt: Instant? get() = signedEvent?.createdAt - - /** Whether the group has ever put its key to this set. */ - val isAgreed: Boolean get() = signedEvent != null - - companion object { - /** - * The reading of one signed event as [set], or null when it is not one. - * - * The same three refusals as `GroupNostrProfile.of`: the wrong kind, a - * signature that is not [chatRoomId]'s, or tags that carry no relay. - */ - fun of( - signedEvent: GroupSignedEvent, - chatRoomId: String, - set: GroupRelaySet, - ): GroupRelayList? { - if (signedEvent.kind != set.kind) return null - if (!signedEvent.verifies()) return null - - return GroupRelayList( - set = set, - signedEvent = signedEvent, - relays = set.parse(signedEvent.tags), - ) - } - - /** - * The newest list [chatRoomId] signed for [set] among [signedEvents]. - * - * Never null: a set the group has never agreed reads back as an unsigned, - * empty list rather than as an absence, so a caller always has a row per - * set to show and [isAgreed] is what separates the two. - * - * Newest by the group's own timestamp with the id breaking a tie, for the - * reason `GroupNostrProfile.newestAmong` gives: these are replaceable, and - * two devices reading the same events in different orders have to agree. - */ - fun newestAmong( - signedEvents: List, - chatRoomId: String, - set: GroupRelaySet, - ): GroupRelayList = - signedEvents - .asSequence() - .mapNotNull { of(it, chatRoomId, set) } - .maxWithOrNull(compareBy({ it.signedAt }, { it.signedEvent?.id })) - ?: GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - - /** Every set, in the order the editor shows them. */ - fun allAmong( - signedEvents: List, - chatRoomId: String, - ): List = - GroupRelaySet.entries.map { newestAmong(signedEvents, chatRoomId, it) } - } -} - -/** - * One relay in one of a group's lists. - * - * [read] and [write] mean something only in [GroupRelaySet.General], which is the - * one list NIP-65 gives markers to; everywhere else a relay is simply in the list - * and both are true. They are kept on the shared type rather than split into two - * so that the editor has one row shape and one add path. - * - * **Neither is not a state.** NIP-65 writes a bare `r` tag for both, `read` for - * read-only and `write` for write-only, and has nothing at all for a relay that is - * neither -- a relay you will not read from and will not write to is one you have - * removed. The editor enforces that rather than this dropping it silently. - */ -data class GroupRelay( - val url: NormalizedRelayUrl, - val read: Boolean = true, - val write: Boolean = true, -) { - /** The host, for a list that is read rather than copied. */ - fun displayUrl(): String = url.displayUrl() -} - -/** - * The relay lists a group keeps, and what each one is for. - * - * The four a person's client keeps, because a group is an author like any other and - * these are the four questions the network asks about one. - * - * **Key packages (MIP-00, kind 10051) are deliberately not here**, though this app - * writes one for every person. A key package is a device's offer to be added to an - * MLS group, and a group has no device and joins nothing -- so a group advertising - * where its key packages live would be pointing at a place that will always be - * empty, which is worse than saying nothing. See `MarmotKeyPackage`, which is keyed - * by member. - * - * **Relay feeds (kind 10012) are not here either**, for the harder reason: the list - * lives in the encrypted half and a threshold key cannot decrypt. See - * [GroupRelayList]'s note on public tags. - */ -enum class GroupRelaySet( - val kind: Kind, - /** Whether NIP-65's read and write markers apply, which is General alone. */ - val hasReadWriteMarkers: Boolean = false, -) { - /** - * NIP-65: where the group publishes and where a reader should look for it. - * - * The one that matters most and the only one with markers. Everything the group - * signs is addressed to whoever wants to read it, and this is the answer to - * where. - */ - General(AdvertisedRelayListEvent.KIND, hasReadWriteMarkers = true), - - /** NIP-17: where a message addressed to the group's key should be sent. */ - Messages(ChatMessageRelayListEvent.KIND), - - /** NIP-50: the relays the group would have a search of its work run against. */ - Search(SearchRelayListEvent.KIND), - - /** NIP-51: relays the group will not talk to, whatever else says otherwise. */ - Blocked(BlockedRelayListEvent.KIND), - ; - - /** - * What a group with nothing agreed starts the editor at. - * - * The app's own relay, which is where everything else this build publishes and - * reads already goes -- see `Relays.ephemeral`. A group seeded with nothing - * would be a group whose first proposal is an empty list, which says less than - * having never said anything at all. - * - * Blocked is the exception and starts empty on purpose: a default there is a - * refusal to talk to somebody that nobody in the group chose. - */ - fun defaults(): List = when (this) { - Blocked -> emptyList() - else -> listOf(GroupRelay(Relays.ephemeral)) - } - - /** The relays out of a signed event's tags, in the order the group wrote them. */ - fun parse(tags: Array>): List = when (this) { - General -> tags.mapNotNull(AdvertisedRelayInfo::parse).map { - GroupRelay( - url = it.relayUrl, - read = it.type.isRead(), - write = it.type.isWrite(), - ) - } - // Both nip51 lists and NIP-17's use a "relay" tag, and the two RelayTag - // classes that parse it are different classes in different packages. Named - // apart at the import so a reader can see which NIP each line is following. - Messages -> tags.mapNotNull(Nip17RelayTag::parse).map { GroupRelay(it) } - Search, Blocked -> tags.mapNotNull(Nip51RelayTag::parse).map { GroupRelay(it) } - }.distinctBy { it.url } - - /** - * The event to ask the group to sign for this set. - * - * Built from scratch rather than from the group's last one, which is the - * opposite of what `GroupNostrProfile.template` does and for a reason: a - * profile is a bag of independent fields where an unknown one is worth keeping, - * and a relay list is one list where the whole point of signing a new one is to - * replace it. Carrying a tag forward here would make a removal impossible. - * - * A relay that is neither read nor write is dropped rather than written, since - * NIP-65 cannot express one -- the editor does not allow the state, and this is - * the second line of that defence rather than the first. - */ - fun template(relays: List): EventTemplate<*> { - val tags = when (this) { - General -> relays.mapNotNull { relay -> - val type = when { - relay.read && relay.write -> AdvertisedRelayType.BOTH - relay.read -> AdvertisedRelayType.READ - relay.write -> AdvertisedRelayType.WRITE - else -> return@mapNotNull null - } - AdvertisedRelayInfo.assemble(relay.url, type) - } - Messages -> relays.map { Nip17RelayTag.assemble(it.url) } - Search, Blocked -> relays.map { Nip51RelayTag.assemble(it.url) } - } - - // Empty content throughout. For General and Messages that is all the kind - // has; for the two nip51 lists it is where the encrypted half would go, and - // a group has no encrypted half. See [GroupRelayList]. - return EventTemplate( - createdAt = kotlin.time.Clock.System.now().epochSeconds, - kind = kind, - tags = tags.toTypedArray(), - content = "", - ) - } - - companion object { - /** - * The kinds a group's relay lists are written as. - * - * A set rather than a walk of [entries], for `ChatMessage.applyInnerEvent`, - * whose dispatch is one `when` over an event's kind -- and a `when` branch - * has to be a constant expression rather than a predicate over an enum. - */ - val KINDS: Set = entries.map { it.kind }.toSet() - - /** - * [url] as a relay a group could actually be told to use, or null. - * - * Structural only, and deliberately narrow: `wss://` because a group's - * signed list is read by strangers over the open network and `ws://` would - * ask them to fetch it in the clear, and no loopback because a relay only - * this device can reach is not something to put a quorum's signature on. - * 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/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt index db522049..171fcc73 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleEvent.kt @@ -141,8 +141,7 @@ class ChronicleEvent( * - a `GroupKeyStateEvent` or a subgroup's birth certificate is a validly * signed statement about the group that anyone holding a copy could * replay -- see [ChronicleKinds]; - * - posts, profiles, relay lists and wallet statements have their own - * ways to a member who joins late, or none worth a chronicle. + * - wallet statements have their own way to a member who joins late. * * So the machinery stays and carries nothing: with an empty list a device * asks for no chronicle, sends none, and applies nothing from one that an diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt index 1587e43a..b53de693 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt @@ -15,9 +15,8 @@ import kotlin.time.Instant * threshold key -- [account] is what [GroupWalletStatementEvent.Reading.verifiedAgainst] * returned, never what the statement said. * - * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies], the way - * `GroupRelayList` is: only an event the room itself authored is the group - * speaking. + * Read off [GroupSignedEvent] and gated on [GroupSignedEvent.verifies]: only an + * event the room itself authored is the group speaking. */ data class GroupWallet( val signedEvent: GroupSignedEvent, @@ -51,9 +50,8 @@ data class GroupWallet( * The newest wallet the group opened on [chain] at [account], or null for * one it never has. * - * Newest by the group's own timestamp with the id breaking a tie, for the - * reason `GroupRelayList.newestAmong` gives: two devices reading the same - * events in different orders have to agree. + * Newest by the group's own timestamp with the id breaking a tie, because + * two devices reading the same events in different orders have to agree. */ fun newestAmong( signedEvents: List, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt index c00421d0..5d261517 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt @@ -37,7 +37,7 @@ import kotlin.time.Clock * * The xpub is every address and the whole balance, to whoever has it. Like the * signing kinds this only ever lives inside an encryption a relay cannot open, - * and the broadcast screen refuses it by kind -- see [NEVER_BROADCAST]. + * and nothing in the app sends a group-signed event to a relay. * * ### Why 30331 * @@ -50,9 +50,6 @@ import kotlin.time.Clock object GroupWalletStatementEvent { val KIND: Kind = 30331 - /** The kinds a member may never send to a relay, whatever the group signed. */ - val NEVER_BROADCAST: Set = setOf(KIND) - private const val D_TAG = "d" private const val CHAIN_TAG = "chain" private const val ACCOUNT_TAG = "account" diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 5e2d8aaa..d09c9fb9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -13,9 +13,6 @@ import com.machankura.bennu.compose.nostr.MarmotProfile import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.managers.MarmotGroupCreation import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.database.model.Participant import com.machankura.bennu.compose.database.model.intermdiate.LocalChatMessage import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom @@ -86,27 +83,6 @@ interface ChatRepository { */ suspend fun parentOf(chatRoomId: String): HexKey? - /** - * The kind:0 this group signed about itself, or null while it has signed - * none. - * - * The group's identity on nostr is the room's own id, so it has one to - * describe whether or not it ever has. Read off the group's signed events and - * verified there -- see `GroupNostrProfile` -- so a room shows the profile its - * own key signed or shows that it has none. - */ - suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? - - /** - * Where this group has said it lives on nostr: one entry per relay set, always - * all of them. - * - * A set the group has never agreed comes back unsigned and empty rather than - * missing, because "never said" is a state the screen has to show and a gap in - * a list is not one. See `GroupRelayList.isAgreed`. - */ - suspend fun groupRelayLists(chatRoomId: String): List - /** * The wallet this group has opened on [chain], or null when it has not -- * read off the group's signed statement and rederived from the room's key. @@ -119,27 +95,6 @@ interface ChatRepository { */ suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? - /** - * The kind:1s this group signed, newest first. - * - * The group speaking as itself, which is a different thing from a member - * speaking in the room -- the transcript is the second. Unlike the profile and - * the relay lists these accumulate rather than replace, so this is a list and - * an empty one means the group has said nothing publicly. - */ - suspend fun groupPosts(chatRoomId: String): List - - /** - * One event the group signed, as the group signed it, or null when this - * device does not hold it or it was signed in some other room. - * - * Scoped to the room rather than looked up by id alone, because the id - * arrives as a navigation argument and the screen it opens names a room in - * its title: an event from one room shown under another room's name would - * be a lie the signature check cannot catch, since both rooms' events verify. - */ - suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? - /** * Whether this device holds a share of the group's key, and so could take * part in signing for it. @@ -366,11 +321,6 @@ interface ChatRepository { override suspend fun parentOf(chatRoomId: String): HexKey? = null - override suspend fun groupNostrProfile(chatRoomId: String): GroupNostrProfile? = null - - override suspend fun groupRelayLists(chatRoomId: String): List = - GroupRelayList.allAmong(emptyList(), chatRoomId) - override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = null override suspend fun groupWalletAccount( @@ -378,13 +328,6 @@ interface ChatRepository { chain: Chain ): GroupWalletDerivation.Account? = null - override suspend fun groupPosts(chatRoomId: String): List = emptyList() - - override suspend fun groupSignedEvent( - chatRoomId: String, - id: HexKey - ): GroupSignedEvent? = null - override suspend fun canSign(chatRoomId: String): Boolean = false override suspend fun refuseSubgroup( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 19e2605f..dd93dc78 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -1,10 +1,7 @@ package com.machankura.bennu.compose.text import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent @@ -13,8 +10,8 @@ import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent * An event a group is being asked to sign, said in words. * * Shown as the thing rather than as an event: a member deciding whether to sign - * is deciding about a profile or a relay list, and "kind 10002" answers a - * question nobody asked. The raw kind stays for anything not recognised, since + * is deciding about a wallet or a subgroup, and "kind 30331" answers a question + * nobody asked. The raw kind stays for anything not recognised, since * refusing to describe an event is better than describing it wrongly. * * Not a composable, and deliberately: the same words appear on the signing @@ -59,39 +56,6 @@ object ProposedEvent { ).joinToString(" · ") ) - // The group's own profile. Named by what the group would be called and - // what it would say about itself, which is the whole of what is being - // decided; the JSON in the content is the one thing a signer should not - // have to read to find that out. - MetadataEvent.KIND -> Summary( - label = "Nostr profile", - detail = MetadataEvent( - event.id, event.pubKey, event.createdAt, event.tags, event.content, event.sig - ).contactMetaData()?.let { metadata -> - listOfNotNull( - metadata.anyName()?.takeIf { it.isNotBlank() }, - metadata.about?.takeIf { it.isNotBlank() } - ).joinToString(" · ").ifEmpty { "An empty profile" } - } ?: "Unreadable profile" - ) - - // A post in the group's name. The words are what is being decided, so - // they are the detail rather than a count of them -- the same call the - // translated-passage arm makes. - TextNoteEvent.KIND -> Summary(label = "Post", detail = event.content) - - // One of the group's relay lists, shown as hosts: every entry in one - // starts wss://, so the scheme is the part that never tells two apart. - // An empty one is a list the group is withdrawing, and says so. - in GroupRelaySet.KINDS -> { - val set = GroupRelaySet.entries.first { it.kind == event.kind } - - Summary( - label = "${set.name} relay list", - detail = set.parse(event.tags).joinToString { it.displayUrl() }.ifEmpty { "No relays" } - ) - } - // The group opening a wallet. What a member is agreeing to is that the // group keeps coins here, so the summary names the network -- the one // thing that changes what the coins are worth -- and the account, and diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt deleted file mode 100644 index 4db17762..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/AddGroupPostScreen.kt +++ /dev/null @@ -1,310 +0,0 @@ -package com.machankura.bennu.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.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -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.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.AddGroupPostViewModel -import com.machankura.bennu.compose.ui.view.state.AddGroupPostUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_post_needs_something_to_say -import bennu.composeapp.generated.resources.add_post -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_post -import bennu.composeapp.generated.resources.propose_post -import bennu.composeapp.generated.resources.the_group_signs_a_post_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_a_post -import bennu.composeapp.generated.resources.what_should_the_group_say -import org.jetbrains.compose.resources.stringResource - -/** - * The draft of something the group would say, in its own name. - * - * Not a message in the room: this is signed by the group's key and read by anybody, - * which is why the byline over the draft is the group's rather than the writer's. - * Whoever types it is proposing words for the group to put its signature to, and - * the words become a post -- attributed to the group and to nobody in particular -- - * only once a quorum has signed. - * - * The byline is the whole of the design here. Every other composer in this app puts - * the author's name over the draft because the author is the person typing; getting - * that wrong on this screen would have a member writing what looks like their own - * note and finding the group had said it. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun AddGroupPostScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val addGroupPostViewModel: AddGroupPostViewModel = viewModel( - factory = AddGroupPostViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddGroupPostUIState = initialAddGroupPostUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_post) - val nothingToSay = stringResource(Res.string.a_post_needs_something_to_say) - - ScreenStateTransition(addGroupPostViewModel.addGroupPostUIState) { uiState -> - when (val addGroupPostUIState = uiState) { - is AddGroupPostUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = addGroupPostUIState.message, onRetry = null) - } - - is AddGroupPostUIState.Loaded -> { - val noteFieldState = rememberTextFieldState() - val canSign = addGroupPostUIState.canSign - - // imePadding: this screen is a text field the size of the screen, - // and without it the software keyboard covers what is being typed. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(text = stringResource(Res.string.add_post)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_post), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose post") }, - enabled = canSign, - onClick = { - addGroupPostViewModel.proposePost( - localChatRoom = addGroupPostUIState.localChatRoom, - noteField = noteFieldState, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. Nothing has been - // posted yet -- the post appears - // when a quorum signs -- so landing - // on the list it is not in would - // read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Both stay on the draft. One is an - // empty note and one is a failure to - // propose, and neither is a reason to - // throw away what was written. - onEmpty = { notify(nothingToSay) }, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - // Whose name this goes out in, said before a word is typed. - // It is the group's, and it is the one thing about this - // screen a member could reasonably get wrong. - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - ProfileAvatar( - size = MaterialTheme.spacing.space500, - publicKey = chatRoomId, - picture = addGroupPostUIState.groupNostrProfile?.picture(), - name = addGroupPostUIState.groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Text( - text = addGroupPostUIState.groupNostrProfile?.name() - ?: addGroupPostUIState.localChatRoom.chatRoom.subject - ?: chatRoomId.take(16), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.the_group_signs_a_post_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_a_post - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = noteFieldState, - // The draft grows into the screen rather than scrolling - // inside three lines: a post is the one thing here - // somebody writes at length, and a composer that hides - // what was written two sentences ago is a composer - // nobody proofreads in. - lineLimits = TextFieldLineLimits.MultiLine(), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - placeholder = { - Text(stringResource(Res.string.what_should_the_group_say)) - } - ) - } - } - } - - AddGroupPostUIState.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.add_post), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialAddGroupPostUIState == AddGroupPostUIState.Loading) { - addGroupPostViewModel.initiateAddGroupPost() - } - } -} - -@ConformancePreviews -@Composable -private fun AddGroupPostScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - AddGroupPostScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialAddGroupPostUIState = AddGroupPostUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the composer renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt deleted file mode 100644 index 07d356e5..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreen.kt +++ /dev/null @@ -1,582 +0,0 @@ -package com.machankura.bennu.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 bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.accepted_by_n_of_m_relays -import bennu.composeapp.generated.resources.add_a_relay_to_broadcast_to -import bennu.composeapp.generated.resources.add_relay -import bennu.composeapp.generated.resources.broadcast -import bennu.composeapp.generated.resources.copied_the_raw_json -import bennu.composeapp.generated.resources.copy_raw_json -import bennu.composeapp.generated.resources.eg_wss_relay_example_com -import bennu.composeapp.generated.resources.no_relays_to_broadcast_to -import bennu.composeapp.generated.resources.relay_url -import bennu.composeapp.generated.resources.relays -import bennu.composeapp.generated.resources.sends_the_event_exactly_as_the_group_signed_it -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.that_is_not_a_relay_address -import bennu.composeapp.generated.resources.that_relay_is_already_in_this_list -import bennu.composeapp.generated.resources.the_signed_event -import bennu.composeapp.generated.resources.where_the_group_has_said_it_lives_is_filled_in -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.text.ProposedEvent -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.label -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.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( - relayLists = broadcastGroupSignedEventUIState.relayLists, - 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.where_the_group_has_said_it_lives_is_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) - - BennuTheme { - 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) - ), - // Nothing agreed, so the list fills in from the app's own - // publish set -- the state a group meets this screen in - // before it has edited its relays. - relayLists = GroupRelayList.allAmong(emptyList(), chatRoomId), - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - publishTransport = object : EventPublishTransport { - override suspend fun publishEvent( - nostrEvent: com.machankura.bennu.compose.database.model.NostrEvent, - relays: Set - ): Flow = emptyFlow() - }, - onNavigateBack = {} - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt index b01ee84b..4f617acb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt @@ -27,10 +27,6 @@ import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DeleteForever import androidx.compose.material.icons.filled.PersonRemove -import androidx.compose.material.icons.filled.Badge -import androidx.compose.material.icons.filled.Campaign -import androidx.compose.material.icons.filled.DataObject -import androidx.compose.material.icons.filled.Dns import androidx.compose.material.icons.filled.Draw import androidx.compose.material.icons.filled.PersonAdd import androidx.compose.material.icons.filled.Unsubscribe @@ -80,10 +76,6 @@ import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.navigation.routes.ProfilePreviewRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route import com.machankura.bennu.compose.ui.composable.navigation.routes.CreateSharedKeyRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.SearchMemberToAddToChatRoomRoute import com.machankura.bennu.compose.extensions.inComparableGroups @@ -97,20 +89,8 @@ import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.ui.view.model.ChatRoomDetailViewModel import com.machankura.bennu.compose.ui.view.state.ChatRoomDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata import com.machankura.bennu.compose.ui.theme.spacing import bennu.composeapp.generated.resources.run_by_members -import bennu.composeapp.generated.resources.nostr_profile -import bennu.composeapp.generated.resources.relays -import bennu.composeapp.generated.resources.posts -import bennu.composeapp.generated.resources.not_described_yet -import bennu.composeapp.generated.resources.n_of_m_relay_lists_agreed -import bennu.composeapp.generated.resources.no_posts_yet -import bennu.composeapp.generated.resources.one_post -import bennu.composeapp.generated.resources.n_posts -import bennu.composeapp.generated.resources.propose_event -import bennu.composeapp.generated.resources.no_name_on_this_profile import bennu.composeapp.generated.resources.parent_group import bennu.composeapp.generated.resources.a_subgroup import bennu.composeapp.generated.resources.created_you_are_not_a_member @@ -122,8 +102,6 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.SelectSubgro import com.machankura.bennu.compose.ui.composable.navigation.routes.NostrEventDetailRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ChatRoomDetailRoute import com.machankura.bennu.compose.managers.SubgroupManager -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupRelaySet import bennu.composeapp.generated.resources.Res import org.jetbrains.compose.resources.stringResource import bennu.composeapp.generated.resources.delete_group @@ -343,122 +321,20 @@ fun ChatRoomDetailScreen( HorizontalDivider() } - // Under the room's identity and above its work, because - // that is what it is: what the rest of nostr reads for - // the key the signing key row names. The room's subject - // and description above are this device's names for it; - // this is the group's own, signed by the group. - // - // One row per kind of statement, each opening the screen - // that shows it, rather than the statements themselves. - // Five sections of cards, every card with a button under - // it, made this screen as long as everything the group - // had ever said, with its members and its subgroups - // somewhere underneath. What a member opening it wants - // first is the shape of that -- a name and a few counts - // -- not every word of it. The row carries the shape; - // the screen behind it carries the rest, with the same - // broadcasts and the same gated ways in the sections had. + // The group's coins, signed by the room's key and read + // by nobody outside the room: the statement opening it + // never leaves the group. Shown to every member, open + // or not -- the screen behind it is where a member who + // can sign asks the group to open one. // // Marmot rooms only, and absent rather than empty in a // NIP-17 one. A NIP-17 room's id is not a key it can - // sign as, so it has no nostr identity at all -- and a - // row saying it has not described one yet would promise - // something that is never coming. - if (chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null) { + // sign as, so it has no wallet to open. + if ( + GroupWalletRollout.ENABLED && + chatRoomDetailUIState.localChatRoom.chatRoom.mlsGroupState != null + ) { item { - SignedWorkRow( - icon = Icons.Default.Badge, - headline = stringResource(Res.string.nostr_profile), - // The name the group gave itself and its - // address where it claims one: the two - // things a reader checks a profile for. - // Named rather than falling back to the - // pubkey, for the reason the card gives. - supporting = chatRoomDetailUIState.groupNostrProfile - ?.let { profile -> - listOfNotNull( - profile.name() - ?: stringResource(Res.string.no_name_on_this_profile), - profile.nip05() - ).joinToString(" · ") - } - ?: stringResource(Res.string.not_described_yet), - onOpen = { - onNavigateToRoute.invoke( - GroupNostrProfileRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // Directly under the profile, because between them - // they are the whole of the group's account of - // itself on nostr: who it says it is, and where it - // says it can be found. - item { - SignedWorkRow( - icon = Icons.Default.Dns, - headline = stringResource(Res.string.relays), - // How many of the four lists the group has - // agreed, counted against the sets rather - // than the entries: the entries come back - // empty in a room that has none of this to - // say, and "0 of 0" would say nothing. - supporting = stringResource( - Res.string.n_of_m_relay_lists_agreed, - chatRoomDetailUIState.groupRelayLists.count { it.isAgreed }, - GroupRelaySet.entries.size - ), - onOpen = { - onNavigateToRoute.invoke( - GroupRelaysRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // Under the relay lists, because these are what the - // lists are *for*: the profile says who the group - // is, the relays say where to find it, and these are - // what a reader would find there. - item { - SignedWorkRow( - icon = Icons.Default.Campaign, - headline = stringResource(Res.string.posts), - supporting = when (val count = chatRoomDetailUIState.groupPosts.size) { - 0 -> stringResource(Res.string.no_posts_yet) - 1 -> stringResource(Res.string.one_post) - else -> stringResource(Res.string.n_posts, count) - }, - onOpen = { - onNavigateToRoute.invoke( - GroupPostsRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) - } - - // The group's coins. After the identity block's - // last signed row and before the paste, because it - // is signed by the same key and read by nobody - // outside the room: the statement opening it never - // leaves the group. Shown to every member, open or - // not -- the screen behind it is where a member who - // can sign asks the group to open one. - if (GroupWalletRollout.ENABLED) item { SignedWorkRow( icon = Icons.Default.AccountBalanceWallet, headline = stringResource(Res.string.group_wallet), @@ -480,44 +356,6 @@ fun ChatRoomDetailScreen( ) } - // The untyped way into everything above it. Each - // row opens a screen with a form that builds one - // kind of event; this takes any of those kinds as - // JSON, pasted from wherever it was made, and it - // lands on whichever screen is its kind's once the - // quorum signs -- the same reading, off the same - // signed events. Last in the block because it is - // about the block rather than about any one row of - // it, and behind the same gate for the same reason. - if (chatRoomDetailUIState.canEditNostrProfile) { - item { - TextButton( - onClick = { - onNavigateToRoute.invoke( - ProposeGroupEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon( - Icons.Default.DataObject, - contentDescription = Decorative - ) - - Spacer( - modifier = Modifier.width( - MaterialTheme.spacing.space125 - ) - ) - - Text(stringResource(Res.string.propose_event)) - } - } - } - item { HorizontalDivider() } @@ -1145,8 +983,8 @@ internal fun GroupKeyStateSheetContent( } /** - * One row of the identity block: a kind of statement the group has signed, a - * line summarising it, and the way to the screen where it is read in full. + * One row for a kind of statement the group has signed: a line summarising it, + * and the way to the screen where it is read in full. * * The same shape as the signing key and parent group rows above it -- a card * with a leading icon and a trailing chevron -- because it is the same kind of @@ -1363,9 +1201,9 @@ private fun ChatRoomMessagingScreenPreview() { subject = "Message title", description = "Description of a chat room so that members now why they are here.", initialGiftWrapPayloadId = "sdfaer", - // A Marmot room, so the nostr profile section renders - // at all -- it is hidden in a NIP-17 one, which has no - // key to have an identity on nostr. + // A Marmot room, so the signed-work block renders at + // all -- it is hidden in a NIP-17 one, which has no key + // to sign with. mlsGroupState = "state" ), localParticipants = listOf( @@ -1395,28 +1233,6 @@ private fun ChatRoomMessagingScreenPreview() { announcedBy = "d".repeat(64), announcedAt = Instant.fromEpochSeconds(1_700_000_000) ), - // A group that has described itself, so the section renders - // with something in it rather than only in its empty state. - // Built directly rather than read out of a signed event: the - // reading checks a signature, and there is no real one here. - groupNostrProfile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = "publicKey", - publicKey = "publicKey", - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ), - canEditNostrProfile = true ), nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt deleted file mode 100644 index ff5fe6c9..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupNostrProfileScreen.kt +++ /dev/null @@ -1,398 +0,0 @@ -package com.machankura.bennu.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.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.rememberScrollState -import androidx.compose.foundation.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.Notes -import androidx.compose.material.icons.filled.AlternateEmail -import androidx.compose.material.icons.filled.Bolt -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material.icons.filled.Image -import androidx.compose.material.icons.filled.Link -import androidx.compose.material.icons.filled.Title -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -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.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextAlign -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.EditGroupNostrProfileViewModel -import com.machankura.bennu.compose.ui.view.state.EditGroupNostrProfileUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.about -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_profile -import bennu.composeapp.generated.resources.edit_nostr_profile -import bennu.composeapp.generated.resources.eg_a_group_translating_hard_books -import bennu.composeapp.generated.resources.eg_group_example_com -import bennu.composeapp.generated.resources.eg_group_getalby_com -import bennu.composeapp.generated.resources.eg_https_example_com -import bennu.composeapp.generated.resources.eg_https_example_com_group_png -import bennu.composeapp.generated.resources.eg_translation_collective -import bennu.composeapp.generated.resources.lightning_address -import bennu.composeapp.generated.resources.name -import bennu.composeapp.generated.resources.nostr_address -import bennu.composeapp.generated.resources.picture_url -import bennu.composeapp.generated.resources.propose_nostr_profile -import bennu.composeapp.generated.resources.the_group_signs_its_profile_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_a_profile -import bennu.composeapp.generated.resources.website -import bennu.composeapp.generated.resources.what_the_group_says_about_itself_on_nostr -import org.jetbrains.compose.resources.stringResource - -/** - * The form for what a group says about itself on nostr. - * - * A group's kind:0 is signed by the group, so pressing the button proposes rather - * than saves: the form goes out as one event for the room's quorum to put its key - * to, and the screen hands over to the signing session it opened. Nothing about the - * profile has changed by the time this screen closes. - * - * The fields start at what the group already says, so an edit is an edit. And they - * are sent as they stand -- **an emptied field clears what the group had said**, - * which is the only way to unsay something a group has signed. Fields this form - * does not offer are carried across untouched; see `GroupNostrProfile.template`. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun EditGroupNostrProfileScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = - EditGroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val editGroupNostrProfileViewModel: EditGroupNostrProfileViewModel = viewModel( - factory = EditGroupNostrProfileViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so the message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_profile) - - ScreenStateTransition(editGroupNostrProfileViewModel.editGroupNostrProfileUIState) { uiState -> - when (val editGroupNostrProfileUIState = uiState) { - is EditGroupNostrProfileUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState( - message = editGroupNostrProfileUIState.message, - onRetry = null - ) - } - - is EditGroupNostrProfileUIState.Loaded -> { - val profile = editGroupNostrProfileUIState.groupNostrProfile - - // Seeded from the profile the group already signed, so the form is - // an edit of it. `rememberTextFieldState` saves what is typed, which - // is what survives a rotation with the edits intact. - val nameFieldState = rememberTextFieldState(profile?.name() ?: "") - val aboutFieldState = rememberTextFieldState(profile?.about() ?: "") - val pictureFieldState = rememberTextFieldState(profile?.picture() ?: "") - val websiteFieldState = rememberTextFieldState(profile?.website() ?: "") - val nip05FieldState = rememberTextFieldState(profile?.nip05() ?: "") - val lud16FieldState = rememberTextFieldState(profile?.lud16() ?: "") - - val canSign = editGroupNostrProfileUIState.canSign - - // imePadding: this screen is nothing but text fields, and without it - // the software keyboard covers whichever one is being typed into. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - editGroupNostrProfileUIState.localChatRoom - .RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_nostr_profile), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose nostr profile") }, - enabled = canSign, - onClick = { - editGroupNostrProfileViewModel.proposeNostrProfile( - localChatRoom = - editGroupNostrProfileUIState.localChatRoom, - groupNostrProfile = profile, - nameField = nameFieldState, - aboutField = aboutFieldState, - pictureField = pictureFieldState, - websiteField = websiteFieldState, - nip05Field = nip05FieldState, - lud16Field = lud16FieldState, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. The profile has not - // changed yet -- it changes when a - // quorum signs -- so landing on a - // group still showing the old one - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Stay on the form with what was typed - // still in it. The proposal is what - // failed, and every word of it is worth - // keeping for the retry. - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - .verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text(stringResource(Res.string.what_the_group_says_about_itself_on_nostr)) - - Text( - text = stringResource( - Res.string.the_group_signs_its_profile_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_a_profile - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - NostrProfileField( - state = nameFieldState, - icon = Icons.Default.Title, - iconDescription = "Name of the group", - label = stringResource(Res.string.name), - placeholder = stringResource(Res.string.eg_translation_collective) - ) - - NostrProfileField( - state = aboutFieldState, - icon = Icons.AutoMirrored.Filled.Notes, - iconDescription = "What the group is for", - label = stringResource(Res.string.about), - placeholder = stringResource( - Res.string.eg_a_group_translating_hard_books - ), - // The one field with prose in it, and the only one a - // single line would truncate while it was being typed. - lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 3) - ) - - NostrProfileField( - state = pictureFieldState, - icon = Icons.Default.Image, - iconDescription = "Picture of the group", - label = stringResource(Res.string.picture_url), - placeholder = stringResource(Res.string.eg_https_example_com_group_png) - ) - - NostrProfileField( - state = websiteFieldState, - icon = Icons.Default.Link, - iconDescription = "Website of the group", - label = stringResource(Res.string.website), - placeholder = stringResource(Res.string.eg_https_example_com) - ) - - NostrProfileField( - state = nip05FieldState, - icon = Icons.Default.AlternateEmail, - iconDescription = "Nostr address of the group", - label = stringResource(Res.string.nostr_address), - placeholder = stringResource(Res.string.eg_group_example_com) - ) - - NostrProfileField( - state = lud16FieldState, - icon = Icons.Default.Bolt, - iconDescription = "Lightning address of the group", - label = stringResource(Res.string.lightning_address), - placeholder = stringResource(Res.string.eg_group_getalby_com) - ) - } - } - } - - EditGroupNostrProfileUIState.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.edit_nostr_profile), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialEditGroupNostrProfileUIState == EditGroupNostrProfileUIState.Loading) { - editGroupNostrProfileViewModel.initiateEditGroupNostrProfile() - } - } -} - -/** - * One field of the profile, in the shape the app's other forms use. - * - * Six of these on one screen is what makes it worth a function: the borderless - * outlined field over the bottom bar's tint is four lines of colours apiece, and - * six copies of that is where a divergence hides. - */ -@Composable -private fun NostrProfileField( - state: TextFieldState, - icon: ImageVector, - iconDescription: String, - label: String, - placeholder: String, - lineLimits: TextFieldLineLimits = TextFieldLineLimits.SingleLine -) { - OutlinedTextField( - modifier = Modifier.fillMaxWidth().background(BottomAppBarDefaults.containerColor), - state = state, - lineLimits = lineLimits, - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - leadingIcon = { - Icon(icon, contentDescription = iconDescription) - }, - label = { - Text(text = label) - }, - placeholder = { - Text(text = placeholder) - } - ) -} - -@ConformancePreviews -@Composable -private fun EditGroupNostrProfileScreenPreview() { - BennuTheme { - Surface( - modifier = Modifier.fillMaxSize() - ) { - EditGroupNostrProfileScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialEditGroupNostrProfileUIState = EditGroupNostrProfileUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation collective", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the form renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt deleted file mode 100644 index a3c9eaec..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/EditGroupRelaysScreen.kt +++ /dev/null @@ -1,551 +0,0 @@ -package com.machankura.bennu.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.Delete -import androidx.compose.material.icons.filled.Draw -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.FilterChip -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.OutlinedTextFieldDefaults -import androidx.compose.material3.PrimaryScrollableTabRow -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.Surface -import androidx.compose.material3.Tab -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.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.EditGroupRelaysViewModel -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.add_relay -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_these_relays -import bennu.composeapp.generated.resources.edit_relays -import bennu.composeapp.generated.resources.eg_wss_relay_example_com -import bennu.composeapp.generated.resources.no_relays_in_this_list -import bennu.composeapp.generated.resources.nothing_has_changed_to_propose -import bennu.composeapp.generated.resources.propose_relays -import bennu.composeapp.generated.resources.relay_read -import bennu.composeapp.generated.resources.relay_set_blocked -import bennu.composeapp.generated.resources.relay_set_blocked_purpose -import bennu.composeapp.generated.resources.relay_set_general -import bennu.composeapp.generated.resources.relay_set_general_purpose -import bennu.composeapp.generated.resources.relay_set_messages -import bennu.composeapp.generated.resources.relay_set_messages_purpose -import bennu.composeapp.generated.resources.relay_set_search -import bennu.composeapp.generated.resources.relay_set_search_purpose -import bennu.composeapp.generated.resources.relay_url -import bennu.composeapp.generated.resources.relay_write -import bennu.composeapp.generated.resources.relays_are_public_a_group_cannot_encrypt -import bennu.composeapp.generated.resources.that_is_not_a_relay_address -import bennu.composeapp.generated.resources.that_relay_is_already_in_this_list -import bennu.composeapp.generated.resources.the_group_signs_each_list_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_relays -import bennu.composeapp.generated.resources.where_the_group_lives_on_nostr -import org.jetbrains.compose.resources.StringResource -import org.jetbrains.compose.resources.stringResource - -/** - * The four relay lists a group keeps, edited as one sitting. - * - * A tab per list, a field to add one, a row per relay with a way to drop it, and -- - * in the one list NIP-65 gives markers to -- a read and a write chip. The shape is - * borrowed from Wisp's relay screen, which is the interface this app was asked to - * match, with one deliberate departure. - * - * **The button proposes rather than publishes.** Wisp signs with the user's own key - * and a tab's publish button is done the moment it is pressed. A group signs with a - * quorum, so what leaves this screen is a proposal, and the screen hands over to - * the session it opened. Nothing has changed until enough members sign. - * - * And it proposes **every list that changed at once**, rather than the tab in front - * of you. Four sessions for one sitting would ask a quorum the same question four - * times over what is plainly one decision -- see `EditGroupRelaysViewModel`, which - * carries the reasoning and works out what actually differs. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun EditGroupRelaysScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState = EditGroupRelaysUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val editGroupRelaysViewModel: EditGroupRelaysViewModel = viewModel( - factory = EditGroupRelaysViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupRelaysUIState = initialEditGroupRelaysUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in a click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_these_relays) - val nothingChanged = stringResource(Res.string.nothing_has_changed_to_propose) - - ScreenStateTransition(editGroupRelaysViewModel.editGroupRelaysUIState) { uiState -> - when (val editGroupRelaysUIState = uiState) { - is EditGroupRelaysUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = editGroupRelaysUIState.message, onRetry = null) - } - - is EditGroupRelaysUIState.Loaded -> { - val urlFieldState = rememberTextFieldState() - val selectedSet = editGroupRelaysViewModel.selectedSet - val canSign = editGroupRelaysUIState.canSign - - // The editor's working copy 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. - // Seeding leaves edits alone, so re-running this changes nothing. - LaunchedEffect(editGroupRelaysUIState.signed) { - editGroupRelaysViewModel.seedWorkingCopy(editGroupRelaysUIState.signed) - } - - // 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 { editGroupRelaysViewModel.clearAddFailure() } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { - editGroupRelaysUIState.localChatRoom.RenderChatRoomTitleText() - }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_relays), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose relays") }, - enabled = canSign, - onClick = { - editGroupRelaysViewModel.proposeRelayLists( - localChatRoom = - editGroupRelaysUIState.localChatRoom, - signed = editGroupRelaysUIState.signed, - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. The lists have not - // changed yet -- they change when a - // quorum signs -- so landing on a - // group still showing the old ones - // would read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // Both stay on the form with the edits - // still in it. One is a question and - // one is a failure, and neither is a - // reason to throw away the typing. - onNothingToPropose = { notify(nothingChanged) }, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize() - ) { - PrimaryScrollableTabRow( - modifier = Modifier.padding(MaterialTheme.spacing.compactPadding), - edgePadding = 10.dp, - selectedTabIndex = selectedSet.ordinal, - ) { - GroupRelaySet.entries.forEach { set -> - Tab( - selected = set == selectedSet, - onClick = { editGroupRelaysViewModel.selectSet(set) }, - text = { Text(text = stringResource(set.label())) } - ) - } - } - - Column( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.screenMargin), - verticalArrangement = Arrangement.spacedBy( - MaterialTheme.spacing.itemGap - ), - horizontalAlignment = Alignment.CenterHorizontally - ) { - Text( - text = stringResource(Res.string.where_the_group_lives_on_nostr), - style = MaterialTheme.typography.titleSmall - ) - - // What this tab's list is actually for. Four relay lists - // is four questions nobody can be expected to hold apart - // from their names alone. - Text( - text = stringResource(selectedSet.purpose()), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource( - Res.string.the_group_signs_each_list_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (selectedSet == GroupRelaySet.Blocked) { - // Said where it matters. A person's client keeps - // this list encrypted, and somebody blocking a relay - // here should know the group cannot. - Text( - text = stringResource( - Res.string.relays_are_public_a_group_cannot_encrypt - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - } - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_relays - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - 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 = editGroupRelaysViewModel.addFailure != null - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - IconButton( - onClick = { - if ( - editGroupRelaysViewModel.addRelay( - urlFieldState.text.toString() - ) - ) { - urlFieldState.clearText() - } - } - ) { - Icon( - Icons.Default.Add, - contentDescription = "Add relay" - ) - } - } - - // Named rather than silent. An add button that does - // nothing for a URL it refuses is indistinguishable from - // a missed tap. - editGroupRelaysViewModel.addFailure?.let { failure -> - Text( - text = when (failure) { - EditGroupRelaysViewModel.AddFailure.NotARelay -> - stringResource(Res.string.that_is_not_a_relay_address) - EditGroupRelaysViewModel.AddFailure.AlreadyListed -> - stringResource( - Res.string.that_relay_is_already_in_this_list - ) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - } - - val relays = editGroupRelaysViewModel.relaysOf(selectedSet) - - if (relays.isEmpty()) { - EmptyState( - message = stringResource(Res.string.no_relays_in_this_list), - icon = Icons.Default.Dns - ) - } else { - LazyColumn( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.screenMargin) - ) { - items(items = relays, key = { it.url.url }) { relay -> - RelayRow( - relay = relay, - hasReadWriteMarkers = selectedSet.hasReadWriteMarkers, - onToggleRead = { - editGroupRelaysViewModel - .toggleRead(selectedSet, relay) - }, - onToggleWrite = { - editGroupRelaysViewModel - .toggleWrite(selectedSet, relay) - }, - onRemove = { - editGroupRelaysViewModel - .removeRelay(selectedSet, relay) - } - ) - } - } - } - } - } - } - - EditGroupRelaysUIState.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.edit_relays), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialEditGroupRelaysUIState == EditGroupRelaysUIState.Loading) { - editGroupRelaysViewModel.initiateEditGroupRelays() - } - } -} - -/** - * The tab's name, and the sentence saying what its list decides. - * - * Kept here rather than on [GroupRelaySet] so the enum stays what it is -- four - * nostr kinds and how to read and write them -- with no catalogue behind it. A - * `when` rather than a field on each entry, so adding a set is a compile error here - * rather than a tab with no name. - */ -private fun GroupRelaySet.label(): StringResource = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general - GroupRelaySet.Messages -> Res.string.relay_set_messages - GroupRelaySet.Search -> Res.string.relay_set_search - GroupRelaySet.Blocked -> Res.string.relay_set_blocked -} - -private fun GroupRelaySet.purpose(): StringResource = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general_purpose - GroupRelaySet.Messages -> Res.string.relay_set_messages_purpose - GroupRelaySet.Search -> Res.string.relay_set_search_purpose - GroupRelaySet.Blocked -> Res.string.relay_set_blocked_purpose -} - -/** - * One relay of one list. - * - * The read and write chips only in [hasReadWriteMarkers], which is NIP-65 alone -- - * the other three kinds have a relay in the list or not, and a chip there would - * offer a distinction the event cannot carry. - */ -@Composable -private fun RelayRow( - relay: GroupRelay, - hasReadWriteMarkers: Boolean, - onToggleRead: () -> Unit, - onToggleWrite: () -> Unit, - 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 - ) - - if (hasReadWriteMarkers) { - Row( - horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - FilterChip( - selected = relay.read, - onClick = onToggleRead, - label = { Text(stringResource(Res.string.relay_read)) } - ) - FilterChip( - selected = relay.write, - onClick = onToggleWrite, - label = { Text(stringResource(Res.string.relay_write)) } - ) - } - } - } - - IconButton(onClick = onRemove) { - Icon( - Icons.Default.Delete, - contentDescription = "Remove relay", - tint = MaterialTheme.colorScheme.error - ) - } - } -} - -@ConformancePreviews -@Composable -private fun EditGroupRelaysScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - EditGroupRelaysScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialEditGroupRelaysUIState = EditGroupRelaysUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // Unsigned lists, which is a group opening this for the first - // time -- so the editor fills in from `GroupRelaySet.defaults` - // and the preview shows the relay a new group actually starts - // with rather than an empty tab. - signed = GroupRelayList.allAmong(emptyList(), "publicKey"), - // A group that can sign, so the form renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt deleted file mode 100644 index 86d51191..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt +++ /dev/null @@ -1,353 +0,0 @@ -package com.machankura.bennu.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.lazy.LazyColumn -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Badge -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.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.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 com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.edit_nostr_profile -import bennu.composeapp.generated.resources.no_name_on_this_profile -import bennu.composeapp.generated.resources.nostr_profile -import bennu.composeapp.generated.resources.signed_by_the_group_on -import bennu.composeapp.generated.resources.this_group_has_not_said_anything_about_itself -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupNostrProfileViewModel -import com.machankura.bennu.compose.ui.view.state.GroupNostrProfileUIState -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, the broadcast under it, - * and -- for a member holding a share of the key -- the way into the editor. - * A group that has said nothing is told so, and offered the editor from the - * same place, since describing itself is the one thing to do about that. - * - * The profile is worth reading either way; proposing one is a signature by the - * group, and `proposeSigningBatch` throws for a device holding no share of the - * key. The editor is hidden rather than disabled, the way every gated way in - * on the group's screen is. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupNostrProfileScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupNostrProfileUIState: GroupNostrProfileUIState = GroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupNostrProfileViewModel: GroupNostrProfileViewModel = viewModel( - factory = GroupNostrProfileViewModel.factory( - chatRoomId = chatRoomId, - initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupNostrProfileUIState == GroupNostrProfileUIState.Loading) { - groupNostrProfileViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.nostr_profile), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupNostrProfileViewModel.groupNostrProfileUIState) { uiState -> - when (val state = uiState) { - is GroupNostrProfileUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupNostrProfileUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupNostrProfileUIState.Loaded -> { - val edit: () -> Unit = { - onNavigateToRoute.invoke( - EditGroupNostrProfileRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - state.groupNostrProfile?.let { 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 - ) { - GroupNostrProfileCard( - groupNostrProfile = groupNostrProfile, - publicKey = chatRoomId - ) - - BroadcastButton( - onClick = { - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = groupNostrProfile.signedEvent.id - ) - ) - } - ) - } - } ?: EmptyState( - message = stringResource( - Res.string.this_group_has_not_said_anything_about_itself - ), - // The way to fill the absence, where this device - // could: describing the group is a signature by it. - action = if (state.canSign) { - { EditNostrProfileButton(onClick = edit) } - } else { - null - } - ) - } - - if (state.canSign && state.groupNostrProfile != null) { - item { - EditNostrProfileButton(onClick = edit) - } - } - } - } - } - } - } -} - -/** - * What the group says about itself on nostr, as the group signed it. - * - * A preview rather than a profile screen: the name, the picture, the nostr address - * and the first lines of the group's own account of itself, which is what a member - * opening the group's details came here to check. The whole thing is one signed - * event and the proposal list is where it can be read out in full. - * - * **The picture and the name come from the metadata; the tint comes from the key.** - * [publicKey] is the room's id, which is the pubkey the group signs as, so a group - * with no picture yet still gets the colour it has everywhere else in the app. - * - * 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` -- and the broadcast - * button under it is how it gets to a relay. - */ -@Composable -private fun GroupNostrProfileCard( - groupNostrProfile: GroupNostrProfile, - publicKey: HexKey -) { - Card(modifier = Modifier.fillMaxWidth()) { - ListItem( - leadingContent = { - ProfileAvatar( - publicKey = publicKey, - picture = groupNostrProfile.picture(), - name = groupNostrProfile.name() - ) - }, - headlineContent = { - Text( - // Named rather than falling back to the pubkey: the signing key - // row on the group's screen already shows that, and showing it - // twice would say the group has a name when it has not. - text = groupNostrProfile.name() - ?: stringResource(Res.string.no_name_on_this_profile), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Column( - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - groupNostrProfile.nip05()?.let { - Text( - text = it, - style = MaterialTheme.typography.labelMedium, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - groupNostrProfile.about()?.let { - Text( - text = it, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.signed_by_the_group_on, - groupNostrProfile.signedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - ) - } -} - -/** The way into `EditGroupNostrProfileScreen`. The icon is decorative because the label is beside it. */ -@Composable -private fun EditNostrProfileButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.Default.Badge, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.edit_nostr_profile)) - } -} - -@ConformancePreviews -@Composable -private fun GroupNostrProfileScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupNostrProfileScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = "d".repeat(64), - relayHint = null, - initialGroupNostrProfileUIState = GroupNostrProfileUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "d".repeat(64), - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - // Built directly rather than read out of a signed event: the - // reading checks a signature, and there is no real one here. - groupNostrProfile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = "d".repeat(64), - publicKey = "d".repeat(64), - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ), - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt deleted file mode 100644 index c3857ca0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreen.kt +++ /dev/null @@ -1,352 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -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.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Campaign -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.Icon -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.TextButton -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 com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_reply -import bennu.composeapp.generated.resources.add_post -import bennu.composeapp.generated.resources.posted_on -import bennu.composeapp.generated.resources.posts -import bennu.composeapp.generated.resources.this_group_has_not_posted_anything_yet -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.extensions.inComparableGroups -import com.machankura.bennu.compose.extensions.toFormattedTimeAndDateString -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.EmptyState -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupPostsViewModel -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState -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 with a broadcast under - * it, and -- for a member holding a share of the key -- the way into the - * composer. A group that has said nothing is told so, and offered the composer - * from the same place. - * - * A post is the one thing the group signs that is meant to be *read* by people - * who were never in the room, so a member without a share reads it like - * anybody else and simply cannot propose the next one: proposing is a signature - * by the group, and `proposeSigningBatch` throws for a device holding no share. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupPostsScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupPostsViewModel: GroupPostsViewModel = viewModel( - factory = GroupPostsViewModel.factory( - chatRoomId = chatRoomId, - initialGroupPostsUIState = initialGroupPostsUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupPostsUIState == GroupPostsUIState.Loading) { - groupPostsViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.posts), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupPostsViewModel.groupPostsUIState) { uiState -> - when (val state = uiState) { - is GroupPostsUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupPostsUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupPostsUIState.Loaded -> { - val add: () -> Unit = { - onNavigateToRoute.invoke( - AddGroupPostRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - if (state.groupPosts.isEmpty()) { - item { - EmptyState( - message = stringResource( - Res.string.this_group_has_not_posted_anything_yet - ), - action = if (state.canSign) { - { AddPostButton(onClick = add) } - } else { - null - } - ) - } - } else { - items( - items = state.groupPosts, - key = { post -> post.signedEvent.id } - ) { post -> - // 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 (state.canSign) { - item { - AddPostButton(onClick = add) - } - } - } - } - } - } - } - } -} - -/** - * One thing the group said, as the group signed it. - * - * The whole note rather than a preview. A post is short by construction -- kind:1 - * with no long-form arm behind it -- and truncating the one kind of content on this - * screen that exists to be *read* would mean opening something to see a paragraph. - * - * **The byline is the group's**, taken from its profile where it has one and from - * the room's own id where it has not. It is worth spelling out because a post is - * the one thing here a reader might otherwise attribute to whichever member - * proposed it -- and the point of signing it as the group is that they cannot. - * - * A reply is marked as one. Nothing in this app writes replies, so the mark is for - * an event that arrived some other way; drawing one as an announcement would put - * half a conversation on a group's page with no sign that it was half. - */ -@Composable -private fun GroupPostCard( - post: GroupPost, - publicKey: HexKey, - groupNostrProfile: GroupNostrProfile? -) { - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - ProfileAvatar( - size = MaterialTheme.spacing.space400, - publicKey = publicKey, - picture = groupNostrProfile?.picture(), - name = groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Column(modifier = Modifier.weight(1f)) { - Text( - text = groupNostrProfile?.name() ?: publicKey.take(16).inComparableGroups(), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - Text( - text = stringResource( - Res.string.posted_on, - post.postedAt.toFormattedTimeAndDateString() - ), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - if (!post.isNewThread()) { - Text( - text = stringResource(Res.string.a_reply), - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - Text( - text = post.content, - style = MaterialTheme.typography.bodyMedium - ) - } - } -} - -/** The way into `AddGroupPostScreen`. The icon is decorative because the label is beside it. */ -@Composable -private fun AddPostButton(onClick: () -> Unit) { - TextButton(onClick = onClick) { - Icon(Icons.Default.Campaign, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.add_post)) - } -} - -@ConformancePreviews -@Composable -private fun GroupPostsScreenPreview() { - val chatRoomId = "d".repeat(64) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupPostsScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupPostsUIState = GroupPostsUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - groupPosts = listOf( - GroupPost( - signedEvent = GroupSignedEvent( - id = "b".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = "The first chapter is out. Read it, and tell us where it reads wrong.", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ) - ) - ), - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt deleted file mode 100644 index 7fe9eb63..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreen.kt +++ /dev/null @@ -1,327 +0,0 @@ -package com.machankura.bennu.compose.ui.composable - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -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.lazy.LazyColumn -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Dns -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.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.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 com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.edit_relays -import bennu.composeapp.generated.resources.no_relays_in_this_list -import bennu.composeapp.generated.resources.not_set_yet -import bennu.composeapp.generated.resources.relay_set_blocked -import bennu.composeapp.generated.resources.relay_set_general -import bennu.composeapp.generated.resources.relay_set_messages -import bennu.composeapp.generated.resources.relay_set_search -import bennu.composeapp.generated.resources.relays -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.BroadcastButton -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.GroupRelaysViewModel -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState -import kotlin.time.Instant - -/** - * Where the group has said it lives on nostr, one line per relay list. - * - * Pushed from its row on the group's screen, which says how many of the four - * lists the group has agreed and nothing more. This is where they are read, - * with a broadcast under each one the group has signed and -- for a member - * holding a share of the key -- the way into the editor. - * - * There is no empty state to draw: every set gets a row whatever the group has - * said, and the row is where "never agreed" and "agreed empty" are told apart. - * See [GroupRelayListsCard]. - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun GroupRelaysScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialGroupRelaysUIState: GroupRelaysUIState = GroupRelaysUIState.Loading, - chatRepository: ChatRepository, - onNavigateToRoute: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val groupRelaysViewModel: GroupRelaysViewModel = viewModel( - factory = GroupRelaysViewModel.factory( - chatRoomId = chatRoomId, - initialGroupRelaysUIState = initialGroupRelaysUIState, - chatRepository = chatRepository, - ) - ) - - LaunchedEffect(true) { - if (initialGroupRelaysUIState == GroupRelaysUIState.Loading) { - groupRelaysViewModel.initiate() - } - } - - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - topBar = { - TopAppBar( - title = { - Text( - text = stringResource(Res.string.relays), - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - }, - navigationIcon = { NavigateBackButton(onNavigateBack) } - ) - } - ) { padding -> - ScreenStateTransition(groupRelaysViewModel.groupRelaysUIState) { uiState -> - when (val state = uiState) { - is GroupRelaysUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, - // and reading it again with the same one fails the same way. - ErrorState( - modifier = Modifier.padding(padding), - message = state.message, - onRetry = null - ) - } - - GroupRelaysUIState.Loading -> { - Column( - modifier = Modifier.fillMaxWidth().padding(padding) - .padding(MaterialTheme.spacing.screenMargin), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.sectionGap) - ) { - Spacer(modifier = Modifier.height(MaterialTheme.spacing.emphasisGap)) - - LoadingDataIndicator(fillScreen = false) - } - } - - is GroupRelaysUIState.Loaded -> { - LazyColumn( - modifier = Modifier.padding(padding).readableContent().fillMaxSize() - .padding(MaterialTheme.spacing.space250), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) - ) { - item { - GroupRelayListsCard( - relayLists = state.groupRelayLists, - onBroadcast = { signedEvent -> - onNavigateToRoute.invoke( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - signedEventId = signedEvent.id - ) - ) - } - ) - } - - // The lists are worth reading either way; proposing them - // is a signature by the group, and `proposeSigningBatch` - // throws for a device holding no share of the key. Hidden - // rather than disabled, the way every gated way in on the - // group's screen is. - if (state.canSign) { - item { - TextButton( - onClick = { - onNavigateToRoute.invoke( - EditGroupRelaysRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint - ) - ) - } - ) { - Icon(Icons.Default.Dns, contentDescription = Decorative) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125)) - - Text(stringResource(Res.string.edit_relays)) - } - } - } - } - } - } - } - } -} - -/** - * Where the group has said it lives on nostr, one line per relay list. - * - * One card holding four rows rather than four cards: they are read together -- the - * question is whether the group is reachable, not what any single list says -- and - * four cards of one line each is four dividers to scroll past for the same four - * facts. - * - * **A list the group has never agreed reads "not set yet", and an agreed empty one - * reads "no relays".** Those are different things: one is a group that has not got - * round to it, and the other is a group that decided. Collapsing them would hide a - * deliberate withdrawal behind an oversight. - */ -@Composable -private fun GroupRelayListsCard( - relayLists: List, - onBroadcast: (GroupSignedEvent) -> Unit -) { - Card(modifier = Modifier.fillMaxWidth()) { - relayLists.forEach { list -> - ListItem( - leadingContent = { - Icon(Icons.Default.Dns, contentDescription = Decorative) - }, - headlineContent = { - Text(text = stringResource(list.set.summaryLabel())) - }, - supportingContent = { - Text( - text = when { - !list.isAgreed -> stringResource(Res.string.not_set_yet) - list.relays.isEmpty() -> - stringResource(Res.string.no_relays_in_this_list) - // Hosts rather than URLs: every one of them starts - // `wss://`, so the scheme is the part that never - // distinguishes two entries. - else -> list.relays.joinToString { it.displayUrl() } - }, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - ) - - // Under the row it sends, and only where there is something signed - // to send: a list the group has never agreed is not an event. Inside - // the card because the four rows share one, so "under the event" has - // to mean under the row -- and at the end, where M3 puts a card's - // actions. An agreed empty list gets one too: a withdrawal is a - // statement, and relays still holding the old list need to hear it. - list.signedEvent?.let { signedEvent -> - Box( - modifier = Modifier.fillMaxWidth() - .padding(horizontal = MaterialTheme.spacing.compactPadding), - contentAlignment = Alignment.CenterEnd - ) { - BroadcastButton(onClick = { onBroadcast(signedEvent) }) - } - } - } - } -} - -/** The name of a relay list, for the row that summarises it. */ -private fun GroupRelaySet.summaryLabel() = when (this) { - GroupRelaySet.General -> Res.string.relay_set_general - GroupRelaySet.Messages -> Res.string.relay_set_messages - GroupRelaySet.Search -> Res.string.relay_set_search - GroupRelaySet.Blocked -> Res.string.relay_set_blocked -} - -@ConformancePreviews -@Composable -private fun GroupRelaysScreenPreview() { - val chatRoomId = "d".repeat(64) - - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - GroupRelaysScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialGroupRelaysUIState = GroupRelaysUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = null, - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - // One agreed list and three the group has not got round to, - // so the two things a row can say are both on the screen. - groupRelayLists = GroupRelaySet.entries.map { set -> - if (set == GroupRelaySet.General) { - GroupRelayList( - set = set, - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - relays = listOf( - GroupRelay(RelayUrlNormalizer.normalize("wss://relay.one.example")) - ) - ) - } else { - GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - } - }, - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt deleted file mode 100644 index 0dd670a3..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreen.kt +++ /dev/null @@ -1,423 +0,0 @@ -package com.machankura.bennu.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.text.input.TextFieldLineLimits -import androidx.compose.foundation.text.input.rememberTextFieldState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Draw -import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.BottomAppBarDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -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.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.text.TextStyle -import androidx.compose.ui.text.font.FontFamily -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.lifecycle.viewmodel.compose.viewModel -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupEventProposal -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.text.ProposedEvent -import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ErrorState -import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator -import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition -import com.machankura.bennu.compose.ui.composable.widgets.buttons.ExtendedFab -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier -import com.machankura.bennu.compose.ui.theme.ConformancePreviews -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.theme.readableContent -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.view.model.ProposeGroupEventViewModel -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.a_post_needs_something_to_say -import bennu.composeapp.generated.resources.an_event_is_a_json_object -import bennu.composeapp.generated.resources.an_event_needs_a_kind -import bennu.composeapp.generated.resources.content_must_be_text -import bennu.composeapp.generated.resources.could_not_ask_the_group_to_sign_this_event -import bennu.composeapp.generated.resources.eg_kind_1_tags_content -import bennu.composeapp.generated.resources.kind_n -import bennu.composeapp.generated.resources.kind_n_has_nowhere_to_go_on_this_screen -import bennu.composeapp.generated.resources.paste_an_unsigned_event_for_the_group_to_sign -import bennu.composeapp.generated.resources.propose_event -import bennu.composeapp.generated.resources.tags_must_be_a_list_of_lists_of_strings -import bennu.composeapp.generated.resources.that_is_not_json -import bennu.composeapp.generated.resources.the_content_is_not_a_profile -import bennu.composeapp.generated.resources.the_group_signs_an_event_so_it_takes_a_quorum -import bennu.composeapp.generated.resources.this_group_has_no_shared_key_to_sign_an_event -import bennu.composeapp.generated.resources.unsigned_event -import bennu.composeapp.generated.resources.what_the_group_would_sign -import org.jetbrains.compose.resources.stringResource - -/** - * An unsigned event, pasted, for the group to sign. - * - * The typed editors each build one kind of statement; this takes any of the - * kinds the group's screen can show, as JSON, the way another tool prints one. - * Above the paste is what the group would be signing, read back the way the - * signing screen will describe it, so a member sees "Post · gm" rather than a - * wall of brackets before deciding -- and sees why the group will - * not be asked when the paste is something it could never show. - * - * The byline is the group's, as on the post composer and for the same reason: - * whatever is pasted goes out in the group's name, and a paste that names some - * other `pubkey` goes out in the group's name anyway. The explanatory line says - * so, because a paste with a `pubkey` in it is the one case where a member could - * reasonably expect otherwise. - */ -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) -@Composable -fun ProposeGroupEventScreen( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState = ProposeGroupEventUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository, - onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, - onNavigateBack: () -> Unit, -) { - val proposeGroupEventViewModel: ProposeGroupEventViewModel = viewModel( - factory = ProposeGroupEventViewModel.factory( - chatRoomId = chatRoomId, - relayHint = relayHint, - initialProposeGroupEventUIState = initialProposeGroupEventUIState, - activeUserPublicKey = activeUserPublicKey, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - ) - - // Read out here rather than in the click handler: both are composable and an - // onClick lambda is not. The scope is the caller's so a message survives this - // screen being replaced by the signing session. - val notify = rememberNotifier(rememberCoroutineScope()) - val couldNotPropose = stringResource(Res.string.could_not_ask_the_group_to_sign_this_event) - - ScreenStateTransition(proposeGroupEventViewModel.proposeGroupEventUIState) { uiState -> - when (val proposeGroupEventUIState = uiState) { - is ProposeGroupEventUIState.Error -> { - // Nothing to retry: the room came from a navigation argument, and - // reading it again with the same one fails the same way. - ErrorState(message = proposeGroupEventUIState.message, onRetry = null) - } - - is ProposeGroupEventUIState.Loaded -> { - val eventFieldState = rememberTextFieldState() - val canSign = proposeGroupEventUIState.canSign - - // Read on every change. A paste is a few kilobytes at most and the - // reading is one JSON parse, so this is cheaper than the debounce - // that would hide the answer for a beat after the paste. - val json = eventFieldState.text.toString() - val reading = remember(json) { - json.takeIf { it.isNotBlank() }?.let(GroupEventProposal::read) - } - - // imePadding: this screen is a text field the size of the screen, - // and without it the software keyboard covers what is being pasted. - Scaffold( - snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, - modifier = Modifier.imePadding(), - topBar = { - TopAppBar( - title = { Text(text = stringResource(Res.string.propose_event)) }, - navigationIcon = { NavigateBackButton(onNavigateBack) }, - ) - }, - bottomBar = { - BottomAppBar( - actions = {}, - floatingActionButton = { - ExtendedFab( - label = stringResource(Res.string.propose_event), - icon = { Icon(Icons.Default.Draw, contentDescription = "Propose event") }, - enabled = canSign, - onClick = { - proposeGroupEventViewModel.proposeEvent( - localChatRoom = proposeGroupEventUIState.localChatRoom, - json = eventFieldState.text.toString(), - onSuccess = { sessionId -> - // Onto the session rather than back - // to the group. Nothing has been - // signed yet -- the event lands when - // a quorum signs -- so landing on a - // screen that does not show it would - // read as a failure. - onNavigateToRouteAndPopUpInclusive.invoke( - FrostSigningRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - sessionId = sessionId - ) - ) - }, - // The reason is already under the paste; - // pressing the button anyway is answered - // rather than ignored, and the paste - // stays. Same on a failure to propose. - onRefused = {}, - onFailure = { notify(couldNotPropose) } - ) - } - ) - } - ) - } - ) { innerPadding -> - Column( - modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize(), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), - horizontalAlignment = Alignment.CenterHorizontally - ) { - // Whose name this goes out in, said before anything is - // pasted. It is the group's, whatever the paste says. - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - ProfileAvatar( - size = MaterialTheme.spacing.space500, - publicKey = chatRoomId, - picture = proposeGroupEventUIState.groupNostrProfile?.picture(), - name = proposeGroupEventUIState.groupNostrProfile?.name() - ) - - Spacer(modifier = Modifier.width(MaterialTheme.spacing.itemGap)) - - Text( - text = proposeGroupEventUIState.groupNostrProfile?.name() - ?: proposeGroupEventUIState.localChatRoom.chatRoom.subject - ?: chatRoomId.take(16), - style = MaterialTheme.typography.titleSmall, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - - Text( - text = stringResource( - Res.string.paste_an_unsigned_event_for_the_group_to_sign - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - Text( - text = stringResource( - Res.string.the_group_signs_an_event_so_it_takes_a_quorum - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center - ) - - if (!canSign) { - Text( - text = stringResource( - Res.string.this_group_has_no_shared_key_to_sign_an_event - ), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error, - textAlign = TextAlign.Center - ) - } - - when (reading) { - null -> Unit - is GroupEventProposal.Ready -> ProposalPreview(reading) - is GroupEventProposal.Refused -> RefusalNotice(reading) - } - - OutlinedTextField( - modifier = Modifier.fillMaxWidth().weight(1f) - .background(BottomAppBarDefaults.containerColor), - state = eventFieldState, - // The paste grows into the screen rather than scrolling - // inside three lines, and is set in a monospace face: - // it is JSON, and a bracket that does not line up is - // the kind of thing a member is looking for in it. - lineLimits = TextFieldLineLimits.MultiLine(), - textStyle = TextStyle(fontFamily = FontFamily.Monospace), - colors = OutlinedTextFieldDefaults.colors( - focusedBorderColor = Color.Transparent, - unfocusedBorderColor = Color.Transparent, - disabledBorderColor = Color.Transparent - ), - label = { Text(stringResource(Res.string.unsigned_event)) }, - placeholder = { - Text( - text = stringResource(Res.string.eg_kind_1_tags_content), - fontFamily = FontFamily.Monospace - ) - }, - isError = reading is GroupEventProposal.Refused - ) - } - } - } - - ProposeGroupEventUIState.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.propose_event), - style = MaterialTheme.typography.bodyLarge, - textAlign = TextAlign.Center - ) - - LoadingDataIndicator(fillScreen = false) - } - } - } - } - - LaunchedEffect(true) { - if (initialProposeGroupEventUIState == ProposeGroupEventUIState.Loading) { - proposeGroupEventViewModel.initiateProposeGroupEvent() - } - } -} - -/** - * What the group would sign, said the way the signing screen will say it. - * - * `ProposedEvent.summarize` rather than a description of this screen's own, so - * that what a member reads here before proposing is word for word what every - * other member reads before signing. Two descriptions of one event would drift. - */ -@Composable -private fun ProposalPreview(ready: GroupEventProposal.Ready) { - val summary = ProposedEvent.summarize(ready.preview()) - - Card(modifier = Modifier.fillMaxWidth()) { - Column( - modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), - verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) - ) { - Text( - text = stringResource(Res.string.what_the_group_would_sign), - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - - Text( - text = stringResource(Res.string.kind_n, ready.kind.toString()) + " · " + summary.label, - style = MaterialTheme.typography.titleSmall - ) - - // Capped, because a kind:1's detail is the whole post and the paste - // under this card is the thing the screen is for. - Text( - text = summary.detail, - style = MaterialTheme.typography.bodyMedium, - maxLines = 6, - overflow = TextOverflow.Ellipsis - ) - } - } -} - -/** - * Why the group will not be asked, under the paste it is about. - * - * Named rather than silent: a button that does nothing for a paste it refuses is - * indistinguishable from a missed tap. - */ -@Composable -private fun RefusalNotice(refused: GroupEventProposal.Refused) { - Text( - text = when (refused) { - GroupEventProposal.Refused.NotJson -> stringResource(Res.string.that_is_not_json) - GroupEventProposal.Refused.NotAnObject -> stringResource(Res.string.an_event_is_a_json_object) - GroupEventProposal.Refused.NoKind -> stringResource(Res.string.an_event_needs_a_kind) - is GroupEventProposal.Refused.KindNotAccepted -> stringResource( - Res.string.kind_n_has_nowhere_to_go_on_this_screen, - refused.kind.toString(), - GroupEventProposal.ACCEPTED_KINDS.sorted().joinToString() - ) - GroupEventProposal.Refused.TagsMalformed -> - stringResource(Res.string.tags_must_be_a_list_of_lists_of_strings) - GroupEventProposal.Refused.ContentNotText -> stringResource(Res.string.content_must_be_text) - GroupEventProposal.Refused.ProfileUnreadable -> - stringResource(Res.string.the_content_is_not_a_profile) - GroupEventProposal.Refused.PostBlank -> stringResource(Res.string.a_post_needs_something_to_say) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.error - ) -} - -@ConformancePreviews -@Composable -private fun ProposeGroupEventScreenPreview() { - BennuTheme { - Surface(modifier = Modifier.fillMaxSize()) { - ProposeGroupEventScreen( - activeUserPublicKey = "", - chatRoomId = "publicKey", - relayHint = null, - initialProposeGroupEventUIState = ProposeGroupEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = "publicKey", - userPublicKey = "", - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ), - ), - // A group that can sign, so the screen renders in the state a - // member actually meets it in rather than greyed out. - canSign = true - ), - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 3b9f350b..eb782bc4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -44,16 +44,8 @@ import com.machankura.bennu.compose.ui.composable.CreateSharedKeyScreen import com.machankura.bennu.compose.ui.composable.DkgRitualScreen import com.machankura.bennu.compose.ui.composable.DkgRound1ApprovalScreen import com.machankura.bennu.compose.ui.composable.DkgRound2ApprovalScreen -import com.machankura.bennu.compose.ui.composable.EditGroupNostrProfileScreen -import com.machankura.bennu.compose.ui.composable.AddGroupPostScreen -import com.machankura.bennu.compose.ui.composable.BroadcastGroupSignedEventScreen -import com.machankura.bennu.compose.ui.composable.ProposeGroupEventScreen -import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen -import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen -import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupWalletScreen import com.machankura.bennu.compose.ui.composable.GroupWalletAddressesScreen -import com.machankura.bennu.compose.ui.composable.GroupPostsScreen import com.machankura.bennu.compose.ui.composable.HomeScreen import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen import com.machankura.bennu.compose.ui.composable.KeyPackageManagementScreen @@ -145,19 +137,11 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposeGroupEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.ProposalListRoute import com.machankura.bennu.compose.ui.composable.FrostSigningScreen @@ -1143,38 +1127,6 @@ fun BennuNavHost( }, ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupNostrProfileScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupRelaysScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() @@ -1229,134 +1181,6 @@ fun BennuNavHost( } ) } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - GroupPostsScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - onNavigateToRoute = { actionRoute -> - navController.navigate(route = actionRoute) - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - EditGroupNostrProfileScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the form so back returns to the group rather than - // to an edit whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - EditGroupRelaysScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the editor so back returns to the group rather - // than to lists whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - AddGroupPostScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the composer so back returns to the group rather - // than to a draft whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } - 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, - // as the entries screen is for its "Broadcast all": a - // group-signed event must not become a `NostrEvent` row, and - // the queue hangs off one. See - // `BroadcastGroupSignedEventViewModel`. - publishTransport = synchronizationViewModel.relaysSocketManager, - onNavigateBack = { - navController.popBackStack() - } - ) - } - composable { backStackEntry -> - val route = backStackEntry.toRoute() - - ProposeGroupEventScreen( - activeUserPublicKey = route.activeUserPublicKey, - chatRoomId = route.chatRoomId, - relayHint = route.relayHint, - chatRepository = databaseChatRepository, - frostSigningRepository = databaseFrostSigningRepository, - onNavigateToRouteAndPopUpInclusive = { signingRoute -> - // Replace the paste so back returns to the group rather - // than to an event whose proposal has already gone out. - navController.navigate(route = signingRoute) { - popUpTo { - inclusive = true - } - } - }, - onNavigateBack = { - navController.popBackStack() - } - ) - } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt deleted file mode 100644 index fc2619ed..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/AddGroupPostRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class AddGroupPostRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt deleted file mode 100644 index 7268d494..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/BroadcastGroupSignedEventRoute.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.machankura.bennu.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/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt deleted file mode 100644 index 18cb2495..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupNostrProfileRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class EditGroupNostrProfileRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt deleted file mode 100644 index 771dd52e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/EditGroupRelaysRoute.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -@Serializable -data class EditGroupRelaysRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt deleted file mode 100644 index 06f3254c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupNostrProfileRoute.kt +++ /dev/null @@ -1,19 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * What the group says about itself on nostr, as the group signed it. - * - * The group's screen names the profile in a row; this is where it is read, with - * the broadcast under it and, for a member holding a share of the key, the way - * into the editor. One of the three screens the group's signed work is split - * across -- see [GroupRelaysRoute] and [GroupPostsRoute] -- each pushed from its - * row on the group's screen. - */ -@Serializable -data class GroupNostrProfileRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt deleted file mode 100644 index be352f7f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupPostsRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * What the group has said publicly, as itself, newest first, with a broadcast - * under each post and the way into the composer for a member holding a share - * of the key. - */ -@Serializable -data class GroupPostsRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt deleted file mode 100644 index a76a9a86..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupRelaysRoute.kt +++ /dev/null @@ -1,15 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** - * Where the group has said it lives on nostr: its four relay lists, as the - * group signed them, with a broadcast under each one it has agreed and the way - * into the editor for a member holding a share of the key. - */ -@Serializable -data class GroupRelaysRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt deleted file mode 100644 index 82c810ba..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/ProposeGroupEventRoute.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.navigation.routes - -import kotlinx.serialization.Serializable - -/** The untyped way into a group's signed statements: an unsigned event, pasted. */ -@Serializable -data class ProposeGroupEventRoute( - val activeUserPublicKey: String, - val chatRoomId: String, // TODO: have this as a publicKey - val relayHint: String? -): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt deleted file mode 100644 index d227381c..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/RelayOutcomeLabel.kt +++ /dev/null @@ -1,30 +0,0 @@ -package com.machankura.bennu.compose.ui.composable.widgets - -import androidx.compose.runtime.Composable -import bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.relay_accepted -import bennu.composeapp.generated.resources.relay_could_not_send -import bennu.composeapp.generated.resources.relay_no_answer -import bennu.composeapp.generated.resources.relay_rejected -import bennu.composeapp.generated.resources.relay_sending -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.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/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt deleted file mode 100644 index dcbe5d5e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/buttons/BroadcastButton.kt +++ /dev/null @@ -1,38 +0,0 @@ -package com.machankura.bennu.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 bennu.composeapp.generated.resources.Res -import bennu.composeapp.generated.resources.broadcast -import org.jetbrains.compose.resources.stringResource -import com.machankura.bennu.compose.ui.composable.widgets.Decorative -import com.machankura.bennu.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/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt index 074ad720..7fa3d7ec 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -346,15 +346,11 @@ fun ChatTranscript( return@items } - // The group's own profile, signed. Same treatment - // and for the same reason: nobody said it. Answered - // and settled because it reports rather than asks -- - // a quorum has already signed by the time this line - // exists. - // - // It leads nowhere. What a reader wants from one is - // the profile, and the nostr profile section of the - // group's detail screen is where that lives. + // Something the group signed. Same treatment and for + // the same reason: nobody said it. Answered and + // settled because it reports rather than asks -- a + // quorum has already signed by the time this line + // exists. It leads nowhere. if (localChatMessage.chatMessage.messageType in ChatMessage.GROUP_IDENTITY_TYPES) { RitualNotice( localChatMessage = localChatMessage, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt index efbf4e97..8c4a36c5 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/profile/ProfileAvatar.kt @@ -56,10 +56,8 @@ fun ProfileAvatar( /** * The same avatar for a subject that has no `Profile` row. * - * A group's is the case in hand: its kind:0 is signed by the group and kept as a - * `GroupSignedEvent`, which is not a `NostrEvent` and so cannot have a `Profile` - * hanging off it -- see `GroupNostrProfile`. The picture and the name are all this - * ever wanted from a profile, so they are what it takes. + * The picture and the name are all this ever wanted from a profile, so they are + * what it takes. * * [name] only reaches the content description. The tint behind a missing picture * comes from [publicKey], which is what keeps the same subject the same colour diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt deleted file mode 100644 index 5adc8b61..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/AddGroupPostViewModel.kt +++ /dev/null @@ -1,154 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -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 co.touchlab.kermit.Logger -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.AddGroupPostUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to say something publicly, in its own name. - * - * The post is not written here and does not exist yet. What goes out is a proposal - * to sign one, and the post appears -- on every member's device at once, authored by - * the room's own key rather than by whoever typed it -- when enough members have - * signed. That author is the room's id: signing runs at the path the room was - * derived at, so a post says which group made it simply by being signed. - * - * That is the difference from a message in the room. A message is a member speaking - * where the group can hear; this is the group speaking where anyone can, and it - * takes a quorum to say. - */ -class AddGroupPostViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var addGroupPostUIState: AddGroupPostUIState by mutableStateOf(initialAddGroupPostUIState) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateAddGroupPost() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - addGroupPostUIState = if (localChatRoom == null) { - AddGroupPostUIState.Error("Couldn't find the chat room") - } else { - AddGroupPostUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // identity to post under -- the same condition the group detail - // screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over one kind:1 authored by the group. - * - * Refuses a blank draft rather than proposing it: a quorum signing an empty note - * would put a post on the record that renders as nothing and cannot be told from - * a broken one -- and kind:1 is not replaceable, so there is no un-saying it. - * `GroupPost.newestFirstAmong` drops blanks on the way back out too, which is - * the second line of the same defence. - * - * The draft is not cleared on success. This screen is replaced by the signing - * session, and on the failure path the words are the thing worth keeping. - */ - fun proposePost( - localChatRoom: LocalChatRoom, - noteField: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onEmpty: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Posts accumulate rather than replace, so a - // second session over the same words is a second post on the record forever. - if (isActionPending.value) return - - val note = noteField.text.toString().trim() - if (note.isBlank()) { - onEmpty.invoke() - return - } - - isActionPending.value = true - - val template = GroupPost.template(note) - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a post for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "AddGroupPostViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialAddGroupPostUIState: AddGroupPostUIState = AddGroupPostUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - AddGroupPostViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialAddGroupPostUIState = initialAddGroupPostUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt deleted file mode 100644 index 86c5e8f7..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModel.kt +++ /dev/null @@ -1,485 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -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 com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.relays.RelayPool -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.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. - * - * The send itself, [sendToRelays], is also what the entries screen's "Broadcast - * all" uses, one entry after another and each to the relays [defaultRelaysFor] - * would have seeded here; what is this screen's is the list the member edits - * and the rows that show each relay's answer. - * - * ### 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 group's own General list where it has agreed one, the - * app's publish set where it has not, plus the indexers for a relay list, minus - * anything the group has blocked. The member can add and remove 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" - ) - - // The group's wallet statement carries its xpub: on a relay it is - // every address and the whole balance, to anyone. - signedEvent.kind in GroupWalletStatementEvent.NEVER_BROADCAST -> - BroadcastGroupSignedEventUIState.Error( - "The group's wallet stays inside the group" - ) - - else -> BroadcastGroupSignedEventUIState.Loaded( - localChatRoom = localChatRoom, - signedEvent = signedEvent, - relayLists = chatRepository.groupRelayLists(chatRoomId), - ) - } - } - } - - /** - * 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( - relayLists: List, - kind: Kind, - ) { - if (isSeeded) return - isSeeded = true - - relays.addAll(defaultRelaysFor(relayLists, 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 = GroupRelaySet.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], which the entries screen's - * "Broadcast all" shares; 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. Shared by the one-event screen and the entries - * screen's "Broadcast all", so that what a relay's answer becomes is - * decided in one place. - */ - suspend fun sendToRelays( - publishTransport: EventPublishTransport, - signedEvent: GroupSignedEvent, - targets: List, - onOutcome: (NormalizedRelayUrl, RelayOutcome) -> Unit = { _, _ -> }, - ): Map { - // The second line of the refusal the loader makes, for the callers that - // never pass through it -- "Broadcast all" among them. - require(signedEvent.kind !in GroupWalletStatementEvent.NEVER_BROADCAST) { - "kind ${signedEvent.kind} never leaves the group" - } - - 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 group's General list is the answer NIP-65 gives -- its write relays, - * where it has agreed any -- and the app's own publish set stands in for a - * group that has not, since a list of nothing would make the button a - * no-op on every group until somebody edits it. A relay list goes to the - * indexers as well: the list says where to find the group, so sending it - * only to the relays it names is circular -- a reader who already knew - * those relays would not need the list. - * - * And nothing goes to a relay the group has blocked, whatever the other - * lists say; that is what a blocked list is for. - */ - fun defaultRelaysFor( - relayLists: List, - kind: Kind, - ): List { - val general = relayLists.firstOrNull { it.set == GroupRelaySet.General } - ?.relays.orEmpty() - .filter { it.write } - .map { it.url } - - val where = general.ifEmpty { Relays.eventPublishRelaySet.toList() } - - val indexers = if (kind in GroupRelaySet.KINDS) { - Relays.DefaultIndexerRelayList.toList() - } else { - emptyList() - } - - val blocked = relayLists.firstOrNull { it.set == GroupRelaySet.Blocked } - ?.relays.orEmpty() - .map { it.url } - .toSet() - - return (where + indexers).distinct().filterNot { it in blocked } - } - - 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/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt index ac4802d0..ebf28d4c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -92,11 +92,7 @@ class ChatRoomDetailViewModel( signedGroupKeyStateEvent = chatRepository.signedGroupKeyStateEvent(chatRoomId), subgroups = chatRepository.subgroupsOf(chatRoomId), parentChatRoomId = chatRepository.parentOf(chatRoomId), - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - groupRelayLists = chatRepository.groupRelayLists(chatRoomId), - groupPosts = chatRepository.groupPosts(chatRoomId), groupWallet = chatRepository.groupWallet(chatRoomId, NodeParamsManager.chain), - canEditNostrProfile = canSign, canAddSubgroup = canSign, canGovern = canGovern, isDisbanded = isDisbanded, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt deleted file mode 100644 index 8467072f..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupNostrProfileViewModel.kt +++ /dev/null @@ -1,161 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.foundation.text.input.TextFieldState -import androidx.compose.runtime.MutableState -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 co.touchlab.kermit.Logger -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupNostrProfileUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to sign what it says about itself on nostr. - * - * The room's id is the pubkey the group signs as, so the kind:0 this proposes is - * the profile the rest of nostr would read for that key -- authored by the group - * rather than by whoever filled the form in. Nothing is saved when the button is - * pressed: what goes out is a proposal, and the profile changes on every member's - * device at once when a quorum has signed it. - */ -class EditGroupNostrProfileViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var editGroupNostrProfileUIState: EditGroupNostrProfileUIState by mutableStateOf( - initialEditGroupNostrProfileUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateEditGroupNostrProfile() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - editGroupNostrProfileUIState = if (localChatRoom == null) { - EditGroupNostrProfileUIState.Error("Couldn't find the chat room") - } else { - EditGroupNostrProfileUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // nostr identity to describe -- the same condition the group - // detail screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over one kind:0 for the group's own key. - * - * A blank field is not a field left alone: it clears what the group had said, - * because that is the only way to unsay it. [GroupNostrProfile.template] hands - * every field to `MetadataEvent`, whose rule for these arguments is that empty - * deletes the key -- and it builds on the group's newest profile, so a field - * this form does not offer is carried across rather than wiped. - * - * The fields are not cleared on success, unlike the add forms': a profile is - * standing state rather than a thing being added, and this screen is replaced - * by the signing session anyway. - */ - fun proposeNostrProfile( - localChatRoom: LocalChatRoom, - groupNostrProfile: GroupNostrProfile?, - nameField: TextFieldState, - aboutField: TextFieldState, - pictureField: TextFieldState, - websiteField: TextFieldState, - nip05Field: TextFieldState, - lud16Field: TextFieldState, - onSuccess: (sessionId: String) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits from repeated taps. A second session over a - // second kind:0 would leave the group's profile decided by whichever - // quorum finished last. - if (isActionPending.value) return - isActionPending.value = true - - val template = GroupNostrProfile.template( - latest = groupNostrProfile, - name = nameField.text.toString().trim(), - about = aboutField.text.toString().trim(), - picture = pictureField.text.toString().trim(), - website = websiteField.text.toString().trim(), - nip05 = nip05Field.text.toString().trim(), - lud16 = lud16Field.text.toString().trim(), - ) - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = template.kind, - tags = template.tags, - content = template.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a nostr profile for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "EditGroupNostrProfileViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupNostrProfileUIState: EditGroupNostrProfileUIState = - EditGroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - EditGroupNostrProfileViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupNostrProfileUIState = initialEditGroupNostrProfileUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt deleted file mode 100644 index 909fc16b..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModel.kt +++ /dev/null @@ -1,299 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -import androidx.compose.runtime.getValue -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.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * The group's relay lists, edited locally and proposed together. - * - * Nothing here is saved. The working copy lives in [working] until the button is - * pressed, and what the button does is open one signing session over the sets that - * changed -- so the group's relay lists change on every member's device at once, - * when a quorum has signed, or not at all. - * - * ### Why one session rather than one per set - * - * Wisp publishes a tab at a time because a person's client signs for itself and - * there is nothing to coordinate. Here every signature costs a quorum's attention, - * and four separate sessions for one sitting at one screen would ask for it four - * times over what is plainly a single decision: where this group lives. - * - * The batch carries **only the sets that differ**, which is what keeps that honest. - * Re-signing a list nobody touched would put a second, identical statement on the - * record with a newer timestamp -- harmless, since these are replaceable, and still - * a lie about when the group last decided anything. - * - * `FrostSigningManager` documents the cost of batching: a batch is all-or-nothing - * and so only as available as its worst item. These four items are the same size, - * the same shape and signed by the same quorum in the same second, so there is no - * worst one to be dragged down by. - */ -class EditGroupRelaysViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var editGroupRelaysUIState: EditGroupRelaysUIState by mutableStateOf( - initialEditGroupRelaysUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - /** - * The working copy: what the lists would be if the group agreed. - * - * A snapshot map so the editor recomposes as rows are added and removed, and - * held on the view model rather than in the composition so that switching tabs - * -- which is a pager page changing -- does not throw away an edit. - */ - val working = mutableStateMapOf>() - - /** Which set the editor is showing, and so what the add field adds to. */ - var selectedSet: GroupRelaySet by mutableStateOf(GroupRelaySet.entries.first()) - private set - - /** - * Why the last add did not happen, or null. Cleared by the next keystroke. - * - * Named rather than silent: Wisp's add button does nothing at all for a URL it - * refuses, and "nothing happened" is indistinguishable from a missed tap. - */ - var addFailure: AddFailure? by mutableStateOf(null) - private set - - enum class AddFailure { - /** Not a `wss://` URL, or one pointing at this machine. */ - NotARelay, - - /** Already in this set, which is a no-op rather than a mistake. */ - AlreadyListed, - } - - fun initiateEditGroupRelays() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - editGroupRelaysUIState = if (localChatRoom == null) { - EditGroupRelaysUIState.Error("Couldn't find the chat room") - } else { - EditGroupRelaysUIState.Loaded( - localChatRoom = localChatRoom, - signed = chatRepository.groupRelayLists(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Fills the working copy from what the group signed, leaving edits alone. - * - * A set the group has agreed starts at its list; one it has not starts at the - * set's defaults, which is what puts this build's own relay in front of a group - * setting up for the first time rather than an empty list. See - * `GroupRelaySet.defaults`. - * - * Called from the screen rather than from [initiateEditGroupRelays], because - * the loader is not the only way a loaded state arrives -- a preview and a - * layout test both hand one straight in, and seeding only on the load path gave - * both of them an editor with nothing in it while the app worked fine. The - * screen has the state either way. - * - * **Only fills what is missing**, so running again after the member has typed - * something does not undo it. That matters because the effect that calls this - * is keyed on a state the view model can re-emit. - */ - fun seedWorkingCopy(signed: List) { - signed.forEach { list -> - if (list.set in working) return@forEach - - working[list.set] = if (list.isAgreed) list.relays else list.set.defaults() - } - } - - fun selectSet(set: GroupRelaySet) { - selectedSet = set - addFailure = null - } - - fun clearAddFailure() { - addFailure = null - } - - fun relaysOf(set: GroupRelaySet): List = working[set] ?: emptyList() - - /** - * Adds [url] to the selected set, 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 = GroupRelaySet.relayUrlOrNull(url) ?: run { - addFailure = AddFailure.NotARelay - return false - } - - val current = relaysOf(selectedSet) - if (current.any { it.url == relayUrl }) { - addFailure = AddFailure.AlreadyListed - return false - } - - working[selectedSet] = current + GroupRelay(relayUrl) - addFailure = null - return true - } - - fun removeRelay(set: GroupRelaySet, relay: GroupRelay) { - working[set] = relaysOf(set).filterNot { it.url == relay.url } - } - - /** - * Turns a NIP-65 marker on or off, refusing to turn off the last one. - * - * A relay that is neither read nor write has no tag in NIP-65 -- see - * `GroupRelaySet.template` -- so the state does not exist to be put the group's - * signature on. What it would mean is that the relay is not in the list, and - * removing it is the row's own button. - */ - fun toggleRead(set: GroupRelaySet, relay: GroupRelay) = - toggle(set, relay) { it.copy(read = !it.read) } - - fun toggleWrite(set: GroupRelaySet, relay: GroupRelay) = - toggle(set, relay) { it.copy(write = !it.write) } - - private fun toggle( - set: GroupRelaySet, - relay: GroupRelay, - change: (GroupRelay) -> GroupRelay, - ) { - working[set] = relaysOf(set).map { - if (it.url != relay.url) return@map it - - change(it).takeIf { changed -> changed.read || changed.write } ?: it - } - } - - /** - * The sets whose working copy says something different to what the group - * signed, in the order the editor shows them. - * - * Order-sensitive on purpose. A relay list is written in the order it is read - * back, and a member who moved a relay to the front meant to; comparing as sets - * would call that no change and quietly refuse to propose it. - * - * A set the group has never agreed counts as changed as soon as it holds - * anything, so a first-time group's seeded defaults are a real proposal rather - * than an accident, and an empty one it has never agreed counts as unchanged -- - * there is nothing to say. - */ - fun changedSets(signed: List): List = - signed.filter { list -> relaysOf(list.set) != list.relays } - .filterNot { list -> !list.isAgreed && relaysOf(list.set).isEmpty() } - .map { it.set } - - /** - * Opens one session over every set that changed. - * - * [onNothingToPropose] rather than a session over nothing: - * `proposeSigningBatch` refuses an empty batch outright, and a member who has - * changed nothing is asking a question rather than making a mistake. - */ - fun proposeRelayLists( - localChatRoom: LocalChatRoom, - signed: List, - onSuccess: (sessionId: String) -> Unit, - onNothingToPropose: () -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. Two sessions over two versions of one relay - // list would leave the group's answer decided by whichever quorum finished - // last. - if (isActionPending.value) return - - val changed = changedSets(signed) - if (changed.isEmpty()) { - onNothingToPropose.invoke() - return - } - - isActionPending.value = true - - val templates = changed.map { set -> set.template(relaysOf(set)) } - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigningBatch( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - events = templates, - ) - }.onFailure { error -> - logger.e("Failed to propose relay lists for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "EditGroupRelaysViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialEditGroupRelaysUIState: EditGroupRelaysUIState = - EditGroupRelaysUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - EditGroupRelaysViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialEditGroupRelaysUIState = initialEditGroupRelaysUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt deleted file mode 100644 index b5b27846..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupNostrProfileViewModel.kt +++ /dev/null @@ -1,71 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupNostrProfileUIState - -/** - * The group's nostr profile, read once for the screen that shows it. - * - * One read rather than a watch, the way the group's screen reads it: a profile - * changes when a quorum signs a new one, which lands as a group event this - * device processes, and the screen is re-entered -- and re-read -- on the way - * back from the signing session that made it. - */ -class GroupNostrProfileViewModel( - val chatRoomId: String, - initialGroupNostrProfileUIState: GroupNostrProfileUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupNostrProfileUIState: GroupNostrProfileUIState by mutableStateOf( - initialGroupNostrProfileUIState - ) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupNostrProfileUIState = if (localChatRoom == null) { - GroupNostrProfileUIState.Error("Couldn't find the group") - } else { - GroupNostrProfileUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room is excluded by the first half: it has no key - // of its own to sign as, so nothing to hold a share of. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupNostrProfileUIState: GroupNostrProfileUIState = - GroupNostrProfileUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupNostrProfileViewModel( - chatRoomId = chatRoomId, - initialGroupNostrProfileUIState = initialGroupNostrProfileUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt deleted file mode 100644 index e3c282ae..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupPostsViewModel.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState - -/** - * The group's posts, read once for the screen that shows them, with the - * profile that bylines them. One read rather than a watch, for the reason - * `GroupNostrProfileViewModel` gives. - */ -class GroupPostsViewModel( - val chatRoomId: String, - initialGroupPostsUIState: GroupPostsUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupPostsUIState: GroupPostsUIState by mutableStateOf(initialGroupPostsUIState) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupPostsUIState = if (localChatRoom == null) { - GroupPostsUIState.Error("Couldn't find the group") - } else { - GroupPostsUIState.Loaded( - localChatRoom = localChatRoom, - groupPosts = chatRepository.groupPosts(chatRoomId), - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupPostsUIState: GroupPostsUIState = GroupPostsUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupPostsViewModel( - chatRoomId = chatRoomId, - initialGroupPostsUIState = initialGroupPostsUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt deleted file mode 100644 index c3c4a5ea..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupRelaysViewModel.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.machankura.bennu.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 kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState - -/** - * The group's relay lists, read once for the screen that shows them. One read - * rather than a watch, for the reason `GroupNostrProfileViewModel` gives. - */ -class GroupRelaysViewModel( - val chatRoomId: String, - initialGroupRelaysUIState: GroupRelaysUIState, - val chatRepository: ChatRepository, -): ViewModel() { - - var groupRelaysUIState: GroupRelaysUIState by mutableStateOf(initialGroupRelaysUIState) - private set - - fun initiate() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - groupRelaysUIState = if (localChatRoom == null) { - GroupRelaysUIState.Error("Couldn't find the group") - } else { - GroupRelaysUIState.Loaded( - localChatRoom = localChatRoom, - groupRelayLists = chatRepository.groupRelayLists(chatRoomId), - canSign = localChatRoom.chatRoom.mlsGroupState != null && - chatRepository.canSign(chatRoomId), - ) - } - } - } - - companion object { - fun factory( - chatRoomId: String, - initialGroupRelaysUIState: GroupRelaysUIState = GroupRelaysUIState.Loading, - chatRepository: ChatRepository, - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - GroupRelaysViewModel( - chatRoomId = chatRoomId, - initialGroupRelaysUIState = initialGroupRelaysUIState, - chatRepository = chatRepository, - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt deleted file mode 100644 index 29607e18..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposeGroupEventViewModel.kt +++ /dev/null @@ -1,158 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import androidx.compose.runtime.MutableState -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 co.touchlab.kermit.Logger -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupEventProposal -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.IO -import kotlinx.coroutines.launch - -/** - * Asks the group to sign an event a member pasted. - * - * Nothing is built here; the paste is the event. What this decides is whether - * the group should be asked at all -- `GroupEventProposal.read` refuses a paste - * the group's screen could never show, so a quorum is not spent on an event that - * would be signed, filed and seen by nobody -- and it hands the kind, tags and - * content to the same `proposeSigning` every typed editor uses. The author and - * the time are the session's to fill in, which is how a pasted `pubkey` or - * `created_at` comes to be ignored: they are never passed along. - * - * Where the event lands is decided by nothing here. `FrostSigningManager.complete` - * files every signed event as a `GroupSignedEvent`, and the group's screen reads - * its profile, posts, relay lists and schemas off those by kind. A pasted kind 0 - * becomes the profile the same way a kind 0 from the profile form does, because - * by the time either is signed there is no telling them apart. - */ -class ProposeGroupEventViewModel( - val chatRoomId: String, - val activeUserPublicKey: HexKey, - val relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState, - val chatRepository: ChatRepository, - val frostSigningRepository: FrostSigningRepository, -): ViewModel() { - - var proposeGroupEventUIState: ProposeGroupEventUIState by mutableStateOf( - initialProposeGroupEventUIState - ) - private set - - private val logger = Logger.withTag(TAG) - - val isActionPending: MutableState = mutableStateOf(false) - - fun initiateProposeGroupEvent() { - viewModelScope.launch(Dispatchers.IO) { - val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) - - proposeGroupEventUIState = if (localChatRoom == null) { - ProposeGroupEventUIState.Error("Couldn't find the chat room") - } else { - ProposeGroupEventUIState.Loaded( - localChatRoom = localChatRoom, - groupNostrProfile = chatRepository.groupNostrProfile(chatRoomId), - // A NIP-17 room has no key of its own to sign as, so it has no - // statements to make -- the same condition the group detail - // screen gates the entry point on. - canSign = localChatRoom.chatRoom.mlsGroupState != null && - frostSigningRepository.canSign(chatRoomId), - ) - } - } - } - - /** - * Opens a session over the pasted event, or says why not. - * - * [onRefused] carries the reading's own reason, which the screen has been - * showing under the paste all along; it is repeated here so pressing the - * button on a refused paste is answered rather than ignored. Both refusals - * and a failed proposal stay on the paste: the JSON is the thing worth - * keeping. - */ - fun proposeEvent( - localChatRoom: LocalChatRoom, - json: String, - onSuccess: (sessionId: String) -> Unit, - onRefused: (GroupEventProposal.Refused) -> Unit, - onFailure: () -> Unit - ) { - // Guard against double submits. A pasted kind:1 accumulates like any - // other post, so a second session over the same paste is a second post - // on the record forever. - if (isActionPending.value) return - - val ready = when (val reading = GroupEventProposal.read(json)) { - is GroupEventProposal.Ready -> reading - is GroupEventProposal.Refused -> { - onRefused.invoke(reading) - return - } - } - - isActionPending.value = true - - viewModelScope.launch(Dispatchers.IO) { - val session = runCatching { - frostSigningRepository.proposeSigning( - localChatRoom = localChatRoom, - userPublicKey = activeUserPublicKey, - kind = ready.kind, - tags = ready.tags, - content = ready.content, - ) - }.onFailure { error -> - logger.e("Failed to propose a pasted kind ${ready.kind} event for $chatRoomId", error) - }.getOrNull() - - viewModelScope.launch(Dispatchers.Main) { - if (session != null) { - onSuccess.invoke(session.id) - } else { - onFailure.invoke() - } - } - - isActionPending.value = false - } - } - - companion object { - private const val TAG = "ProposeGroupEventViewModel" - - fun factory( - activeUserPublicKey: HexKey, - chatRoomId: String, - relayHint: String?, - initialProposeGroupEventUIState: ProposeGroupEventUIState = - ProposeGroupEventUIState.Loading, - chatRepository: ChatRepository, - frostSigningRepository: FrostSigningRepository - ): ViewModelProvider.Factory = viewModelFactory { - initializer { - ProposeGroupEventViewModel( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = relayHint, - initialProposeGroupEventUIState = initialProposeGroupEventUIState, - chatRepository = chatRepository, - frostSigningRepository = frostSigningRepository - ) - } - } - } -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt deleted file mode 100644 index 0c499154..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/AddGroupPostUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface AddGroupPostUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Who the group says it is, for the byline over the draft. - * - * A post is signed by the group and read as the group, so the composer - * shows whose voice is being written in -- which is not the member typing. - * Null in a group that has not described itself, and the byline falls back - * to the room. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the draft writable and the button inert, for the same reason - * the other two editors do: reading and composing cost nothing, and only a - * share-holder can open the session that would sign it. - */ - val canSign: Boolean = false, - ): AddGroupPostUIState - - data class Error( - val message: String - ): AddGroupPostUIState - - data object Loading: AddGroupPostUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt deleted file mode 100644 index a9b4b6b0..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/BroadcastGroupSignedEventUIState.kt +++ /dev/null @@ -1,26 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -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, - /** - * Where the group has said it lives, which is what the relay picker starts - * from: the General list's write relays when the group has agreed one, and - * never a relay the group has blocked. See - * `BroadcastGroupSignedEventViewModel.defaultRelaysFor`. - */ - val relayLists: List = emptyList(), - ): BroadcastGroupSignedEventUIState - - data class Error( - val message: String - ): BroadcastGroupSignedEventUIState - - data object Loading: BroadcastGroupSignedEventUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt index 60729548..5de31b9e 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -6,9 +6,6 @@ import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.managers.SubgroupManager import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList sealed interface ChatRoomDetailUIState { data class Loaded( @@ -50,63 +47,12 @@ sealed interface ChatRoomDetailUIState { * really is a subgroup. */ val parentChatRoomId: HexKey? = null, - /** - * The kind:0 the group signed about itself, or null while it has signed - * none. - * - * Its row sits under the room's identity and above its work, because that - * is what it is: the name and the picture the rest of nostr sees on the - * key the signing key row names. The row shows the name and the address; - * the profile itself is read on `GroupNostrProfileScreen`. Null is an - * ordinary state and the row says so -- a group has an identity from the - * moment it has a key and describes it whenever somebody gets round to it. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Where the group has said it lives on nostr, one entry per relay set. - * - * Beside the profile because they are the same kind of fact -- the group's - * own account of itself, signed by the group -- and read in the same breath - * by anybody checking whether the group is reachable. The row counts how - * many the group has agreed; the lists are read on `GroupRelaysScreen`. - * - * Empty only in a room that has none of this to say. Every other case has - * four entries, some of them unsigned; see `ChatRepository.groupRelayLists`. - */ - val groupRelayLists: List = emptyList(), - /** - * What the group has said publicly, as itself, newest first. - * - * Under the relay lists because it is the thing they are *for*: the profile - * says who the group is, the relay lists say where to find it, and these - * are what a reader would find there. The row counts them; they are read - * on `GroupPostsScreen`. Empty in a group that has said nothing, which is - * every group until somebody proposes one. - */ - val groupPosts: List = emptyList(), /** * The wallet this group has opened on the app's network, or null for one - * it has not. Under the identity block because it is not part of the - * group's account of itself on nostr -- nobody outside the room reads it -- - * and the row says only whether it is open; the coins are read on + * it has not. The row says only whether it is open; the coins are read on * `GroupWalletScreen`. */ val groupWallet: GroupWallet? = null, - /** - * Whether this device could sign an event for the group, which on this - * screen gates the paste at the end of the identity block. Each of the - * three screens the rows open reads the same capability for its own gate. - * - * The same capability [canAddSubgroup] wants, and wanted for the same - * reason: proposing anything in the group's name is a signature by the - * group, and `FrostSigningManager.proposeSigningBatch` throws for a - * device holding no share of the key. It is not about permission -- any - * member with a share may propose -- and the quorum is what decides. - * - * A NIP-17 room is excluded by the same condition, since it has no key of - * its own to sign as and so no nostr identity to describe. - */ - val canEditNostrProfile: Boolean = false, /** * Whether this device could open a subgroup here at all. * diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt deleted file mode 100644 index a2a39725..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupNostrProfileUIState.kt +++ /dev/null @@ -1,34 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface EditGroupNostrProfileUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has already said about itself, or null the first time. - * - * The form starts from it, and so does the event: an edit is built with - * `MetadataEvent.updateFromPast` so a field this app does not offer survives - * being edited rather than being dropped by it. See - * [GroupNostrProfile.template]. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the form readable and the button inert, which is the honest - * shape: the profile is worth reading either way, and a member without a - * share cannot open a session for one. See - * `ChatRoomDetailUIState.canEditNostrProfile`. - */ - val canSign: Boolean = false, - ): EditGroupNostrProfileUIState - - data class Error( - val message: String - ): EditGroupNostrProfileUIState - - data object Loading: EditGroupNostrProfileUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt deleted file mode 100644 index e957ce76..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/EditGroupRelaysUIState.kt +++ /dev/null @@ -1,33 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface EditGroupRelaysUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has signed for each set, which is what an edit is measured - * against. - * - * Kept beside the working copy rather than replaced by it, because the - * button only proposes the sets that actually differ -- and "differ" needs - * both halves. See `EditGroupRelaysViewModel.changedSets`. - */ - val signed: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the lists readable and the button inert: where the group - * says it lives is worth reading whoever is looking, and proposing a change - * to it is a signature only a share-holder can start. - */ - val canSign: Boolean = false, - ): EditGroupRelaysUIState - - data class Error( - val message: String - ): EditGroupRelaysUIState - - data object Loading: EditGroupRelaysUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt deleted file mode 100644 index d4a47e41..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupNostrProfileUIState.kt +++ /dev/null @@ -1,35 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface GroupNostrProfileUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * The kind:0 the group signed about itself, or null while it has signed - * none. - * - * Null is an ordinary state and the screen says so -- a group has an - * identity from the moment it has a key and describes it whenever - * somebody gets round to it. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the profile readable and hides the way into the editor: - * proposing one is a signature by the group, and - * `FrostSigningManager.proposeSigningBatch` throws for a device holding - * no share. It is not about permission -- any member with a share may - * propose -- and the quorum is what decides. - */ - val canSign: Boolean = false, - ): GroupNostrProfileUIState - - data class Error( - val message: String - ): GroupNostrProfileUIState - - data object Loading: GroupNostrProfileUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt deleted file mode 100644 index a4d93d9e..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupPostsUIState.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost - -sealed interface GroupPostsUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * What the group has said publicly, as itself, newest first. Empty in - * a group that has said nothing, which is every group until somebody - * proposes a post. - */ - val groupPosts: List = emptyList(), - /** - * The group's profile, for the byline on every post. - * - * Read alongside the posts because a post is the one thing here a - * reader might otherwise attribute to whichever member proposed it, - * and the group's own name and picture are what say it was the group. - * Null where the group has not described itself, and the byline falls - * back to the key. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the posts readable and hides the way into the composer, - * for the reason `GroupNostrProfileUIState.Loaded.canSign` gives. - */ - val canSign: Boolean = false, - ): GroupPostsUIState - - data class Error( - val message: String - ): GroupPostsUIState - - data object Loading: GroupPostsUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt deleted file mode 100644 index cd2a0e14..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupRelaysUIState.kt +++ /dev/null @@ -1,31 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupRelayList - -sealed interface GroupRelaysUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Where the group has said it lives on nostr, one entry per relay set. - * - * Empty only in a room that has none of this to say. Every other case - * has four entries, some of them unsigned; see - * `ChatRepository.groupRelayLists`. - */ - val groupRelayLists: List = emptyList(), - /** - * Whether this device holds a share of the group's key. - * - * False leaves the lists readable and hides the way into the editor, - * for the reason `GroupNostrProfileUIState.Loaded.canSign` gives. - */ - val canSign: Boolean = false, - ): GroupRelaysUIState - - data class Error( - val message: String - ): GroupRelaysUIState - - data object Loading: GroupRelaysUIState -} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt deleted file mode 100644 index 6e867343..00000000 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ProposeGroupEventUIState.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.machankura.bennu.compose.ui.view.state - -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile - -sealed interface ProposeGroupEventUIState { - data class Loaded( - val localChatRoom: LocalChatRoom, - /** - * Who the group says it is, for the byline over the paste. - * - * Whatever is pasted goes out signed by the group and read as the group, - * so the screen shows whose name it will carry -- which is not the - * member pasting it, and not whatever `pubkey` the paste may name. - */ - val groupNostrProfile: GroupNostrProfile? = null, - /** - * Whether this device holds a share of the group's key. - * - * False leaves the paste writable and the button inert, for the same - * reason the typed editors do: reading and checking cost nothing, and - * only a share-holder can open the session that would sign it. - */ - val canSign: Boolean = false, - ): ProposeGroupEventUIState - - data class Error( - val message: String - ): ProposeGroupEventUIState - - data object Loading: ProposeGroupEventUIState -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt deleted file mode 100644 index 2e9862fb..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupEventProposalTest.kt +++ /dev/null @@ -1,300 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -/** - * What a pasted event may become, and where it goes once the group has signed it. - * - * Two halves. The first is the reading: which pastes are refused and why, and - * that what is refused is exactly what a reader would refuse -- the point of - * checking before proposing is that a quorum is never asked to sign something - * that will be filed and shown nowhere. - * - * The second is the promise the feature makes: a pasted kind 0 becomes the - * profile, a kind 1 a post, a relay list a relay list. That - * is not this module's doing -- `FrostSigningManager.complete` files every signed - * event and the group's screen reads each section off those by kind -- so the - * test is the whole chain: the paste read here, signed by a real quorum through - * the same shape `FrostSigningManager.advance` runs, and read back by the reader - * that section uses. - */ -class GroupEventProposalTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - /** - * A post as another client would print it: a whole event, id, author, - * signature and time included. - */ - private val pastedPost = """ - { - "id": "b2f8c7a7b4d5e6f70123456789abcdef0123456789abcdef0123456789abcdef", - "pubkey": "7c965d8c2acdfd635562da3bcb82596b595be28b008d8b54ec702ed4c67d9d25", - "created_at": 1735689600, - "kind": 1, - "tags": [ - ["t", "translation"], - ["alt", "{\"chapter\":1,\"of\":12}"] - ], - "content": "We have finished the first chapter.", - "sig": "c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00" - } - """.trimIndent() - - @Test - fun `a pasted event is read as its kind tags and content and nothing else`() { - val ready = assertIs(GroupEventProposal.read(pastedPost)) - - assertEquals(1, ready.kind) - assertEquals("We have finished the first chapter.", ready.content) - assertEquals(2, ready.tags.size) - assertEquals(listOf("t", "translation"), ready.tags.first().toList()) - // A JSON value inside a tag comes through verbatim, escapes and all. - assertEquals("{\"chapter\":1,\"of\":12}", ready.tags[1][1]) - - // The id, author, signature and time are not the paste's to decide, and - // there is nowhere on a reading for them to go: the session hashes the id - // over the room's key and the time it opens at. - val preview = ready.preview() - assertEquals("", preview.pubKey) - assertEquals(0L, preview.createdAt) - } - - @Test - fun `a bare template with no tags or content still reads`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 0, "content": "{}"}""") - ) - assertEquals(0, ready.kind) - assertEquals(0, ready.tags.size) - - // A numeric string for the kind is what a hand types; a relay writes a number. - assertIs( - GroupEventProposal.read("""{"kind": "1", "content": "Hello"}""") - ) - } - - @Test - fun `what is not an event is refused and named`() { - assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("not json at all")) - assertEquals(GroupEventProposal.Refused.NotJson, GroupEventProposal.read("{\"kind\": 1,")) - assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("[1, 2, 3]")) - assertEquals(GroupEventProposal.Refused.NotAnObject, GroupEventProposal.read("\"a string\"")) - assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"content": "Hello"}""")) - assertEquals(GroupEventProposal.Refused.NoKind, GroupEventProposal.read("""{"kind": "one"}""")) - assertEquals( - GroupEventProposal.Refused.TagsMalformed, - GroupEventProposal.read("""{"kind": 1, "tags": "e", "content": "Hello"}""") - ) - assertEquals( - GroupEventProposal.Refused.TagsMalformed, - GroupEventProposal.read("""{"kind": 1, "tags": [["e", 1]], "content": "Hello"}""") - ) - assertEquals( - GroupEventProposal.Refused.ContentNotText, - GroupEventProposal.read("""{"kind": 1, "content": {"note": "Hello"}}""") - ) - } - - @Test - fun `a kind the group's screen has no place for is refused whatever else it says`() { - // A long-form article is a perfectly good nostr event and the group could - // sign it. It would then be filed and shown nowhere, with nothing to tell - // the member their quorum was spent on it. - assertEquals( - GroupEventProposal.Refused.KindNotAccepted(30023), - GroupEventProposal.read("""{"kind": 30023, "tags": [["d", "x"]], "content": "An article"}""") - ) - - // The kinds with a section: the profile, the posts and the four relay - // lists. A subgroup certificate is deliberately not among them. - assertEquals( - setOf(0, 1, 10002, 10050, 10007, 10006), - GroupEventProposal.ACCEPTED_KINDS - ) - } - - @Test - fun `a kind zero whose content is not a profile is refused and an empty one is not`() { - assertEquals( - GroupEventProposal.Refused.ProfileUnreadable, - GroupEventProposal.read("""{"kind": 0, "content": "not a profile"}""") - ) - - // Wiping a profile is a thing groups are entitled to do -- the same line - // `GroupNostrProfile.of` draws. - assertIs(GroupEventProposal.read("""{"kind": 0, "content": ""}""")) - assertIs( - GroupEventProposal.read("""{"kind": 0, "content": "{\"name\":\"Translation collective\"}"}""") - ) - } - - @Test - fun `a blank post is refused the way the composer refuses one`() { - listOf("", " ", "\\n\\n").forEach { blank -> - assertEquals( - GroupEventProposal.Refused.PostBlank, - GroupEventProposal.read("""{"kind": 1, "content": "$blank"}"""), - "a post saying \"$blank\" was accepted" - ) - } - } - - @Test - fun `a relay list reads whether or not it names a relay`() { - // An empty one is a list the group is withdrawing, which the relays card - // shows as "no relays" rather than as nothing. - assertIs(GroupEventProposal.read("""{"kind": 10002}""")) - assertIs( - GroupEventProposal.read("""{"kind": 10002, "tags": [["r", "wss://relay.example.com", "write"]]}""") - ) - } - - @Test - fun `a pasted kind zero once signed is the group's profile`() { - val ready = assertIs( - GroupEventProposal.read( - """{"kind": 0, "pubkey": "not the group", "content": "{\"name\":\"Translation collective\",\"about\":\"We translate hard books.\"}"}""" - ) - ) - - val profile = assertNotNull(GroupNostrProfile.of(signed(ready), chatRoomId)) - - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals(chatRoomId, profile.publicKey) - } - - @Test - fun `a pasted kind one once signed is one of the group's posts`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 1, "tags": [], "content": "We have finished the first chapter."}""") - ) - - val posts = GroupPost.newestFirstAmong(listOf(signed(ready)), chatRoomId) - - assertEquals(listOf("We have finished the first chapter."), posts.map { it.content }) - assertTrue(posts.single().isNewThread()) - } - - @Test - fun `a pasted relay list once signed is one of the group's relay lists`() { - val ready = assertIs( - GroupEventProposal.read("""{"kind": 10002, "tags": [["r", "wss://relay.example.com", "write"]]}""") - ) - - val list = GroupRelayList.newestAmong(listOf(signed(ready)), chatRoomId, GroupRelaySet.General) - - assertTrue(list.isAgreed) - assertEquals(listOf("relay.example.com"), list.relays.map { it.displayUrl() }) - assertEquals(listOf(false), list.relays.map { it.read }) - assertEquals(listOf(true), list.relays.map { it.write }) - } - - /** - * A reading as `FrostSigningManager.complete` would file it: authored by the - * room's key at its path, the id hashed over that, a real quorum's signature - * on it, and the time the session opened at rather than anything pasted. - */ - private fun signed(ready: GroupEventProposal.Ready, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val groupPubKey = SharedKeyDerivation - .derive(groupMaterial.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = ready.kind, - tags = ready.tags, - content = ready.content - ) - - return GroupSignedEvent.fromEvent( - event = Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = ready.kind, - tags = ready.tags, - content = ready.content, - sig = groupSignature(groupMaterial, id) - ), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt deleted file mode 100644 index e80ae282..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupNostrProfileTest.kt +++ /dev/null @@ -1,438 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull - -/** - * What a group's nostr profile is allowed to be read out of. - * - * A room's id is the pubkey it signs as, so a kind:0 authored by that key is the - * group describing itself and a kind:0 authored by anything else is not -- however - * it came to be filed against the room. The reading is what the group detail screen - * shows and what an edit is built on top of, so both halves are worth pinning: - * which events become a profile, and what an edit does to the one before it. - * - * The edit half is the one with a silent failure behind it. `updateFromPast` is - * used precisely so a field this app does not offer survives being edited, and - * `createNew` in its place would compile, pass any test that only looked at the - * fields the form knows about, and quietly wipe the rest of the group's profile - * every time somebody fixed a typo in its name. - */ -class GroupNostrProfileTest { - private val participants = 3 - private val threshold = 2 - - /** The group whose profile this is. */ - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the profiles signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - private val strangerChatRoomId = - SharedKeyDerivation.marmotGroupId(strangerMaterial.thresholdPublicKey.value.toHex(), path) - - @Test - fun `a kind zero the room signed is the group's profile`() { - val profile = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Translation collective","about":"We translate hard books.",""" + - """"picture":"https://example.com/group.png","nip05":"group@example.com"}""" - ), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals("https://example.com/group.png", profile.picture()) - assertEquals("group@example.com", profile.nip05()) - assertEquals(chatRoomId, profile.publicKey) - } - - @Test - fun `display_name is what a name is read out of when both are set`() { - // Every other nostr client prefers it, and `template` writes both so they - // agree. A group whose two names disagree got them from somewhere else, - // and the answer has to be the one the rest of nostr will give. - val profile = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"collective","display_name":"Translation collective"}""" - ), - chatRoomId = chatRoomId - ) - - assertEquals("Translation collective", profile?.name()) - } - - @Test - fun `a kind zero another group signed is not this group's profile`() { - // A real quorum and a real signature by a group with no standing to say - // anything about this room. The row names this room because that is where - // the event was filed; the author is what decides whose profile it is. - val stranger = GroupSignedEvent.fromEvent( - event = metadataEvent( - content = """{"name":"Somebody else"}""", - material = strangerMaterial - ), - chatRoomId = chatRoomId - ) - - assertEquals(strangerChatRoomId, stranger.publicKey, "the fixture signs as the stranger") - assertNull(GroupNostrProfile.of(signedEvent = stranger, chatRoomId = chatRoomId)) - } - - @Test - fun `a kind zero whose signature is not the room's is not a profile`() { - // Authored by the room, saying the right things, and signed by a key that - // is not the room's. This is the shape a member forging a rename produces. - assertNull( - GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Renamed by one member"}""", - signer = strangerMaterial - ), - chatRoomId = chatRoomId - ) - ) - - // And everything off the wire is allowed to be nonsense, which means no - // rather than an exception. - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"x"}""", signature = rubbish), - chatRoomId = chatRoomId - ), - "a profile signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not a profile`() { - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"x"}""").copy(kind = 1), - chatRoomId = chatRoomId - ) - ) - } - - @Test - fun `the newest profile the group signed is the one that counts`() { - // kind:0 is replaceable: editing a profile signs a second one, and the - // second is the answer whatever order the query hands them over in. - val older = signed(content = """{"name":"What it was called"}""", createdAt = 1_700_000_000) - val newer = signed(content = """{"name":"What it is called"}""", createdAt = 1_700_000_900) - - listOf(listOf(older, newer), listOf(newer, older)).forEach { events -> - assertEquals( - "What it is called", - GroupNostrProfile.newestAmong(events, chatRoomId)?.name(), - "the newest profile lost to query order" - ) - } - } - - @Test - fun `two profiles signed in the same second resolve the same way on every device`() { - // Two devices catching up read the same events in whatever order the - // relay or the query gives them, and they have to end up showing the same - // profile. A tie on the timestamp is broken by the id, which every device - // agrees on because it is a hash of the event. - val one = signed(content = """{"name":"One"}""", createdAt = 1_700_000_000) - val other = signed(content = """{"name":"Other"}""", createdAt = 1_700_000_000) - - val expected = GroupNostrProfile.newestAmong(listOf(one, other), chatRoomId)?.name() - - assertNotNull(expected) - assertEquals( - expected, - GroupNostrProfile.newestAmong(listOf(other, one), chatRoomId)?.name(), - "a tie on the timestamp was broken differently by the two orderings" - ) - assertEquals( - if (one.id > other.id) "One" else "Other", - expected, - "the tie should break on the id, which is the only thing both devices share" - ) - } - - @Test - fun `the first profile a group signs carries the fields it was given`() { - val template = GroupNostrProfile.template( - latest = null, - name = "Translation collective", - about = "We translate hard books.", - picture = "https://example.com/group.png", - website = "https://example.com", - nip05 = "group@example.com", - lud16 = "group@getalby.com" - ) - - val profile = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertEquals(MetadataEvent.KIND, template.kind) - assertEquals("Translation collective", profile.name()) - assertEquals("We translate hard books.", profile.about()) - assertEquals("https://example.com/group.png", profile.picture()) - assertEquals("https://example.com", profile.website()) - assertEquals("group@example.com", profile.nip05()) - assertEquals("group@getalby.com", profile.lud16()) - } - - @Test - fun `an edit keeps a field the form does not offer`() { - // The reason `template` builds on the group's own event rather than from - // scratch. `bot` is not on the form and never will be reached by it; an - // edit that dropped it would be this app deciding a group is not a bot - // because somebody fixed its name. - val existing = GroupNostrProfile.of( - signedEvent = signed(content = """{"name":"Old name","bot":true}"""), - chatRoomId = chatRoomId - ) - assertNotNull(existing) - - val template = GroupNostrProfile.template( - latest = existing, - name = "New name", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val edited = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(edited) - assertEquals("New name", edited.name()) - assertEquals(true, edited.metadata.bot, "an edit dropped a field the form does not offer") - } - - @Test - fun `an emptied field unsays what the group had said`() { - // The only way to withdraw something a group has signed. A form that sent - // nulls for its blanks could add to a profile and never subtract from one. - val existing = GroupNostrProfile.of( - signedEvent = signed( - content = """{"name":"Translation collective","about":"Something regretted"}""" - ), - chatRoomId = chatRoomId - ) - assertNotNull(existing) - - val template = GroupNostrProfile.template( - latest = existing, - name = "Translation collective", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val edited = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - ) - - assertNotNull(edited) - assertNull(edited.about()) - assertEquals("Translation collective", edited.name()) - } - - @Test - fun `a name is written to both of the keys a reader might look in`() { - val template = GroupNostrProfile.template( - latest = null, - name = "Translation collective", - about = "", - picture = "", - website = "", - nip05 = "", - lud16 = "" - ) - - val metadata = GroupNostrProfile.of( - signedEvent = signed(content = template.content), - chatRoomId = chatRoomId - )?.metadata - - assertNotNull(metadata) - assertEquals("Translation collective", metadata.name) - assertEquals( - "Translation collective", - metadata.displayName, - "a client preferring display_name would show the old name after an edit" - ) - } - - @Test - fun `an empty profile is a profile rather than a parse failure`() { - // Wiping a profile is something a group is entitled to do, and an empty - // kind:0 is how nostr says it. Reading it as nothing would leave the - // screen claiming the group had never said anything. - val profile = GroupNostrProfile.of( - signedEvent = signed(content = ""), - chatRoomId = chatRoomId - ) - - assertNotNull(profile) - assertNull(profile.name()) - assertNull(profile.about()) - } - - @Test - fun `content that is not a profile at all is refused`() { - assertNull( - GroupNostrProfile.of( - signedEvent = signed(content = "not json"), - chatRoomId = chatRoomId - ) - ) - } - - /** - * A profile row as `FrostSigningManager.complete` files one: the content under - * the room's own key, with the id hashed over it and the group's signature on - * it. - * - * [signer] is pulled apart from the author so a signature by the wrong quorum - * can be tested, and [signature] replaces the real one outright for what is - * not a signature at all. - */ - private fun signed( - content: String, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = metadataEvent( - content = content, - createdAt = createdAt, - material = material, - signer = signer, - signature = signature - ), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun metadataEvent( - content: String, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - * - * Assembled any other way it would not be evidence about the signatures this - * app actually produces. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt deleted file mode 100644 index 92362772..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupPostTest.kt +++ /dev/null @@ -1,307 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What may be shown as something the group said. - * - * The reading gate is `GroupNostrProfileTest`'s -- the room has to be the author and - * the signature has to be the room's -- and it matters more here than anywhere else - * in this feature. A profile read wrong shows the wrong name; a post read wrong puts - * words in a group's mouth under a byline saying a quorum agreed to them, on a page - * whose whole purpose is to be read by people who were not there. - * - * The ordering half is the other thing worth pinning. Posts are the one statement - * here that **accumulates**: kind:1 is not replaceable, so a second post stands - * beside the first rather than replacing it, and everything the profile and the - * relay lists do with "newest wins" is wrong for these. - */ -class GroupPostTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the posts signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - @Test - fun `a kind one the room signed is a post by the group`() { - val post = GroupPost.of( - signedEvent = signed("We have finished the first chapter."), - chatRoomId = chatRoomId - ) - - assertEquals("We have finished the first chapter.", post?.content) - assertEquals(chatRoomId, post?.publicKey) - assertTrue(post?.isNewThread() == true) - } - - @Test - fun `a kind one another group signed is not this group's post`() { - // A real quorum and a real signature by a group with no standing to speak - // for this one. The row names this room because that is where it was filed; - // the author is what decides whose words they are. - val stranger = GroupSignedEvent.fromEvent( - event = noteEvent("Said by somebody else entirely.", material = strangerMaterial), - chatRoomId = chatRoomId - ) - - assertNull(GroupPost.of(signedEvent = stranger, chatRoomId = chatRoomId)) - } - - @Test - fun `a kind one the room did not sign is not a post`() { - // Authored by the room and signed by somebody else: the shape a member - // putting words in the group's mouth would produce, and the reason the - // reading verifies rather than trusting the author field. - assertNull( - GroupPost.of( - signedEvent = signed("The group has decided to disband.", signer = strangerMaterial), - chatRoomId = chatRoomId - ) - ) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupPost.of( - signedEvent = signed("Anything at all", signature = rubbish), - chatRoomId = chatRoomId - ), - "a post signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `an event of another kind is not a post`() { - assertNull( - GroupPost.of( - signedEvent = signed("Hello").copy(kind = 30023), - chatRoomId = chatRoomId - ) - ) - } - - @Test - fun `posts accumulate rather than replace newest first`() { - // The property that separates these from the profile and the relay lists. - // A reading that kept only the newest would silently delete a group's whole - // history the first time it posted twice. - val first = signed("First", createdAt = 1_700_000_000) - val second = signed("Second", createdAt = 1_700_000_900) - val third = signed("Third", createdAt = 1_700_001_800) - - listOf( - listOf(first, second, third), - listOf(third, second, first), - listOf(second, third, first), - ).forEach { events -> - assertEquals( - listOf("Third", "Second", "First"), - GroupPost.newestFirstAmong(events, chatRoomId).map { it.content }, - "posts came back in the wrong order, or one of them went missing" - ) - } - } - - @Test - fun `two posts signed in the same second resolve the same way on every device`() { - // Two devices reading the same posts in whatever order the query hands them - // over have to show the same feed. A tie on the timestamp breaks on the id, - // which both agree on because it is a hash of the event. - val one = signed("One", createdAt = 1_700_000_000) - val other = signed("Other", createdAt = 1_700_000_000) - - val expected = GroupPost.newestFirstAmong(listOf(one, other), chatRoomId).map { it.content } - - assertEquals( - expected, - GroupPost.newestFirstAmong(listOf(other, one), chatRoomId).map { it.content }, - "a tie on the timestamp was broken differently by the two orderings" - ) - assertEquals( - if (one.id > other.id) listOf("One", "Other") else listOf("Other", "One"), - expected, - "the tie should break on the id, which is the only thing both devices share" - ) - } - - @Test - fun `a blank post is dropped rather than drawn as an empty card`() { - // The composer will not produce one, so anything reaching here empty came - // from somewhere this app does not control -- and an empty signed card - // cannot be told from a broken one. - listOf("", " ", "\n\n").forEach { blank -> - assertEquals( - emptyList(), - GroupPost.newestFirstAmong(listOf(signed(blank)), chatRoomId), - "a post saying \"$blank\" was shown" - ) - } - } - - @Test - fun `a reply is marked as one`() { - // Nothing here writes replies, so this is about an event that arrived some - // other way. Drawing one as an announcement would put half a conversation on - // a group's page with no sign that it was half. - val reply = GroupPost.of( - signedEvent = signed( - "Yes, agreed.", - tags = arrayOf(arrayOf("e", "b".repeat(64), "", "reply")) - ), - chatRoomId = chatRoomId - ) - - assertFalse(reply?.isNewThread() == true) - } - - @Test - fun `the composer builds a bare note and trims it`() { - // No reply tags, no mentions, no subject: every tag `TextNoteEvent.build` - // can add describes a relationship to something else, which a group's first - // way of posting does not have and should not guess at. - val template = GroupPost.template(" Something the group would say. ") - - assertEquals(TextNoteEvent.KIND, template.kind) - assertEquals("Something the group would say.", template.content) - assertEquals(emptyList(), template.tags.toList()) - } - - @Test - fun `a post the composer built reads back as the group said it`() { - val template = GroupPost.template("We have finished the first chapter.") - val post = GroupPost.of( - signedEvent = signed(template.content, tags = template.tags), - chatRoomId = chatRoomId - ) - - assertEquals("We have finished the first chapter.", post?.content) - assertTrue(post?.isNewThread() == true) - } - - /** A post as `FrostSigningManager.complete` files one. */ - private fun signed( - note: String, - tags: Array> = emptyArray(), - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = noteEvent(note, tags, createdAt, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun noteEvent( - note: String, - tags: Array> = emptyArray(), - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = TextNoteEvent.KIND, - tags = tags, - content = note - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = TextNoteEvent.KIND, - tags = tags, - content = note, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt deleted file mode 100644 index 22ed566e..00000000 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/GroupRelayListTest.kt +++ /dev/null @@ -1,398 +0,0 @@ -package com.machankura.bennu.compose.nostr - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.extensions.toHex -import com.machankura.bennu.compose.managers.SharedKeyDerivation -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray -import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -import fr.acinq.bitcoin.ByteVector -import fr.acinq.bitcoin.ByteVector32 -import fr.acinq.bitcoin.PrivateKey -import fr.acinq.bitcoin.crypto.frost.Frost -import fr.acinq.bitcoin.crypto.frost.IndividualNonce -import fr.acinq.bitcoin.crypto.frost.KeyMaterial -import fr.acinq.bitcoin.crypto.frost.SecretNonce -import fr.acinq.bitcoin.crypto.frost.Session -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNull -import kotlin.test.assertTrue - -/** - * What a group's relay lists are allowed to be read out of, and what an edit - * produces. - * - * The reading half is `GroupNostrProfileTest`'s again -- the room has to be the - * author, the signature has to be the room's -- and it is repeated here because - * these are four different kinds through two different tag vocabularies, and a - * mistake in any one of them would be invisible in the other three. - * - * The writing half is the one that could not be settled by reading the code. - * NIP-65's markers are absent for both, `read` for read-only and `write` for - * write-only, so the tag for the ordinary case is the one with the least in it -- - * exactly the shape a round trip is most likely to lose. And "neither" is a state - * the format cannot express at all, which is why the editor refuses it and why - * building one drops it rather than writing a tag that means the opposite. - */ -class GroupRelayListTest { - private val participants = 3 - private val threshold = 2 - - private val groupMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("1c0ffee0000000000000000000000000000000000000000000000000000000a1") - ), - nParticipants = participants, - threshold = threshold - ) - - /** Another group entirely, for the lists signed by the wrong room. */ - private val strangerMaterial: KeyMaterial = Frost.trustedDealerKeygen( - thresholdSecretKey = PrivateKey( - ByteVector32("3decade0000000000000000000000000000000000000000000000000000000c3") - ), - nParticipants = participants, - threshold = threshold - ) - - private val path = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH - - private val chatRoomId = - SharedKeyDerivation.marmotGroupId(groupMaterial.thresholdPublicKey.value.toHex(), path) - - private val one = RelayUrlNormalizer.normalize("wss://relay.one.example") - private val two = RelayUrlNormalizer.normalize("wss://relay.two.example") - - @Test - fun `every set round trips through the tags it is written in`() { - // Four kinds and two tag vocabularies: NIP-65's "r" for General and the - // "relay" tag for the other three, through two RelayTag classes that are - // different classes in different packages. A set wired to the wrong one - // writes tags nothing reads back. - GroupRelaySet.entries.forEach { set -> - val relays = listOf(GroupRelay(one), GroupRelay(two)) - val list = GroupRelayList.of( - signedEvent = signed(set.template(relays)), - chatRoomId = chatRoomId, - set = set - ) - - assertEquals( - listOf(one, two), - list?.relays?.map { it.url }, - "${set.name} did not round trip through its own tags" - ) - } - } - - @Test - fun `a relay list only reads back as the set it was written as`() { - // The kinds are the only thing separating a general list from a blocked - // one, and reading a blocked list as a general one would have the group - // publishing to the relays it refuses to talk to. - val blocked = signed(GroupRelaySet.Blocked.template(listOf(GroupRelay(one)))) - - assertNull(GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.General)) - assertNull(GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.Search)) - assertEquals( - listOf(one), - GroupRelayList.of(blocked, chatRoomId, GroupRelaySet.Blocked)?.relays?.map { it.url } - ) - } - - @Test - fun `read and write markers survive being written and read`() { - // The ordinary case is the dangerous one: NIP-65 writes both by *omitting* - // the marker, so a round trip that lost the third element entirely would - // still look correct for a both-ways relay and would silently turn a - // read-only relay into a write one. - val relays = listOf( - GroupRelay(one, read = true, write = true), - GroupRelay(two, read = true, write = false), - GroupRelay(RelayUrlNormalizer.normalize("wss://relay.three.example"), - read = false, write = true), - ) - - val readBack = GroupRelayList.of( - signedEvent = signed(GroupRelaySet.General.template(relays)), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - - assertEquals(relays, readBack?.relays) - } - - @Test - fun `a relay that is neither read nor write is not written at all`() { - // NIP-65 has no marker for it. The editor will not produce the state, and - // this is the second line of that defence: writing a bare `r` tag would - // advertise it as both, which is the opposite of what was asked. - val list = GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template( - listOf( - GroupRelay(one, read = false, write = false), - GroupRelay(two), - ) - ) - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - - assertEquals(listOf(two), list?.relays?.map { it.url }) - } - - @Test - fun `a relay list another group signed is not this group's`() { - val stranger = GroupSignedEvent.fromEvent( - event = relayEvent( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - material = strangerMaterial - ), - chatRoomId = chatRoomId - ) - - assertNull(GroupRelayList.of(stranger, chatRoomId, GroupRelaySet.General)) - } - - @Test - fun `a relay list the room did not sign is not a relay list`() { - // Authored by the room and signed by somebody else -- the shape a member - // redirecting a group's traffic would produce. - assertNull( - GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - signer = strangerMaterial - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ) - ) - - listOf("f".repeat(128), "not a signature", "").forEach { rubbish -> - assertNull( - GroupRelayList.of( - signedEvent = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - signature = rubbish - ), - chatRoomId = chatRoomId, - set = GroupRelaySet.General - ), - "a list signed with \"$rubbish\" was accepted" - ) - } - } - - @Test - fun `a set the group never agreed reads back unsigned and empty`() { - // Not null. The screen has a row per set whatever the group has said, and - // `isAgreed` is what separates "never said" from "said nothing". - val list = GroupRelayList.newestAmong(emptyList(), chatRoomId, GroupRelaySet.Search) - - assertFalse(list.isAgreed) - assertEquals(emptyList(), list.relays) - assertEquals(GroupRelaySet.Search, list.set) - assertNull(list.signedAt) - } - - @Test - fun `an agreed empty list is not the same as one never agreed`() { - // A group withdrawing its relay list signs an empty one, and that decision - // has to survive being read back -- otherwise a deliberate withdrawal looks - // exactly like never having got round to it. - val list = GroupRelayList.of( - signedEvent = signed(GroupRelaySet.Messages.template(emptyList())), - chatRoomId = chatRoomId, - set = GroupRelaySet.Messages - ) - - assertTrue(list?.isAgreed == true) - assertEquals(emptyList(), list?.relays) - } - - @Test - fun `the newest list the group signed is the one that counts`() { - val older = signed( - GroupRelaySet.General.template(listOf(GroupRelay(one))), - createdAt = 1_700_000_000 - ) - val newer = signed( - GroupRelaySet.General.template(listOf(GroupRelay(two))), - createdAt = 1_700_000_900 - ) - - listOf(listOf(older, newer), listOf(newer, older)).forEach { events -> - assertEquals( - listOf(two), - GroupRelayList.newestAmong(events, chatRoomId, GroupRelaySet.General) - .relays.map { it.url }, - "the newest relay list lost to query order" - ) - } - } - - @Test - fun `allAmong sorts every set into one entry each`() { - val events = listOf( - signed(GroupRelaySet.General.template(listOf(GroupRelay(one)))), - signed(GroupRelaySet.Blocked.template(listOf(GroupRelay(two)))), - ) - - val all = GroupRelayList.allAmong(events, chatRoomId) - - assertEquals(GroupRelaySet.entries.toList(), all.map { it.set }) - assertEquals(listOf(one), all.first { it.set == GroupRelaySet.General }.relays.map { it.url }) - assertEquals(listOf(two), all.first { it.set == GroupRelaySet.Blocked }.relays.map { it.url }) - assertFalse(all.first { it.set == GroupRelaySet.Search }.isAgreed) - assertFalse(all.first { it.set == GroupRelaySet.Messages }.isAgreed) - } - - @Test - fun `every set but blocked starts at the app's own relay`() { - // What a group setting up for the first time is shown. Seeding with nothing - // would make its first proposal an empty list, which says less than never - // having said anything. - GroupRelaySet.entries.filterNot { it == GroupRelaySet.Blocked }.forEach { set -> - assertEquals( - listOf(Relays.ephemeral), - set.defaults().map { it.url }, - "${set.name} did not default to the app's relay" - ) - } - - // And blocked starts empty: a default there is a refusal to talk to - // somebody that nobody in the group chose. - assertEquals(emptyList(), GroupRelaySet.Blocked.defaults()) - } - - @Test - fun `only a wss relay somewhere other than this device is accepted`() { - assertEquals(one, GroupRelaySet.relayUrlOrNull("wss://relay.one.example")) - assertEquals(one, GroupRelaySet.relayUrlOrNull(" wss://relay.one.example ")) - - // A group's list is read by strangers over the open network: ws:// asks - // them to fetch it in the clear, and loopback names a relay only one device - // can reach. - listOf( - "ws://relay.one.example", - "http://relay.one.example", - "relay.one.example", - "wss://localhost", - "wss://127.0.0.1", - "", - ).forEach { - assertNull(GroupRelaySet.relayUrlOrNull(it), "\"$it\" was accepted as a relay") - } - } - - @Test - fun `a duplicated relay is read once`() { - // Two tags for one relay is one relay said twice, and a list that shows it - // twice reads as two to a human -- the same reasoning a birth certificate's - // admin roster is deduplicated on. - val duplicated = Event( - id = "", - pubKey = chatRoomId, - createdAt = 1_700_000_000, - kind = AdvertisedRelayListEvent.KIND, - tags = arrayOf(arrayOf("r", one.url), arrayOf("r", one.url, "read")), - content = "", - sig = "" - ) - - assertEquals(listOf(one), GroupRelaySet.General.parse(duplicated.tags).map { it.url }) - } - - /** A relay list as `FrostSigningManager.complete` files one. */ - private fun signed( - template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): GroupSignedEvent = GroupSignedEvent.fromEvent( - event = relayEvent(template, createdAt, material, signer, signature), - chatRoomId = chatRoomId, - derivationPath = SharedKeyDerivation.formatPath(path) - ) - - private fun relayEvent( - template: com.vitorpamplona.quartz.nip01Core.signers.EventTemplate<*>, - createdAt: Long = 1_700_000_000, - material: KeyMaterial = groupMaterial, - signer: KeyMaterial = material, - signature: String? = null - ): Event { - val groupPubKey = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .hex - - val id = EventHasher.hashId( - pubKey = groupPubKey, - createdAt = createdAt, - kind = template.kind, - tags = template.tags, - content = template.content - ) - - return Event( - id = id, - pubKey = groupPubKey, - createdAt = createdAt, - kind = template.kind, - tags = template.tags, - content = template.content, - sig = signature ?: groupSignature(signer, id) - ) - } - - /** - * A real FROST signature by [material]'s quorum over [eventId], through the - * same shape `FrostSigningManager.advance` runs. - */ - private fun groupSignature(material: KeyMaterial, eventId: String): String { - val cache = SharedKeyDerivation - .derive(material.thresholdPublicKey.value.toHex(), path) - .cache - val message = ByteVector(eventId.hexToByteArray()) - val signerIds = listOf(0, 1) - - val nonces = signerIds.map { signerId -> - SecretNonce.generate( - sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), - secretShare = material.secretShares[signerId], - publicShare = material.publicShares[signerId], - tweakedThresholdPublicKey = cache.tweakedPublicKey, - message = message, - extraInput = null - ) - } - - val signingSession = Session.create( - aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, - signerIds = signerIds.map { it.toUInt() }, - signerPublicShares = signerIds.map { material.publicShares[it] }, - nParticipants = participants, - threshold = threshold, - tweakCache = cache, - message = message - ) - - val partials = signerIds.mapIndexed { position, signerId -> - signingSession.sign( - nonces[position].first, - material.secretShares[signerId], - signerId.toUInt() - ).right!! - } - - return signingSession.aggregateSigs(partials).right!!.toByteArray().toHex() - } -} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt index 73c237ef..7af91bf4 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/chronicle/ChronicleTestKinds.kt @@ -13,13 +13,12 @@ import com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent * * Chosen for three properties: * - * - **each is a group-signed kind `ChatMessage.applyInnerEvent` has an arm - * for**, so a payload goes down the real apply path rather than falling - * through to "unsupported"; - * - **none of those arms writes a row of its own or throws** -- the group's - * profile, relay lists and posts are read straight off `GroupSignedEvent` - * -- so what a receiver holds afterwards is exactly the `GroupSignedEvent` - * rows the chronicle recorded, and comparing those is comparing the work; + * - **none is a kind the app gives a meaning of its own** -- a profile and a + * relay list apply to nothing, and a kind:1 to the "unsupported" line it + * has always been -- so applying one neither throws nor writes a + * `GroupSignedEvent` of its own, and the `GroupSignedEvent` rows a receiver + * holds afterwards are exactly the ones the chronicle recorded: comparing + * those is comparing the work; * - **the order disagrees with the kind numbers** (10002 before 0 before 1), * so a test that the order is the list's cannot pass by sorting on kind. * diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt index 62889d8b..09ef5b85 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/text/ProposedEventTest.kt @@ -8,55 +8,15 @@ import kotlin.test.Test import kotlin.test.assertEquals /** - * How the events a group signs about itself are said to the member signing them. + * How the events a group signs are said to the member signing them. * - * These are read on the signing screen, in the room's list of proposals and now - * on the paste screen before proposing, and the same words in all three is the - * point of there being one mapping. What is pinned is that each kind is said as - * the thing it is and by the part of it a signer is actually deciding about -- - * a profile by its name, a post by its words, a relay list by its hosts -- and - * never as "kind 0" over a wall of JSON. + * These are read on the signing screen and in the room's list of proposals, and + * the same words in both is the point of there being one mapping. What is + * pinned is that a kind the app has no words for is said by its number rather + * than described wrongly. */ class ProposedEventTest { - @Test - fun `a profile is said by its name and what it says about itself`() { - val summary = ProposedEvent.summarize( - event(MetadataEvent.KIND, content = """{"name":"Translation collective","about":"We translate hard books."}""") - ) - - assertEquals("Nostr profile", summary.label) - assertEquals("Translation collective · We translate hard books.", summary.detail) - - // Empty and unreadable are different things, and a signer should know which. - assertEquals("An empty profile", ProposedEvent.summarize(event(MetadataEvent.KIND, content = "{}")).detail) - assertEquals("Unreadable profile", ProposedEvent.summarize(event(MetadataEvent.KIND, content = "not json")).detail) - } - - @Test - fun `a post is said by its words`() { - val summary = ProposedEvent.summarize(event(TextNoteEvent.KIND, content = "We have finished the first chapter.")) - - assertEquals("Post", summary.label) - assertEquals("We have finished the first chapter.", summary.detail) - } - - @Test - fun `a relay list is said by which list it is and its hosts`() { - val summary = ProposedEvent.summarize( - event( - AdvertisedRelayListEvent.KIND, - tags = arrayOf(arrayOf("r", "wss://relay.one.example"), arrayOf("r", "wss://relay.two.example", "read")) - ) - ) - - assertEquals("General relay list", summary.label) - assertEquals("relay.one.example, relay.two.example", summary.detail) - - // An empty list is a withdrawal, which is worth saying in as many words. - assertEquals("No relays", ProposedEvent.summarize(event(AdvertisedRelayListEvent.KIND)).detail) - } - @Test fun `a kind with no words of its own keeps its number`() { // Refusing to describe an event is better than describing it wrongly. @@ -66,6 +26,16 @@ class ProposedEventTest { assertEquals("An article", summary.detail) } + @Test + fun `a profile, a post and a relay list are no longer described`() { + // The group's nostr profile, posts and relay lists were removed, and with + // them the words for what they were; a proposal for one from an older + // build is said like any other kind the app does not know. + listOf(MetadataEvent.KIND, TextNoteEvent.KIND, AdvertisedRelayListEvent.KIND).forEach { kind -> + assertEquals("Event of kind $kind", ProposedEvent.summarize(event(kind)).label) + } + } + private fun event( kind: Int, tags: Array> = emptyArray(), diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt deleted file mode 100644 index a1ffe4fc..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/BroadcastGroupSignedEventScreenJvmTest.kt +++ /dev/null @@ -1,240 +0,0 @@ -package com.machankura.bennu.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.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.nip10Notes.TextNoteEvent -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.flowOf -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.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 relays the - * group has said it lives at already in the list, and a way to add one. 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 group'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 group's own General list, as hosts. - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("relay.two.example").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("relay.one.example").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, - ), - ) - ) - ) { - 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(relayLists = GroupRelayList.allAmong(emptyList(), chatRoomId), seedNothing = true) - ) { - onNodeWithText("No relays to broadcast to. Add one above.").assertIsDisplayed() - } - - 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), - ) - - /** A General list of two relays, agreed, so the screen has something of the group's to fill in. */ - private fun agreedRelayLists(): List = - GroupRelayList.allAmong(emptyList(), chatRoomId).map { list -> - if (list.set != GroupRelaySet.General) return@map list - - GroupRelayList( - set = list.set, - signedEvent = GroupSignedEvent( - id = "a".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = list.set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ), - relays = listOf(GroupRelay(one), GroupRelay(two)), - ) - } - - /** - * [seedNothing] blocks every relay the seed would otherwise fall back to, so - * the screen can be seen with an empty list -- a group that has agreed - * nothing is filled in from the app's own set, which is the point of the - * fallback and the opposite of what this fixture wants. - */ - private fun state( - relayLists: List = agreedRelayLists(), - seedNothing: Boolean = false, - ) = 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(), - relayLists = if (seedNothing) { - relayLists.map { list -> - if (list.set != GroupRelaySet.Blocked) return@map list - - GroupRelayList( - set = list.set, - signedEvent = null, - relays = Relays.eventPublishRelaySet.map { GroupRelay(it) }, - ) - } - } else { - relayLists - }, - ) - - private fun render( - uiState: BroadcastGroupSignedEventUIState, - transport: EventPublishTransport = FakeTransport(emptyList()), - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 1600) { - setContent { - BennuTheme { - 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/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt deleted file mode 100644 index ef996630..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreenJvmTest.kt +++ /dev/null @@ -1,153 +0,0 @@ -package com.machankura.bennu.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.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 -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.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, what the - * broadcast under it sends, and who is offered the editor. - */ -@OptIn(ExperimentalTestApi::class) -class GroupNostrProfileScreenJvmTest { - - @Test - fun `the profile is drawn whole, with its broadcast under it`() { - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText("Translation collective").assertIsDisplayed() - onNodeWithText("group@example.com").assertIsDisplayed() - onNodeWithText("A group translating hard books into Sesotho.").assertIsDisplayed() - onAllNodesWithText("Signed by the group on", substring = true).assertCountEquals(1) - - // One, under the card it sends, and it sends the profile's event. - 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 `a member holding a share of the key is offered the editor`() { - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText("Edit Nostr profile").assertIsDisplayed().performClick() - } - - assertEquals( - EditGroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), - opened - ) - } - - @Test - fun `a member holding no share of the key reads the profile and is offered no edit`() = render( - state(groupNostrProfile = profile, canSign = false) - ) { - // The profile is worth reading whoever is looking; proposing one needs a - // share, and `proposeSigningBatch` throws without one. The broadcast - // stays: the signature is the group's whoever repeats it. - onNodeWithText("Translation collective").assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(1) - } - - @Test - fun `a group that has said nothing says so, and offers to say something`() = render( - state(groupNostrProfile = null) - ) { - onNodeWithText("This group hasn't said anything about itself on Nostr yet.") - .assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertIsDisplayed() - - // Nothing signed, so nothing to send. - onAllNodesWithText("Broadcast").assertCountEquals(0) - } - - @Test - fun `a group that has said nothing offers no editor to a member holding no share`() = render( - state(groupNostrProfile = null, canSign = false) - ) { - onNodeWithText("This group hasn't said anything about itself on Nostr yet.") - .assertIsDisplayed() - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - } - - private fun state( - groupNostrProfile: GroupNostrProfile?, - canSign: Boolean = true - ) = GroupNostrProfileUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupNostrProfile = groupNostrProfile, - canSign = canSign - ) - - /** - * The screen at a phone's width. The state is passed in, so the NO_OP - * repository is never asked for anything: `initiate` only runs for a screen - * that arrives loading. - */ - private fun render( - uiState: GroupNostrProfileUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupNostrProfileScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupNostrProfileUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt deleted file mode 100644 index 21ee20b8..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupPostsScreenJvmTest.kt +++ /dev/null @@ -1,167 +0,0 @@ -package com.machankura.bennu.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.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 -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.post -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.navigation.routes.AddGroupPostRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupPostsUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The group's posts on their own screen: newest first and whole, under the - * group's name, each with its broadcast, and the composer for a member holding - * a share. - */ -@OptIn(ExperimentalTestApi::class) -class GroupPostsScreenJvmTest { - - @Test - fun `the posts are drawn newest first, under the group's name`() = render( - state(posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000))) - ) { - // Newest first, and whole rather than previewed -- a post is the one thing - // the group signs that exists to be read. - val newest = onNodeWithText("The second thing").getBoundsInRoot().top - val oldest = onNodeWithText("The first thing").getBoundsInRoot().top - assertTrue(newest < oldest, "the posts were drawn oldest first") - - // Under the group's name, not the member's. The whole point of signing a - // post as the group is that no member can be blamed for it. Once per - // post: there is no profile card on this screen to add a third. - onAllNodesWithText("Translation collective").assertCountEquals(2) - onNodeWithText("Add post").assertIsDisplayed() - } - - @Test - fun `a group that has not described itself bylines its posts with the key`() = render( - state(posts = listOf(post("Something the group said", 1_700_000_000)), groupNostrProfile = null) - ) { - onNodeWithText("Something the group said").assertIsDisplayed() - 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))), - 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 - - render(state(posts = emptyList()), onNavigateToRoute = { opened = it }) { - onNodeWithText("This group hasn't posted anything yet.").assertIsDisplayed() - onAllNodesWithText("Broadcast").assertCountEquals(0) - onNodeWithText("Add post").assertIsDisplayed().performClick() - } - - assertEquals(AddGroupPostRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) - } - - @Test - fun `a member holding no share of the key reads the posts and is offered no composer`() = render( - state(posts = listOf(post("Something the group said", 1_700_000_000)), canSign = false) - ) { - // A post is the one thing here that is meant to be read by people who - // were not in the room, so a member without a share reads it like - // anybody else and simply cannot propose the next one. - onNodeWithText("Something the group said").assertIsDisplayed() - onNodeWithText("Add post").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(1) - } - - @Test - fun `a group that has posted nothing offers no composer to a member holding no share`() = render( - state(posts = emptyList(), canSign = false) - ) { - onNodeWithText("This group hasn't posted anything yet.").assertIsDisplayed() - onNodeWithText("Add post").assertDoesNotExist() - } - - private fun state( - posts: List, - groupNostrProfile: GroupNostrProfile? = profile, - canSign: Boolean = true - ) = GroupPostsUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupPosts = posts, - groupNostrProfile = groupNostrProfile, - canSign = canSign - ) - - private fun render( - uiState: GroupPostsUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupPostsScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupPostsUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt deleted file mode 100644 index 0e8368fa..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupRelaysScreenJvmTest.kt +++ /dev/null @@ -1,139 +0,0 @@ -package com.machankura.bennu.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.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 -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.relaySignedEvent -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.signedRelayLists -import com.machankura.bennu.compose.ui.composable.navigation.routes.BroadcastGroupSignedEventRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRelaysRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.Route -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.GroupRelaysUIState -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -/** - * The group's relay lists on their own screen: a row per set whatever the - * group has said, a broadcast under each list it has agreed, and the editor - * for a member holding a share. - */ -@OptIn(ExperimentalTestApi::class) -class GroupRelaysScreenJvmTest { - - @Test - fun `every set gets a row, and the two absences read differently`() = render(state()) { - onNodeWithText("General").assertIsDisplayed() - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("Messages").assertIsDisplayed() - onNodeWithText("Search").assertIsDisplayed() - onNodeWithText("Blocked").assertIsDisplayed() - // Two of them, because Messages and Search are both unagreed -- and the - // count is the assertion: a row per set, not a row per set the group has - // got round to. The blocked list was agreed empty, which is a decision - // and reads as one. - onAllNodesWithText("Not set yet").assertCountEquals(2) - onNodeWithText("No relays in this list").assertIsDisplayed() - } - - @Test - fun `every agreed list offers a broadcast under its row, the withdrawn one included`() { - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - // The two the group has agreed -- the withdrawn one included, since a - // withdrawal is a statement relays still holding the old list need to - // hear -- and not the two it has never agreed, which are not events. - val buttons = onAllNodesWithText("Broadcast") - buttons.assertCountEquals(2) - - val general = onNodeWithText("General").getBoundsInRoot().top - val blocked = onNodeWithText("Blocked").getBoundsInRoot().top - val first = buttons[0].getBoundsInRoot().top - val second = buttons[1].getBoundsInRoot().top - - assertTrue(general < first && first < blocked, "the general list's broadcast is not under its row") - assertTrue(blocked < second, "the blocked list's broadcast is not under its row") - - buttons[1].performClick() - } - - assertEquals( - BroadcastGroupSignedEventRoute( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - signedEventId = relaySignedEvent(GroupRelaySet.Blocked).id - ), - opened - ) - } - - @Test - fun `a member holding a share of the key is offered the editor`() { - var opened: Route? = null - - render(state(), onNavigateToRoute = { opened = it }) { - onNodeWithText("Edit relays").assertIsDisplayed().performClick() - } - - assertEquals(EditGroupRelaysRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) - } - - @Test - fun `a member holding no share of the key reads the relays and is offered no edit`() = render( - state(canSign = false) - ) { - onNodeWithText("General").assertIsDisplayed() - onNodeWithText("relay.one.example").assertIsDisplayed() - onNodeWithText("Edit relays").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(2) - } - - private fun state(canSign: Boolean = true) = GroupRelaysUIState.Loaded( - localChatRoom = GroupSignedWorkFixtures.localChatRoom(), - groupRelayLists = signedRelayLists(), - canSign = canSign - ) - - private fun render( - uiState: GroupRelaysUIState, - onNavigateToRoute: (Route) -> Unit = {}, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 2000) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - GroupRelaysScreen( - activeUserPublicKey = activeUserPublicKey, - chatRoomId = chatRoomId, - relayHint = null, - initialGroupRelaysUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - onNavigateToRoute = onNavigateToRoute, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt index f1ab7895..d04e9580 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkFixtures.kt @@ -1,27 +1,16 @@ package com.machankura.bennu.compose.ui.composable -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GroupKeyState -import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet import kotlin.time.Instant /** - * One group's signed work, for the six screens that show it: the group's own, - * where a row names each kind, and the five behind those rows. + * One group, for the screens that show it. * - * Everything here is built rather than read out of a signed event. The reading - * checks a real signature, and these tests are about the screens rather than - * about that -- so nothing here verifies, and none of the keys derive. + * Everything here is built rather than read out of a signed event, and these + * tests are about the screens rather than about signatures -- so nothing here + * verifies, and none of the keys derive. */ internal object GroupSignedWorkFixtures { @@ -29,13 +18,7 @@ internal object GroupSignedWorkFixtures { val activeUserPublicKey = "a".repeat(64) - /** - * The room, as this device names it. - * - * The subject is deliberately not the profile's name: the room's subject is - * this device's name for it and the profile is the group's own, and a test - * that used one string for both could not tell them apart. - */ + /** The room, as this device names it. */ fun localChatRoom(mlsGroupState: String? = "state") = LocalChatRoom( chatRoom = ChatRoom( id = chatRoomId, @@ -48,9 +31,8 @@ internal object GroupSignedWorkFixtures { ) /** - * A key state, so the signing key row the identity block sits under is on - * the group's screen to be measured against. Not a real key: nothing here - * derives. + * A key state, so the signing key row is on the group's screen. Not a real + * key: nothing here derives. */ val groupKeyState = GroupKeyState( chatRoomId = chatRoomId, @@ -60,69 +42,4 @@ internal object GroupSignedWorkFixtures { announcedBy = chatRoomId, announcedAt = Instant.fromEpochSeconds(1_700_000_000) ) - - val profile = GroupNostrProfile( - signedEvent = GroupSignedEvent( - id = "e".repeat(64), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = MetadataEvent.KIND, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ), - metadata = UserMetadata().apply { - displayName = "Translation collective" - about = "A group translating hard books into Sesotho." - nip05 = "group@example.com" - } - ) - - /** - * Two agreed sets and two absences, which is the only fixture that exercises - * the three things a relay row can say: a list, "not set yet", and "no - * relays". - */ - fun signedRelayLists(): List = GroupRelaySet.entries.map { set -> - when (set) { - GroupRelaySet.General -> GroupRelayList( - set = set, - signedEvent = relaySignedEvent(set), - relays = listOf(GroupRelay(RelayUrlNormalizer.normalize("wss://relay.one.example"))) - ) - // Agreed and empty: the group withdrew its list rather than never - // having had one. - GroupRelaySet.Blocked -> GroupRelayList( - set = set, - signedEvent = relaySignedEvent(set), - relays = emptyList() - ) - else -> GroupRelayList(set = set, signedEvent = null, relays = emptyList()) - } - } - - fun relaySignedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000) - ) - - fun post(content: String, createdAt: Long) = GroupPost( - signedEvent = GroupSignedEvent( - id = createdAt.toString().padStart(64, 'b'), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = TextNoteEvent.KIND, - tags = emptyArray(), - content = content, - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(createdAt) - ) - ) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt index c1f443f6..044f8aad 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt @@ -5,213 +5,84 @@ 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.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 import androidx.compose.ui.test.runDesktopComposeUiTest -import com.vitorpamplona.quartz.nip01Core.metadata.UserMetadata -import com.machankura.bennu.compose.nostr.GroupNostrProfile -import com.machankura.bennu.compose.nostr.GroupPost -import com.machankura.bennu.compose.nostr.GroupRelayList import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.activeUserPublicKey import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.chatRoomId -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.post -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.profile -import com.machankura.bennu.compose.ui.composable.GroupSignedWorkFixtures.signedRelayLists -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupPostsRoute -import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.ui.view.state.ChatRoomDetailUIState +import com.machankura.bennu.compose.wallet.GroupWalletRollout import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue /** - * The three rows on the group's screen that stand for its signed work, and what - * each one opens. + * The row on the group's screen that stands for its signed work, and what it + * opens. * - * The rows' contents need little testing -- a name and a count in a `ListItem` - * -- but three things about them do, and none is settled by reading the screen - * top to bottom. - * - * **Their place in the order.** They go under what the room *is* -- the key it - * signs as and whose child it is -- and above what the room has *made*, because - * the group's account of itself is part of its identity rather than part of its - * work; and among themselves they read as a chain, from who the group says it is - * to what it has said. That ordering is an intention a later `item {}` in - * the wrong place would silently undo, and the screen is long enough that - * nobody would notice. - * - * **What they open.** A row is a promise about the screen behind it, and three - * rows that look alike are three chances to wire one to the wrong route. - * - * **Their absence in a NIP-17 room.** A NIP-17 room's id is a conversation, not - * a key it can sign as, so it has no nostr identity and never will. A row there - * would promise something that is not coming, which is worse than saying - * nothing. + * The group's nostr profile, relay lists and posts had rows here, and a paste + * for proposing any of them; they are gone, and the wallet is what is left. */ @OptIn(ExperimentalTestApi::class) class GroupSignedWorkRowsJvmTest { @Test - fun `the rows sit under the signing key and above the group's work, in the order the block reads`() = - render(state(groupNostrProfile = profile)) { - val signingKey = onNodeWithText("Signing key").getBoundsInRoot().top - val nostrProfile = onNodeWithText("Nostr profile").getBoundsInRoot().top - val relays = onNodeWithText("Relays").getBoundsInRoot().top - val posts = onNodeWithText("Posts").getBoundsInRoot().top - val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top + fun `the wallet row sits under the signing key and above the subgroups`() = render(state()) { + if (!GroupWalletRollout.ENABLED) return@render - assertTrue(signingKey < nostrProfile, "the nostr profile row climbed above the signing key row") - assertTrue(nostrProfile < relays, "the relays row climbed above the profile") - assertTrue(relays < posts, "the posts row climbed above the relays") - assertTrue(posts < subgroups, "the identity block fell below the group's work") - } - - @Test - fun `each row says what its screen holds`() = render( - state( - groupNostrProfile = profile, - relayLists = signedRelayLists(), - posts = listOf(post("The second thing", 1_700_000_900), post("The first thing", 1_700_000_000)), - ) - ) { - // The group's own name and address, not the room's subject: the row is - // about what the rest of nostr sees. - onNodeWithText("Translation collective · group@example.com").assertIsDisplayed() - // Counted against the four sets, the withdrawn one included: an agreed - // empty list is a decision, and the row counts decisions. - onNodeWithText("2 of 4 lists agreed").assertIsDisplayed() - onNodeWithText("2 posts").assertIsDisplayed() - } - - @Test - fun `a group that has signed nothing has rows that say so`() = render( - state(groupNostrProfile = null) - ) { - onNodeWithText("Not described yet").assertIsDisplayed() - onNodeWithText("0 of 4 lists agreed").assertIsDisplayed() - onNodeWithText("No posts yet").assertIsDisplayed() - } - - @Test - fun `a profile with no name is not named after the key`() = render( - state( - groupNostrProfile = GroupNostrProfile( - signedEvent = profile.signedEvent, - metadata = UserMetadata() - ) - ) - ) { - // The signing key row already shows the key, and showing it twice would - // say the group has a name when it has not. - onNodeWithText("No name on this profile").assertIsDisplayed() - } - - @Test - fun `each row opens the screen for its section`() { - val expected = mapOf( - "Nostr profile" to GroupNostrProfileRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Relays" to GroupRelaysRoute(activeUserPublicKey, chatRoomId, relayHint = null), - "Posts" to GroupPostsRoute(activeUserPublicKey, chatRoomId, relayHint = null), - ) - - expected.forEach { (row, route) -> - var opened: Route? = null - - render(state(groupNostrProfile = profile), onNavigateToRoute = { opened = it }) { - onNodeWithText(row).performClick() - } - - assertEquals(route, opened, "the $row row opened the wrong screen") - } - } - - @Test - fun `the contents stay off the group's screen`() = render( - state( - groupNostrProfile = profile, - relayLists = signedRelayLists(), - posts = listOf(post("Something the group said", 1_700_000_000)), - ) - ) { - // The rows summarise; the cards, their broadcasts and the gated ways in - // are on the screens behind them. A card that stayed here would be the - // old section under a new name. - onNodeWithText("A group translating hard books into Sesotho.").assertDoesNotExist() - onNodeWithText("relay.one.example").assertDoesNotExist() - onNodeWithText("Something the group said").assertDoesNotExist() - onAllNodesWithText("Broadcast").assertCountEquals(0) - onNodeWithText("Edit Nostr profile").assertDoesNotExist() - onNodeWithText("Edit relays").assertDoesNotExist() - onNodeWithText("Add post").assertDoesNotExist() - } - - @Test - fun `a member holding a share of the key may propose any event the rows can open`() = render( - state(groupNostrProfile = profile) - ) { - // Last in the identity block: after the rows and before the divider, - // because it is about the whole block rather than any one row of it. - val posts = onNodeWithText("Posts").getBoundsInRoot().top - val propose = onNodeWithText("Propose event").getBoundsInRoot().top + val signingKey = onNodeWithText("Signing key").getBoundsInRoot().top + val wallet = onNodeWithText("Group onchain wallet").getBoundsInRoot().top val subgroups = onNodeWithText("Subgroups").getBoundsInRoot().top - assertTrue(posts < propose, "the paste entry climbed above the rows") - assertTrue(propose < subgroups, "the paste entry fell out of the identity block") + assertTrue(signingKey < wallet, "the wallet row climbed above the signing key row") + assertTrue(wallet < subgroups, "the wallet row fell below the group's subgroups") } @Test - fun `a member holding no share of the key is offered no paste`() = render( - state(groupNostrProfile = profile, canEditNostrProfile = false) - ) { - // The same gate as every way in behind the rows: proposing is a signature - // by the group, and `proposeSigning` throws for a device holding no share. - // The rows themselves stay, because reading takes no share. - onNodeWithText("Propose event").assertDoesNotExist() - onNodeWithText("Nostr profile").assertIsDisplayed() - onNodeWithText("Posts").assertIsDisplayed() + fun `the wallet row opens the wallet`() { + if (!GroupWalletRollout.ENABLED) return + + var opened: Route? = null + + render(state(), onNavigateToRoute = { opened = it }) { + onNodeWithText("Not opened yet").assertIsDisplayed() + onNodeWithText("Group onchain wallet").performClick() + } + + assertEquals(GroupWalletRoute(activeUserPublicKey, chatRoomId, relayHint = null), opened) } @Test - fun `a NIP-17 room has no nostr identity and so no rows`() = render( - state(groupNostrProfile = null, mlsGroupState = null, canEditNostrProfile = false) - ) { + fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) { onNodeWithText("Nostr profile").assertDoesNotExist() - onNodeWithText("Not described yet").assertDoesNotExist() - - // The other two go with it: all three describe a nostr identity this - // room does not have, and so does the paste. onNodeWithText("Relays").assertDoesNotExist() onNodeWithText("Posts").assertDoesNotExist() onNodeWithText("Propose event").assertDoesNotExist() - // The rest of the screen is untouched, so the rows' absence is an - // absence rather than a screen that failed to draw. + // The rest of the screen is there, so the rows' absence is an absence + // rather than a screen that failed to draw. onNodeWithText("Subgroups").assertIsDisplayed() } - private fun state( - groupNostrProfile: GroupNostrProfile?, - relayLists: List = GroupRelayList.allAmong(emptyList(), chatRoomId), - posts: List = emptyList(), - canEditNostrProfile: Boolean = true, - mlsGroupState: String? = "state" - ) = ChatRoomDetailUIState.Loaded( + @Test + fun `a NIP-17 room has no key to sign with and so no wallet row`() = render( + state(mlsGroupState = null) + ) { + onNodeWithText("Group onchain wallet").assertDoesNotExist() + onNodeWithText("Subgroups").assertIsDisplayed() + } + + private fun state(mlsGroupState: String? = "state") = ChatRoomDetailUIState.Loaded( localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState), groupKeyState = GroupSignedWorkFixtures.groupKeyState, - groupNostrProfile = groupNostrProfile, - groupRelayLists = relayLists, - groupPosts = posts, - canEditNostrProfile = canEditNostrProfile ) /** diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt deleted file mode 100644 index 522e622e..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ProposeGroupEventScreenJvmTest.kt +++ /dev/null @@ -1,115 +0,0 @@ -package com.machankura.bennu.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.assertIsNotEnabled -import androidx.compose.ui.test.onNodeWithContentDescription -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performTextInput -import androidx.compose.ui.test.runDesktopComposeUiTest -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.state.ProposeGroupEventUIState -import kotlin.test.Test - -/** - * What the paste screen says back as an event is typed into it. - * - * The screen's one job beyond a text field is to tell a member, before a quorum - * is asked, what the group would be signing or why it will not be asked. Both - * are read live off the paste, so both are tested by typing: a relay list reads back - * as the signing screen would describe it, junk is named as junk, and a kind - * with no section to land in is refused with the kinds that have one. - */ -@OptIn(ExperimentalTestApi::class) -class ProposeGroupEventScreenJvmTest { - - private val chatRoomId = "d4c3b2a1".repeat(8) - - private val relayList = """{"kind":10002,"created_at":1735689600,""" + - """"tags":[["r","wss://relay.one.example"],["r","wss://relay.two.example","read"]],"content":""}""" - - @Test - fun `a pasted relay list is read back as the signing screen would say it`() = render(state()) { - onNodeWithText("Unsigned event").performTextInput(relayList) - - onNodeWithText("What the group would sign").assertIsDisplayed() - onNodeWithText("Kind 10002 · General relay list").assertIsDisplayed() - onNodeWithText("relay.one.example, relay.two.example").assertIsDisplayed() - } - - @Test - fun `junk is named as junk`() = - render(state()) { - onNodeWithText("Unsigned event").performTextInput("this is not an event") - onNodeWithText("That isn't JSON.").assertIsDisplayed() - onNodeWithText("What the group would sign").assertDoesNotExist() - } - - @Test - fun `a kind the screen cannot file is refused with the kinds it can`() = render(state()) { - onNodeWithText("Unsigned event").performTextInput("""{"kind": 30023, "content": "An article"}""") - - onNodeWithText("Kind 30023 has nowhere to go on the group's screen.", substring = true) - .assertIsDisplayed() - onNodeWithText("0, 1, 10002, 10006, 10007, 10050", substring = true).assertIsDisplayed() - } - - @Test - fun `a member holding no share of the key is told so and the button is inert`() = render( - state(canSign = false) - ) { - onNodeWithText("This group has no shared key, so it cannot sign an event.", substring = true) - .assertIsDisplayed() - onNodeWithContentDescription("Propose event").assertIsNotEnabled() - } - - private fun state(canSign: Boolean = true) = ProposeGroupEventUIState.Loaded( - localChatRoom = LocalChatRoom( - chatRoom = ChatRoom( - id = chatRoomId, - userPublicKey = "a".repeat(64), - subject = "Translation room", - description = "A group translating hard books.", - initialGiftWrapPayloadId = "sdfaer", - mlsGroupState = "state" - ) - ), - canSign = canSign, - ) - - private fun render( - uiState: ProposeGroupEventUIState, - assertions: ComposeUiTest.() -> Unit - ) = runDesktopComposeUiTest(width = 400, height = 1200) { - setContent { - BennuTheme { - ProvideSnackbarHost { - Box(modifier = Modifier.fillMaxSize()) { - ProposeGroupEventScreen( - activeUserPublicKey = "a".repeat(64), - chatRoomId = chatRoomId, - relayHint = null, - initialProposeGroupEventUIState = uiState, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = - FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - onNavigateToRouteAndPopUpInclusive = {}, - onNavigateBack = {}, - ) - } - } - } - } - - assertions() - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt deleted file mode 100644 index 8a721014..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/BroadcastGroupSignedEventViewModelJvmTest.kt +++ /dev/null @@ -1,373 +0,0 @@ -package com.machankura.bennu.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 com.vitorpamplona.quartz.nip65RelayList.AdvertisedRelayListEvent -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 com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.database.model.NostrEvent -import com.machankura.bennu.compose.exceptions.NostrPublishException -import com.machankura.bennu.compose.network.dto.RelayDTO -import com.machankura.bennu.compose.network.relays.EventPublishTransport -import com.machankura.bennu.compose.network.relays.NostrPublishResult -import com.machankura.bennu.compose.network.sockets.NostrIncomingMessage -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.ui.view.model.BroadcastGroupSignedEventViewModel.RelayOutcome -import com.machankura.bennu.compose.ui.view.state.BroadcastGroupSignedEventUIState -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -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, so it has to be the - * group's own answer where the group has given one, has to leave out what the - * group has blocked, and has to widen for relay lists, whose readers would not - * otherwise find them. - * - * **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 relaySignedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - /** Every set unsigned, which is a group that has never said where it lives. */ - private fun nothingAgreed() = GroupRelayList.allAmong(emptyList(), chatRoomId) - - private fun agreed(vararg lists: Pair>) = - nothingAgreed().map { list -> - lists.firstOrNull { it.first == list.set } - ?.let { GroupRelayList(list.set, relaySignedEvent(list.set), it.second) } - ?: list - } - - 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 ------------------------ - - @Test - fun `a group that has not said where it lives sends to the app's publish set`() { - assertEquals( - Relays.eventPublishRelaySet.toList(), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(nothingAgreed(), TextNoteEvent.KIND), - ) - } - - @Test - fun `a group's own general list wins, and only the relays it writes to`() { - val relayLists = agreed( - GroupRelaySet.General to listOf( - GroupRelay(one), - // Read-only: where the group looks, not where it puts things. - GroupRelay(two, read = true, write = false), - ) - ) - - // The group's answer and nothing from the app's set beside it: a member - // who edited the relays meant them, and padding the list would send the - // group's post somewhere the group decided not to be. - assertEquals( - listOf(one), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND), - ) - } - - @Test - fun `a blocked relay is dropped whatever the other lists say`() { - val relayLists = agreed( - GroupRelaySet.General to listOf(GroupRelay(one), GroupRelay(two)), - GroupRelaySet.Blocked to listOf(GroupRelay(two)), - ) - - assertEquals( - listOf(one), - BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND), - ) - } - - @Test - fun `a relay list also goes to the indexers, since its readers do not yet know the relays it names`() { - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - - val seeded = BroadcastGroupSignedEventViewModel.defaultRelaysFor( - relayLists, AdvertisedRelayListEvent.KIND - ) - - assertEquals(one, seeded.first()) - Relays.DefaultIndexerRelayList.forEach { indexer -> - assertTrue(indexer in seeded, "the relay list would not reach ${indexer.url}") - } - - // And a post does not: nobody looks an indexer up for a kind 1. - val post = BroadcastGroupSignedEventViewModel.defaultRelaysFor(relayLists, TextNoteEvent.KIND) - Relays.DefaultIndexerRelayList.forEach { indexer -> - assertFalse(indexer in post, "a post was sent to the indexer ${indexer.url}") - } - } - - @Test - fun `seeding happens once, so an emptied list stays empty`() { - val viewModel = viewModel() - val relayLists = agreed(GroupRelaySet.General to listOf(GroupRelay(one))) - val event = signedEvent() - - viewModel.seedRelays(relayLists, event.kind) - viewModel.seedRelays(relayLists, event.kind) - assertEquals(listOf(one), viewModel.relays.toList()) - - viewModel.removeRelay(one) - viewModel.seedRelays(relayLists, 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()) - } - - // -- what never goes at all ------------------------------------------------ - - @Test - fun `the group's wallet statement is never handed to a relay`() { - val transport = FakeTransport(mapOf(one.url to ok(one))) - - // The xpub on a relay is every address and the whole balance, to anyone. - // A refusal nobody tested is the one that disappears in a refactor of - // what the broadcast list accepts. - assertFailsWith { - runBlocking { - BroadcastGroupSignedEventViewModel.sendToRelays( - publishTransport = transport, - signedEvent = signedEvent(kind = GroupWalletStatementEvent.KIND), - targets = listOf(one), - ) - } - } - assertNull(transport.sent, "nothing reached the transport") - } -} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt deleted file mode 100644 index 007312ca..00000000 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/EditGroupRelaysViewModelJvmTest.kt +++ /dev/null @@ -1,224 +0,0 @@ -package com.machankura.bennu.compose.ui.view.model - -import com.machankura.bennu.compose.database.model.GroupSignedEvent -import com.machankura.bennu.compose.nostr.GroupRelay -import com.machankura.bennu.compose.nostr.GroupRelayList -import com.machankura.bennu.compose.nostr.GroupRelaySet -import com.machankura.bennu.compose.nostr.Relays -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.ui.view.state.EditGroupRelaysUIState -import com.vitorpamplona.quartz.nip01Core.relay.normalizer.RelayUrlNormalizer -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertTrue -import kotlin.time.Instant - -/** - * The two decisions the relay editor makes that nothing else can check. - * - * **What counts as a change.** The button proposes only the lists that differ, so - * this is what decides whether a quorum is asked at all -- and getting it wrong in - * either direction is quiet. Too eager and every visit re-signs four lists nobody - * touched, dating a decision the group did not make; too shy and an edit is - * silently dropped on a screen that said it had been sent. - * - * **What a NIP-65 marker is allowed to become.** A relay that is neither read nor - * write has no tag in the format, so the state must not be reachable. - * `GroupRelaySet.template` drops one as a last resort; this is where it is actually - * prevented. - */ -class EditGroupRelaysViewModelJvmTest { - 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 fun viewModel() = EditGroupRelaysViewModel( - chatRoomId = chatRoomId, - activeUserPublicKey = "a".repeat(64), - relayHint = null, - initialEditGroupRelaysUIState = EditGroupRelaysUIState.Loading, - chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, - frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, - ) - - private fun signedEvent(set: GroupRelaySet) = GroupSignedEvent( - id = "a" + set.kind.toString().padStart(5, '0') + "0".repeat(58), - chatRoomId = chatRoomId, - publicKey = chatRoomId, - kind = set.kind, - tags = emptyArray(), - content = "", - signature = "f".repeat(128), - createdAt = Instant.fromEpochSeconds(1_700_000_000), - ) - - /** Every set unsigned, which is a group opening the editor for the first time. */ - private fun nothingSigned() = GroupRelayList.allAmong(emptyList(), chatRoomId) - - private fun signed(set: GroupRelaySet, relays: List) = - nothingSigned().map { - if (it.set == set) GroupRelayList(set, signedEvent(set), relays) else it - } - - @Test - fun `a first-time group is seeded with the app's own relay and that is a change`() { - val signed = nothingSigned() - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals( - listOf(Relays.ephemeral), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - - // Seeded and therefore proposable. A group whose editor filled itself in - // and then refused to send it would be showing a plan it will not carry out. - assertEquals( - listOf(GroupRelaySet.General, GroupRelaySet.Messages, GroupRelaySet.Search), - viewModel.changedSets(signed), - ) - } - - @Test - fun `blocked is never seeded and so is never proposed by simply opening the screen`() { - val signed = nothingSigned() - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals(emptyList(), viewModel.relaysOf(GroupRelaySet.Blocked)) - assertFalse(GroupRelaySet.Blocked in viewModel.changedSets(signed)) - } - - @Test - fun `opening a group that has agreed everything proposes nothing`() { - // The case that has to be silent. A member opening the editor, reading it - // and pressing the button must not spend a quorum on four identical lists. - val signed = GroupRelaySet.entries.map { set -> - GroupRelayList(set, signedEvent(set), listOf(GroupRelay(one))) - } - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - assertEquals(emptyList(), viewModel.changedSets(signed)) - } - - @Test - fun `only the set that was edited is proposed`() { - val signed = GroupRelaySet.entries.map { set -> - GroupRelayList(set, signedEvent(set), listOf(GroupRelay(one))) - } - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.Search) - assertTrue(viewModel.addRelay(two.url)) - - assertEquals(listOf(GroupRelaySet.Search), viewModel.changedSets(signed)) - } - - @Test - fun `reordering a list is a change`() { - // A relay list is written in the order it is read back, and a member who - // moved a relay to the front meant to. Comparing as sets would call this no - // change and refuse to propose it. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one), GroupRelay(two))) - - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.General) - viewModel.removeRelay(GroupRelaySet.General, GroupRelay(one)) - assertTrue(viewModel.addRelay(one.url)) - - assertEquals( - listOf(two, one), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - assertTrue(GroupRelaySet.General in viewModel.changedSets(signed)) - } - - @Test - fun `emptying an agreed list is a change, and emptying an unagreed one is not`() { - // Withdrawing a list the group agreed is a decision worth a signature. - // "Still nothing" is not a decision at all, and proposing an empty list for - // a set nobody ever set would be a signature over silence. - val agreed = signed(GroupRelaySet.Messages, listOf(GroupRelay(one))) - val withdrawing = viewModel() - withdrawing.seedWorkingCopy(agreed) - withdrawing.removeRelay(GroupRelaySet.Messages, GroupRelay(one)) - - assertTrue(GroupRelaySet.Messages in withdrawing.changedSets(agreed)) - - val untouched = nothingSigned() - val quiet = viewModel() - quiet.seedWorkingCopy(untouched) - // Clear the seeded default so the set is unagreed *and* empty. - quiet.removeRelay(GroupRelaySet.Search, GroupRelay(Relays.ephemeral)) - - assertFalse(GroupRelaySet.Search in quiet.changedSets(untouched)) - } - - @Test - fun `a relay cannot be turned into one that is neither read nor write`() { - // NIP-65 has no tag for it, so the state has to be unreachable. What it - // would mean is that the relay is not in the list, and removing it is the - // row's own button. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one))) - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - - viewModel.toggleWrite(GroupRelaySet.General, GroupRelay(one)) - assertEquals( - listOf(GroupRelay(one, read = true, write = false)), - viewModel.relaysOf(GroupRelaySet.General), - ) - - // The second toggle is the one that would leave it as neither. - viewModel.toggleRead( - GroupRelaySet.General, - viewModel.relaysOf(GroupRelaySet.General).first(), - ) - assertEquals( - listOf(GroupRelay(one, read = true, write = false)), - viewModel.relaysOf(GroupRelaySet.General), - "a relay was left neither read nor write, which NIP-65 cannot express", - ) - } - - @Test - fun `a url that is not a relay is refused and named`() { - val viewModel = viewModel() - viewModel.seedWorkingCopy(nothingSigned()) - viewModel.selectSet(GroupRelaySet.Search) - - assertFalse(viewModel.addRelay("http://relay.one.example")) - assertEquals(EditGroupRelaysViewModel.AddFailure.NotARelay, viewModel.addFailure) - - // And a duplicate is a no-op rather than a mistake, said differently. - assertTrue(viewModel.addRelay(one.url)) - assertFalse(viewModel.addRelay(one.url)) - assertEquals(EditGroupRelaysViewModel.AddFailure.AlreadyListed, viewModel.addFailure) - } - - @Test - fun `seeding again leaves an edit alone`() { - // The effect that seeds is keyed on a state the view model can re-emit, so - // running twice has to be harmless -- otherwise a reload halfway through - // typing throws the typing away. - val signed = signed(GroupRelaySet.General, listOf(GroupRelay(one))) - val viewModel = viewModel() - viewModel.seedWorkingCopy(signed) - viewModel.selectSet(GroupRelaySet.General) - assertTrue(viewModel.addRelay(two.url)) - - viewModel.seedWorkingCopy(signed) - - assertEquals( - listOf(one, two), - viewModel.relaysOf(GroupRelaySet.General).map { it.url }, - ) - } -} diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index c0ee5df7..c7064e84 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -444,12 +444,13 @@ is a record that the group agreed, not a source of keys. The app never reads an address out of it. **Never broadcast.** The xpub on a public relay is the group's whole history on -chain, to anyone. `BroadcastGroupSignedEventScreen` refuses this kind, and a test -says it refuses it, because a refusal nobody tested is the one that disappears -in a refactor of the broadcast list. +chain, to anyone. `BroadcastGroupSignedEventScreen` refused this kind, and a test +said it refused it. That screen has since been removed with the group's nostr +profile, relay lists and posts, and nothing in the app now sends a group-signed +event to a relay. -`GroupWallet` is a read model over `GroupSignedEvent`, in the shape of -`GroupRelayList.of`/`newestAmong`. There is no table: a wallet is a signed event +`GroupWallet` is a read model over `GroupSignedEvent`, in the shape the +since-removed `GroupRelayList.of`/`newestAmong` had. There is no table: a wallet is a signed event and a derivation. **Not batched** with anything. A wallet statement is what every spend proposal is diff --git a/docs/npub-profile-preview.md b/docs/npub-profile-preview.md index a7ba285f..4bbe26f1 100644 --- a/docs/npub-profile-preview.md +++ b/docs/npub-profile-preview.md @@ -96,7 +96,7 @@ Almost all of it. The preview is a new screen over pieces that exist. | a kind 0 arriving overwrites the placeholder row | [NostrDao.kt:424](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/NostrDao.kt) | the observed flow emits it | | the stack shape for "a profile becomes a chat": push the room, pop the profile | [BennuNavHost.kt:1706](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt), `NostrEventDetailRoute`'s DM exit | copied | | `ProfileAvatar`, `humanReadableNameOrPubkey()`, `staticIdentifier()`, `hexToNpubHrp()` | `Profile.kt`, `Credentials.kt` | built | -| a constant app bar with the state transition inside it | [GroupNostrProfileScreen.kt:106](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupNostrProfileScreen.kt) | the layout to copy | +| a constant app bar with the state transition inside it | `GroupNostrProfileScreen`, since removed with the group's nostr profile | the layout to copy | | `LoadingDataIndicator(text = …)`, `EmptyState(message, icon, action)`, `ErrorState(onRetry)`, `NavigateBackButton`, `LocalCanSign` | `widgets/` | built | | strings: `profile`, `try_again`, `start_chat`, `send_message` | `strings.xml` | present; the new ones are listed per phase |