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

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / whatsapp / WhatsAppEventProcessor.kt

WhatsAppEventProcessor.kt284 lines · 12.7 KiBRaw
1package com.vayunmathur.communicate.data.whatsapp
2
3import com.vayunmathur.library.log.Log
4import kotlinx.coroutines.CoroutineScope
5import kotlinx.coroutines.Dispatchers
6import kotlinx.coroutines.SupervisorJob
7import kotlinx.coroutines.cancel
8import kotlinx.coroutines.flow.SharedFlow
9import kotlinx.coroutines.launch
10
11/**
12 * Drains [WhatsAppClient.events] into Room ([WhatsAppDatabase]) so the merged inbox survives restarts
13 * and reflects rich features. Runs on its own `Dispatchers.IO + SupervisorJob` scope; [HistorySync]
14 * is written in a batched `@Transaction` (via `upsertAll`) to avoid per-row overhead.
15 */
16class WhatsAppEventProcessor(private val db: WhatsAppDatabase) {
17
18 private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
19 private val messages = db.cachedMessageDao()
20 private val callLog = db.callLogDao()
21 private val reactions = db.cachedReactionDao()
22 private val conversations = db.conversationDao()
23
24 private companion object {
25 private const val MS_PER_SECOND = 1000L
26 private const val TAG = "WAEventProcessor"
27 }
28
29 fun start(events: SharedFlow<WhatsAppEvent>) {
30 scope.launch {
31 events.collect { event ->
32 try {
33 handle(event)
34 } catch (expected: Throwable) {
35 Log.error(TAG, "failed to process ${event::class.simpleName}", expected)
36 }
37 }
38 }
39 }
40
41 fun stop() {
42 scope.cancel()
43 }
44
45 private suspend fun handle(event: WhatsAppEvent) {
46 when (event) {
47 is WhatsAppEvent.IncomingMessage -> handleIncomingMessage(event)
48 is WhatsAppEvent.MessageUpdate -> handleMessageUpdate(event)
49 is WhatsAppEvent.MessageEdited -> handleMessageEdited(event)
50 is WhatsAppEvent.MessageDeleted -> handleMessageDeleted(event)
51 is WhatsAppEvent.ReactionReceived -> handleReactionReceived(event)
52 is WhatsAppEvent.ReactionRemoved -> handleReactionRemoved(event)
53 is WhatsAppEvent.PollVote -> handlePollVote(event)
54 is WhatsAppEvent.ConversationUpdate -> handleConversationUpdate(event)
55 is WhatsAppEvent.ConversationDeleted -> handleConversationDeleted(event)
56 is WhatsAppEvent.ReadReceipt -> handleReadReceipt(event)
57 is WhatsAppEvent.HistorySync -> handleHistorySync(event)
58 is WhatsAppEvent.CallEnded -> handleCallEnded(event)
59 else -> { /* StateChanged, receipts, typing, presence, call offer/state, etc. — not persisted here. */ }
60 }
61 }
62 private suspend fun handleIncomingMessage(event: WhatsAppEvent.IncomingMessage) {
63 val cid = chatJid(event.conversationId)
64 // Only bump unread for a genuinely new message — the same stanza can be delivered
65 // more than once (live + offline replay/retry), which otherwise over-counts.
66 val isNew = messages.get(event.messageId) == null
67 val sd = WhatsAppServiceData(
68 senderName = event.senderName,
69 senderJid = event.senderId,
70 pollQuestion = event.pollQuestion,
71 pollOptions = event.pollOptions.map { PollOptionData(it) },
72 mediaUrl = event.attachments.firstOrNull()?.url,
73 mediaMime = event.attachments.firstOrNull()?.mimeType,
74 mediaName = event.attachments.firstOrNull()?.fileName,
75 )
76 messages.upsert(
77 WhatsAppCachedMessage(
78 messageId = event.messageId,
79 conversationJid = cid,
80 body = event.body,
81 timestamp = event.timestamp,
82 outgoing = false,
83 senderJid = event.senderId ?: "",
84 senderName = event.senderName ?: "",
85 mediaUrl = event.attachments.firstOrNull()?.url,
86 mediaMime = event.attachments.firstOrNull()?.mimeType,
87 mediaName = event.attachments.firstOrNull()?.fileName,
88 serviceData = event.serviceData ?: sd.serialize(),
89 ),
90 )
91 touchConversation(cid, event.timestamp, incrementUnread = isNew)
92 }
93
94 private suspend fun handleMessageUpdate(event: WhatsAppEvent.MessageUpdate) {
95 messages.upsert(
96 WhatsAppCachedMessage(
97 messageId = event.messageId,
98 conversationJid = chatJid(event.conversationId),
99 body = event.body,
100 timestamp = event.timestamp,
101 outgoing = event.outgoing,
102 senderJid = event.senderId ?: "",
103 senderName = event.senderName ?: "",
104 mediaMime = event.mediaMime,
105 mediaName = event.mediaName,
106 serviceData = event.serviceData,
107 ),
108 )
109 touchConversation(chatJid(event.conversationId), event.timestamp, incrementUnread = false)
110 }
111
112 private suspend fun handleMessageEdited(event: WhatsAppEvent.MessageEdited) {
113 messages.markEdited(event.messageId, event.newBody)
114 mergeServiceData(event.messageId) { it.copy(isEdited = true) }
115 }
116
117 private suspend fun handleMessageDeleted(event: WhatsAppEvent.MessageDeleted) {
118 messages.markRevoked(event.messageId)
119 mergeServiceData(event.messageId) { it.copy(isRevoked = true) }
120 }
121
122 private suspend fun handleReactionReceived(event: WhatsAppEvent.ReactionReceived) {
123 reactions.upsert(
124 WhatsAppCachedReaction(event.messageId, event.emoji, event.senderId, System.currentTimeMillis()),
125 )
126 refreshReactions(event.messageId)
127 }
128
129 private suspend fun handleReactionRemoved(event: WhatsAppEvent.ReactionRemoved) {
130 reactions.remove(event.messageId, event.senderId)
131 refreshReactions(event.messageId)
132 }
133
134 private suspend fun handlePollVote(event: WhatsAppEvent.PollVote) {
135 mergeServiceData(event.pollMessageId) { sd ->
136 val updated = sd.pollOptions.map { opt ->
137 if (opt.name in event.optionNames && event.voterId !in opt.voters) {
138 opt.copy(voteCount = opt.voteCount + 1, voters = opt.voters + event.voterId)
139 } else {
140 opt
141 }
142 }
143 sd.copy(pollOptions = updated)
144 }
145 }
146
147 private suspend fun handleConversationUpdate(event: WhatsAppEvent.ConversationUpdate) {
148 val jid = chatJid(event.conversationId)
149 touchConversation(jid, event.lastTimestamp, incrementUnread = false)
150 // Persist group metadata (name + participants) so groups render named/flagged and
151 // survive restarts. Only overwrite with non-empty values so a later bare update
152 // (e.g. a plain message touch) doesn't clobber a good name/participant list.
153 val isGroup = event.isGroup || jid.endsWith("@g.us")
154 val participantsJson = participantsJsonFromServiceData(event.serviceData)
155 if (isGroup || !event.peerName.isNullOrBlank() || participantsJson != null) {
156 val existing = conversations.getConversation(jid) ?: WhatsAppConversation(chatJid = jid)
157 conversations.upsert(
158 existing.copy(
159 isGroup = isGroup || existing.isGroup,
160 name = event.peerName?.takeIf { it.isNotBlank() } ?: existing.name,
161 participants = participantsJson ?: existing.participants,
162 ),
163 )
164 }
165 }
166
167 private suspend fun handleConversationDeleted(event: WhatsAppEvent.ConversationDeleted) {
168 messages.deleteConversation(chatJid(event.conversationId))
169 conversations.delete(chatJid(event.conversationId))
170 }
171
172 private suspend fun handleReadReceipt(event: WhatsAppEvent.ReadReceipt) {
173 // Advance the outgoing message's tick: delivery → Delivered (grey ✓✓), read → Read
174 // (blue ✓✓). The client emits one event per message id (incl. <list><item> batches),
175 // so a single update per event covers the batch case.
176 event.messageId?.let { id ->
177 if (event.isDelivery) messages.markDelivered(id) else messages.markReadStatus(id)
178 }
179 }
180
181 private suspend fun handleHistorySync(event: WhatsAppEvent.HistorySync) {
182 val rows = ArrayList<WhatsAppCachedMessage>()
183 for (conv in event.conversations) {
184 for (m in conv.messages) {
185 rows.add(
186 WhatsAppCachedMessage(
187 messageId = m.messageId,
188 conversationJid = chatJid(conv.conversationId),
189 body = m.body,
190 timestamp = m.timestamp,
191 outgoing = m.outgoing,
192 senderJid = m.senderId ?: "",
193 senderName = m.senderName ?: "",
194 serviceData = m.serviceData,
195 ),
196 )
197 }
198 val newest = conv.messages.maxOfOrNull { it.timestamp } ?: 0L
199 touchConversation(chatJid(conv.conversationId), newest, incrementUnread = false)
200 }
201 if (rows.isNotEmpty()) messages.upsertAll(rows)
202 }
203
204 private suspend fun handleCallEnded(event: WhatsAppEvent.CallEnded) {
205 // Persist a call-log row (Phase D 3e). Best-effort; peer/name/direction come from
206 // the live call state if still present.
207 val st = com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallManager.state.value
208 runCatching {
209 callLog.upsert(
210 WhatsAppCallLog(
211 callId = event.callId,
212 peerJid = st.peerJid,
213 peerName = st.peerName,
214 outgoing =
215 st.phase == com.vayunmathur.communicate.data.whatsapp.call.WhatsAppCallPhase.Outgoing,
216 video = st.isVideo,
217 startTime = System.currentTimeMillis() - event.durationSeconds * MS_PER_SECOND,
218 durationSeconds = event.durationSeconds,
219 outcome = event.reason,
220 ),
221 )
222 }
223 }
224
225 /** Canonical chat JID: strip the "wa:" source prefix and any :device suffix (user:5@srv -> user@srv). */
226 private fun chatJid(raw: String): String = canonicalWhatsAppChatJid(raw)
227
228 /**
229 * Extract the group's participant display names from a [WhatsAppEvent.ConversationUpdate]'s
230 * serviceData blob (`{"participantNames":[...]}`, emitted by `fetchAndEmitGroupInfo`) and
231 * re-serialize them as a JSON array for the conversation's `participants` column. Returns null
232 * when there is nothing to persist (so we don't clobber an existing list).
233 */
234 private fun participantsJsonFromServiceData(serviceData: String?): String? {
235 if (serviceData.isNullOrBlank()) return null
236 return runCatching {
237 val arr = org.json.JSONObject(serviceData).optJSONArray("participantNames") ?: return null
238 if (arr.length() == 0) return null
239 arr.toString()
240 }.getOrNull()
241 }
242
243 private suspend fun touchConversation(jid: String, timestamp: Long, incrementUnread: Boolean) {
244 val existing = conversations.getConversation(jid)
245 val unread = (existing?.unreadCount ?: 0) + if (incrementUnread) 1 else 0
246 conversations.upsert(
247 (existing ?: WhatsAppConversation(chatJid = jid)).copy(
248 lastMessageTimestamp = maxOf(existing?.lastMessageTimestamp ?: 0L, timestamp),
249 unreadCount = unread,
250 ),
251 )
252 }
253
254 /** Rebuild the emoji→count reaction summary into the cached message's serviceData. */
255 private suspend fun refreshReactions(messageId: String) {
256 val rows = reactions.getForMessage(messageId)
257 val summary = rows.groupingBy { it.emoji }.eachCount().map { Reaction(it.key, it.value) }
258 mergeServiceData(messageId) { it.copy(reactions = summary) }
259 }
260
261 private suspend fun mergeServiceData(
262 messageId: String,
263 transform: (WhatsAppServiceData) -> WhatsAppServiceData,
264 ) {
265 val msg = messages.get(messageId) ?: return
266 val current = WhatsAppServiceData.parse(msg.serviceData) ?: WhatsAppServiceData()
267 messages.updateServiceData(messageId, transform(current).serialize())
268 }
269}
270
271/**
272 * Canonical chat JID for a raw WhatsApp conversation id: strip the "wa:"
273 * source prefix the client puts on event conversation ids and any :device
274 * suffix in the user part (`wa:user:5@srv` -> `user@srv`). This is the form
275 * cached messages/conversations are stored under, so every other surface
276 * (thread list, conversation screen, notification shortcut/tap target) must
277 * use it too — a raw `wa:`-prefixed id matches no stored conversation.
278 */
279fun canonicalWhatsAppChatJid(raw: String): String {
280 val s = raw.removePrefix("wa:")
281 val at = s.indexOf('@')
282 if (at <= 0) return s
283 return s.substring(0, at).substringBefore(':') + s.substring(at)
284}