Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalGroupOps.kt
SignalGroupOps.kt245 lines · 10.7 KiBRaw
| 1 | package com.vayunmathur.communicate.data.signal |
| 2 | |
| 3 | import com.vayunmathur.library.log.Log |
| 4 | import com.vayunmathur.communicate.data.signal.transport.SignalGroupsApi |
| 5 | import kotlinx.coroutines.launch |
| 6 | import org.signal.storageservice.storage.protos.groups.GroupChange |
| 7 | |
| 8 | /** |
| 9 | * SignalClient group operations (split from SignalClient.kt for file length). |
| 10 | * |
| 11 | * Extension functions on [SignalClient]; behavior identical, call sites unchanged. |
| 12 | */ |
| 13 | |
| 14 | private const val MS_PER_SECOND = 1000L |
| 15 | |
| 16 | suspend fun SignalClient.createGroup(subject: String, contacts: List<String>): String? { |
| 17 | val (masterKey, _) = SignalGroups.generateMasterKeyAndSecretParams() |
| 18 | val groupId = SignalProtocol.toConversationId("", masterKey) |
| 19 | val requestBody = SignalGroups.buildCreateGroupRequest(masterKey, subject, contacts, revision = 0) |
| 20 | val auth = authData ?: return null |
| 21 | val ok = SignalGroups.putNewGroup(authData = auth, requestBody = requestBody, sslSocketFactory = signalTls()) |
| 22 | eventsMutable.emit(SignalEvent.ConversationUpdate( |
| 23 | conversationId = groupId, |
| 24 | peerName = subject, |
| 25 | peerPhone = null, |
| 26 | avatarUrl = null, |
| 27 | lastPreview = null, |
| 28 | lastTimestamp = System.currentTimeMillis(), |
| 29 | unreadCount = 0, |
| 30 | isGroup = true, |
| 31 | participantCount = contacts.size)) |
| 32 | try { |
| 33 | // The master key must be kept: without it we cannot address the group again. |
| 34 | db?.conversationDao()?.upsert( |
| 35 | SignalConversation( |
| 36 | chatId = groupId, |
| 37 | isGroup = true, |
| 38 | name = subject, |
| 39 | participants = contacts.joinToString(","), |
| 40 | groupMasterKey = masterKey, |
| 41 | groupRevision = 0, |
| 42 | ), |
| 43 | ) |
| 44 | Log.status(TAG, "createGroup $groupId (PUT /v2/groups/ ${if (ok) "ok" else "failed"})") |
| 45 | } catch (_: Exception) {} |
| 46 | return groupId |
| 47 | } |
| 48 | |
| 49 | suspend fun SignalClient.setGroupName(conversationId: String, name: String): Boolean { |
| 50 | val existing = try { db?.conversationDao()?.getConversation(conversationId) } catch (_: Exception) { null } |
| 51 | val masterKey = existing?.groupMasterKey |
| 52 | if (masterKey == null) { |
| 53 | // Previously this generated a fresh random master key per rename, which described an |
| 54 | // unrelated group rather than this one. |
| 55 | Log.status(TAG, "no stored master key for $conversationId, cannot rename the group") |
| 56 | return false |
| 57 | } |
| 58 | val revision = existing.groupRevision + 1 |
| 59 | val accepted = groupChange(masterKey) { secretParams -> |
| 60 | SignalGroupsApi.titleChange(secretParams, name, revision) |
| 61 | } |
| 62 | if (!accepted) { |
| 63 | // The local name is not updated on rejection: claiming success for a change the server refused is |
| 64 | // how the group drifts out of step with everyone else's view of it. |
| 65 | Log.status(TAG, "the server rejected renaming $conversationId") |
| 66 | return false |
| 67 | } |
| 68 | eventsMutable.emit(SignalEvent.ConversationNameChanged(conversationId = conversationId, newName = name)) |
| 69 | try { |
| 70 | db?.conversationDao()?.upsert(existing.copy(name = name, groupRevision = revision)) |
| 71 | } catch (_: Exception) {} |
| 72 | return true |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Submit a group change built by [build], handling the credential dance. |
| 77 | * |
| 78 | * Returns whether the server accepted it, so callers can avoid recording a change that did not happen. |
| 79 | */ |
| 80 | private suspend fun SignalClient.groupChange( |
| 81 | masterKey: ByteArray, |
| 82 | build: (org.signal.libsignal.zkgroup.groups.GroupSecretParams) -> GroupChange.Actions?, |
| 83 | ): Boolean { |
| 84 | val auth = authData ?: return false |
| 85 | return try { |
| 86 | val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey( |
| 87 | org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey), |
| 88 | ) |
| 89 | val actions = build(secretParams) ?: return false |
| 90 | val credential = SignalGroupsApi |
| 91 | .fetchCredentials(basicAuthHeader(), signalTls()) |
| 92 | .minByOrNull { kotlin.math.abs(it.redemptionTimeSeconds - System.currentTimeMillis() / MS_PER_SECOND) } |
| 93 | ?: return false |
| 94 | val authorization = SignalGroupsApi.authorizationFor(auth, secretParams, credential) ?: return false |
| 95 | SignalGroupsApi.patchGroup(authorization, actions, signalTls()) |
| 96 | } catch (expected: Throwable) { |
| 97 | Log.status(TAG, "could not submit a group change", expected) |
| 98 | false |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | suspend fun SignalClient.updateGroupParticipants( |
| 103 | conversationId: String, |
| 104 | participantIds: List<String>, |
| 105 | action: String): Boolean { |
| 106 | val existing = try { db?.conversationDao()?.getConversation(conversationId) } catch (_: Exception) { null } |
| 107 | val masterKey = existing?.groupMasterKey |
| 108 | if (masterKey == null) { |
| 109 | Log.status(TAG, "no stored master key for $conversationId, cannot change membership") |
| 110 | return false |
| 111 | } |
| 112 | val revision = existing.groupRevision + 1 |
| 113 | val accepted = when (action) { |
| 114 | "add" -> groupChange(masterKey) { secretParams -> |
| 115 | SignalGroupsApi.addMembersChange(secretParams, participantIds, revision) |
| 116 | } |
| 117 | else -> { |
| 118 | // Removal needs DeleteMemberAction, which is not built yet; refuse rather than pretend. |
| 119 | Log.status(TAG, "removing members from a Signal group is not implemented") |
| 120 | false |
| 121 | } |
| 122 | } |
| 123 | if (!accepted) { |
| 124 | Log.status(TAG, "the server rejected the membership change for $conversationId") |
| 125 | return false |
| 126 | } |
| 127 | for (pid in participantIds) { |
| 128 | if (action == "add") eventsMutable.emit(SignalEvent.ParticipantAdded( |
| 129 | conversationId = conversationId, |
| 130 | participantId = pid)) |
| 131 | else eventsMutable.emit(SignalEvent.ParticipantRemoved(conversationId = conversationId, participantId = pid)) |
| 132 | } |
| 133 | return true |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Refresh a group's membership and title from the server. |
| 138 | * |
| 139 | * This is what makes a reply reach the whole group: membership learned from inbound messages only covers |
| 140 | * whoever has spoken, whereas the server knows everyone. Returns false when the group could not be fetched, |
| 141 | * leaving the locally-known membership in place rather than emptying it. |
| 142 | */ |
| 143 | suspend fun SignalClient.refreshGroup(conversationId: String): Boolean { |
| 144 | val auth = authData ?: return false |
| 145 | val dao = db?.conversationDao() ?: return false |
| 146 | val existing = try { dao.getConversation(conversationId) } catch (_: Exception) { null } ?: return false |
| 147 | val masterKey = existing.groupMasterKey ?: return false |
| 148 | return try { |
| 149 | val state = fetchGroupState(auth, masterKey) ?: return false |
| 150 | dao.upsert( |
| 151 | existing.copy( |
| 152 | isGroup = true, |
| 153 | name = state.title.ifBlank { existing.name }, |
| 154 | participants = state.memberAcis.joinToString(","), |
| 155 | groupRevision = state.revision, |
| 156 | ), |
| 157 | ) |
| 158 | Log.status( |
| 159 | TAG, |
| 160 | "refreshed $conversationId: \"${state.title}\" revision=${state.revision} " + |
| 161 | "members=${state.memberAcis.size} pending=${state.pendingCount}", |
| 162 | ) |
| 163 | true |
| 164 | } catch (expected: Throwable) { |
| 165 | Log.status(TAG, "could not refresh the group $conversationId", expected) |
| 166 | false |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /** Decrypted group state for [masterKey], or null when unfetchable. */ |
| 171 | private suspend fun SignalClient.fetchGroupState( |
| 172 | auth: SignalAuthData, |
| 173 | masterKey: ByteArray, |
| 174 | ): SignalGroupsApi.GroupState? { |
| 175 | val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey( |
| 176 | org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey), |
| 177 | ) |
| 178 | val credential = SignalGroupsApi |
| 179 | .fetchCredentials(basicAuthHeader(), signalTls()) |
| 180 | // Credentials come a week at a time; the one for today is the only one the server accepts now. |
| 181 | .minByOrNull { kotlin.math.abs(it.redemptionTimeSeconds - System.currentTimeMillis() / MS_PER_SECOND) } |
| 182 | ?: return null |
| 183 | val authorization = SignalGroupsApi.authorizationFor(auth, secretParams, credential) ?: return null |
| 184 | val group = SignalGroupsApi.fetchGroup(authorization, signalTls()) ?: return null |
| 185 | return SignalGroupsApi.decryptGroup(secretParams, group) |
| 186 | } |
| 187 | |
| 188 | /** The group authorization a calling request needs, derived from the group behind [groupId]. */ |
| 189 | internal suspend fun SignalClient.groupAuthorization(groupId: ByteArray): String? { |
| 190 | val auth = authData ?: return null |
| 191 | val conversation = conversationForGroupId(groupId) ?: return null |
| 192 | val masterKey = conversation.groupMasterKey ?: return null |
| 193 | val secretParams = org.signal.libsignal.zkgroup.groups.GroupSecretParams.deriveFromMasterKey( |
| 194 | org.signal.libsignal.zkgroup.groups.GroupMasterKey(masterKey), |
| 195 | ) |
| 196 | val credential = SignalGroupsApi |
| 197 | .fetchCredentials(basicAuthHeader(), signalTls()) |
| 198 | .minByOrNull { kotlin.math.abs(it.redemptionTimeSeconds - System.currentTimeMillis() / MS_PER_SECOND) } |
| 199 | ?: return null |
| 200 | return SignalGroupsApi.authorizationFor(auth, secretParams, credential) |
| 201 | } |
| 202 | |
| 203 | internal suspend fun SignalClient.conversationForGroupId(groupId: ByteArray) = try { |
| 204 | db?.conversationDao()?.getConversation(SignalProtocol.groupConversationId(groupId)) |
| 205 | } catch (_: Exception) { |
| 206 | null |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Record a group we received a message from, so we can reply to it. |
| 211 | * |
| 212 | * Membership is learned incrementally from whoever has spoken: the envelope names only its sender, and the |
| 213 | * full member list comes from the server's group state. Until that is fetched, a reply reaches everyone we |
| 214 | * have heard from rather than everyone in the group — which is a real limitation, but strictly better than |
| 215 | * refusing to send at all. |
| 216 | */ |
| 217 | internal suspend fun SignalClient.rememberInboundGroup( |
| 218 | conversationId: String, |
| 219 | masterKey: ByteArray, |
| 220 | senderAci: String) { |
| 221 | val dao = db?.conversationDao() ?: return |
| 222 | try { |
| 223 | val existing = dao.getConversation(conversationId) |
| 224 | val members = buildSet { |
| 225 | existing?.participants?.split(",")?.forEach { entry -> |
| 226 | entry.trim().takeIf { it.isNotEmpty() }?.let { add(it) } |
| 227 | } |
| 228 | add(senderAci) |
| 229 | // Ourselves: a fan-out send skips our own address, but membership should still be accurate. |
| 230 | authData?.aci?.takeIf { it.isNotEmpty() }?.let { add(it) } |
| 231 | } |
| 232 | dao.upsert( |
| 233 | (existing ?: SignalConversation(chatId = conversationId)).copy( |
| 234 | isGroup = true, |
| 235 | groupMasterKey = masterKey, |
| 236 | participants = members.joinToString(","), |
| 237 | ), |
| 238 | ) |
| 239 | // Now that the master key is known, ask the server for the real membership. Best-effort: the |
| 240 | // message is already usable with what we learned from the envelope. |
| 241 | scope.launch { refreshGroup(conversationId) } |
| 242 | } catch (expected: Throwable) { |
| 243 | Log.status(TAG, "could not record the group behind $conversationId", expected) |
| 244 | } |
| 245 | } |