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

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

SignalInbound.kt635 lines · 26.0 KiBRaw
1package com.vayunmathur.communicate.data.signal
2
3import android.util.Base64 as AndroidBase64
4import com.vayunmathur.library.log.Log
5import com.vayunmathur.communicate.data.signal.e2e.remoteRegistrationId
6import com.vayunmathur.communicate.data.signal.e2e.senderRegistrationId
7import com.vayunmathur.communicate.data.signal.transport.SignalPayload
8import org.signal.libsignal.protocol.message.DecryptionErrorMessage
9import org.signal.libsignal.protocol.message.PlaintextContent
10import org.whispersystems.signalservice.internal.push.SignalServiceProtos
11import signal.proto.chat_websocket.SignalChatWebsocket.WebSocketMessage
12
13/**
14 * SignalClient inbound envelope pipeline (split from SignalClient.kt for file length).
15 *
16 * Extension functions on [SignalClient]; behavior identical, call sites unchanged.
17 */
18
19// -- Inbound ----
20
21internal suspend fun SignalClient.handleInboundFrame(raw: ByteArray) {
22 val wsMessage = SignalProtocol.parseWebSocketMessage(raw)
23 if (wsMessage == null) {
24 Log.status(TAG, "unparseable ws frame len=${raw.size}")
25 return
26 }
27 if (wsMessage.type != WebSocketMessage.Type.REQUEST || !wsMessage.hasRequest()) return
28 val req = wsMessage.request
29 val ackId = if (req.hasId()) req.id else null
30
31 // Control frames carry nothing to persist, so they can be acked straight away.
32 val isControlFrame = SignalProtocol.isQueueEmptySignal(raw) ||
33 (req.hasPath() && req.path.contains("keepalive")) ||
34 !req.hasBody()
35 if (isControlFrame) {
36 ackEnvelope(ackId)
37 return
38 }
39
40 val handled = try {
41 processEnvelope(wsMessage)
42 } catch (expected: kotlinx.coroutines.CancellationException) {
43 throw expected
44 } catch (expected: Throwable) {
45 // Redelivery cannot fix a deterministic failure, and there is no attempt counter, so
46 // acking is the lesser evil: not acking would spin on the same envelope forever.
47 Log.error(TAG, "failed to process envelope, acking anyway to avoid a redelivery loop", expected)
48 true
49 }
50 // An ack deletes the message from the server's queue, so it is deferred until the envelope has
51 // been decrypted, validated and handed to the event pipeline. Note this is hand-off, not a
52 // durable write: SignalEventProcessor persists asynchronously and swallows its own failures.
53 if (handled) {
54 ackEnvelope(ackId)
55 } else {
56 Log.status(TAG, "not acking envelope; leaving it queued for redelivery")
57 }
58}
59
60private suspend fun SignalClient.ackEnvelope(requestId: Long?) {
61 if (requestId == null) return
62 val ack = SignalProtocol.buildWsResponseProto(requestId, 200)
63 try { socket?.send(SignalProtocol.encodeWebSocketResponse(ack)) } catch (_: Exception) {}
64}
65
66/**
67 * Returns whether the envelope may be acked. False means "leave it on the server queue", which is
68 * only appropriate when we could not even attempt to handle it — a malformed or undecryptable
69 * message returns true, since redelivering it would only spin.
70 */
71private suspend fun SignalClient.processEnvelope(wsMessage: WebSocketMessage): Boolean {
72 val envelopeProto = SignalProtocol.parseEnvelopeFromWsMessage(wsMessage) ?: return true
73 val env = SignalProtocol.toSignalEnvelope(envelopeProto)
74
75 // Server delivery receipt (plaintext, no content) -> emit ReadReceipt as delivery
76 if (env.type == SignalServiceProtos.Envelope.Type.SERVER_DELIVERY_RECEIPT) {
77 emitServerReceipt(env)
78 return true
79 }
80
81 if (env.content.isEmpty()) return true
82 return processDecryptedEnvelope(env)
83}
84
85/** Decrypt, validate, and dispatch an envelope with content. */
86private suspend fun SignalClient.processDecryptedEnvelope(env: SignalProtocol.SignalEnvelope): Boolean {
87 val paddedPlaintext = decryptEnvelope(env) ?: return true
88 // Signal pads the plaintext before encrypting, for every envelope type.
89 val plaintext = SignalProtocol.stripMessagePadding(paddedPlaintext)
90
91 val content = SignalProtocol.parseContent(plaintext)
92 if (content == null) {
93 Log.status(TAG, "parseContent failed for ${env.sourceAci}")
94 return true
95 }
96 if (env.type == SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT &&
97 !SignalProtocol.isValidPlaintextContent(content)
98 ) {
99 Log.status(TAG, "dropping PLAINTEXT_CONTENT carrying more than a DecryptionErrorMessage from ${env.sourceAci}")
100 return true
101 }
102 val parsed = SignalProtocol.classifyContent(content)
103 captureSenderKeys(env, parsed, content)
104 val masterKeyFromData = masterKeyFrom(parsed)
105 // A verified PNI signature merges the sender's ACI with the PNI we knew them by, which is what
106 // keeps their reply in the conversation we sent to instead of opening a second one.
107 if (content.hasPniSignatureMessage()) {
108 linkPniToAci(env.sourceAci, content.pniSignatureMessage)
109 }
110 val conversationId = if (masterKeyFromData != null) {
111 SignalProtocol.toConversationId(env.sourceAci, masterKeyFromData)
112 } else {
113 // Anchored on the contact rather than the raw service id, so ACI- and PNI-addressed traffic
114 // share one thread.
115 conversationIdFor(env.sourceAci)
116 }
117 val senderDisplayName = displayNameFor(env.sourceAci)
118 val senderAci = env.sourceAci
119 // Remember the group's identity so a reply can be sent. Without this the conversation is created with
120 // no master key or members and every reply is refused or silently dropped.
121 if (masterKeyFromData != null) {
122 rememberInboundGroup(conversationId, masterKeyFromData, env.sourceAci)
123 }
124 val senderDevice = env.sourceDevice
125 val serverGuid = env.serverGuid ?: SignalProtocol.generateMessageId()
126 val timestamp = env.timestamp
127
128 dispatchParsedContent(
129 parsed,
130 InboundDispatch(
131 env,
132 conversationId,
133 senderAci,
134 senderDevice,
135 senderDisplayName,
136 timestamp,
137 serverGuid,
138 masterKeyFromData,
139 ),
140 )
141 return true
142}
143
144/**
145 * Capture the sender's keys before dispatching: the profile key (what lets us send sealed-sender
146 * back to them, independent of message kind) and any sender-key distribution (what lets their
147 * later group messages decrypt, including when it arrives on its own Content with no DataMessage).
148 */
149private suspend fun SignalClient.captureSenderKeys(
150 env: SignalProtocol.SignalEnvelope,
151 parsed: SignalProtocol.ParsedContent,
152 content: SignalServiceProtos.Content,
153) {
154 profileKeyFrom(parsed)?.let { key ->
155 db?.let { SignalSealedSender.rememberProfileKey(it, env.sourceAci, key) }
156 }
157 if (!content.hasSenderKeyDistributionMessage()) return
158 try {
159 e2e?.processSenderKeyDistribution(
160 env.sourceAci,
161 env.sourceDevice,
162 content.senderKeyDistributionMessage.toByteArray(),
163 )
164 Log.status(TAG, "stored a sender key from ${env.sourceAci}:${env.sourceDevice}")
165 } catch (expected: Throwable) {
166 // Losing this means later group messages from this sender cannot be decrypted.
167 Log.status(TAG, "failed to store sender key distribution from ${env.sourceAci}", expected)
168 }
169}
170
171/**
172 * Tell [env]'s sender that we could not decrypt, so they rebuild the session.
173 *
174 * This is the protocol's recovery path: a `DecryptionErrorMessage` in a plaintext envelope makes the
175 * sender archive their session and fetch a fresh pre-key bundle. Without it a session that has drifted
176 * — for instance because our Kyber pre-key was replaced — stays broken forever, with every retry
177 * failing identically.
178 *
179 * Sent unencrypted by design; `PLAINTEXT_CONTENT` is the one envelope type that may be, and it may
180 * carry nothing but this.
181 */
182private suspend fun SignalClient.sendRetryReceipt(env: SignalProtocol.SignalEnvelope) {
183 val e = e2e ?: return
184 val sender = env.sourceAci.takeIf { it.isNotEmpty() } ?: return
185 if (env.content.isEmpty()) return
186 try {
187 val errorMessage = DecryptionErrorMessage.forOriginalMessage(
188 env.content,
189 env.type.number,
190 env.timestamp,
191 env.sourceDevice,
192 )
193 val body = PlaintextContent(errorMessage).serialize()
194 // The server rejects a send whose destinationRegistrationId does not match the recipient's, so
195 // this must be their real one. A pre-key message carries it; otherwise fall back to the session.
196 // Deliberately read before anything touches the session, and the session is not archived here —
197 // the receipt asks *them* to archive theirs.
198 val registrationId = e.senderRegistrationId(env.content)
199 ?: e.remoteRegistrationId(sender, env.sourceDevice)
200 if (registrationId == null) {
201 Log.status(TAG, "no registration id for $sender:${env.sourceDevice}, cannot send a retry receipt")
202 return
203 }
204 val message = SignalPayload.OutgoingPushMessage(
205 type = SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT.number,
206 destinationDeviceId = env.sourceDevice,
207 destinationRegistrationId = registrationId,
208 content = body,
209 )
210 val json = SignalPayload.buildPutMessagesBody(
211 destinationAci = sender,
212 messages = listOf(message),
213 timestamp = System.currentTimeMillis(),
214 urgent = false,
215 )
216 when (val outcome = putMessages(sender, json, accessKey = null)) {
217 is SignalClient.SendOutcome.Success ->
218 Log.status(TAG, "sent a retry receipt to $sender:${env.sourceDevice}")
219 else -> Log.status(TAG, "could not send a retry receipt to $sender: $outcome")
220 }
221 } catch (expected: Throwable) {
222 Log.status(TAG, "could not build a retry receipt for $sender", expected)
223 }
224}
225
226/**
227 * Inbound attachment pointers, previously dropped entirely. The CDN URL is derived from
228 * `cdnKey`/`cdnNumber`; the key and digest travel with the pointer and are what
229 * [SignalClient.downloadMedia] needs to decrypt and verify.
230 */
231/** Original messageId for a reaction/edit/delete/poll target timestamp, else the timestamp itself. */
232private suspend fun SignalClient.messageIdForTimestamp(conversationId: String, targetTs: Long): String {
233 val cached = db?.cachedMessageDao()?.getForConversation(conversationId)
234 return cached?.firstOrNull { it.timestamp == targetTs }?.messageId ?: targetTs.toString()
235}
236
237private fun SignalClient.attachmentsFrom(dm: SignalServiceProtos.DataMessage): List<SignalAttachment> =
238 dm.attachmentsList.mapNotNull { pointer ->
239 val cdnKey = pointer.cdnKey?.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
240 val mime = pointer.contentType?.takeIf { it.isNotEmpty() } ?: "application/octet-stream"
241 SignalAttachment(
242 url = attachmentUrl(cdnKey, pointer.cdnNumber),
243 mimeType = mime,
244 attachmentType = when {
245 mime.startsWith("image/") -> "image"
246 mime.startsWith("video/") -> "video"
247 mime.startsWith("audio/") -> "audio"
248 else -> "file"
249 },
250 fileName = pointer.fileName?.takeIf { it.isNotEmpty() },
251 width = pointer.width,
252 height = pointer.height,
253 )
254 }
255
256private fun SignalClient.attachmentUrl(cdnKey: String, cdnNumber: Int): String {
257 val host = if (cdnNumber == 0) "cdn.signal.org" else "cdn$cdnNumber.signal.org"
258 return "https://$host/attachments/$cdnKey"
259}
260
261private suspend fun SignalClient.emitReadSync(timestamp: Long, fallbackConversationId: String) {
262 val cached = try { db?.cachedMessageDao()?.getByTimestamp(timestamp) } catch (_: Exception) { null }
263 eventsMutable.emit(
264 SignalEvent.ReadReceipt(
265 conversationId = cached?.conversationId ?: fallbackConversationId,
266 messageId = cached?.messageId ?: timestamp.toString(),
267 timestampMs = timestamp,
268 timestamp = timestamp,
269 isDelivery = false,
270 ),
271 )
272}
273
274private suspend fun SignalClient.emitDecryptionError(env: SignalProtocol.SignalEnvelope, message: String?) {
275 val cid = SignalProtocol.toConversationId(env.sourceAci, null as ByteArray?)
276 eventsMutable.emit(
277 SignalEvent.DecryptionError(
278 conversationId = cid,
279 senderAci = env.sourceAci,
280 senderDeviceId = env.sourceDevice,
281 timestamp = env.timestamp,
282 errorMessage = message,
283 ),
284 )
285}
286
287/**
288 * Sealed-sender trust roots. These are build constants in the official client
289 * (`UNIDENTIFIED_SENDER_TRUST_ROOTS`), a list so the server can rotate; a certificate is accepted
290 * if it validates against any of them.
291 */
292private fun SignalClient.unidentifiedSenderTrustRoots(): List<org.signal.libsignal.protocol.ecc.ECPublicKey> =
293 TRUST_ROOTS_B64.map {
294 org.signal.libsignal.protocol.ecc.ECPublicKey(AndroidBase64.decode(it, AndroidBase64.NO_WRAP))
295 }
296
297/** The group conversation id a DataMessage belongs to, or empty when it is not a group message. */
298private fun SignalClient.groupIdFor(dm: SignalServiceProtos.DataMessage): String {
299 return if (dm.hasGroupV2() && dm.groupV2.hasMasterKey()) {
300 SignalProtocol.toConversationId("", dm.groupV2.masterKey.toByteArray())
301 } else {
302 ""
303 }
304}
305
306
307
308/** Emit a server delivery receipt as a ReadReceipt. */
309private suspend fun SignalClient.emitServerReceipt(env: SignalProtocol.SignalEnvelope) {
310 val cid = env.sourceAci.ifEmpty { env.destinationAci ?: "unknown" }
311 val ts = if (env.timestamp != 0L) env.timestamp else env.serverTimestamp
312 eventsMutable.emit(SignalEvent.ReadReceipt(
313 conversationId = cid,
314 messageId = env.serverGuid,
315 timestampMs = ts,
316 timestamp = ts,
317 isDelivery = true))
318}
319
320/**
321 * Decrypt the envelope content; null when queued (no store) or acked (decrypt failure).
322 * A failure must never fall back to the raw envelope bytes: those are attacker
323 * controlled, so treating them as a Content would let anyone forge a message from any ACI.
324 */
325private suspend fun SignalClient.decryptEnvelope(env: SignalProtocol.SignalEnvelope): ByteArray? {
326 val e = e2e
327 if (e == null) {
328 // Defensive: start() refuses to connect without a store, so this should be unreachable.
329 // Keep the envelope queued rather than acking something we never tried to decrypt.
330 Log.status(TAG, "no protocol store, leaving envelope from ${env.sourceAci} queued")
331 return null
332 }
333 return try {
334 // Which identity the sender addressed matters: a message to our PNI must be decrypted with the
335 // PNI identity and its own pre-keys, not the ACI ones.
336 Log.status(
337 TAG,
338 "envelope type=${env.type} from=${env.sourceAci}:${env.sourceDevice} " +
339 "destination=${env.destinationAci} ourAci=${authData?.aci} ourPni=${authData?.pni}",
340 )
341 when (env.type) {
342 SignalServiceProtos.Envelope.Type.UNIDENTIFIED_SENDER ->
343 e.sealedSenderDecrypt(env.content, unidentifiedSenderTrustRoots(), env.serverTimestamp)
344 SignalServiceProtos.Envelope.Type.PREKEY_MESSAGE ->
345 e.decryptDM(env.sourceAci, env.sourceDevice, true, env.content)
346 SignalServiceProtos.Envelope.Type.DOUBLE_RATCHET ->
347 e.decryptDM(env.sourceAci, env.sourceDevice, false, env.content)
348 // The one unencrypted envelope type, and it may only carry a DecryptionErrorMessage
349 // (enforced after parsing, below).
350 SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT -> env.content
351 else -> throw IllegalArgumentException("unknown envelope type ${env.type}")
352 }
353 } catch (expected: Throwable) {
354 Log.status(TAG, "decrypt failed for ${env.sourceAci}:${env.sourceDevice}", expected)
355 emitDecryptionError(env, expected.message)
356 // Ask the sender to rebuild the session; otherwise this fails identically forever.
357 if (env.type != SignalServiceProtos.Envelope.Type.PLAINTEXT_CONTENT) sendRetryReceipt(env)
358 // Redelivery cannot fix a decrypt failure, so ack rather than spin on it.
359 null
360 }
361}
362
363/** Group master key from Data/Edit content, or null. */
364private fun masterKeyFrom(parsed: SignalProtocol.ParsedContent): ByteArray? = when (parsed) {
365 is SignalProtocol.ParsedContent.Data -> {
366 val group = parsed.dataMessage.takeIf { it.hasGroupV2() }?.groupV2
367 group?.takeIf { it.hasMasterKey() }?.masterKey?.toByteArray()
368 }
369 is SignalProtocol.ParsedContent.Edit -> {
370 val data = parsed.editMessage.takeIf { it.hasDataMessage() }?.dataMessage
371 val group = data?.takeIf { it.hasGroupV2() }?.groupV2
372 group?.takeIf { it.hasMasterKey() }?.masterKey?.toByteArray()
373 }
374 else -> null
375}
376
377/** Shared inbound dispatch state for one envelope. */
378private class InboundDispatch(
379 val env: SignalProtocol.SignalEnvelope,
380 val conversationId: String,
381 val senderAci: String,
382 val senderDevice: Int,
383 val senderDisplayName: String,
384 val timestamp: Long,
385 val serverGuid: String,
386 val masterKeyFromData: ByteArray?,
387)
388
389/** Handle one parsed content branch. */
390private suspend fun SignalClient.dispatchParsedContent(
391 parsed: SignalProtocol.ParsedContent,
392 dispatch: InboundDispatch,
393) {
394 when (parsed) {
395 is SignalProtocol.ParsedContent.Data -> handleDataContent(parsed, dispatch)
396 is SignalProtocol.ParsedContent.Receipt -> handleReceiptContent(parsed, dispatch)
397 is SignalProtocol.ParsedContent.Typing -> handleTypingContent(parsed, dispatch)
398 is SignalProtocol.ParsedContent.Edit -> handleEditContent(parsed, dispatch)
399 is SignalProtocol.ParsedContent.Call -> handleCallContent(parsed, dispatch)
400 is SignalProtocol.ParsedContent.Sync -> handleSyncContent(parsed, dispatch)
401 else -> {
402 Log.status(TAG, "unhandled Content type ${parsed::class.simpleName} from ${dispatch.senderAci}")
403 }
404 }
405}
406/** Handle Data content. */
407private suspend fun SignalClient.handleDataContent(
408 parsed: SignalProtocol.ParsedContent.Data,
409 dispatch: InboundDispatch,
410) {
411 val dm = parsed.dataMessage
412 when {
413 dm.hasReaction() -> handleReaction(dm, dispatch)
414 dm.hasDelete() -> handleDelete(dm, dispatch)
415 dm.hasPollCreate() -> handlePollCreate(dm, dispatch)
416 dm.hasPollVote() -> handlePollVote(dm, dispatch)
417 dm.hasPollTerminate() -> handlePollTerminate(dm, dispatch)
418 else -> handleTextData(dm, dispatch)
419 }
420}
421
422/** Resolve a target message id by timestamp, falling back to the timestamp itself. */
423private suspend fun SignalClient.targetMessageId(conversationId: String, targetTs: Long): String = try {
424 messageIdForTimestamp(conversationId, targetTs)
425} catch (_: Exception) {
426 targetTs.toString()
427}
428
429private suspend fun SignalClient.handleReaction(
430 dm: SignalServiceProtos.DataMessage,
431 dispatch: InboundDispatch,
432) {
433 val r = dm.reaction
434 val targetId = targetMessageId(dispatch.conversationId, r.targetSentTimestamp)
435 if (r.remove) {
436 eventsMutable.emit(SignalEvent.ReactionRemoved(
437 conversationId = dispatch.conversationId,
438 messageId = targetId,
439 senderId = dispatch.senderAci))
440 } else {
441 eventsMutable.emit(SignalEvent.ReactionReceived(
442 conversationId = dispatch.conversationId,
443 messageId = targetId,
444 senderId = dispatch.senderAci,
445 emoji = r.emoji))
446 }
447}
448
449private suspend fun SignalClient.handleDelete(
450 dm: SignalServiceProtos.DataMessage,
451 dispatch: InboundDispatch,
452) {
453 val targetId = targetMessageId(dispatch.conversationId, dm.delete.targetSentTimestamp)
454 eventsMutable.emit(SignalEvent.MessageDeleted(
455 messageId = targetId,
456 conversationId = dispatch.conversationId,
457 timestamp = dispatch.timestamp))
458}
459
460private suspend fun SignalClient.handlePollCreate(
461 dm: SignalServiceProtos.DataMessage,
462 dispatch: InboundDispatch,
463) {
464 val pc = dm.pollCreate
465 val sd = SignalServiceData(
466 pollQuestion = pc.question,
467 pollOptions = pc.optionsList.map { SignalPollOptionData(it) },
468 senderId = dispatch.senderAci)
469 eventsMutable.emit(SignalEvent.IncomingMessage(
470 conversationId = dispatch.conversationId,
471 messageId = dispatch.serverGuid,
472 body = pc.question,
473 peerName = dispatch.senderDisplayName,
474 peerPhone = null,
475 timestamp = dispatch.timestamp,
476 senderId = dispatch.senderAci,
477 serviceData = sd.serialize(),
478 pollQuestion = pc.question,
479 pollOptions = pc.optionsList))
480}
481
482private suspend fun SignalClient.handlePollVote(
483 dm: SignalServiceProtos.DataMessage,
484 dispatch: InboundDispatch,
485) {
486 val pv = dm.pollVote
487 val pollId = targetMessageId(dispatch.conversationId, pv.targetSentTimestamp)
488 val pollCached = try { db?.cachedMessageDao()?.get(pollId) } catch (_: Exception) { null }
489 val pollOptions = pollCached?.serviceData?.let { raw ->
490 SignalServiceData.parse(raw)?.pollOptions?.map { o -> o.name }
491 } ?: emptyList()
492 val selected = pv.optionIndexesList.mapNotNull { idx ->
493 pollOptions.getOrNull(idx)
494 }.ifEmpty { pv.optionIndexesList.map { it.toString() } }
495 eventsMutable.emit(SignalEvent.PollVote(
496 conversationId = dispatch.conversationId,
497 pollMessageId = pollId,
498 voterId = dispatch.senderAci,
499 optionNames = selected))
500}
501
502private suspend fun SignalClient.handlePollTerminate(
503 dm: SignalServiceProtos.DataMessage,
504 dispatch: InboundDispatch,
505) {
506 // Treat as generic incoming for now; live will handle poll closure UI via serviceData flag.
507 eventsMutable.emit(SignalEvent.IncomingMessage(
508 conversationId = dispatch.conversationId,
509 messageId = dispatch.serverGuid,
510 body = dm.body,
511 peerName = dispatch.senderDisplayName,
512 peerPhone = null,
513 timestamp = dispatch.timestamp,
514 senderId = dispatch.senderAci,
515 serviceData = SignalServiceData(senderId = dispatch.senderAci).serialize()))
516}
517
518private suspend fun SignalClient.handleTextData(
519 dm: SignalServiceProtos.DataMessage,
520 dispatch: InboundDispatch,
521) {
522 val body = dm.body
523 if (body.isBlank() && dm.attachmentsCount == 0 && !dm.hasGroupV2()) return
524 // senderKeyDistributionMessage is handled above, before content dispatch.
525 val sd = SignalServiceData(
526 senderId = dispatch.senderAci,
527 senderName = dispatch.senderDisplayName,
528 isGroup = dispatch.masterKeyFromData != null)
529 eventsMutable.emit(
530 SignalEvent.IncomingMessage(
531 conversationId = dispatch.conversationId,
532 messageId = dispatch.serverGuid,
533 body = body,
534 peerName = dispatch.senderDisplayName,
535 peerPhone = null,
536 timestamp = dispatch.timestamp,
537 senderId = dispatch.senderAci,
538 attachments = attachmentsFrom(dm),
539 serviceData = sd.serialize(),
540 ),
541 )
542}
543
544/** Handle Receipt content. */
545private suspend fun SignalClient.handleReceiptContent(
546 parsed: SignalProtocol.ParsedContent.Receipt,
547 dispatch: InboundDispatch,
548) {
549 val rm = parsed.receiptMessage
550 val isDelivery = rm.type == SignalServiceProtos.ReceiptMessage.Type.DELIVERY
551 Log.status(
552 TAG,
553 "receipt from ${dispatch.env.sourceAci}: type=${rm.type} timestamps=${rm.timestampList}",
554 )
555 for (tsVal in rm.timestampList) {
556 // Resolved by timestamp rather than by conversation: the outgoing message may have been
557 // filed under a different id (phone number vs service id) than this receipt resolves to,
558 // and the timestamp is the message's protocol-level identity either way.
559 val cached = try {
560 db?.cachedMessageDao()?.getOutgoingByTimestamp(tsVal)
561 } catch (_: Exception) { null }
562 if (cached == null) {
563 Log.status(TAG, "receipt for unknown outgoing message at $tsVal")
564 }
565 eventsMutable.emit(
566 SignalEvent.ReadReceipt(
567 conversationId = cached?.conversationId ?: dispatch.conversationId,
568 messageId = cached?.messageId ?: tsVal.toString(),
569 timestampMs = tsVal,
570 timestamp = tsVal,
571 isDelivery = isDelivery,
572 ),
573 )
574 }
575}
576
577/** Handle Typing content. */
578private suspend fun SignalClient.handleTypingContent(
579 parsed: SignalProtocol.ParsedContent.Typing,
580 dispatch: InboundDispatch,
581) {
582 val tm = parsed.typingMessage
583 val isTyping = tm.action == SignalServiceProtos.TypingMessage.Action.STARTED
584 val cid = if (tm.hasGroupId()) {
585 // groupId is the 32-byte GroupIdentifier, which is exactly what the conversation id
586 // encodes, so it maps across directly.
587 SignalProtocol.toConversationId("", SignalGroups.run { tm.groupId.toByteArray().toHex() })
588 } else dispatch.conversationId
589 eventsMutable.emit(SignalEvent.TypingIndicator(
590 conversationId = cid,
591 senderId = dispatch.senderAci,
592 isTyping = isTyping))
593}
594
595/** Handle Edit content. */
596private suspend fun SignalClient.handleEditContent(
597 parsed: SignalProtocol.ParsedContent.Edit,
598 dispatch: InboundDispatch,
599) {
600 val em = parsed.editMessage
601 val targetTs = em.targetSentTimestamp
602 val newBody = em.dataMessage.body
603 val targetId = try {
604 messageIdForTimestamp(dispatch.conversationId, targetTs)
605 } catch (_: Exception) { targetTs.toString() }
606 eventsMutable.emit(SignalEvent.MessageEdited(
607 conversationId = dispatch.conversationId,
608 messageId = targetId,
609 newBody = newBody,
610 timestamp = dispatch.timestamp))
611}
612
613/** Handle Call content. */
614private suspend fun SignalClient.handleCallContent(
615 parsed: SignalProtocol.ParsedContent.Call,
616 dispatch: InboundDispatch,
617) {
618 handleCallMessage(parsed.callMessage, dispatch.senderAci, dispatch.senderDevice, dispatch.env, dispatch.timestamp)
619}
620
621/** Handle Sync content. */
622private suspend fun SignalClient.handleSyncContent(
623 parsed: SignalProtocol.ParsedContent.Sync,
624 dispatch: InboundDispatch,
625) {
626 val sm = parsed.syncMessage
627 // Read/viewed syncs from our own other devices refer to inbound messages by sent timestamp,
628 // so resolve on that rather than scoping to a conversation id that may not match.
629 for (r in sm.readList) {
630 emitReadSync(r.timestamp, dispatch.conversationId)
631 }
632 for (v in sm.viewedList) {
633 emitReadSync(v.timestamp, dispatch.conversationId)
634 }
635}