Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / SignalMessaging.kt

SignalMessaging.kt499 lines · 19.7 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import com.vayunmathur.library.log.Log
4import com.vayunmathur.communicate.data.signal.SignalAttachmentCipher
5import com.vayunmathur.communicate.data.signal.transport.SignalAttachmentUpload
6import com.vayunmathur.communicate.data.signal.transport.SignalPayload
7import com.vayunmathur.library.network.NetworkClient
8import org.whispersystems.signalservice.internal.push.SignalServiceProtos
9
10/**
11 * SignalClient messaging (split from SignalClient.kt for file length).
12 *
13 * Public signatures stable. Extension functions on [SignalClient]; behavior identical,
14 * call sites unchanged.
15 */
16
17// ---- Messaging (public signatures stable) ----
18
19suspend fun SignalClient.sendMessage(recipient: String, body: String): String? {
20 if (body.isBlank()) return null
21 val id = SignalProtocol.generateMessageId()
22 val ts = System.currentTimeMillis()
23 val aci = recipient.trim()
24 val isGroup = SignalProtocol.isGroupConversation(aci)
25 val groupMasterKey = if (isGroup) groupMasterKeyForConversation(aci) else null
26 if (isGroup && groupMasterKey == null) {
27 // Without the master key the recipients cannot tell which group this belongs to.
28 Log.status(TAG, "no stored master key for $aci, cannot send to the group")
29 eventsMutable.emit(SignalEvent.SendFailed(conversationId = aci, messageId = id, errorMessage = "unknown group"))
30 return null
31 }
32 val dataMessage = SignalPayload.buildDataMessage(
33 body = body,
34 timestamp = ts,
35 groupV2MasterKey = groupMasterKey,
36 groupV2Revision = if (groupMasterKey != null) groupRevisionForConversation(aci) else null,
37 )
38 val content = SignalPayload.buildContentWithDataMessage(dataMessage)
39 val ok = sendContent(aci, content)
40 if (!ok) {
41 eventsMutable.emit(
42 SignalEvent.SendFailed(
43 conversationId = aci,
44 messageId = id,
45 errorMessage = "could not send (see log: no ACI, no session, or server rejected)",
46 ),
47 )
48 return null
49 }
50 val sd = SignalServiceData(senderId = authData?.aci, isGroup = isGroup)
51 try { db?.cachedMessageDao()?.upsert(SignalCachedMessage(
52 messageId = id,
53 conversationId = aci,
54 body = body,
55 timestamp = ts,
56 outgoing = true,
57 senderId = authData?.aci ?: "",
58 serviceData = sd.serialize(),
59 status = 1)) } catch (_: Exception) {}
60 eventsMutable.emit(SignalEvent.MessageUpdate(
61 conversationId = aci,
62 messageId = id,
63 body = body,
64 outgoing = true,
65 timestamp = ts,
66 senderName = null,
67 senderId = authData?.aci))
68 return id
69}
70
71/**
72 * Encrypt, upload, and send an attachment. Returns null on any failure — the plaintext never leaves
73 * the device unencrypted, so a failed upload simply means no message.
74 */
75suspend fun SignalClient.sendMedia(
76 recipient: String,
77 bytes: ByteArray,
78 mimeType: String,
79 fileName: String? = null,
80): String? {
81 val encrypted = try {
82 SignalAttachmentCipher.encrypt(bytes)
83 } catch (expected: Throwable) {
84 Log.status(TAG, "attachment encryption failed", expected)
85 return sendMediaFailed(recipient, "could not encrypt the attachment")
86 }
87 val form = SignalAttachmentUpload.fetchForm(
88 uploadLength = encrypted.blob.size,
89 authHeader = basicAuthHeader(),
90 sslSocketFactory = signalTls(),
91 ) ?: return sendMediaFailed(recipient, "could not get an upload form")
92
93 if (!SignalAttachmentUpload.upload(form, encrypted.blob, signalTls())) {
94 return sendMediaFailed(recipient, "attachment upload failed")
95 }
96
97 val ts = System.currentTimeMillis()
98 val pointer = buildAttachmentPointer(form, encrypted, mimeType, fileName)
99 val (mediaGroupKey, mediaGroupRev) = groupContextFor(recipient)
100 val dm = SignalPayload.buildDataMessage(
101 body = "",
102 timestamp = ts,
103 attachments = listOf(pointer),
104 groupV2MasterKey = mediaGroupKey,
105 groupV2Revision = mediaGroupRev,
106 )
107 val content = SignalPayload.buildContentWithDataMessage(dm)
108 if (!sendContent(recipient, content)) {
109 return sendMediaFailed(recipient, "send failed")
110 }
111
112 return cacheOutgoingMedia(recipient, mimeType, ts)
113}
114
115/** Build the attachment pointer for an encrypted blob. */
116private fun buildAttachmentPointer(
117 form: SignalAttachmentUpload.UploadForm,
118 encrypted: SignalAttachmentCipher.Encrypted,
119 mimeType: String,
120 fileName: String?,
121): SignalServiceProtos.AttachmentPointer {
122 return SignalServiceProtos.AttachmentPointer.newBuilder()
123 .setCdnKey(form.key)
124 .setCdnNumber(form.cdn)
125 .setContentType(mimeType)
126 // size is the plaintext length; the recipient uses it to trim CBC padding.
127 .setSize(encrypted.plaintextSize)
128 .setKey(com.google.protobuf.ByteString.copyFrom(encrypted.key))
129 .setDigest(com.google.protobuf.ByteString.copyFrom(encrypted.digest))
130 .apply {
131 // Without a name a document arrives untitled on a real Signal client; images and videos are
132 // rendered inline so a name is optional there.
133 if (!fileName.isNullOrBlank()) setFileName(fileName)
134 }
135 .build()
136}
137
138/** Cache the outgoing media message and emit the update; returns the message id. */
139private suspend fun SignalClient.cacheOutgoingMedia(
140 recipient: String,
141 mimeType: String,
142 ts: Long,
143): String {
144 val id = SignalProtocol.generateMessageId()
145 val sd = SignalServiceData(mediaMime = mimeType, senderId = authData?.aci)
146 try {
147 db?.cachedMessageDao()?.upsert(
148 SignalCachedMessage(
149 messageId = id,
150 conversationId = recipient,
151 body = "[Media: $mimeType]",
152 timestamp = ts,
153 outgoing = true,
154 senderId = authData?.aci ?: "",
155 serviceData = sd.serialize(),
156 status = 1,
157 ),
158 )
159 } catch (_: Exception) {}
160 eventsMutable.emit(
161 SignalEvent.MessageUpdate(
162 conversationId = recipient,
163 messageId = id,
164 body = "[Media: $mimeType]",
165 outgoing = true,
166 timestamp = ts,
167 senderName = null,
168 serviceData = sd.serialize(),
169 ),
170 )
171 return id
172}
173
174private suspend fun SignalClient.sendMediaFailed(recipient: String, reason: String): String? {
175 Log.status(TAG, "attachment send to $recipient failed: $reason")
176 eventsMutable.emit(SignalEvent.SendFailed(conversationId = recipient, errorMessage = reason))
177 return null
178}
179
180suspend fun SignalClient.sendReaction(conversationId: String, messageId: String, emoji: String): Boolean {
181 val ts = System.currentTimeMillis()
182 // Resolve targetSentTimestamp + targetAuthorAci from cached message for wire-correct Reaction targeting.
183 val cached = try { db?.cachedMessageDao()?.get(messageId) } catch (_: Exception) { null }
184 val targetTimestamp = cached?.timestamp ?: ts
185 val targetAuthorAci =
186 cached?.senderId?.takeIf { it.isNotEmpty() } ?: conversationId.takeIf { it.matches(Regex("[0-9a-fA-F]{8}-.*")) }
187 val targetAuthorBinary = try {
188 if (targetAuthorAci != null) uuidStringToBytes(targetAuthorAci) else null
189 } catch (_: Exception) { null }
190 val isRemove = emoji.isEmpty()
191 val effectiveEmoji = if (isRemove) "" else emoji
192 val reaction = SignalPayload.buildReaction(
193 emoji = effectiveEmoji,
194 remove = isRemove,
195 targetAuthorAci = if (targetAuthorBinary == null) targetAuthorAci else null,
196 targetAuthorAciBinary = targetAuthorBinary,
197 targetSentTimestamp = targetTimestamp,
198 )
199 val (groupKey, groupRev) = groupContextFor(conversationId)
200 val dm = SignalPayload.buildDataMessage(
201 body = "",
202 timestamp = ts,
203 reaction = reaction,
204 groupV2MasterKey = groupKey,
205 groupV2Revision = groupRev,
206 )
207 val content = SignalPayload.buildContentWithDataMessage(dm)
208 val ok = sendContent(conversationId, content)
209 if (isRemove) {
210 eventsMutable.emit(SignalEvent.ReactionRemoved(
211 conversationId = conversationId,
212 messageId = messageId,
213 senderId = authData?.aci ?: ""))
214 } else {
215 eventsMutable.emit(SignalEvent.ReactionReceived(
216 conversationId = conversationId,
217 messageId = messageId,
218 senderId = authData?.aci ?: "",
219 emoji = emoji))
220 }
221 return ok || true
222}
223
224suspend fun SignalClient.removeReaction(conversationId: String, messageId: String): Boolean = sendReaction(
225 conversationId,
226 messageId,
227 "")
228
229suspend fun SignalClient.editMessage(conversationId: String, targetMessageId: String, newBody: String): Boolean {
230 val ts = System.currentTimeMillis()
231 val cached = try { db?.cachedMessageDao()?.get(targetMessageId) } catch (_: Exception) { null }
232 val targetTs = cached?.timestamp ?: ts
233 val (groupKey, groupRev) = groupContextFor(conversationId)
234 val newDm = SignalPayload.buildDataMessage(
235 body = newBody,
236 timestamp = ts,
237 groupV2MasterKey = groupKey,
238 groupV2Revision = groupRev,
239 )
240 val content = SignalPayload.buildContentForEdit(targetSentTimestamp = targetTs, newDataMessage = newDm)
241 try { sendContent(conversationId, content) } catch (_: Exception) {}
242 try { db?.cachedMessageDao()?.markEdited(targetMessageId, newBody) } catch (_: Exception) {}
243 eventsMutable.emit(SignalEvent.MessageEdited(
244 conversationId = conversationId,
245 messageId = targetMessageId,
246 newBody = newBody,
247 timestamp = ts))
248 return true
249}
250
251suspend fun SignalClient.revoke(conversationId: String, targetMessageId: String): Boolean {
252 val cached = try { db?.cachedMessageDao()?.get(targetMessageId) } catch (_: Exception) { null }
253 val targetTs = cached?.timestamp ?: System.currentTimeMillis()
254 val del = SignalPayload.buildDelete(targetSentTimestamp = targetTs)
255 val (groupKey, groupRev) = groupContextFor(conversationId)
256 val dm = SignalPayload.buildDataMessage(
257 body = "",
258 timestamp = System.currentTimeMillis(),
259 delete = del,
260 groupV2MasterKey = groupKey,
261 groupV2Revision = groupRev,
262 )
263 val content = SignalPayload.buildContentWithDataMessage(dm)
264 try { sendContent(conversationId, content) } catch (_: Exception) {}
265 try { db?.cachedMessageDao()?.markRevoked(targetMessageId) } catch (_: Exception) {}
266 eventsMutable.emit(SignalEvent.MessageDeleted(
267 messageId = targetMessageId,
268 conversationId = conversationId,
269 timestamp = System.currentTimeMillis()))
270 return true
271}
272
273suspend fun SignalClient.poll(conversationId: String, question: String, options: List<String>): String? {
274 val ts = System.currentTimeMillis()
275 val id = SignalProtocol.generateMessageId()
276 val pollCreate = SignalPayload.buildPollCreate(question, options, allowMultiple = false)
277 val (groupKey, groupRev) = groupContextFor(conversationId)
278 val dm = SignalPayload.buildDataMessage(
279 body = question,
280 timestamp = ts,
281 pollCreate = pollCreate,
282 groupV2MasterKey = groupKey,
283 groupV2Revision = groupRev,
284 )
285 val content = SignalPayload.buildContentWithDataMessage(dm)
286 try { sendContent(conversationId, content) } catch (_: Exception) {}
287 val sd = SignalServiceData(
288 pollQuestion = question,
289 pollOptions = options.map { SignalPollOptionData(it) },
290 senderId = authData?.aci)
291 try { db?.cachedMessageDao()?.upsert(SignalCachedMessage(
292 messageId = id,
293 conversationId = conversationId,
294 body = question,
295 timestamp = ts,
296 outgoing = true,
297 senderId = authData?.aci ?: "",
298 serviceData = sd.serialize())) } catch (_: Exception) {}
299 eventsMutable.emit(SignalEvent.MessageUpdate(
300 conversationId = conversationId,
301 messageId = id,
302 body = question,
303 outgoing = true,
304 timestamp = ts,
305 senderName = null,
306 serviceData = sd.serialize()))
307 return id
308}
309
310suspend fun SignalClient.sendPollVote(
311 conversationId: String,
312 pollMessageId: String,
313 selectedOptions: List<String>): Boolean {
314 val cached = try { db?.cachedMessageDao()?.get(pollMessageId) } catch (_: Exception) { null }
315 val pollData = cached?.serviceData?.let { SignalServiceData.parse(it) }
316 val optionNames = pollData?.pollOptions?.map { it.name } ?: emptyList()
317 val indexes = selectedOptions.mapNotNull { sel ->
318 val idx = optionNames.indexOf(sel)
319 if (idx >= 0) idx else null
320 }.ifEmpty { selectedOptions.mapIndexed { idx, _ -> idx } }
321 val targetTs = cached?.timestamp ?: System.currentTimeMillis()
322 val targetAuthorBinary = try { cached?.senderId?.let { uuidStringToBytes(it) } } catch (_: Exception) { null }
323 val pollVote = SignalPayload.buildPollVote(
324 targetAuthorAciBinary = targetAuthorBinary,
325 targetSentTimestamp = targetTs,
326 optionIndexes = indexes,
327 voteCount = selectedOptions.size,
328 )
329 val (groupKey, groupRev) = groupContextFor(conversationId)
330 val dm = SignalPayload.buildDataMessage(
331 body = "",
332 timestamp = System.currentTimeMillis(),
333 pollVote = pollVote,
334 groupV2MasterKey = groupKey,
335 groupV2Revision = groupRev,
336 )
337 val content = SignalPayload.buildContentWithDataMessage(dm)
338 try { sendContent(conversationId, content) } catch (_: Exception) {}
339 eventsMutable.emit(SignalEvent.PollVote(
340 conversationId = conversationId,
341 pollMessageId = pollMessageId,
342 voterId = authData?.aci ?: "",
343 optionNames = selectedOptions))
344 return true
345}
346
347suspend fun SignalClient.readReceipt(conversationId: String, lastMessageId: String?, lastTimestamp: Long): Boolean {
348 val cached = lastMessageId?.let { try { db?.cachedMessageDao()?.get(it) } catch (_: Exception) { null } }
349 val ts = cached?.timestamp ?: lastTimestamp
350 val content = SignalPayload.buildContentForReceipt(SignalServiceProtos.ReceiptMessage.Type.READ, listOf(ts))
351 try { sendContent(conversationId, content) } catch (_: Exception) {}
352 eventsMutable.emit(SignalEvent.ReadReceipt(
353 conversationId = conversationId,
354 messageId = lastMessageId,
355 timestampMs = ts,
356 timestamp = ts,
357 isDelivery = false))
358 return true
359}
360
361suspend fun SignalClient.markRead(conversationId: String, messageIds: List<String>) {
362 val ts = System.currentTimeMillis()
363 for (mid in messageIds) {
364 try { db?.cachedMessageDao()?.markReadStatus(mid) } catch (_: Exception) {}
365 }
366 // Batch READ receipt as repeated timestamps per SignalService.proto Content.ReceiptMessage.timestamp[]
367 val timestamps: List<Long> = try {
368 messageIds.mapNotNull { id -> db?.cachedMessageDao()?.get(id)?.timestamp }
369 } catch (_: Exception) { emptyList() }
370 val effectiveTimestamps = timestamps.ifEmpty { listOf(ts) }
371 val content = SignalPayload.buildContentForReceipt(
372 SignalServiceProtos.ReceiptMessage.Type.READ,
373 effectiveTimestamps)
374 try { sendContent(conversationId, content) } catch (_: Exception) {}
375 // Also emit per-message for processor compatibility
376 for (mid in messageIds) {
377 eventsMutable.emit(SignalEvent.ReadReceipt(
378 conversationId = conversationId,
379 messageId = mid,
380 timestampMs = ts,
381 timestamp = ts,
382 isDelivery = false))
383 }
384}
385
386suspend fun SignalClient.sendTyping(conversationId: String, isTyping: Boolean) {
387 eventsMutable.emit(SignalEvent.TypingIndicator(
388 conversationId = conversationId,
389 senderId = authData?.aci ?: "",
390 isTyping = isTyping))
391 val ts = System.currentTimeMillis()
392 // TypingMessage.groupId is the 32-byte GroupIdentifier, which the conversation id already encodes.
393 val groupId: ByteArray? = SignalProtocol.groupIdentifierOf(conversationId)
394 val action = if (isTyping) {
395 SignalServiceProtos.TypingMessage.Action.STARTED
396 } else {
397 SignalServiceProtos.TypingMessage.Action.STOPPED
398 }
399 val content = SignalPayload.buildContentForTyping(timestamp = ts, action = action, groupId = groupId)
400 try { sendContent(conversationId, content) } catch (_: Exception) {}
401}
402
403fun SignalClient.isLoggedIn(): Boolean = isConnected()
404
405/**
406 * Download and decrypt an attachment. [key] is the 64-byte combined key from the
407 * `AttachmentPointer`, and [digest] its digest when present — both are verified before the
408 * plaintext is returned, so a CDN that served the wrong bytes produces null rather than garbage.
409 *
410 * Note the upload side is not implemented, so nothing in the app produces pointers yet; this handles
411 * pointers from real peers.
412 */
413suspend fun SignalClient.downloadMedia(
414 url: String,
415 key: ByteArray,
416 type: String,
417 digest: ByteArray? = null,
418 plaintextSize: Int? = null,
419): ByteArray? {
420 val blob = try {
421 // Signal attachments live on cdn.signal.org (Signal's private CA); other hosts hit
422 // public CAs. signalTls() is a union factory (Signal roots + system), safe for both.
423 val resp = NetworkClient.execute(url, method = "GET", sslSocketFactory = signalTls())
424 if (!resp.isSuccess) {
425 Log.status(TAG, "attachment download failed: ${resp.status} ${resp.statusMessage}")
426 return null
427 }
428 resp.bytes
429 } catch (expected: Throwable) {
430 Log.status(TAG, "attachment download failed", expected)
431 return null
432 }
433 return try {
434 SignalAttachmentCipher.decrypt(blob, key, digest, plaintextSize)
435 } catch (expected: Throwable) {
436 Log.status(TAG, "attachment did not decrypt ($type)", expected)
437 null
438 }
439}
440
441suspend fun SignalClient.refreshPresence(conversationId: String) {
442 // Signal has no presence REST; typing/read are only presence cues per verification report §8.
443 // Keep as local no-op with PresenceUpdate for UI compatibility; do not hit /api/v1/accounts/*/presence.
444 Log.status(TAG, "refreshPresence no-op (Signal has no presence REST; typing/read indicate presence)")
445 eventsMutable.emit(SignalEvent.PresenceUpdate(
446 conversationId = conversationId,
447 isOnline = false,
448 lastSeen = System.currentTimeMillis()))
449}
450
451/**
452 * Share a contact card.
453 *
454 * Sent as `DataMessage.contact` rather than as a text blob or a vCard attachment, so the recipient can save
455 * or call it directly.
456 */
457suspend fun SignalClient.sendContactCard(
458 conversationId: String,
459 givenName: String,
460 familyName: String?,
461 phoneNumbers: List<Pair<String, String?>>,
462 emails: List<String>,
463): Boolean {
464 val contact = SignalPayload.buildSharedContact(
465 givenName = givenName,
466 familyName = familyName,
467 phoneNumbers = phoneNumbers,
468 emails = emails,
469 ) ?: run {
470 Log.status(TAG, "refusing to share a contact with no name and no numbers")
471 return false
472 }
473 val ts = System.currentTimeMillis()
474 val (groupKey, groupRev) = groupContextFor(conversationId)
475 val dm = SignalPayload.buildDataMessage(
476 body = "",
477 timestamp = ts,
478 contact = contact,
479 groupV2MasterKey = groupKey,
480 groupV2Revision = groupRev,
481 )
482 return sendContent(conversationId, SignalPayload.buildContentWithDataMessage(dm))
483}
484
485private const val UUID_BYTES = 16
486private val MSB_RANGE = 7 downTo 0
487private val LSB_RANGE = 15 downTo 8
488private const val BYTE_MASK = 0xFFL
489private const val BYTE_BITS = 8
490
491private fun SignalClient.uuidStringToBytes(uuid: String): ByteArray {
492 val u = java.util.UUID.fromString(uuid)
493 val b = ByteArray(UUID_BYTES)
494 var msb = u.mostSignificantBits
495 var lsb = u.leastSignificantBits
496 for (i in MSB_RANGE) { b[i] = (msb and BYTE_MASK).toByte(); msb = msb shr BYTE_BITS }
497 for (i in LSB_RANGE) { b[i] = (lsb and BYTE_MASK).toByte(); lsb = lsb shr BYTE_BITS }
498 return b
499}